202 lines
10 KiB
JavaScript
202 lines
10 KiB
JavaScript
// The fixture workspace: a Git repository with history and changes, a 50-page PDF, background images, and a Project Management store.
|
|
// It lives in the system temporary folder, outside the repository, so the file watcher of the app does not see the worktree.
|
|
import { execFile } from "node:child_process";
|
|
import { createHash } from "node:crypto";
|
|
import { existsSync, realpathSync } from "node:fs";
|
|
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import path from "node:path";
|
|
import { promisify } from "node:util";
|
|
import { encodePng, gradientPixel } from "./png.mjs";
|
|
import { writePdf } from "./pdf.mjs";
|
|
|
|
const run = promisify(execFile);
|
|
export const FIXTURE_VERSION = 1;
|
|
export const COMMITS = 30;
|
|
export const TEXT_FILES = 50;
|
|
export const PDF_PAGES = 50;
|
|
export const BOARDS = 8;
|
|
export const CARDS_PER_BOARD = 50;
|
|
export const IMAGES = 5;
|
|
export const IMAGE_SIZE = { width: 1920, height: 1080 };
|
|
/** A file at the workspace root that the tree shows at once. The start time waits for its row. */
|
|
export const KNOWN_ROW = "sample.pdf";
|
|
|
|
export const fixtureRoot = () => path.join(tmpdir(), "runestone-phase7-fixture");
|
|
|
|
/** A UUID with the version 4 layout, made from `seed`, so each fixture build has the same IDs. */
|
|
export function seededUuid(seed) {
|
|
const hex = createHash("sha256").update(seed).digest("hex");
|
|
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-${"89ab"[parseInt(hex[16], 16) % 4]}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
|
|
}
|
|
|
|
/** The card file name: the hex of the UTF-8 card ID, then `.md`. */
|
|
export const cardFileName = id => `${Buffer.from(id, "utf8").toString("hex")}.md`;
|
|
|
|
/** An order key that sorts in the same order as `index`. */
|
|
const orderKey = index => `a${String.fromCharCode(97 + Math.floor(index / 26))}${String.fromCharCode(97 + (index % 26))}`;
|
|
|
|
const textName = index => `note-${String(index + 1).padStart(2, "0")}.txt`;
|
|
|
|
function git(cwd, args, env = {}) {
|
|
const config = ["-c", "user.name=RuneStone Fixture", "-c", "[email protected]", "-c", "commit.gpgsign=false", "-c", "core.autocrlf=false", "-c", "init.defaultBranch=main"];
|
|
return run("git", ["-C", cwd, ...config, ...args], { env: { ...process.env, GIT_TERMINAL_PROMPT: "0", ...env }, windowsHide: true, maxBuffer: 16 * 1024 * 1024 });
|
|
}
|
|
|
|
const LISTS = [
|
|
{ id: "backlog", name: "Backlog", status: null },
|
|
{ id: "todo", name: "To do", status: "todo" },
|
|
{ id: "doing", name: "In progress", status: "doing" },
|
|
{ id: "done", name: "Done", status: "done" },
|
|
];
|
|
|
|
/** The Project Management store: `workspace.json`, the card files, and the two `.gitignore` files. */
|
|
export function pmFiles() {
|
|
const files = new Map();
|
|
files.set(".runestone/pm/.gitignore", "# RuneStone PM local data\n*\n");
|
|
files.set(".runestone/pm/cards/.gitignore", "*\n");
|
|
const boards = [];
|
|
for (let b = 0; b < BOARDS; b++) {
|
|
const id = seededUuid(`board-${b}`);
|
|
boards.push({
|
|
name: `Fixture board ${b + 1}`,
|
|
value: {
|
|
schema: 1, kind: "board", id,
|
|
lists: LISTS.map(list => ({ id: list.id, name: list.name, status: list.status, collapsed: false })),
|
|
defaults: { todo: "todo", doing: "doing", done: "done" },
|
|
},
|
|
});
|
|
for (let c = 0; c < CARDS_PER_BOARD; c++) {
|
|
const cardId = seededUuid(`card-${b}-${c}`);
|
|
const list = LISTS[c % LISTS.length];
|
|
const status = list.status ?? "todo";
|
|
const source = [
|
|
"---",
|
|
"runestone_pm:",
|
|
" schema: 1",
|
|
` id: ${cardId}`,
|
|
" kind: task",
|
|
` status: ${status}`,
|
|
" tags: []",
|
|
" sessions: []",
|
|
" archived: false",
|
|
` order: ${orderKey(b * CARDS_PER_BOARD + c)}`,
|
|
" placements:",
|
|
` ${id}:`,
|
|
` listId: ${list.id}`,
|
|
` order: ${orderKey(c)}`,
|
|
` title: Fixture card ${c + 1} on board ${b + 1}`,
|
|
` priority: ${["low", "medium", "high"][c % 3]}`,
|
|
"---",
|
|
"",
|
|
`This card is fixture data for the memory measurement. Board ${b + 1}, card ${c + 1}.`,
|
|
"",
|
|
].join("\n");
|
|
files.set(`.runestone/pm/cards/${cardFileName(cardId)}`, source);
|
|
}
|
|
}
|
|
files.set(".runestone/pm/workspace.json", JSON.stringify({ schema: 1, boards, deletedBoardIds: [] }, null, 2) + "\n");
|
|
return files;
|
|
}
|
|
|
|
const COLORS = [
|
|
[[16, 42, 120], [220, 90, 40], 0.3],
|
|
[[10, 110, 80], [240, 220, 60], 1.2],
|
|
[[120, 20, 90], [40, 200, 230], 2.1],
|
|
[[30, 30, 30], [200, 200, 210], 0],
|
|
[[200, 40, 40], [20, 60, 160], Math.PI / 2],
|
|
];
|
|
|
|
async function writeFiles(root, files) {
|
|
for (const [rel, contents] of files) {
|
|
const target = path.join(root, ...rel.split("/"));
|
|
await mkdir(path.dirname(target), { recursive: true });
|
|
await writeFile(target, contents);
|
|
}
|
|
}
|
|
|
|
/** Build the fixture in `root`. The caller removes an old fixture first. */
|
|
export async function buildFixture(root) {
|
|
const workspace = path.join(root, "workspace");
|
|
const backgrounds = path.join(root, "backgrounds");
|
|
await mkdir(workspace, { recursive: true });
|
|
await mkdir(backgrounds, { recursive: true });
|
|
for (const [index, [from, to, angle]] of COLORS.entries()) {
|
|
const { width, height } = IMAGE_SIZE;
|
|
await writeFile(path.join(backgrounds, `background-${index + 1}.png`), encodePng(width, height, gradientPixel(width, height, from, to, angle)));
|
|
}
|
|
await git(workspace, ["init", "-q"]);
|
|
await writeFile(path.join(workspace, ".gitignore"), ".runestone/\n");
|
|
await writeFile(path.join(workspace, "sample.pdf"), writePdf(Array.from({ length: PDF_PAGES }, (_, index) => `Page ${index + 1}`)));
|
|
const line = (file, version) => `Fixture file ${file + 1}, version ${version}.\n`;
|
|
const versions = Array(TEXT_FILES).fill(0);
|
|
for (let file = 0; file < TEXT_FILES; file++) await writeFile(path.join(workspace, textName(file)), line(file, 0));
|
|
for (let commit = 0; commit < COMMITS; commit++) {
|
|
if (commit > 0) {
|
|
// Each later commit changes five files, so the graph and the diffs have content.
|
|
for (let k = 0; k < 5; k++) {
|
|
const file = (commit * 7 + k * 11) % TEXT_FILES;
|
|
versions[file]++;
|
|
await writeFile(path.join(workspace, textName(file)), Array.from({ length: versions[file] + 1 }, (_, v) => line(file, v)).join(""));
|
|
}
|
|
}
|
|
await git(workspace, ["add", "-A"]);
|
|
const date = new Date(Date.UTC(2026, 0, 1 + commit, 12)).toISOString();
|
|
await git(workspace, ["commit", "-q", "--no-verify", "-m", commit === 0 ? "Add the fixture files" : `Change fixture files, step ${commit}`], { GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date });
|
|
}
|
|
for (let file = 0; file < TEXT_FILES; file++) {
|
|
const target = path.join(workspace, textName(file));
|
|
await writeFile(target, (await readFile(target, "utf8")) + `Changed after the last commit (file ${file + 1}).\n`);
|
|
}
|
|
await writeFiles(workspace, pmFiles());
|
|
await writeFile(path.join(root, "fixture.json"), JSON.stringify({ version: FIXTURE_VERSION, commits: COMMITS, changes: TEXT_FILES, pages: PDF_PAGES, boards: BOARDS, cards: BOARDS * CARDS_PER_BOARD, images: IMAGES }, null, 2) + "\n");
|
|
}
|
|
|
|
/** Check that the fixture in `root` is complete and unchanged. Return a list of problems, empty when it matches. */
|
|
export async function checkFixture(root) {
|
|
const problems = [];
|
|
const workspace = path.join(root, "workspace");
|
|
try {
|
|
const record = JSON.parse(await readFile(path.join(root, "fixture.json"), "utf8"));
|
|
if (record.version !== FIXTURE_VERSION) problems.push(`fixture version ${record.version}`);
|
|
} catch { problems.push("no fixture.json"); return problems; }
|
|
for (let index = 0; index < IMAGES; index++) if (!existsSync(path.join(root, "backgrounds", `background-${index + 1}.png`))) problems.push(`no background ${index + 1}`);
|
|
if (!existsSync(path.join(workspace, "sample.pdf"))) problems.push("no sample.pdf");
|
|
try {
|
|
const status = (await git(workspace, ["status", "--porcelain"])).stdout.split("\n").filter(Boolean);
|
|
if (status.length !== TEXT_FILES || status.some(entry => !entry.startsWith(" M "))) problems.push(`git status shows ${status.length} entries, not ${TEXT_FILES} changed files`);
|
|
const count = Number((await git(workspace, ["rev-list", "--count", "HEAD"])).stdout.trim());
|
|
if (count !== COMMITS) problems.push(`${count} commits, not ${COMMITS}`);
|
|
} catch (error) { problems.push(`git: ${error.message}`); }
|
|
for (const [rel, contents] of pmFiles()) {
|
|
const target = path.join(workspace, ...rel.split("/"));
|
|
if (!existsSync(target)) { problems.push(`no ${rel}`); break; }
|
|
if (rel.endsWith("workspace.json") && (await readFile(target, "utf8")) !== contents) problems.push("workspace.json changed");
|
|
}
|
|
return problems;
|
|
}
|
|
|
|
/** Reuse the fixture when it matches, or build it again. Return the canonical paths. */
|
|
export async function prepareFixture({ fresh = false, root = fixtureRoot(), log = () => {} } = {}) {
|
|
let problems = fresh ? ["--fresh-fixture"] : await checkFixture(root);
|
|
if (problems.length) {
|
|
log(`Building the fixture in ${root} (${problems.join(", ")}).`);
|
|
// The fixture folder belongs to this tool. It is in the system temporary folder.
|
|
if (path.basename(root) !== "runestone-phase7-fixture") throw new Error(`Refusing to remove ${root}.`);
|
|
await rm(root, { recursive: true, force: true });
|
|
await buildFixture(root);
|
|
problems = await checkFixture(root);
|
|
if (problems.length) throw new Error(`The new fixture does not match: ${problems.join(", ")}.`);
|
|
} else log(`Reusing the fixture in ${root}.`);
|
|
// The canonical path expands short 8.3 names, so the app and the grants see the same path.
|
|
const real = realpathSync.native(root);
|
|
return { root: real, workspace: path.join(real, "workspace"), backgrounds: path.join(real, "backgrounds") };
|
|
}
|
|
|
|
/** Run the read-only Project Management helper of the skill. Return the number of boards that it lists. */
|
|
export async function inspectPmBoards(workspace, helper = path.join(process.env.USERPROFILE ?? "", ".claude", "skills", "runestone-project-management", "scripts", "inspect.mjs")) {
|
|
if (!existsSync(helper)) return { checked: false, reason: `no helper at ${helper}` };
|
|
const { stdout } = await run(process.execPath, [helper, "boards", "--workspace", workspace], { windowsHide: true, maxBuffer: 16 * 1024 * 1024 });
|
|
return { checked: true, output: stdout };
|
|
}
|