#!/usr/bin/env node /** * taste — the two verbs that are code. * * node taste.mjs derive scaffold a transcript, then run _derive.md * node taste.mjs publish compile taste.md and social.md into pipeforge * node taste.mjs publish --check re-compile and diff; fails on drift * node taste.mjs publish --review keep the text, move the review date * * `taste build` is not here. It is a reading protocol, described in SKILL.md. * * Publish is deterministic: bodies are compiled from the library with no dates * in them, and dates live only in the provenance comment. Re-running publish * with an unchanged library writes nothing. */ import { createHash } from "node:crypto"; import { access, mkdir, readFile, readdir, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; const HERE = path.dirname(fileURLToPath(import.meta.url)); const PIPE = process.env.PIPEFORGE_DIR || path.join(homedir(), "Documents", "pipeforge"); const REVIEW_DAYS = 90; const META = new Set(["AGENTS.md", "README.md", "SKILL.md"]); /** Written first line of every published file. Dates are provenance, not content. */ const HEADER = /^\n\n/; function sha256(text) { return createHash("sha256").update(text, "utf8").digest("hex"); } function today() { const now = new Date(); const pad = (value) => String(value).padStart(2, "0"); return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`; } function addDays(iso, days) { const date = new Date(`${iso}T00:00:00Z`); date.setUTCDate(date.getUTCDate() + days); return date.toISOString().slice(0, 10); } /** * A category header carries `Read-back: ` until the day-later read has * happened, then `Read-back: done `. A date in the past that is still * pending is a draft being published early. Files that predate the convention * have no line and are left alone rather than retro-failed. */ function readBack(source) { const match = source.match(/^Read-back:[ \t]*(.+)$/m); if (!match) return { state: "unrecorded" }; const value = match[1].trim(); if (/^done\b/i.test(value)) return { state: "done" }; if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return { state: "due", date: value }; return { state: "unknown", value }; } /** * README's "## Earned" list is the gate. Categories are earned, not declared, * and the list is the only place that says which. Returns the reason text, or * null when the category is not on it. */ function earnedReason(readme, category) { const section = readme.split(/^## Earned$/m)[1]; if (!section) return null; const block = section.split(/^## /m)[0]; const line = block.match(new RegExp(`^-\\s+\`${category}\`\\s*[—–-]?\\s*(.*)$`, "m")); return line ? line[1].trim() : null; } async function exists(file) { try { await access(file); return true; } catch { return false; } } async function read(file) { return readFile(path.join(HERE, file), "utf8"); } function readSection(source, title) { const start = source.match(new RegExp(`^## ${title}\\s*$`, "m")); if (!start) return ""; const rest = source.slice(start.index + start[0].length); const next = rest.search(/^## /m); return (next === -1 ? rest : rest.slice(0, next)).trim(); } function dropSection(source, title) { const start = source.match(new RegExp(`^## ${title}\\s*$`, "m")); if (!start) return source; const rest = source.slice(start.index); const next = rest.slice(1).search(/^## /m); const end = next === -1 ? source.length : start.index + 1 + next; return (source.slice(0, start.index) + source.slice(end)).trim(); } function stripTitle(source) { return source.replace(/^#[^\n]*\n+/, ""); } /** * Category files are written for an agent and carry bookkeeping an outside * reader does not need: source tags and the "never for this file" note. Strength * markers stay, because which parts are checked is the point. */ function stripForPublic(source) { return dropSection(dropSection(source, "Never for this file"), "Notes for me") // A tag on its own line goes with its newline; an inline tag goes with its // backticks. Doing the standalone case first keeps list items joined. .replace(/\n[ \t]*`?\[from:[^\]]+\]`?[ \t]*(?=\n)/g, "") .replace(/[ \t]*`?\[from:[^\]]+\]`?/g, "") .replace(/[ \t]+$/gm, "") .replace(/\n{3,}/g, "\n\n") .trim(); } function titleCase(word) { return word.charAt(0).toUpperCase() + word.slice(1); } async function categories() { const files = (await readdir(HERE)) .filter((file) => file.endsWith(".md") && !file.startsWith("_") && !META.has(file)) .sort(); const published = []; const skipped = []; for (const file of files) { const source = await read(file); const body = readSection(source, "Public"); if (!body) { skipped.push(file); continue; } const name = source.match(/^Category:\s*([^.\n]+)/m)?.[1].trim() || file.replace(/\.md$/, ""); published.push({ file, name: titleCase(name), body, readBack: readBack(source) }); } return { published, skipped }; } function composeTaste({ general, published }) { const names = published.map((category) => category.name); const list = names.length === 1 ? names[0] : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`; const sections = published .map((category) => `## ${category.name}\n\n${category.body}`) .join("\n\n"); // General sits one level under the page: its rules are subsections, like each // category's entries. const generalBody = general.replace(/^## /gm, "### "); return `# Taste A summary of a private taste library. The rules and the counter-examples are here; the interviews, the behaviour data and anything that names a person stay private. It is grounds for refusal, not a description to live up to. If you are working with me and a direction fails one of these, say which one and move on. Categories so far: ${list}. A category is added when it has been earned, not to fill a list. If you want to work on something, [say so](/social). The same link is at the bottom, if you got here by reading instead. ## How to read this - [hard] is not negotiable. [soft] needs a reason. [guess] is unverified and is a question to ask, not a rule to apply. - Silence is not permission. If something is not covered here, ask me. - One deliberate violation per project is allowed, and it has to be announced. - A rejection needs a rule cited. "This fails the runs-not-saves rule" is useful; "this is not quite my thing" is not. ## General ${generalBody} ${sections} ## What is not here The full category files, the interview transcripts and the behaviour data stay private. What is published is the criteria and the current state, not the record. The template that builds this page is public: [Taste](https://taste.pipeforge.org). ## How to reach me [How to reach me](/social) says what I am open to and what to put in the message. `; } async function compile() { const general = stripForPublic(stripTitle(await read("_general.md"))); const { published, skipped } = await categories(); const social = (await read("_social.md")).trim() + "\n"; return { taste: composeTaste({ general, published }), social, skipped, published, publicText: published.map((category) => category.body).join("\n\n"), }; } /** * The published text is authored in a private file written about the owner, so * third person and bookkeeping leak easily. Fail loudly rather than publish a * voice that sounds like a consultant. */ function lint(label, text) { const issues = []; const banned = [ [/\[from:/, "internal source tag"], [/\[(hard|soft|guess)\]/, "strength marker"], [/\bthe user\b/i, "third person"], [/\bthe owner\b/i, "third person"], [/\.md\b/, "file reference"], [/\bTODO\b/, "unfinished note"], ]; for (const [pattern, reason] of banned) { if (pattern.test(text)) issues.push(`${label}: contains a ${reason} (${pattern.source})`); } return issues; } function normalize(body) { return `${body.trim()}\n`; } /** Site-relative links in a published body. External URLs need the network. */ function internalLinks(source) { return [ ...new Set( [...source.matchAll(/\[[^\]]*\]\(([^)\s]+)\)/g)] .map((match) => match[1]) .filter((href) => href.startsWith("/")) .map((href) => href.split("#")[0].split("?")[0]) .filter(Boolean), ), ]; } /** * Every internal link in _social.md has to land on a page the site actually * built. A retired project left in "Working on" is the failure this catches. */ async function unresolvedLinks(source) { const dist = path.join(PIPE, "dist"); if (!(await exists(dist))) return null; const missing = []; for (const href of internalLinks(source)) { const rel = href.replace(/^\/+|\/+$/g, ""); const candidates = rel === "" ? ["index.html"] : [path.join(rel, "index.html"), `${rel}.html`, rel]; let found = false; for (const candidate of candidates) { if (await exists(path.join(dist, candidate))) { found = true; break; } } if (!found) missing.push(href); } return missing; } function render(record, derived) { const head = `\n\n`; return head + record.body; } function parse(source) { const match = source.match(HEADER); if (!match) return null; return { derived: match[1], review: match[2], sha: match[3], body: source.slice(match[0].length), }; } function firstDifference(expected, actual) { const a = expected.split("\n"); const b = actual.split("\n"); for (let index = 0; index < Math.max(a.length, b.length); index += 1) { if (a[index] !== b[index]) { return `line ${index + 1}\n published: ${JSON.stringify(b[index] ?? "(nothing)")}\n compiled: ${JSON.stringify(a[index] ?? "(nothing)")}`; } } return "bodies differ only in trailing whitespace"; } async function publish(argv) { const check = argv.includes("--check"); const review = argv.includes("--review"); if (!(await exists(PIPE))) { throw new Error(`PIPEFORGE_DIR is not a directory: ${PIPE}`); } const { taste, social, skipped, published, publicText } = await compile(); for (const file of skipped) { console.warn(`note: ${file} has no "## Public" section; not published.`); } const records = [ { file: path.join(PIPE, "content", "taste.md"), body: normalize(taste) }, { file: path.join(PIPE, "content", "social.md"), body: normalize(social) }, ]; // A voice leak is a reason not to write at all, not a warning. const problems = [...lint("public blocks", publicText), ...lint("social", social)]; const missing = await unresolvedLinks(await read("_social.md")); if (missing === null) { console.warn("note: the site is not built (no dist); social links were not checked."); } else { for (const href of missing) { problems.push(`social: link ${href} does not resolve to a built page; fix the project or drop it`); } } // A draft is allowed to sit in the library; it is not allowed on the site. for (const category of published) { if (category.readBack.state !== "due" || category.readBack.date >= today()) continue; const message = `${category.file}: read-back was due ${category.readBack.date} and has not happened. Read it back, delete anything that describes a person, then set "Read-back: done ${today()}".`; if (check) problems.push(message); else console.warn(`warn: ${message}`); } if (problems.length > 0) { for (const problem of problems) console.error(`fail: ${problem}`); process.exitCode = 1; return; } for (const record of records) { const relative = path.relative(PIPE, record.file); const current = (await exists(record.file)) ? await readFile(record.file, "utf8") : null; const parsed = current ? parse(current) : null; if (check) { if (!current) { problems.push(`${relative}: not published yet`); continue; } if (!parsed) { problems.push(`${relative}: missing the provenance comment; publish again`); continue; } if (sha256(parsed.body) !== parsed.sha) { problems.push(`${relative}: body was edited by hand; change the library and publish`); continue; } if (normalize(parsed.body) !== record.body) { problems.push(`${relative}: differs from a fresh compile\n ${firstDifference(record.body, normalize(parsed.body))}`); } if (today() > parsed.review) { problems.push(`${relative}: review date ${parsed.review} has passed; re-read it, then publish --review`); } continue; } if (review && current) { const next = render({ body: normalize(parsed?.body ?? record.body) }, today()); if (next === current) { console.log(`${relative}: already reviewed today.`); } else { await writeFile(record.file, next); console.log(`${relative}: review moved to ${addDays(today(), REVIEW_DAYS)}.`); } continue; } if (parsed && parsed.sha === sha256(record.body)) { console.log(`${relative}: unchanged.`); continue; } await writeFile(record.file, render(record, today())); console.log(`${relative}: written.`); } if (problems.length > 0) { for (const problem of problems) console.error(`fail: ${problem}`); process.exitCode = 1; } else if (check) { console.log("ok: published files match the library."); } } async function derive(category) { if (!/^[a-z][a-z0-9-]*$/.test(category)) { throw new Error(`"${category}" is not a category slug (lowercase, hyphens).`); } const earned = earnedReason(await read("README.md"), category); if (earned === null) { throw new Error( `"${category}" is not earned. Add it to README.md "## Earned" with the date and reason, or extend an existing category instead.`, ); } const dir = path.join(HERE, "_transcripts"); await mkdir(dir, { recursive: true }); const date = today(); const file = path.join(dir, `${category}-${date}.md`); if (await exists(file)) throw new Error(`${file} already exists. Continue in it.`); await writeFile( file, `# derive: ${category} — ${date} Protocol: ../_derive.md. Questions come from there, one at a time. Rules while transcribing: verbatim answers, no tidying, no summary in place of a quote, and every claim marked [hard], [soft] or [guess]. Uncited means [guess]. The category file is written from this transcript in a later sitting, not here. Why this category is earned (README.md, "When to derive"): ${earned} Transcript starts here. ## Phase 1 — peak, not library ## Phase 2 — the moment ## Phase 3 — counter-examples ## Phase 4 — behaviour ## Phase 5 — outliers ## Phase 6 — tensions ## Phase 7 — the cut ## Read-back Written to ../${category}.md on: `, ); console.log(`created ${path.relative(process.cwd(), file) || file}`); console.log("next: run _derive.md one question at a time, then write the category file from it."); } async function walk(root, prefix = "") { const entries = (await readdir(path.join(root, prefix), { withFileTypes: true })).sort( (a, b) => a.name.localeCompare(b.name), ); const files = []; for (const entry of entries) { const relative = path.join(prefix, entry.name); if (entry.isDirectory()) files.push(...(await walk(root, relative))); else if (entry.isFile()) files.push(relative); } return files; } /** * The template is a copy of the docs plus the tool itself. It never contains a * category, a transcript or the social file, because those are the library and * the library is personal. */ async function writeTemplate(dest) { const src = path.join(HERE, "template"); if (!(await exists(src))) throw new Error("this copy has no template/ directory beside taste.mjs"); const files = await walk(src); for (const file of files) { const target = path.join(dest, file); await mkdir(path.dirname(target), { recursive: true }); await writeFile(target, await readFile(path.join(src, file))); } await writeFile(path.join(dest, "taste.mjs"), await readFile(path.join(HERE, "taste.mjs"))); console.log(`created ${path.relative(process.cwd(), dest) || dest} (${files.length + 1} files)`); console.log("next: edit README.md ## Earned, then node taste.mjs derive "); } const [verb, argument] = process.argv.slice(2); try { if (verb === "derive") await derive(argument); else if (verb === "template") await writeTemplate(argument || "taste-template"); else if (verb === "publish") await publish(process.argv.slice(2)); else { console.log(`taste node taste.mjs derive scaffold a transcript node taste.mjs template [dir] write a copyable library into dir node taste.mjs publish compile into the site node taste.mjs publish --check fail when the site differs from the library node taste.mjs publish --review move the review date, keep the text `); process.exitCode = verb ? 1 : 0; } } catch (error) { console.error(`error: ${error.message}`); process.exitCode = 1; }