Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
One-time setup that gathers your project's design context and saves it to CLAUDE.md for future sessions.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
scripts/critique-storage.mjs
1#!/usr/bin/env node2/**3* Critique persistence helper.4*5* Each run of /impeccable critique writes a per-target snapshot to6* .impeccable/critique/<timestamp>__<slug>.md7* with a small YAML frontmatter carrying the score + P0/P1 counts.8*9* /impeccable polish reads the latest matching snapshot at start as its10* fix backlog. No other skill auto-reads critique output.11*12* The slug is derived mechanically from the *resolved* primary artifact13* (file path or URL), never from the user's natural-language phrasing.14* Slug stability across runs is what lets the trend display work.15*16* CLI entry points (called from skill instructions):17* node critique-storage.mjs slug <resolved-target>18* node critique-storage.mjs write <slug> <snapshot-body-file>19* node critique-storage.mjs latest <slug>20* node critique-storage.mjs trend <slug> [limit]21*22* Note: there is intentionally no `ignore` subcommand. ignore.md is a plain23* markdown file; the model reads it directly with its file-read tool. This24* helper only exists for operations the model can't trivially do inline25* (normalizing paths, generating filenames, globbing + parsing frontmatter).26*/2728import fs from 'node:fs';29import path from 'node:path';30import { getCritiqueDir } from './impeccable-paths.mjs';3132const SLUG_MAX = 50;3334/**35* Mechanically derive a slug from a resolved target. Returns null if the36* input doesn't look like a stable identifier (empty, project root, etc).37*38* Accepts file paths and URLs. The model resolves "the homepage" to a39* concrete artifact before calling this — we never slug a natural-language40* phrase.41*/42export function slugFromTarget(resolved, { cwd = process.cwd() } = {}) {43if (!resolved || typeof resolved !== 'string') return null;44const trimmed = resolved.trim();45if (!trimmed) return null;4647// URL48if (/^https?:\/\//i.test(trimmed)) {49let url;50try { url = new URL(trimmed); } catch { return null; }51const hostPath = `${url.hostname}${url.pathname}`;52return kebab(hostPath);53}5455// File path. Make it project-relative so two devs critiquing the same56// checkout get the same slug regardless of where their repo is cloned.57const abs = path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);58let rel = path.relative(cwd, abs);59// If the target is outside cwd, fall back to the basename so we still60// produce a stable slug (vs the absolute path, which would include61// home dirs / usernames).62if (rel.startsWith('..') || path.isAbsolute(rel)) {63rel = path.basename(abs);64}65if (!rel || rel === '.' || rel === '') return null;66return kebab(rel);67}6869function kebab(s) {70const slug = s71.toLowerCase()72.replace(/[/\\.]+/g, '-')73.replace(/[^a-z0-9-]+/g, '-')74.replace(/-+/g, '-')75.replace(/^-|-$/g, '');76if (!slug) return null;77// Cap from the tail — the tail (filename) is more identifying than the78// top-level directory.79return slug.length <= SLUG_MAX ? slug : slug.slice(slug.length - SLUG_MAX).replace(/^-/, '');80}8182/**83* Filename-safe UTC ISO timestamp: hyphens for separators, trailing Z.84* Plain colons aren't allowed on Windows filesystems.85*/86export function nowFilenameStamp(date = new Date()) {87const iso = date.toISOString(); // 2026-05-12T18:30:00.123Z88return iso.replace(/[:.]/g, '-').replace(/-\d+Z$/, 'Z');89}9091/**92* Write a snapshot for `slug`. `meta` carries the small structured frontmatter93* keys read back by readTrend(). `body` is the human-readable critique94* report (everything below the frontmatter).95*96* Returns the absolute path written.97*/98export function writeSnapshot({ slug, meta, body, cwd = process.cwd(), now = new Date() }) {99if (!slug) throw new Error('writeSnapshot requires a slug');100const dir = getCritiqueDir(cwd);101fs.mkdirSync(dir, { recursive: true });102const timestamp = nowFilenameStamp(now);103const filePath = path.join(dir, `${timestamp}__${slug}.md`);104// Spread `meta` first so internally computed `timestamp` and `slug`105// always win. Otherwise a caller-supplied meta blob (parsed from the106// IMPECCABLE_CRITIQUE_META env var) could clobber them, leaving the107// filename in disagreement with its frontmatter and corrupting trends.108const front = serializeFrontmatter({ ...meta, timestamp, slug });109fs.writeFileSync(filePath, `${front}\n${body.trim()}\n`, 'utf-8');110return filePath;111}112113function serializeFrontmatter(obj) {114const lines = ['---'];115for (const [key, value] of Object.entries(obj)) {116if (value === undefined || value === null) continue;117const str = typeof value === 'string' ? value : String(value);118// Quote strings that contain : or # to keep parsing simple.119const needsQuotes = typeof value === 'string' && /[:#]/.test(str);120lines.push(`${key}: ${needsQuotes ? JSON.stringify(str) : str}`);121}122lines.push('---');123return lines.join('\n');124}125126function parseFrontmatter(text) {127const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---/);128if (!match) return {};129const out = {};130for (const line of match[1].split(/\r?\n/)) {131const colon = line.indexOf(':');132if (colon < 0) continue;133const key = line.slice(0, colon).trim();134let value = line.slice(colon + 1).trim();135if (/^".*"$/.test(value)) {136try { value = JSON.parse(value); } catch { /* leave as-is */ }137} else if (/^-?\d+$/.test(value)) {138value = Number(value);139}140out[key] = value;141}142return out;143}144145/**146* Return all snapshot files for `slug`, sorted oldest → newest.147*/148function listSnapshotsForSlug(slug, cwd) {149const dir = getCritiqueDir(cwd);150if (!fs.existsSync(dir)) return [];151const suffix = `__${slug}.md`;152return fs.readdirSync(dir)153.filter((f) => f.endsWith(suffix))154.sort()155.map((f) => path.join(dir, f));156}157158/**159* Return the most recent snapshot for `slug`, or null. Polish reads this160* to find its fix backlog when the slug matches.161*/162export function readLatestSnapshot(slug, { cwd = process.cwd() } = {}) {163const all = listSnapshotsForSlug(slug, cwd);164if (!all.length) return null;165const latest = all[all.length - 1];166const body = fs.readFileSync(latest, 'utf-8');167return { path: latest, body, meta: parseFrontmatter(body) };168}169170/**171* Return the last `limit` snapshots' frontmatter, oldest → newest.172* Critique appends a one-line trend to its output using this.173*/174export function readTrend(slug, { limit = 5, cwd = process.cwd() } = {}) {175const all = listSnapshotsForSlug(slug, cwd);176const slice = all.slice(-limit);177return slice.map((file) => parseFrontmatter(fs.readFileSync(file, 'utf-8')));178}179180// ---- CLI ---------------------------------------------------------------181182function main(argv) {183const [cmd, ...args] = argv;184switch (cmd) {185case 'slug': {186const slug = slugFromTarget(args[0]);187if (!slug) { process.stderr.write('no stable slug for input\n'); process.exit(1); }188process.stdout.write(`${slug}\n`);189return;190}191case 'write': {192const [slug, bodyFile] = args;193if (!slug || !bodyFile) { process.stderr.write('usage: write <slug> <body-file>\n'); process.exit(1); }194const raw = fs.readFileSync(bodyFile, 'utf-8');195// The body file may be a full report. The caller passes the meta as196// a JSON object on stdin if it wants structured frontmatter; otherwise197// we write with minimal metadata.198let meta = {};199const metaArg = process.env.IMPECCABLE_CRITIQUE_META;200if (metaArg) {201try { meta = JSON.parse(metaArg); } catch { /* ignore */ }202}203const out = writeSnapshot({ slug, meta, body: raw });204process.stdout.write(`${out}\n`);205return;206}207case 'latest': {208const latest = readLatestSnapshot(args[0]);209if (!latest) { process.exit(2); }210process.stdout.write(latest.body);211return;212}213case 'trend': {214const rows = readTrend(args[0], { limit: args[1] ? Number(args[1]) : 5 });215process.stdout.write(JSON.stringify(rows, null, 2) + '\n');216return;217}218default:219process.stderr.write('usage: critique-storage.mjs <slug|write|latest|trend> [args]\n');220process.exit(1);221}222}223224if (import.meta.url === `file://${process.argv[1]}`) {225main(process.argv.slice(2));226}227