// Web console tests, independent sessions: first paint, streams, hand-off, cleanup, overview. // Run with: node --test scripts/test-web-console-server.mjs // // Shared setup (a per-process console home, the CLI runner, fixtures) lives in // web-console-test-helpers.mjs; see the comment at its top. import test from "node:test"; import assert from "node:assert/strict"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { execFileSync, spawn } from "node:child_process"; import http from "node:http"; import { ACCENTS, CARD_WIDTHS, cardWidth, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, } from "../src/web-console/public/palette.js"; import { activityLabel, BUILD_WORKFLOWS, taskLabel, workingLine } from "../src/web-console/public/labels.js"; import { bindLoopback, cleanupFindings, handOff, PROTECTED_CONSOLE_FILES, readOverview, readSpecFile, removeCleanup, removeScratch, removeSessions, repoRoots, SESSION_MAX_AGE_MS, staleScratch, STRAY_GRACE_MS, staleSessions, terminalLine, } from "../src/web-console/sessions.mjs"; import { validate } from "../src/web-console/patches.mjs"; // Scrubs this process's git config, so the Cleanup fixtures and git-repo.mjs agree. import { gitInit } from "./skill-script-helpers.mjs"; import { joinedCss } from "./css-helpers.mjs"; import { ROOT, HANDOFFS_DIR, HOME, ENV, MODELS_DIR, cookieFor, cli, payload, BASE, backdate, cliIn, sessionUrl, readState, sleep, until, } from "./web-console-test-helpers.mjs"; // Every page load used to fetch /state, then /looks, then open the stream, // before drawing anything real. The first state now rides in the page. test("the page carries its first state, title and badge, so the first paint needs no fetch", async () => { const hostile = "Lunch $& $' app"; const res = cli(["open", "--workflow", "implement", "--title", hostile, "--no-open"]); const m = res.json.url.match(/^(http:\/\/127\.0\.0\.1:\d+)\/s\/([^/]+)\//); const html = await (await fetch(m[1] + "/", { headers: { cookie: cookieFor(m[1], m[2]) } })).text(); const block = html.match(/ is the block's own. assert.equal(block[1].includes("<"), false); assert.equal((html.match(/Lunch </script><script>alert(1)</script> $& $' app`)); assert.ok(html.includes('Building')); assert.ok(html.includes("Starting Implement"), "the static starting screen names the skill"); assert.ok(html.includes('rel="modulepreload" href="/app.js"')); cli(["stop", "--session", res.json.sid, "--force"]); }); test("open without --title names the session after the project folder", () => { const res = cli(["open", "--workflow", "pathfinder", "--no-open"]); const state = JSON.parse(fs.readFileSync(path.join(res.json.session, "state.json"), "utf8")); assert.equal(state.title, path.basename(ROOT)); cli(["stop", "--session", res.json.sid, "--force"]); }); // A saved dark theme and accent used to flash the default light accent for as // long as it took the script to fetch /looks. The server paints them now. test("saved looks are painted by the server before any script runs", async () => { const looksFile = path.join(HOME, "looks.json"); const before = fs.existsSync(looksFile) ? fs.readFileSync(looksFile) : null; fs.writeFileSync( looksFile, JSON.stringify({ looks: { theme: "dark", accent: "violet", sound: true, width: "wide" } }) ); try { const res = cli(["open", "--workflow", "plan", "--no-open"]); const m = res.json.url.match(/^(http:\/\/127\.0\.0\.1:\d+)\/s\/([^/]+)\//); const cookie = cookieFor(m[1], m[2]); const html = await (await fetch(m[1] + "/", { headers: { cookie } })).text(); assert.match(html, //); const css = await (await fetch(m[1] + "/app.css", { headers: { cookie } })).text(); assert.ok(css.includes(`:root[data-looks-accent="violet"][data-theme="dark"]{--accent:${ACCENTS.violet.dark[0]}`)); assert.ok(!css.includes(`data-looks-accent="${DEFAULT_ACCENT}"`), "the default needs no rule"); const boot = JSON.parse(html.match(/id="boot">([\s\S]*?)<\/script>/)[1]); assert.equal(boot.looks.accent, "violet"); cli(["stop", "--session", res.json.sid, "--force"]); } finally { if (before) fs.writeFileSync(looksFile, before); else fs.rmSync(looksFile, { force: true }); } }); test("static assets revalidate with an ETag instead of downloading again", async () => { const res = cli(["open", "--workflow", "review", "--no-open"]); const m = res.json.url.match(/^(http:\/\/127\.0\.0\.1:\d+)\/s\/([^/]+)\//); const cookie = cookieFor(m[1], m[2]); const first = await fetch(m[1] + "/app.js", { headers: { cookie } }); assert.equal(first.status, 200); assert.equal(first.headers.get("cache-control"), "no-cache"); const etag = first.headers.get("etag"); assert.ok(etag); await first.arrayBuffer(); const again = await fetch(m[1] + "/app.js", { headers: { cookie, "if-none-match": etag } }); assert.equal(again.status, 304); cli(["stop", "--session", res.json.sid, "--force"]); }); // The page drew from the inline state; the stream's opening frame would only // make it draw the same screen again. It is skipped when the page's `have` // still matches, and sent whenever anything differs. test("the stream skips its opening frame only when the page already has that exact state", async () => { const res = cli(["open", "--file", payload("have.json", BASE), "--no-open"]); const m = res.json.url.match(/^(http:\/\/127\.0\.0\.1:(\d+))\/s\/([^/]+)\//); const cookie = cookieFor(m[1], m[3]); await (await fetch(m[1] + "/state", { headers: { cookie } })).json(); const firstChunk = (have) => new Promise((resolve, reject) => { const req = http.request( { host: "127.0.0.1", port: Number(m[2]), path: "/events" + (have ? "?have=" + encodeURIComponent(have) : ""), headers: { cookie }, }, (r) => { let buf = ""; r.setEncoding("utf8"); r.on("data", (c) => (buf += c)); setTimeout(() => { req.destroy(); resolve(buf); }, 300); } ); req.on("error", reject); req.end(); }); assert.match(await firstChunk(null), /event: state/, "no key: the frame goes"); assert.match(await firstChunk("0.0.00"), /event: state/, "a stale key: the frame goes"); // The ledger poll's first tick pushes a frame to every connected client // whatever the key (the newLaunch check in checkLedger), and it lands inside // the 300 ms read above when the connection is mid-window. Wait that tick // out and re-read the key, or its broadcast reads as the skipped frame. await sleep(1200); const still = await (await fetch(m[1] + "/state", { headers: { cookie } })).json(); assert.doesNotMatch(await firstChunk(still.have), /event: state/, "the page's own key: skipped"); cli(["stop", "--session", res.json.sid, "--force"]); }); // `open` binds the port and sends the browser before the server has booted. // Whatever connects in that gap must be served, not refused: queued requests // wait in the socket, and one `open` already accepted is passed across. test("a request that arrives before the server takes the socket is still answered", async () => { const dir = fs.mkdtempSync(path.join(HOME, "handoff-")); fs.writeFileSync(path.join(dir, "state.json"), JSON.stringify({ sid: path.basename(dir), phase: "collecting" })); const pre = await bindLoopback(); const port = pre.address().port; // In flight before the server process even exists. const early = fetch(`http://127.0.0.1:${port}/health`, { signal: AbortSignal.timeout(10000) }).then((r) => r.json()); await new Promise((r) => setTimeout(r, 50)); const child = spawn( process.execPath, [path.join(ROOT, "src", "web-console", "server.mjs"), "--session", dir, "--token", "t", "--project", dir, "--handoff"], { env: ENV, stdio: ["ignore", "ignore", "ignore", "ipc"], windowsHide: true } ); try { await handOff(child, pre); assert.equal((await early).sid, path.basename(dir)); const late = await (await fetch(`http://127.0.0.1:${port}/health`)).json(); assert.equal(late.sid, path.basename(dir), "the server kept the port after the handover"); } finally { child.kill(); } }); // Each skill's Interface step has to put `open` before any reading: a skill // that says "read console.md" first costs the person a whole model turn of // staring at a terminal before the page appears. test("every skill opens the console before it reads anything", () => { const skills = fs.readdirSync(path.join(ROOT, "src")).filter((f) => /^plan2code(-.*)?\.md$/.test(f)); assert.ok(skills.length >= 13); for (const f of skills) { const text = fs.readFileSync(path.join(ROOT, "src", f), "utf8"); const open = text.search(/console\.mjs" open(?! --resume)/); assert.ok(open > -1, `${f} names the open command`); const firstRead = text.search(/read (?:\/)?console\.md/i); if (firstRead > -1) assert.ok(open < firstRead, `${f} opens before it reads console.md`); } }); /* ------------------------------------------- polish 2: plumbing (phase 1) */ test("the card-width presets validate a saved width and fall back to comfortable", () => { for (const key of Object.keys(CARD_WIDTHS)) assert.equal(cardWidth(key), key); for (const junk of [undefined, "huge", "__proto__", 42]) assert.equal(cardWidth(junk), "comfortable"); assert.equal(DEFAULT_CARD_WIDTH, "comfortable"); assert.deepEqual( Object.values(CARD_WIDTHS).map((w) => w.px), [720, 880, 1080, 1440] ); }); test("a build's phase-numbered task label is rewritten to count within the phase", () => { assert.equal(taskLabel("Task 4.2 of 6: x"), "Task 2 of 6: x"); assert.equal(taskLabel("Task 12.10 of 14"), "Task 10 of 14"); for (const same of ["Task 2 of 6: x", "Reading files", "", null]) assert.equal(taskLabel(same), same); assert.deepEqual([...BUILD_WORKFLOWS].sort(), ["implement", "implement-review"]); }); test("only a build's activity line is rewritten", () => { assert.equal(activityLabel("Task 4.2 of 6: x", "implement"), "Task 2 of 6: x"); assert.equal(activityLabel("Task 4.2 of 6: x", "implement-review"), "Task 2 of 6: x"); assert.equal(activityLabel("Task 4.2 of 6: x", "plan"), "Task 4.2 of 6: x"); assert.equal(activityLabel("Task 4.2 of 6: x", "quick-task"), "Task 4.2 of 6: x"); assert.equal(activityLabel("Task 4.2 of 6: x", "dashboard"), "Task 4.2 of 6: x"); }); test("a working agent's line falls back to its headline note", () => { const working = { status: "working" }; assert.equal(workingLine({ ...working, activity: " Task 4.2 of 6: x " }, { note: "n" }, "implement"), "Task 2 of 6: x"); assert.equal(workingLine(working, { stage: "Writing the spec", note: " Turning the plan into files. " }, "document"), "Turning the plan into files."); assert.equal(workingLine(working, { stage: "Writing the spec" }, "document"), ""); assert.equal(workingLine({ status: "waiting", activity: "x" }, { note: "n" }, "document"), ""); assert.equal(workingLine(undefined, undefined, "document"), ""); }); test("the terminal line is the exact text every command hands back", () => { assert.equal(terminalLine("http://127.0.0.1:1/s/abc/"), "→ Look at the web console: http://127.0.0.1:1/s/abc/"); // Under the desktop app the page is beside the terminal: no address to print. const inApp = terminalLine("http://127.0.0.1:1/s/abc/", { PLAN2CODE_IN_APP: "1" }); assert.equal(inApp.includes("127.0.0.1"), false, "no address under the app"); assert.equal(terminalLine("http://127.0.0.1:1/s/abc/", {}), "→ Look at the web console: http://127.0.0.1:1/s/abc/"); }); test("repoRoots reads the branch off disk: named, detached, a linked worktree's own, and none", () => { const base = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-branch-")); try { const named = path.join(base, "named"); fs.mkdirSync(path.join(named, ".git"), { recursive: true }); fs.writeFileSync(path.join(named, ".git", "HEAD"), "ref: refs/heads/feature/x\n"); assert.equal(repoRoots(named).branch, "feature/x"); const detached = path.join(base, "detached"); fs.mkdirSync(path.join(detached, ".git"), { recursive: true }); fs.writeFileSync(path.join(detached, ".git", "HEAD"), "a".repeat(40) + "\n"); assert.equal(repoRoots(detached).branch, ""); // A linked worktree: `.git` is a file naming its own git dir, whose HEAD // is on a different branch from the main checkout's. const wtGit = path.join(named, ".git", "worktrees", "wt"); fs.mkdirSync(wtGit, { recursive: true }); fs.writeFileSync(path.join(wtGit, "HEAD"), "ref: refs/heads/other\n"); fs.writeFileSync(path.join(wtGit, "commondir"), "../..\n"); const wt = path.join(base, "wt"); fs.mkdirSync(wt); fs.writeFileSync(path.join(wt, ".git"), `gitdir: ${wtGit}\n`); assert.equal(repoRoots(wt).branch, "other"); const plain = path.join(base, "plain"); fs.mkdirSync(plain); assert.equal(repoRoots(plain).branch, ""); } finally { fs.rmSync(base, { recursive: true, force: true }); } }); // With git's relocation variables set, repoRoots asks git. A repository with // no commits yet must still key on the right project and name its branch. test("repoRoots asks git when GIT_DIR is set, even before the first commit", () => { const base = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-gitdir-")); const repo = path.join(base, "repo"); fs.mkdirSync(repo); execFileSync("git", ["init", "-q", "-b", "fresh-start"], { cwd: repo, stdio: "ignore" }); const before = process.env.GIT_DIR; process.env.GIT_DIR = path.join(repo, ".git"); try { const roots = repoRoots(repo); const full = fs.realpathSync.native(repo); assert.deepEqual(roots, { project: full, worktree: full, branch: "fresh-start" }); } finally { if (before === undefined) delete process.env.GIT_DIR; else process.env.GIT_DIR = before; fs.rmSync(base, { recursive: true, force: true }); } }); test("the session sweep removes only month-old session dirs, never the one being opened", async () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-sessions-")); try { const make = (name, { stale = true, state = true } = {}) => { const d = path.join(dir, name); fs.mkdirSync(d, { recursive: true }); if (state) { fs.writeFileSync(path.join(d, "state.json"), "{}"); if (stale) backdate(path.join(d, "state.json")); } return d; }; const old = make("20250801-101010-aaaaaa"); const fresh = make("20260920-101010-bbbbbb", { stale: false }); const skip = make("20250801-101010-cccccc"); const notes = make("notes"); const noState = make("20250801-101010-dddddd", { state: false }); const plainFile = path.join(dir, "20250801-101010-eeeeee"); fs.writeFileSync(plainFile, "x"); backdate(plainFile); const stale = staleSessions(dir, Date.now(), SESSION_MAX_AGE_MS, "20250801-101010-cccccc"); assert.deepEqual(stale, ["20250801-101010-aaaaaa"]); assert.deepEqual(await removeSessions(dir, [...stale, "../escape", "notes"]), ["20250801-101010-aaaaaa"]); assert.equal(fs.existsSync(old), false); for (const p of [fresh, skip, notes, noState, plainFile]) assert.ok(fs.existsSync(p), p); assert.deepEqual(staleSessions(path.join(dir, "missing"), Date.now(), SESSION_MAX_AGE_MS, ""), []); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("the scratch sweep removes old patches and helpers, never looks, the pointer, the update cache or a directory", async () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-scratch-")); try { const file = (name, stale = true) => { const p = path.join(dir, name); fs.writeFileSync(p, "{}"); if (stale) backdate(p); return p; }; const removable = [file("p2.json"), file("helper.mjs")]; const kept = [ file("looks.json"), file("workspaces.json"), file("loop-setup.json"), file("spec-carry.json"), file("loop-reports.json"), file("subagents.json"), file("pr-hosts.json"), file("console-dir"), file("update-check.json"), file("notes.txt"), file("p3.json", false), ]; const subdir = path.join(dir, "x.json"); fs.mkdirSync(subdir); backdate(subdir); kept.push(subdir); const stale = staleScratch(dir, Date.now(), SESSION_MAX_AGE_MS).sort(); assert.deepEqual(stale, ["helper.mjs", "p2.json"]); assert.deepEqual( (await removeScratch(dir, [...stale, "looks.json", "workspaces.json", "loop-setup.json", "loop-reports.json", "subagents.json", "spec-carry.json", "pr-hosts.json", "../p.json", "console-dir", "update-check.json"])).sort(), ["helper.mjs", "p2.json"] ); for (const p of removable) assert.equal(fs.existsSync(p), false, p); for (const p of kept) assert.ok(fs.existsSync(p), p); assert.deepEqual([...PROTECTED_CONSOLE_FILES].sort(), [ "console-dir", "looks.json", "loop-reports.json", "loop-setup.json", "pr-hosts.json", "spec-carry.json", "subagents.json", "update-check.json", "workspaces.json", ]); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("cleanup finds old sessions and strays in both folders, and keeps every protected name and this session", async () => { const plan2code = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-cleanup-")); const consoleDir = path.join(plan2code, "console"); try { // Strays count only once they have sat for the grace period, so every one // this test expects to be found is backdated. const put = (p, body = "{}") => { fs.mkdirSync(path.dirname(p), { recursive: true }); fs.writeFileSync(p, body); return p; }; const stray = (p, body) => { put(p, body); backdate(p); return p; }; const session = (sid, stale) => { const state = put(path.join(consoleDir, "sessions", sid, "state.json")); if (stale) backdate(state); return path.dirname(state); }; const old = session("20250801-101010-aaaaaa", true); const current = session("20250801-101010-bbbbbb", true); const fresh = session("20260920-101010-cccccc", false); // A month-old state.json, but a draft saved today: still in use. const drafted = session("20250801-101010-dddddd", true); put(path.join(drafted, "draft.json")); const kept = [ ...["looks.json", "workspaces.json", "subagents.json", "console-dir", "update-check.json"].map((n) => put(path.join(consoleDir, n)) ), put(path.join(plan2code, "launcher.json")), put(path.join(plan2code, "models.json")), put(path.join(plan2code, "bin", "plan2code.js"), "x"), current, fresh, drafted, ]; stray(path.join(consoleDir, "p1.json"), "12345"); put(path.join(consoleDir, "runtime", "x.json")); // The shared console install, one folder per version, however old: never a stray. const installed = stray(path.join(consoleDir, "3.0.4", "console.mjs"), "x"); backdate(path.dirname(installed)); kept.push(installed); // A folder that is not a version stays a stray. backdate(put(path.join(consoleDir, "3.0", "x.txt"))); backdate(path.join(consoleDir, "3.0")); backdate(put(path.join(plan2code, "console-dev", "sessions", "x.txt"), "abc")); backdate(path.join(plan2code, "console-dev")); // An old folder with a file rewritten just now: the folder's own mtime // never moves for that, so only its contents show it is in use. const busy = put(path.join(plan2code, "busy", "log.txt")); backdate(path.join(plan2code, "busy")); kept.push(busy); stray(path.join(plan2code, "notes.txt")); // Handoffs are Plan2Code's own, however old: swept by age on open, never offered here. backdate(put(path.join(plan2code, "handoffs", "2025-01-01-0900-handoff.md"))); backdate(path.join(plan2code, "handoffs")); // The desktop app and its settings are Plan2Code's own too, however old. backdate(put(path.join(plan2code, "app", "plan2code-app"), "x")); backdate(path.join(plan2code, "app")); backdate(put(path.join(plan2code, "app.json"))); backdate(put(path.join(plan2code, "agents.json"))); // UI Prototype drafts are swept by age by the skill's own script, never offered here. backdate(put(path.join(plan2code, "prototypes", "my-app-0123456789ab", "invoices", "invoices-round-1.html"), "x")); backdate(path.join(plan2code, "prototypes")); // Learning's waiting items and pause are swept by the core's own 30-day rule, never offered here. backdate(put(path.join(plan2code, "learning", "my-app-0123456789ab", "pause.json"), "{}")); backdate(path.join(plan2code, "learning", "my-app-0123456789ab")); backdate(path.join(plan2code, "learning")); // In use right now: a held lock and a temp between its write and rename. const live = [put(path.join(consoleDir, "workspaces.json.lock"), ""), put(path.join(plan2code, "models.json.123.tmp"))]; kept.push(...live); stray(path.join(consoleDir, "looks.json.456.tmp")); const opts = { consoleDir, plan2codeDir: plan2code, skipSid: "20250801-101010-bbbbbb" }; const { items, bytes } = await cleanupFindings(opts); assert.deepEqual(items.map((i) => i.id).sort(), [ "console:3.0", "console:looks.json.456.tmp", "console:p1.json", "root:console-dev", "root:notes.txt", "session:20250801-101010-aaaaaa", ]); assert.equal(items.some((i) => i.id === "root:handoffs"), false, "the handoffs folder is never a stray"); for (const id of ["root:app", "root:app.json", "root:agents.json", "root:prototypes", "root:learning"]) assert.equal(items.some((i) => i.id === id), false, `${id} is never a stray`); assert.equal(STRAY_GRACE_MS, 60 * 60 * 1000); assert.equal(items.find((i) => i.id === "console:p1.json").bytes, 5); assert.equal(items.find((i) => i.id === "root:console-dev").kind, "folder"); assert.equal(bytes, items.reduce((n, i) => n + i.bytes, 0)); // A console running from another home never reaches the folder above it. const elsewhere = await cleanupFindings({ ...opts, plan2codeDir: path.join(plan2code, "other") }); assert.deepEqual(elsewhere.items.map((i) => i.where).sort(), ["console", "console", "console", "session"]); // Only ids a fresh scan still finds are removed; anything else is ignored. const done = await removeCleanup( ["console:p1.json", "session:20250801-101010-aaaaaa", "session:20250801-101010-dddddd", "root:busy", "root:console-dev", "console:looks.json", "root:bin", "session:20250801-101010-bbbbbb", "console:workspaces.json.lock", "root:models.json.123.tmp", "console:../escape", 7], opts ); assert.deepEqual(done.removed.sort(), ["console:p1.json", "root:console-dev", "session:20250801-101010-aaaaaa"]); assert.deepEqual(done.failed, []); assert.equal(done.bytes, 5 + 3 + 2); assert.equal(fs.existsSync(old), false); assert.equal(fs.existsSync(path.join(plan2code, "console-dev")), false); assert.ok(fs.existsSync(path.join(plan2code, "notes.txt")), "not asked for, so not removed"); for (const p of kept) assert.ok(fs.existsSync(p), p); assert.ok(fs.existsSync(path.join(consoleDir, "runtime", "x.json"))); } finally { fs.rmSync(plan2code, { recursive: true, force: true }); } }); test("cleanup lists the project's completed specs untouched for 30 days, and removes only those", async () => { const base = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-cleanup-completed-")); const consoleDir = path.join(base, "home", "console"); const project = path.join(base, "project"); const completed = path.join(project, "specs--completed"); try { const put = (p, body = "{}") => { fs.mkdirSync(path.dirname(p), { recursive: true }); fs.writeFileSync(p, body); return p; }; fs.mkdirSync(consoleDir, { recursive: true }); fs.mkdirSync(project, { recursive: true }); const g = gitInit(project); const opts = { consoleDir, plan2codeDir: path.join(base, "home"), skipSid: "x", project }; // No specs--completed/ at all is just nothing to list. assert.deepEqual((await cleanupFindings(opts)).items, []); backdate(put(path.join(completed, "old-spec", "overview.md"), "abc")); backdate(path.join(completed, "old-spec")); put(path.join(completed, "fresh-spec", "overview.md")); // An old folder with one file finalized today: still recent. backdate(put(path.join(completed, "touched-spec", "phase-1.md"))); put(path.join(completed, "touched-spec", "overview.md")); backdate(put(path.join(completed, "README.md"))); backdate(put(path.join(project, "specs", "live-spec", "overview.md"))); // Committed, so Cleanup may delete it (an untracked one is refused: see the next test). g("add", "specs--completed/old-spec"); g("commit", "-q", "-m", "archive old-spec"); const { items } = await cleanupFindings(opts); assert.deepEqual(items.map((i) => i.id), ["completed:old-spec"]); assert.equal(items[0].where, "completed"); assert.equal(items[0].kind, "folder"); assert.equal(items[0].bytes, 3); // Without a project, the archive is never looked at. const { project: _p, ...noProject } = opts; assert.deepEqual((await cleanupFindings(noProject)).items, []); const done = await removeCleanup(["completed:old-spec", "completed:fresh-spec", "completed:../specs", "completed:README.md"], opts); assert.deepEqual(done.removed, ["completed:old-spec"]); assert.equal(fs.existsSync(path.join(completed, "old-spec")), false); for (const p of ["fresh-spec", "touched-spec", "README.md"]) assert.ok(fs.existsSync(path.join(completed, p)), p); assert.ok(fs.existsSync(path.join(project, "specs", "live-spec"))); } finally { fs.rmSync(base, { recursive: true, force: true }); } }); test("cleanup refuses a completed spec git does not track, says why, and still deletes a tracked one and everything else", async () => { const base = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-cleanup-guard-")); const home = path.join(base, "home"); const consoleDir = path.join(home, "console"); const project = path.join(base, "project"); const completed = path.join(project, "specs--completed"); try { const put = (p, body = "{}") => { fs.mkdirSync(path.dirname(p), { recursive: true }); fs.writeFileSync(p, body); return p; }; const oldSpec = (name, file = "overview.md") => { backdate(put(path.join(completed, name, file), "abc")); backdate(path.join(completed, name)); }; fs.mkdirSync(consoleDir, { recursive: true }); fs.mkdirSync(project, { recursive: true }); const g = gitInit(project); // The default: Init gitignores the archive, so only a forced add tracks a spec. put(path.join(project, ".gitignore"), "specs--completed/\n"); oldSpec("tracked-spec"); oldSpec("untracked-spec"); oldSpec("partly-spec"); oldSpec("edited-spec"); g("add", ".gitignore"); g("add", "-f", "specs--completed/tracked-spec", "specs--completed/partly-spec", "specs--completed/edited-spec"); g("commit", "-q", "-m", "archive"); // A file added after the commit: git could not give it back. oldSpec("partly-spec", "notes.md"); // A tracked file edited after the commit: git could give back only the old text. backdate(put(path.join(completed, "edited-spec", "overview.md"), "edited")); backdate(path.join(completed, "edited-spec")); // Not a spec: removed as before, in the same call. backdate(put(path.join(consoleDir, "stray.json"))); const opts = { consoleDir, plan2codeDir: home, skipSid: "x", project }; const ids = ["completed:tracked-spec", "completed:untracked-spec", "completed:partly-spec", "completed:edited-spec", "console:stray.json"]; assert.deepEqual((await cleanupFindings(opts)).items.map((i) => i.id).sort(), [...ids].sort(), "the scan still lists all of them"); const done = await removeCleanup(ids, opts); assert.deepEqual(done.removed.sort(), ["completed:tracked-spec", "console:stray.json"]); assert.deepEqual(done.refused.sort(), ["completed:edited-spec", "completed:partly-spec", "completed:untracked-spec"]); assert.deepEqual(done.failed, []); assert.equal(fs.existsSync(path.join(completed, "tracked-spec")), false, "a tracked spec is deleted"); assert.equal(fs.existsSync(path.join(consoleDir, "stray.json")), false); for (const name of ["untracked-spec", "partly-spec", "edited-spec"]) assert.ok(fs.existsSync(path.join(completed, name, "overview.md")), name + " is kept"); assert.ok(fs.existsSync(path.join(completed, "partly-spec", "notes.md"))); assert.match(done.refusal, /^Kept 3 completed specs git does not track as they stand, so deleting them would lose them for good: /); assert.ok(done.refusal.includes("specs--completed/untracked-spec/"), done.refusal); assert.ok(done.refusal.includes("specs--completed/partly-spec/"), done.refusal); assert.ok(done.refusal.includes("specs--completed/edited-spec/"), done.refusal); assert.equal(fs.readFileSync(path.join(completed, "edited-spec", "overview.md"), "utf8"), "edited", "the uncommitted edit survives"); assert.equal(done.refusal.includes("specs--completed/tracked-spec/"), false, "the deleted spec is not named"); // A project that is not a repository at all: nothing there is tracked. const loose = path.join(base, "loose"); backdate(put(path.join(loose, "specs--completed", "only-spec", "overview.md"))); backdate(path.join(loose, "specs--completed", "only-spec")); const alone = await removeCleanup(["completed:only-spec"], { ...opts, project: loose }); assert.deepEqual(alone.removed, []); assert.deepEqual(alone.refused, ["completed:only-spec"]); assert.equal(alone.refusal, "Kept specs--completed/only-spec/: git does not track it as it stands, so deleting it would lose it for good. Commit it first, or delete it yourself once it is backed up."); assert.ok(fs.existsSync(path.join(loose, "specs--completed", "only-spec"))); // Nothing refused: no line. assert.equal((await removeCleanup([], opts)).refusal, ""); } finally { fs.rmSync(base, { recursive: true, force: true }); } }); test("User Preferences: wider, its body scrolls and the button bar stays put, without touching dialogs that borrow .looks", () => { const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8"); const css = joinedCss(); const dialog = html.match(/]*>([\s\S]*?)<\/dialog>/); assert.ok(dialog, "the Preferences dialog carries the prefs class"); const body = dialog[1].indexOf('
'); const actions = dialog[1].indexOf('