AetheriaLore/scripts/concept-mill/build.mjs

293 lines
14 KiB
JavaScript
Raw Permalink Normal View History

// Builds the Concept Mill's manifest and render derivatives from two inputs:
// ships.yaml (hand-curated ships) and the prompt benches (benches/<bench>.yaml
// with their frozen rounds in rounds/<bench>/, rendered through bench.mjs).
//
// node scripts/concept-mill/build.mjs [--renders <dir>] [--force]
//
// For every variant with a `source`, and every bench image, it writes a WebP
// of at most 1600 px (never enlarged) and a thumbnail into
// Aetheria/media/concept-mill/ and publishes the render's record as
// prompts/<image>.txt: the .md for a ships.yaml render, text generated from
// raven-image's <image>.json for a bench render. Originals are only read.
// Existing derivatives are kept unless --force is given, so a run without the
// renders on disk still works. It then writes the manifest the page component
// imports. A bench item with renders is one row; its images are the variants.
// A screen grade ranks and annotates a bench render; none removes one.
//
// js-yaml and sharp come from GameCult-Quartz, which the site build already
// requires beside this repo (or at GAMECULT_QUARTZ_ROOT).
import fs from "node:fs/promises"
import path from "node:path"
import { fileURLToPath } from "node:url"
import { GRADE_RANK, benchNames, gradeOf, loadBench, loadRecipe, loadScreens, imageBase, recipeFiles, repoRoot, rubric, sharp, yaml } from "./bench.mjs"
const here = path.dirname(fileURLToPath(import.meta.url))
const args = process.argv.slice(2)
const flag = (name) => args.includes(name)
const option = (name, fallback) => {
const i = args.indexOf(name)
return i >= 0 ? args[i + 1] : fallback
}
const rendersRoot = path.resolve(option("--renders", path.join(repoRoot, "Aetheria", "Brainstorming", "Renders")))
const force = flag("--force")
const mediaDir = path.join(repoRoot, "Aetheria", "media", "concept-mill")
const promptDir = path.join(mediaDir, "prompts")
const manifestPath = path.join(repoRoot, "site", "quartz", "components", "data", "conceptMill.json")
const mediaUrl = "/media/concept-mill/"
const FULL_WIDTH = 1600
const THUMB_WIDTH = 720
const SECTIONS = [
{ kind: "pass", title: "Kept" },
{ kind: "new", title: "Unreviewed" },
{ kind: "scrap", title: "Scrap bin" },
]
const exists = (p) => fs.access(p).then(() => true, () => false)
async function derive(image, png) {
const opts = { width: FULL_WIDTH, withoutEnlargement: true }
await sharp(png).resize(opts).webp({ quality: 82 }).toFile(path.join(mediaDir, `${image}.webp`))
await sharp(png).resize({ ...opts, width: THUMB_WIDTH }).webp({ quality: 72 }).toFile(path.join(mediaDir, `${image}-thumb.webp`))
}
async function ingest(variant) {
const full = path.join(mediaDir, `${variant.image}.webp`)
const thumb = path.join(mediaDir, `${variant.image}-thumb.webp`)
const record = path.join(promptDir, `${variant.prompt}.txt`)
const png = path.join(rendersRoot, `${variant.source}.png`)
const md = path.join(rendersRoot, `${variant.source}.md`)
const have = (await exists(full)) && (await exists(thumb)) && (await exists(record))
if (have && !force) return false
if (!(await exists(png)) || !(await exists(md))) {
throw new Error(`${variant.image}: derivatives missing and source not found at ${png}`)
}
await derive(variant.image, png)
await fs.copyFile(md, record)
return true
}
// A render record is Markdown with "## Hypothesis" and "## Agent verdict"
// (or "## Agent observation", the round 4-5 heading) sections.
function section(text, headings) {
const lines = text.split(/\r?\n/)
const start = lines.findIndex((l) => l.startsWith("## ") && headings.includes(l.slice(3).trim().toLowerCase()))
if (start < 0) return undefined
const body = []
for (const line of lines.slice(start + 1)) {
if (line.startsWith("## ")) break
body.push(line)
}
const out = body.join(" ").replace(/`/g, "").replace(/\s+/g, " ").trim()
return out || undefined
}
function fail(message) {
console.error(`concept-mill: ${message}`)
process.exit(1)
}
const data = yaml.load(await fs.readFile(path.join(here, "ships.yaml"), "utf8"))
await fs.mkdir(promptDir, { recursive: true })
const shipIds = new Set()
let ingested = 0
const ships = []
for (const ship of data.ships) {
if (shipIds.has(ship.id)) fail(`duplicate ship id ${ship.id}`)
shipIds.add(ship.id)
if (!SECTIONS.some((s) => s.kind === ship.status?.kind)) fail(`${ship.id}: unknown status kind`)
if (!ship.variants?.length) fail(`${ship.id}: no variants`)
const picks = ship.variants.filter((v) => v.pick || v.default)
if (picks.length > 1) fail(`${ship.id}: more than one pick or default variant`)
const variants = []
const variantIds = new Set()
for (const v of ship.variants) {
if (variantIds.has(v.id)) fail(`${ship.id}: duplicate variant id ${v.id}`)
variantIds.add(v.id)
const variant = { ...v, prompt: v.prompt ?? v.image }
if (variant.source && (await ingest(variant))) ingested++
for (const file of [`${variant.image}.webp`, `${variant.image}-thumb.webp`, `prompts/${variant.prompt}.txt`]) {
if (!(await exists(path.join(mediaDir, file)))) fail(`${ship.id}/${v.id}: missing ${file}`)
}
const record = await fs.readFile(path.join(promptDir, `${variant.prompt}.txt`), "utf8")
variants.push({
id: v.id,
round: String(v.round),
image: `${mediaUrl}${variant.image}.webp`,
thumb: `${mediaUrl}${variant.image}-thumb.webp`,
prompt: `${mediaUrl}prompts/${variant.prompt}.txt`,
hypothesis: v.hypothesis ?? section(record, ["hypothesis"]),
verdict: v.verdict ?? section(record, ["agent verdict", "agent observation"]),
operator: v.operator,
pick: Boolean(v.pick),
})
}
const { variants: _, ...readout } = ship
ships.push({
...readout,
crew: String(ship.crew),
hardpoints: ship.hardpoints.map(([qty, size, mount]) => ({ qty: String(qty), size, mount })),
variants,
menuGroup: ship.faction,
defaultVariant: variants[ship.variants.findIndex((v) => v.pick || v.default)]?.id ?? variants[variants.length - 1].id,
})
}
// ---------- bench rows ----------
// One row per bench item that has renders; its variants are that item's images,
// in round order then by k. Ship ids and bench row ids share one namespace.
const readJson = async (file) => JSON.parse(await fs.readFile(file, "utf8"))
function benchRecord(bench, group, item, recipe, image, run, screen) {
const lines = [
`# ${image.id}`,
"",
`Bench: ${bench.title} (${bench.bench}) · round ${recipe.label} (${recipe.round}) · group ${group.title}`,
`Item: ${item.id} · ${item.name}${item.bet ? ` · ${item.bet}` : ""}`,
`Group note: ${group.note}`,
"",
"## Prompt as typed (the upsampler's input, before it rewrote it)",
"",
image.text,
"",
"## Final caption",
"",
"The exact text the image model's encoder received, written by the upsampler from the prompt above.",
"",
run.caption,
"",
"## Generation",
"",
...(recipe.reproduces
? [`Reproduction: ${recipe.reproduces}. The original render was made ${image.original_utc ?? "at an unrecorded time"}; this copy was made ${run.utc}.`, ""]
: []),
`Model ${run.models?.["1"]} · upsampler ${run.models?.["10"] ?? "off"} · seed ${run.seed} · ${run.size} · ${run.steps} steps · cfg ${run.cfg} · ${run.sampler}/${run.scheduler} · raven-image ${String(run.client_sha256).slice(0, 12)}, graph ${String(run.graph_sha256).slice(0, 12)} · ${run.utc}`,
]
if (screen) {
lines.push("", "## Structural screen", "", `${screen.model} (${String(screen.digest).slice(0, 12)}), rubric ${screen.rubric_sha256.slice(0, 12)}: ${screen.grade}. ${screen.reason}`)
if (screen.override) lines.push(`Operator correction: ${screen.override.grade}. ${screen.override.reason}`)
}
return lines.join("\n") + "\n"
}
// An unscreened render ranks as a doubt: no grade is no reason to bury it.
const rank = (v) => GRADE_RANK[v.screen?.grade ?? "doubt"]
const benchRows = []
let staleScreens = 0
try {
const { sha: currentRubric, thresholds } = rubric()
for (const name of benchNames()) {
const bench = loadBench(name)
const recipes = recipeFiles(name).map(loadRecipe)
const known = new Set(recipes.flatMap((r) => r.images.map((i) => i.id)))
for (const id of Object.keys(bench.images ?? {})) if (!known.has(id)) fail(`${name}: images.${id} names no recipe image`)
for (const [itemId, { item, group }] of bench.items) {
const rowId = `${name}-${itemId}`
if (shipIds.has(rowId)) fail(`bench row id ${rowId} collides with a ship id`)
const variants = []
for (const recipe of recipes) {
const screens = loadScreens(recipe)
const roundId = recipe.round.replace(/^\d{4}-\d{2}-\d{2}-/, "")
for (const image of recipe.images.filter((i) => i.item === itemId).sort((a, b) => a.k - b.k)) {
const stem = imageBase(recipe, rendersRoot, image)
const have = (await exists(path.join(mediaDir, `${image.id}.webp`))) && (await exists(path.join(mediaDir, `${image.id}-thumb.webp`)))
const rendered = (await exists(`${stem}.png`)) && (await exists(`${stem}.json`))
if ((await exists(`${stem}.png`)) !== (await exists(`${stem}.json`))) fail(`${image.id}: the render and its .json record must both exist`)
if (!have && !rendered) continue
const mine = bench.images?.[image.id] ?? {}
// The committed screen record is the input: a missing grade stops the build rather than flipping defaults.
const found = screens[image.id]
if (!found) fail(`${image.id}: no committed screen record; run bench.mjs screen ${path.relative(repoRoot, path.join(here, "rounds", name, `${recipe.round}.yaml`))}`)
const model = { ...found, grade: gradeOf(found.checks, thresholds) }
if (model.rubric_sha256 !== currentRubric) staleScreens++
const override = mine.screen_override
if (override && !(override.grade in GRADE_RANK && override.reason)) fail(`${image.id}: screen_override needs a grade and a reason`)
let screen
if (model) screen = { grade: model.grade, reason: model.reason, corrected: false }
if (override) screen = { grade: override.grade, reason: override.reason, corrected: true, modelGrade: model?.grade }
if (rendered) {
const run = await readJson(`${stem}.json`)
if (!have || force) await derive(image.id, `${stem}.png`)
const record = benchRecord(bench, group, item, recipe, image, run, { ...model, override })
const target = path.join(promptDir, `${image.id}.txt`)
if (!(await exists(target)) || (await fs.readFile(target, "utf8")) !== record) {
await fs.writeFile(target, record)
ingested++
}
}
if (!(await exists(path.join(promptDir, `${image.id}.txt`)))) fail(`${image.id}: missing prompts/${image.id}.txt`)
variants.push({
id: `${roundId}-${image.k}`,
round: recipe.label,
image: `${mediaUrl}${image.id}.webp`,
thumb: `${mediaUrl}${image.id}-thumb.webp`,
prompt: `${mediaUrl}prompts/${image.id}.txt`,
hypothesis: group.note,
promptText: image.text,
generation: `FLUX.3 Klein · seed ${image.seed} · ${recipe.size} · upsampler ${recipe.enhance === false ? "off" : "on"}${recipe.reproduces ? ` · reproduces the render of ${image.original_utc ?? "an unrecorded time"}` : ""}`,
operator: mine.operator,
pick: Boolean(mine.pick),
screen,
})
}
}
if (!variants.length) continue
if (new Set(variants.map((v) => v.id)).size !== variants.length) fail(`${rowId}: duplicate variant id`)
if (variants.filter((v) => v.pick).length > 1) fail(`${rowId}: more than one pick variant`)
const status = item.status ?? { kind: "new", stamp: "UNREVIEWED", verdict: "Bench prompt; awaiting the operator" }
if (!SECTIONS.some((s) => s.kind === status.kind)) fail(`${rowId}: unknown status kind`)
// Default: the lab pick, else the best-graded render (latest round first).
const best = [...variants].reverse().sort((a, b) => rank(a) - rank(b))[0]
benchRows.push({
id: rowId,
name: item.name,
code: bench.ship.code,
faction: bench.ship.faction,
role: bench.ship.role,
desig: bench.ship.desig,
crew: String(bench.ship.crew),
mass: bench.ship.mass,
hardpoints: [],
loadout: [],
concept: bench.brief.replace(/\s+/g, " ").trim(),
notes: `${item.bet ? `${item.bet === "safe" ? "Safe bet" : "Moonshot"}. ` : ""}${group.note}`,
beaten: "",
status,
variants,
menuGroup: `${bench.title} · ${group.title}`,
defaultVariant: (variants.find((v) => v.pick) ?? best).id,
})
shipIds.add(rowId)
}
}
} catch (e) {
if (e.name === "BenchError") fail(e.message)
throw e
}
if (staleScreens) console.warn(`concept-mill: ${staleScreens} screen grades predate the current rubric; run bench.mjs screen to re-screen`)
ships.push(...benchRows)
// Menu order: section, then menu group in first-seen order, then file order.
const ordered = SECTIONS.flatMap(({ kind }) => {
const inSection = ships.filter((s) => s.status.kind === kind)
const groups = [...new Set(inSection.map((s) => s.menuGroup))]
return groups.flatMap((g) => inSection.filter((s) => s.menuGroup === g))
})
const manifest = {
sections: SECTIONS,
votes: data.votes ?? { enabled: false },
ships: ordered,
}
await fs.mkdir(path.dirname(manifestPath), { recursive: true })
await fs.writeFile(manifestPath, JSON.stringify(manifest, null, 1) + "\n")
const variantCount = ordered.reduce((n, s) => n + s.variants.length, 0)
console.log(`concept-mill: ${ordered.length} ships, ${variantCount} variants, ${ingested} renders ingested`)
console.log(`concept-mill: wrote ${path.relative(repoRoot, manifestPath)}`)