Files
plan2code/scripts/test-web-console-review-loop.mjs
T

199 lines
11 KiB
JavaScript
Raw Normal View History

// Web console tests: the Review Loop's setup store and its route. Run with:
// node --test scripts/test-web-console-review-loop.mjs
//
// The store (review-loop-setup.mjs) keeps one entry per project in
// review-loop-setup.json; GET and POST /review-loop-setup serve it. The
// store fixes its file at import time from PLAN2CODE_CONSOLE_HOME, so it runs
// in a child process here, as test-web-console-loop.mjs does for loop-setup.mjs.
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { pathToFileURL } from "node:url";
import { ROOT, ENV, HOME, cli, sessionUrl } from "./web-console-test-helpers.mjs";
const APP_VARS = ["PLAN2CODE_IN_APP", "PLAN2CODE_EMBED_ORIGIN", "PLAN2CODE_APP_ANNOUNCE", "PLAN2CODE_APP_TOKEN", "PLAN2CODE_CONSOLE_SID", "PLAN2CODE_LOOP_STRENGTH"];
const SETUP_PATH = path.join(HOME, "review-loop-setup.json");
const LOOP_SETUP_PATH = path.join(HOME, "loop-setup.json");
const STORE_URL = pathToFileURL(path.join(ROOT, "src", "web-console", "review-loop-setup.mjs")).href;
function cleanEnv() {
const env = { ...ENV };
for (const key of APP_VARS) delete env[key];
return env;
}
// Runs `fn(m, args)` in a child process where m is review-loop-setup.mjs. `fn`
// must be self-contained: it is sent as source text. Returns its JSON result.
function inStore(fn, args = {}) {
const code =
`const m = await import(${JSON.stringify(STORE_URL)});` +
`const out = await (${fn.toString()})(m, ${JSON.stringify(args)});` +
"console.log(JSON.stringify(out));";
const res = spawnSync(process.execPath, ["--input-type=module", "-e", code], { env: cleanEnv(), encoding: "utf8", cwd: ROOT });
assert.equal(res.status, 0, res.stderr);
return JSON.parse(String(res.stdout).trim().split("\n").pop());
}
const projectA = path.join(HOME, "review-store-a");
const projectB = path.join(HOME, "review-store-b");
test("review-loop-setup: a new project reads as the defaults with remembered false, and nothing is written", () => {
fs.rmSync(SETUP_PATH, { force: true });
const got = inStore((m, { project }) => ({ setup: m.readReviewLoopSetup(project), defaults: m.REVIEW_LOOP_DEFAULTS }), { project: projectA });
assert.deepEqual(got.setup, { ...got.defaults, remembered: false });
assert.deepEqual(got.defaults, { scope: "branch", spec: "", cap: 3, commit: true, suggestions: false, strength: "", silenceMinutes: 20, notifyRounds: false });
assert.equal(fs.existsSync(SETUP_PATH), false, "reading never creates the file");
});
test("review-loop-setup: a save reads back per project and keeps another project's entry", () => {
fs.rmSync(SETUP_PATH, { force: true });
inStore(
(m, { a, b }) => {
m.saveReviewLoopSetup(a, { ...m.REVIEW_LOOP_DEFAULTS, cap: 5, suggestions: true, scope: "spec", spec: "specs/demo", strength: "best" });
m.saveReviewLoopSetup(b, { ...m.REVIEW_LOOP_DEFAULTS, cap: 2, notifyRounds: true });
return null;
},
{ a: projectA, b: projectB }
);
const got = inStore((m, { a, b }) => ({ a: m.readReviewLoopSetup(a), b: m.readReviewLoopSetup(b) }), { a: projectA, b: projectB });
assert.equal(got.a.cap, 5);
assert.equal(got.a.suggestions, true);
assert.equal(got.a.scope, "spec");
assert.equal(got.a.spec, "specs/demo");
assert.equal(got.a.strength, "best");
assert.equal(got.a.remembered, true);
assert.equal(got.b.cap, 2);
assert.equal(got.b.notifyRounds, true);
const file = JSON.parse(fs.readFileSync(SETUP_PATH, "utf8"));
assert.equal(file.schema, 1);
assert.equal(Object.keys(file.projects).length, 2);
for (const entry of Object.values(file.projects)) assert.match(entry.saved, /^\d{4}-\d\d-\d\dT/);
});
test("review-loop-setup: unknown keys and out-of-range values are refused with the problem named", () => {
fs.rmSync(SETUP_PATH, { force: true });
const problems = (patch) => inStore((m, { patch }) => m.reviewLoopSetupProblems({ ...m.REVIEW_LOOP_DEFAULTS, ...patch }), { patch });
assert.deepEqual(problems({}), []);
assert.match(problems({ notifyUrl: "https://x.example/" }).join(), /"notifyUrl" is not a setup field/, "the notify address is the loop setup's, never kept here");
assert.match(problems({ cap: 0 }).join(), /"cap" must be a whole number from 1 to 6/);
assert.match(problems({ cap: 7 }).join(), /"cap"/);
assert.match(problems({ cap: 2.5 }).join(), /"cap"/);
assert.deepEqual(problems({ cap: 1 }), []);
assert.deepEqual(problems({ cap: 6 }), []);
assert.match(problems({ silenceMinutes: 0 }).join(), /"silenceMinutes" must be a whole number from 1 to 60/);
assert.match(problems({ silenceMinutes: 61 }).join(), /"silenceMinutes"/);
assert.match(problems({ scope: "everything" }).join(), /"scope" must be one of branch, uncommitted, spec/);
for (const spec of ["demo", "specs/", "specs/a/b", "specs/.hidden", "../x", 3]) {
assert.match(problems({ spec }).join(), /"spec" must be empty or a folder directly under specs\//, `spec ${spec}`);
}
assert.deepEqual(problems({ spec: "specs/demo" }), []);
assert.match(problems({ commit: "yes" }).join(), /"commit" must be true or false/);
assert.match(problems({ strength: "mighty" }).join(), /"strength"/);
assert.match(inStore((m) => m.reviewLoopSetupProblems(null), {}).join(), /must be an object/);
const before = inStore((m, { a }) => (m.saveReviewLoopSetup(a, { ...m.REVIEW_LOOP_DEFAULTS }), null), { a: projectA });
assert.equal(before, null);
const text = fs.readFileSync(SETUP_PATH, "utf8");
const threw = inStore(
(m, { a }) => {
try {
m.saveReviewLoopSetup(a, { ...m.REVIEW_LOOP_DEFAULTS, cap: 99 });
return "saved";
} catch (e) {
return { message: e.message, problems: e.problems };
}
},
{ a: projectA }
);
assert.match(threw.message, /the review loop setup is not valid/);
assert.equal(threw.problems.length, 1);
assert.equal(fs.readFileSync(SETUP_PATH, "utf8"), text, "a refused save leaves the file as it was");
});
test("review-loop-setup: the picks live only in review-loop-setup.json, never in the project or the loop's setup", () => {
fs.rmSync(SETUP_PATH, { force: true });
fs.rmSync(LOOP_SETUP_PATH, { force: true });
const project = fs.mkdtempSync(path.join(HOME, "review-nowrite-"));
inStore((m, { project }) => (m.saveReviewLoopSetup(project, { ...m.REVIEW_LOOP_DEFAULTS, cap: 4 }), null), { project });
assert.ok(fs.existsSync(SETUP_PATH));
assert.equal(fs.existsSync(LOOP_SETUP_PATH), false, "the Implementation Loop's file is untouched");
assert.deepEqual(fs.readdirSync(project), [], "nothing appears in the project");
});
test("review-loop-setup: Cleanup never offers the file", () => {
const code = `const m = await import(${JSON.stringify(pathToFileURL(path.join(ROOT, "src", "web-console", "sessions.mjs")).href)}); console.log(JSON.stringify([...m.PROTECTED_CONSOLE_FILES]));`;
const res = spawnSync(process.execPath, ["--input-type=module", "-e", code], { env: cleanEnv(), encoding: "utf8", cwd: ROOT });
assert.equal(res.status, 0, res.stderr);
assert.ok(JSON.parse(String(res.stdout).trim().split("\n").pop()).includes("review-loop-setup.json"));
});
test("review-loop-setup: GET and POST /review-loop-setup, with ?spec= filling the answer without saving", async () => {
fs.rmSync(SETUP_PATH, { force: true });
const cwd = fs.mkdtempSync(path.join(HOME, "review-route-"));
const opened = cli(["open", "--workflow", "review", "--no-open"], { cwd });
const parsed = JSON.parse(String(opened.stdout).trim().split("\n").filter((l) => l.startsWith("{")).pop());
const { base, cookie } = sessionUrl(parsed.url);
const get = async (query = "") => {
const res = await fetch(`${base}/review-loop-setup${query}`, { headers: { cookie, connection: "close" } });
return { status: res.status, body: await res.json() };
};
const send = (body, { origin = base } = {}) =>
fetch(`${base}/review-loop-setup`, {
method: "POST",
headers: { "content-type": "application/json", cookie, ...(origin ? { origin } : {}), connection: "close" },
body: typeof body === "string" ? body : JSON.stringify(body),
});
try {
const bare = await get();
assert.equal(bare.status, 200);
assert.equal(bare.body.remembered, false);
assert.equal(bare.body.scope, "branch");
assert.equal(bare.body.cap, 3);
const filled = await get("?spec=specs/demo");
assert.equal(filled.body.spec, "specs/demo");
assert.equal(filled.body.scope, "spec");
assert.equal(filled.body.remembered, false);
assert.equal(fs.existsSync(SETUP_PATH), false, "a pre-fill is never saved");
assert.equal((await get()).body.scope, "branch", "and the next plain read is the defaults again");
for (const spec of ["../x", "specs/../x", "specs/a/b", "specs/.hidden", "specs", "specs/"]) {
const refused = await get(`?spec=${spec}`);
assert.equal(refused.status, 400, `spec=${spec} is refused`);
assert.match(refused.body.error, /spec must be a folder directly under specs\//);
}
const facts = await get("?facts=1");
assert.equal(typeof facts.body.branch, "string");
assert.ok("pending" in facts.body);
const good = { scope: "uncommitted", spec: "", cap: 4, commit: false, suggestions: true, strength: "balanced", silenceMinutes: 15, notifyRounds: true };
const saved = await send(good);
assert.equal(saved.status, 200, await saved.clone().text());
const back = await get();
assert.equal(back.body.remembered, true);
for (const [key, value] of Object.entries(good)) assert.equal(back.body[key], value, key);
const bad = await send({ ...good, cap: 9, extra: 1 });
assert.equal(bad.status, 400);
const badBody = await bad.json();
assert.equal(badBody.ok, false);
assert.ok(badBody.problems.some((p) => /"cap"/.test(p)));
assert.ok(badBody.problems.some((p) => /"extra" is not a setup field/.test(p)));
assert.equal((await get()).body.cap, 4, "a refused save changes nothing");
assert.equal((await send("[1]")).status, 400);
// The POST is origin-checked: another page's origin is refused, and nothing is saved by it.
const before = JSON.stringify((await get()).body);
const foreign = await send({ ...good, cap: 2 }, { origin: "http://evil.example" });
assert.equal(foreign.status, 403, "a foreign origin is refused");
assert.equal(JSON.stringify((await get()).body), before);
} finally {
cli(["stop", "--session", parsed.sid, "--force"], { cwd, expectFail: true });
}
assert.deepEqual(fs.readdirSync(cwd), [], "the route never wrote into the project");
assert.equal(fs.existsSync(LOOP_SETUP_PATH), false, "and never touched the Implementation Loop's file");
});