Add Learning, move tool folders under .plan2code, and the Loop, Snake and console changes

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-13 23:29:12 -08:00
1 parent de8a05b958
commit bb5bd5986d
87 files changed
+9163 -256

No files matched your search

+11 -2
View File
@@ -6,7 +6,8 @@
// [--out <dir>] [--compare]
//
// Every shot is staged with no agent: a throwaway sample project called
// `task-api`, a throwaway console home (PLAN2CODE_CONSOLE_HOME), then
// `task-api`, a throwaway console home (PLAN2CODE_CONSOLE_HOME) and Learning
// store (PLAN2CODE_LEARNING_DIR), then
// `console.mjs open` and `post` with the payloads in scripts/screenshots/.
// Each screen is saved light and dark, at 1280x800 and twice the pixel
// density, as `<out>/<shot>-light.webp` and `<out>/<shot>-dark.webp`.
@@ -589,7 +590,15 @@ async function main() {
SCRATCH = fs.mkdtempSync(path.join(SCRATCH_ROOT, "p2c-shots-"));
HOME = path.join(SCRATCH, "console-home");
ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_NOTEPADS_DIR: path.join(SCRATCH, "notepads"), PLAN2CODE_NO_BROWSER: "1" };
// A throwaway Learning store too, and no sample project has a .plan2code/settings.json,
// so the dashboard's Learning row reads Not set up with nothing waiting in every shot.
ENV = {
...process.env,
PLAN2CODE_CONSOLE_HOME: HOME,
PLAN2CODE_NOTEPADS_DIR: path.join(SCRATCH, "notepads"),
PLAN2CODE_LEARNING_DIR: path.join(SCRATCH, "learning"),
PLAN2CODE_NO_BROWSER: "1",
};
fs.mkdirSync(HOME, { recursive: true });
fs.mkdirSync(OUT, { recursive: true });
let browser = null;
+11 -1
View File
@@ -64,12 +64,22 @@ export function scrubbedEnv(extra = {}) {
for (const k of AMBIENT_GIT_ENV) delete process.env[k];
Object.assign(process.env, { GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: EMPTY_GITCONFIG });
// Learning's store on this machine (~/.plan2code/learning): a script run from a
// test never reaches the real one. A test that checks the store passes its own
// PLAN2CODE_LEARNING_DIR in `env`; every other run shares this throwaway one.
let sandboxLearningDir;
const learningDirFor = (env) => {
if (env && env.PLAN2CODE_LEARNING_DIR) return env.PLAN2CODE_LEARNING_DIR;
sandboxLearningDir ||= fs.mkdtempSync(path.join(fs.realpathSync.native(os.tmpdir()), "p2c-learning-"));
return sandboxLearningDir;
};
export function runScript(skill, script, args, { cwd, env, input } = {}) {
const r = spawnSync(process.execPath, [path.join(SKILLS, skill, "scripts", script), ...args], {
cwd: cwd || ROOT,
encoding: "utf8",
input,
env: scrubbedEnv({ PLAN2CODE_NOW: NOW, ...env }),
env: scrubbedEnv({ PLAN2CODE_NOW: NOW, ...env, PLAN2CODE_LEARNING_DIR: learningDirFor(env) }),
});
let json = null;
try {
+6 -5
View File
@@ -30,21 +30,22 @@ export const BUDGETS = {
notes: {
"changelog.md": 1400,
"dead-code.md": 4900,
"diagnose.md": 2700,
"deps.md": 5700,
"diagnose.md": 2840, // raised by the lessons card line's bytes only
"document.md": 400,
"finalize.md": 2000,
"git.md": 6500,
"handoff.md": 300,
"implement.md": 5700,
"init.md": 300,
"loop.md": 11600,
"loop.md": 11712, // raised by the failed report's nextStep line's bytes only
"pathfinder.md": 2622, // raised by the UI prototype line's bytes only
"plan.md": 1023, // raised by the UI prototype line's bytes only
"pr-prep.md": 4500,
"quick-task.md": 4729, // raised by the UI prototype line's, the prototype recap line's and the prototype archive wording's bytes only
"review.md": 1000,
"quick-task.md": 4869, // raised by the UI prototype line's, the prototype recap line's, the prototype archive wording's and the lessons card line's bytes only
"review.md": 1140, // raised by the lessons card line's bytes only
"revise-plan.md": 1422, // raised by the UI prototype line's bytes only
"test.md": 5400,
"test.md": 5540, // raised by the lessons card line's bytes only
"ui-prototype.md": 4000,
"xray.md": 2500,
},
+5
View File
@@ -16,8 +16,10 @@
"test-script-changelog.mjs",
"test-script-coverage.mjs",
"test-script-dead-code.mjs",
"test-script-deps.mjs",
"test-script-finalize.mjs",
"test-script-git.mjs",
"test-script-lessons.mjs",
"test-script-pathfinder.mjs",
"test-script-pr-prep.mjs",
"test-script-run-check.mjs",
@@ -51,6 +53,7 @@
"test-launcher.mjs",
"test-standalone-check.mjs",
"test-ui-prototype-page.mjs",
"test-web-console-activities-bounce-arcade.mjs",
"test-web-console-activities-bounce-cars.mjs",
"test-web-console-activities-bounce-game.mjs",
"test-web-console-activities-bounce.mjs",
@@ -100,6 +103,7 @@
"test-web-console-handoffs.mjs",
"test-web-console-hardening.mjs",
"test-web-console-in-app.mjs",
"test-web-console-learning.mjs",
"test-web-console-lifecycle.mjs",
"test-web-console-logic.mjs",
"test-web-console-loop.mjs",
@@ -110,6 +114,7 @@
"test-web-console-page-dashboard.mjs",
"test-web-console-page-git.mjs",
"test-web-console-page-help.mjs",
"test-web-console-page-learning.mjs",
"test-web-console-page-loop.mjs",
"test-web-console-page-notepad.mjs",
"test-web-console-page-prefs.mjs",
+34 -12
View File
@@ -491,7 +491,7 @@ test("narrow: a missing file exits 3, invalid JSON or no candidates array exits
/* ------------------------------------------------------------- keep list */
const KEEP = ".plan2code-dead-code/keep.md";
const KEEP = ".plan2code/dead-code/keep.md";
/** A small project: two source files with declarations to keep. */
function keepProject(name) {
@@ -556,6 +556,20 @@ test("keep add: an empty reason exits 2, a missing line exits 3, and keep list w
assert.equal(runDeadCode(["keep", "sweep"], { cwd: dir }).code, 2);
});
test("keep: an old .plan2code-dead-code/keep.md is neither read nor changed", () => {
const dir = keepProject("dc-keep-old-folder");
const old = "# Dead Code keep list\n\n| File | Name | Hash | Reason | Date |\n| --- | --- | --- | --- | --- |\n| src/a.js | foo | 0123456789ab | Old reason | 2026-01-01 |\n";
write(dir, ".plan2code-dead-code/keep.md", old);
const list = runDeadCode(["keep", "list"], { cwd: dir });
assert.equal(list.code, 0, list.stderr);
assert.deepEqual([list.json.exists, list.json.entries, list.json.path], [false, [], KEEP]);
const add = runDeadCode(["keep", "add", "--file", "src/a.js", "--name", "bar", "--line", "5", "--reason", "Kept"], { cwd: dir });
assert.equal(add.code, 0, add.stderr);
assert.equal(add.json.path, KEEP);
assert.match(read(dir, KEEP), /\| src\/a\.js \| bar \|/);
assert.equal(read(dir, ".plan2code-dead-code/keep.md"), old);
});
test("keep filter: hides a current entry, shows an edited one as wasKept, lists a deleted file as gone; --fresh shows all", () => {
const dir = keepProject("dc-keep-filter");
const add = (file, name, line, reason) => assert.equal(runDeadCode(["keep", "add", "--file", file, "--name", name, "--line", String(line), "--reason", reason], { cwd: dir }).code, 0);
@@ -1003,7 +1017,7 @@ test("report write: three sections in order with label, source, rule, reason and
const dir = tmp("dc-report");
const r = runDeadCode(["report", "write", "--findings", findingsFile(dir, FINDINGS)], { cwd: dir });
assert.equal(r.code, 0, r.stderr);
assert.equal(r.json.path, ".plan2code-dead-code/reports/DEAD-CODE-2026-08-03.md");
assert.equal(r.json.path, ".plan2code/dead-code/reports/DEAD-CODE-2026-08-03.md");
const text = read(dir, r.json.path);
assert.match(text, /^# Dead Code report/);
assert.match(text, /\*\*Date:\*\* 2026-08-03/);
@@ -1073,8 +1087,8 @@ test("report write: a list of two or more tools prints Tools, one prints Tool, n
assert.equal(r.code, 0, r.stderr);
assert.match(read(dir, r.json.path), line);
}
assert.match(read(dir, ".plan2code-dead-code/reports/DEAD-CODE-2026-08-10.md"), /\*\*Found by:\*\* the tools' lists, verified by a caller search/);
const one = read(dir, ".plan2code-dead-code/reports/DEAD-CODE-2026-08-11.md");
assert.match(read(dir, ".plan2code/dead-code/reports/DEAD-CODE-2026-08-10.md"), /\*\*Found by:\*\* the tools' lists, verified by a caller search/);
const one = read(dir, ".plan2code/dead-code/reports/DEAD-CODE-2026-08-11.md");
assert.doesNotMatch(one, /\*\*Tools:\*\*/);
assert.match(one, /\*\*Found by:\*\* the tool's list, verified by a caller search/);
});
@@ -1085,7 +1099,7 @@ test("report write: a tool that is not an id, a list of ids or null exits 4 and
assert.equal(r.code, 4);
assert.equal(r.json.error, "findings-invalid");
assert.match(r.json.message, /tool must be a tool id, a list of ids, or null/);
assert.equal(fs.existsSync(path.join(dir, ".plan2code-dead-code", "reports", "DEAD-CODE-2026-08-13.md")), false);
assert.equal(fs.existsSync(path.join(dir, ".plan2code", "dead-code", "reports", "DEAD-CODE-2026-08-13.md")), false);
});
/* ------------------------------------------------------------- gitignore */
@@ -1108,25 +1122,33 @@ test("gitignore-check and gitignore-add on a git project: appends one line, neve
const add = runDeadCode(["gitignore-add"], { cwd: dir });
assert.equal(add.code, 0, add.stderr);
assert.equal(add.json.added, true);
assert.equal(read(dir, ".gitignore"), "node_modules/\n.plan2code-dead-code/reports/\n");
assert.equal(read(dir, ".gitignore"), "node_modules/\n.plan2code/dead-code/reports/\n");
const after = runDeadCode(["gitignore-check"], { cwd: dir });
assert.deepEqual([after.json.ignored, after.json.line, after.json.file], [true, ".plan2code-dead-code/reports/", ".gitignore"]);
assert.deepEqual([after.json.ignored, after.json.line, after.json.file], [true, ".plan2code/dead-code/reports/", ".gitignore"]);
const again = runDeadCode(["gitignore-add"], { cwd: dir });
assert.deepEqual([again.json.added, again.json.already], [false, true]);
assert.equal(read(dir, ".gitignore"), "node_modules/\n.plan2code-dead-code/reports/\n");
assert.equal(read(dir, ".gitignore"), "node_modules/\n.plan2code/dead-code/reports/\n");
});
test("gitignore-check: reports/ in the state folder's .gitignore, or a wider rule git applies, counts as ignored", () => {
const own = gitProject("dc-gitignore-own");
write(own, ".plan2code-dead-code/.gitignore", "reports/\n");
write(own, ".plan2code/dead-code/.gitignore", "reports/\n");
const r = runDeadCode(["gitignore-check"], { cwd: own });
assert.deepEqual([r.json.ignored, r.json.line, r.json.file], [true, "reports/", ".plan2code-dead-code/.gitignore"]);
assert.deepEqual([r.json.ignored, r.json.line, r.json.file], [true, "reports/", ".plan2code/dead-code/.gitignore"]);
const wide = gitProject("dc-gitignore-wide");
write(wide, ".gitignore", ".plan2code-dead-code/\n");
write(wide, ".gitignore", ".plan2code/dead-code/\n");
const w = runDeadCode(["gitignore-check"], { cwd: wide });
assert.deepEqual([w.json.ignored, w.json.line], [true, null]);
});
test("gitignore-check: the old .plan2code-dead-code/reports/ line does not count", () => {
const dir = gitProject("dc-gitignore-old-line");
write(dir, ".gitignore", ".plan2code-dead-code/reports/\n");
const r = runDeadCode(["gitignore-check"], { cwd: dir });
assert.equal(r.code, 0, r.stderr);
assert.deepEqual([r.json.ignored, r.json.line, r.json.file], [false, null, null]);
});
test("gitignore-check and gitignore-add on a folder that is not a git repo", () => {
const dir = tmp("dc-not-git");
const env = { GIT_CEILING_DIRECTORIES: path.dirname(dir) };
@@ -1172,7 +1194,7 @@ test("--dry-run writes nothing for every writing command", () => {
assert.deepEqual(snapshot(dir), project, "the project is unchanged");
assert.deepEqual(snapshot(temp), temps, "the backups are unchanged");
const preview = runDeadCode(runs["report write"], { cwd: dir, env }).json;
assert.equal(preview.path, ".plan2code-dead-code/reports/DEAD-CODE-2026-08-03.md");
assert.equal(preview.path, ".plan2code/dead-code/reports/DEAD-CODE-2026-08-03.md");
assert.equal(preview.preview[0], "# Dead Code report");
});
File diff suppressed because it is too large. Load diff
+22 -2
View File
@@ -22,13 +22,14 @@ test("npm test runs every scripts/test-*.mjs file, and names none that is missin
assert.deepEqual(listed, onDisk);
});
test("every skill with scripts ships common.mjs and version.json; dashboard ships none", () => {
test("every skill with scripts ships common.mjs and version.json; the dashboard ships only Learning's", () => {
const withScripts = skillNames().filter((s) => fs.existsSync(path.join(SKILLS, s, "scripts")));
assert.ok(withScripts.length >= 11, `expected most skills to carry scripts, got ${withScripts.join(", ")}`);
for (const s of withScripts) {
for (const f of ["common.mjs", "version.json"]) assert.ok(fs.existsSync(path.join(SKILLS, s, "scripts", f)), `${s}/scripts/${f}`);
}
assert.ok(!fs.existsSync(path.join(SKILLS, "plan2code", "scripts")), "the dashboard needs no scripts");
// The dashboard runs the approval step (lessons.mjs) and nothing else.
assert.deepEqual(fs.readdirSync(path.join(SKILLS, "plan2code", "scripts")).sort(), ["common.mjs", "glob.mjs", "lessons.mjs", "test-map.mjs", "version.json"]);
const v = JSON.parse(fs.readFileSync(path.join(ROOT, "version.json"), "utf8")).version;
assert.equal(JSON.parse(fs.readFileSync(path.join(SKILLS, "plan2code-4-finalize", "scripts", "version.json"), "utf8")).version, v);
});
@@ -842,6 +843,25 @@ test("the skills that run test-match.mjs ship glob.mjs and test-map.mjs beside i
assert.ok(fs.existsSync(path.join(SKILLS, "plan2code-test", "scripts", "coverage.mjs")), "plan2code-test ships its own coverage.mjs");
});
test("Learning: fifteen skills read lessons, seven note them, and each ships the script and the reference", () => {
const reading = ["0-pathfinder", "1-plan", "1b-revise-plan", "2-document", "3-implement", "3-implement-review", "review", "4-finalize", "quick-task", "diagnose", "xray", "test", "pr-prep", "dead-code", "ui-prototype"].map((n) => `plan2code-${n}`);
const noting = ["3-implement", "3-implement-review", "quick-task", "diagnose", "xray", "review", "test"].map((n) => `plan2code-${n}`);
const skillMd = (s) => fs.readFileSync(path.join(SKILLS, s, "SKILL.md"), "utf8");
const ships = (s) => {
for (const f of ["lessons.mjs", "glob.mjs", "test-map.mjs"]) assert.ok(fs.existsSync(path.join(SKILLS, s, "scripts", f)), `${s}/scripts/${f}`);
assert.ok(fs.existsSync(path.join(SKILLS, s, "references", "lessons.md")), `${s}/references/lessons.md`);
};
for (const s of skillNames()) if (skillMd(s).includes("lessons.mjs")) ships(s);
for (const s of [...reading, "plan2code"]) ships(s);
for (const s of reading) assert.ok(skillMd(s).includes("references/lessons.md"),`${s} reads the lessons reference`);
const withEnd = skillNames().filter((s) => skillMd(s).includes("lessons.md` → End")).sort();
assert.deepEqual(withEnd, [...noting].sort(), "exactly the seven noting skills run End");
for (const s of ["plan2code-init", "plan2code-init-update"]) {
assert.ok(!skillMd(s).includes("lessons.mjs") && !skillMd(s).includes("references/lessons.md"), `${s} is unchanged`);
assert.ok(!fs.existsSync(path.join(SKILLS, s, "references", "lessons.md")), `${s} ships no lessons reference`);
}
});
test("common.mjs exports the shared loop-token and scrape patterns", async () => {
const common = await import(new URL(`file:///${path.join(SKILLS, "plan2code-2-document", "scripts", "common.mjs").replace(/\\/g, "/")}`).href);
assert.ok(common.LOOP_TOKENS instanceof RegExp);
+181 -2
View File
@@ -12,7 +12,7 @@ import assert from "node:assert/strict";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { ACTIVITIES, bestKey, bestKeys, memoKey, musicKey, musicLevel, orderGames, playedKey } from "../src/web-console/public/activities.js";
import { BOSS_BITES, COMBO_MS, MAX_LEVEL, MUSIC_TRACKS, dealMusic, heat, trackFor, DISCOVERIES, FOOD_PER_LEVEL, FRUITS, GRID, ICE_STEPS, LEVELS, MAX_COMBO, MIN_CELL, MIN_STEP_MS, POWERS, STEP_MS, SURPRISES, age, applyPower, applySurprise, fruitFor, tallyBit, newRound, onFood, SPECIALS, pace, placeFood, step, stepMs, turn } from "../src/web-console/public/activities/snake.js";
import { BOSSES, GRACE_MS, MAX_LIVES, START_LIVES, awardLives, lifeMark, onBoss, BOSS_BITES, COMBO_MS, MAX_LEVEL, MUSIC_TRACKS, dealMusic, heat, trackFor, DISCOVERIES, FOOD_PER_LEVEL, FRUITS, GRID, ICE_STEPS, LEVELS, MAX_COMBO, MIN_CELL, MIN_STEP_MS, POWERS, STEP_MS, SURPRISES, age, applyPower, applySurprise, fruitFor, tallyBit, newRound, onFood, SPECIALS, pace, placeFood, step, stepMs, turn } from "../src/web-console/public/activities/snake.js";
import golf, * as golfRules from "../src/web-console/public/activities/golf.js";
import { COURSE_W, COURSE_H, COURSES, FRONT_NINE, HOLE_COUNT, courseById } from "../src/web-console/public/activities/golf-holes.js";
import { holeQuip, holeWord, knownGround, knownLiquid } from "../src/web-console/public/activities/golf-draw.js";
@@ -367,7 +367,7 @@ test("orderGames splits played from not played yet and orders each group", () =>
test("musicKey builds a flat looks.json key, and a game with music has a default volume a saved one replaces", () => {
assert.equal(musicKey("ghoul"), "activityMusicGhoul");
assert.deepEqual(ACTIVITIES.filter((a) => a.music !== undefined).map((a) => [a.id, a.music]), [["snake", 70], ["trails", 70], ["drive", 70], ["ghoul", 65], ["flock", 70]], "the games with music, at about the level they were picked at on the prototype pages");
assert.deepEqual(ACTIVITIES.filter((a) => a.music !== undefined).map((a) => [a.id, a.music]), [["snake", 70], ["trails", 70], ["drive", 70], ["bounce", 70], ["ghoul", 65], ["flock", 70]], "the games with music, at about the level they were picked at on the prototype pages");
const ghoulEntry = ACTIVITIES.find((a) => a.id === "ghoul");
assert.equal(musicLevel(ghoulEntry, undefined), 0.65, "nothing saved: the default");
assert.equal(musicLevel(ghoulEntry, "loud"), 0.65, "not a number: the default");
@@ -506,6 +506,7 @@ test("Snake: a wall hit ends the round and onScore fires once", async () => {
const g = game.create({ canvas, tone: (n) => tones.push(n), onScore: (s) => scores.push(s) });
g.resize(GRID * MIN_CELL, GRID * MIN_CELL);
g.start();
g.round.lives = 1;
// Heading right from mid-board, the wall is at most GRID steps away, and a
// tick of STEP_MS is at least one step whatever the snake has eaten.
for (let i = 0; i < GRID + 2 && g.state === "running"; i++) g.tick(STEP_MS);
@@ -553,6 +554,7 @@ test("Snake: it asks for the deal's track while a round runs, and the next round
g.tick(STEP_MS);
assert.equal(asked.length, 0, "silent before a round");
g.start();
g.round.lives = 1;
g.tick(16);
assert.equal(asked.length, 1, "asked once a tick");
const [first, opening] = asked[0];
@@ -564,12 +566,14 @@ test("Snake: it asks for the deal's track while a round runs, and the next round
g.tick(STEP_MS * 10);
assert.equal(asked.length, before, "nothing asked for once the round is over");
g.start();
g.round.lives = 1;
g.tick(16);
assert.notEqual(asked.at(-1)[0], first, "the next round opens on another track");
});
test("Snake: running into its own body ends the round", () => {
const round = newRound(GRID, () => 0);
round.lives = 1;
// Head at (5,5) heading right into (6,5), which is body, not the tail.
round.snake = [{ x: 5, y: 5 }, { x: 5, y: 6 }, { x: 6, y: 6 }, { x: 6, y: 5 }, { x: 6, y: 4 }];
round.dir = { x: 1, y: 0 };
@@ -634,6 +638,7 @@ async function snakeGame(randomValue) {
Math.random = () => randomValue;
try {
g.start();
g.round.lives = 1;
} finally {
Math.random = real;
}
@@ -678,6 +683,7 @@ test("Snake game: after eating, the snake moves on the shorter step", async () =
Math.random = () => roll;
try {
g.start();
g.round.lives = 1;
roll = 0;
g.tick(stepMs(3));
assert.equal(g.score, 1, "the first food is eaten at the starting step");
@@ -729,6 +735,7 @@ function plainRound() {
round.snake = [{ x: 5, y: 5 }, { x: 4, y: 5 }, { x: 3, y: 5 }];
round.dir = { x: 1, y: 0 };
round.food = { x: 0, y: 19 };
round.lives = 1;
return round;
}
@@ -6350,3 +6357,175 @@ test("Stack Deploy and Sunset Drive: the banner's strip counts the slider, and a
assert.equal(drive.underBanner(drive.H / 2), false, "a flat road stays below the strip");
assert.equal(drive.underBanner(drive.H * 0.36), true, "a hill into the strip");
});
/* ------------------------------------------------- Snake's lives and bosses */
test("Snake: a round starts with three lives, a crash costs one and puts the snake back mid-board with free passage, and the last ends the round", () => {
assert.equal(START_LIVES, 3);
const round = newRound(GRID, () => 0);
assert.equal(round.lives, 3);
round.snake = [{ x: 19, y: 5 }, { x: 18, y: 5 }, { x: 17, y: 5 }];
round.dir = { x: 1, y: 0 };
round.score = 7;
assert.equal(step(round), "hit");
assert.equal(round.lives, 2);
assert.equal(round.crashed, null);
assert.equal(round.score, 7, "the score is kept");
assert.deepEqual(round.snake[0], { x: 10, y: 10 });
assert.equal(round.grace, GRACE_MS);
assert.ok(round.events.some((e) => e.type === "life" && e.by === "wall" && e.lives === 2));
// Free passage: the wall wraps the snake and costs nothing, until it runs out.
round.snake = [{ x: 19, y: 5 }, { x: 18, y: 5 }, { x: 17, y: 5 }];
assert.equal(step(round), null);
assert.equal(round.lives, 2);
age(round, GRACE_MS, () => 0.99);
assert.equal(round.grace, 0);
round.snake = [{ x: 19, y: 5 }, { x: 18, y: 5 }, { x: 17, y: 5 }];
assert.equal(step(round), "hit");
assert.equal(round.lives, 1);
age(round, GRACE_MS, () => 0.99);
round.snake = [{ x: 19, y: 5 }, { x: 18, y: 5 }, { x: 17, y: 5 }];
assert.equal(step(round), "crash");
assert.equal(round.lives, 0);
assert.equal(round.crashed, "wall");
});
test("Snake: a lost life clears the middle of the board, and endless lives never cost one", () => {
const round = plainRound();
round.lives = 3;
round.rocks = [{ x: 10, y: 10, warn: 0 }, { x: 1, y: 1, warn: 0 }];
round.snake = [{ x: 19, y: 5 }, { x: 18, y: 5 }, { x: 17, y: 5 }];
step(round);
assert.deepEqual(round.rocks, [{ x: 1, y: 1, warn: 0 }], "only the rock in the way is cleared");
const endless = plainRound();
endless.infinite = true;
for (let i = 0; i < 6; i++) {
endless.snake = [{ x: 19, y: 5 }, { x: 18, y: 5 }, { x: 17, y: 5 }];
endless.grace = 0;
assert.equal(step(endless), "hit");
}
assert.equal(endless.lives, 1, "lives stay as they were");
});
test("Snake: a life is earned at each score mark, never past MAX_LIVES, and the mark moves on at the cap", () => {
assert.deepEqual([0, 1, 2, 3, 4, 5].map(lifeMark), [100, 250, 450, 700, 1000, 1300]);
const round = plainRound();
round.lives = 3;
round.score = 99;
awardLives(round);
assert.equal(round.lives, 3);
round.score = 100;
awardLives(round);
assert.equal(round.lives, 4);
assert.ok(round.events.some((e) => e.type === "bonusLife" && e.lives === 4));
round.score = 5000;
awardLives(round);
assert.equal(round.lives, MAX_LIVES);
assert.ok(round.lifeAt > 6, "the marks passed at the cap are used up");
const before = round.events.length;
awardLives(round);
assert.equal(round.events.length, before, "nothing more until the next mark");
});
test("Snake: levels 4, 6 and 8 each open with a boss whose orbs are the food", () => {
assert.deepEqual(Object.keys(BOSSES), ["4", "6", "8"]);
for (const level of [4, 6, 8]) {
const round = plainRound();
round.level = level - 1;
round.eaten = (level - 1) * FOOD_PER_LEVEL - 1;
round.food = { x: 6, y: 5 };
step(round, () => 0.5);
assert.equal(round.level, level);
const b = round.boss;
assert.ok(b, `level ${level} has a boss`);
assert.equal(b.hp, BOSSES[level].hp);
assert.ok(round.food.orb, "the food is an orb");
assert.ok(!onBoss(b, round.food), "the orb is not under the boss");
assert.ok(!round.snake.some((c) => onBoss(b, c)), "the boss is clear of the snake");
assert.ok(round.events.some((e) => e.type === "fight" && e.id === b.id));
}
});
test("Snake: each orb hurts the boss and the level waits, the last pays out, grows the snake and earns a life", () => {
const round = plainRound();
round.level = 4;
round.eaten = 15;
round.lives = 3;
round.boss = { id: "golem", name: "Grumpy Golem", sub: "", color: "#8f877c", size: 3, hp: 2, max: 2, x: 15, y: 15, tx: null, ty: null, moveMs: 0, actMs: 9e9, leap: null, hurt: 0 };
round.food = { x: 6, y: 5, orb: true };
assert.equal(step(round, () => 0.5), "eat");
assert.equal(round.boss.hp, 1);
assert.equal(round.eaten, 15, "an orb is not a food toward the next level");
assert.ok(round.food.orb);
round.snake = [{ x: round.food.x - 1, y: round.food.y }, { x: round.food.x - 2, y: round.food.y }, { x: round.food.x - 3, y: round.food.y }];
round.dir = { x: 1, y: 0 };
const before = round.score;
step(round, () => 0.5);
assert.equal(round.boss, null, "beaten");
assert.equal(round.lives, 4);
assert.ok(round.score - before >= 12 * 4, "a bonus of 12 a level");
assert.ok(round.events.some((e) => e.type === "bossDown" && e.lives === 4));
assert.ok(!round.food.orb, "the food is plain again");
});
test("Snake: running into a boss is a crash, with or without free passage", () => {
const round = plainRound();
round.lives = 1;
round.boss = { id: "golem", name: "G", sub: "", color: "#888", size: 3, hp: 3, max: 3, x: 6, y: 4, tx: null, ty: null, moveMs: 0, actMs: 9e9, leap: null, hurt: 0 };
round.grace = 1000;
assert.equal(step(round), "crash");
assert.equal(round.crashed, "boss");
});
test("Snake: the Golem drops rocks, the Comet Queen calls a comet and the Thunder Toad lands where its ring showed", () => {
const base = (id) => ({ id, name: id, sub: "", color: "#888", size: 3, hp: 4, max: 4, x: 14, y: 14, tx: null, ty: null, moveMs: 0, actMs: 100, leap: null, hurt: 0 });
const golem = plainRound();
golem.boss = base("golem");
age(golem, 150, () => 0.5);
assert.ok(golem.rocks.length >= 1, "rocks come down");
const queen = plainRound();
queen.boss = base("queen");
age(queen, 150, () => 0.5);
assert.equal(queen.comets.length, 1);
const toad = plainRound();
toad.boss = base("toad");
age(toad, 150, () => 0.5);
assert.ok(toad.boss.leap, "a landing ring is shown first");
const ring = { ...toad.boss.leap };
assert.equal(toad.boss.x, 14, "still where it was");
age(toad, 1000, () => 0.5);
assert.deepEqual([toad.boss.x, toad.boss.y], [ring.x, ring.y]);
assert.ok(toad.events.some((e) => e.type === "land"));
// Landing on the head is a crash, unless free passage still runs.
const stomp = plainRound();
stomp.lives = 1;
stomp.boss = { ...base("toad"), leap: { x: 4, y: 4, warn: 50 } };
assert.equal(age(stomp, 100, () => 0.5), "crash");
assert.equal(stomp.crashed, "boss");
});
test("Snake game: the lives pill is drawn, a crash with lives to spare keeps the round going, and the endless-lives code is answered", async () => {
const { g } = await snakeGame(0);
g.start();
assert.equal(g.round.lives, 3);
g.round.lives = 2;
for (let i = 0; i < GRID + 2 && g.round.lives === 2; i++) g.tick(STEP_MS);
assert.equal(g.round.lives, 1);
assert.equal(g.state, "running", "one life lost, the round goes on");
g.cheat(true);
assert.equal(g.round.infinite, true);
g.start();
assert.equal(g.round.infinite, false, "a new round starts without it");
});
test("Snake game: every boss and the toad's landing ring draw, and the HUD shows its hit points", async () => {
const { g } = await snakeGame(0);
g.start();
for (const id of ["golem", "queen", "toad"]) {
g.round.boss = { id, name: id, sub: "", color: "#888888", size: 3, hp: 2, max: 3, x: 14, y: 2, tx: null, ty: null, moveMs: 0, actMs: 9e9, leap: id === "toad" ? { x: 2, y: 14, warn: 400 } : null, hurt: 100 };
g.round.food = { x: 0, y: 19, orb: true };
g.round.grace = 500;
g.tick(16);
}
assert.equal(g.state, "running");
});
+277
View File
@@ -0,0 +1,277 @@
// Web console tests, Learning on the server: the dashboard scan's `learning`
// field, Pause for me (`POST /learning/pause`) and the two read-only routes
// (`GET /learning/state`, `GET /learning/lessons`). Run with:
// node --test scripts/test-web-console-learning.mjs
//
// Each session opens in a throwaway project folder, so the repository this runs
// in is never read or written. Learning's store on this machine is the test
// home's (PLAN2CODE_LEARNING_DIR, set by web-console-test-helpers.mjs).
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 { spawnSync } from "node:child_process";
import { ENV, HOME, LEARNING_DIR, ROOT, cli, postPatch, readState, sessionUrl } from "./web-console-test-helpers.mjs";
import { learningScan, storeDir, writePause, writeWaiting } from "../src/web-console/learning.mjs";
import { sessionActions } from "../src/web-console/cmd-post-wait.mjs";
import { indentReply, learningAction, learningBannerText, learningReply, lessonsReply } from "../src/web-console/public/answers.js";
const LESSONS = path.join(ROOT, "src", "skill-scripts", "lessons.mjs");
let projects = 0;
function project(files = {}) {
const dir = path.join(HOME, "learning-projects", `p${++projects}`);
fs.mkdirSync(dir, { recursive: true });
for (const [rel, text] of Object.entries(files)) {
fs.mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true });
fs.writeFileSync(path.join(dir, rel), text);
}
return fs.realpathSync(dir);
}
const SETTINGS = (learning) => ({ ".plan2code/settings.json": JSON.stringify({ format: 1, learning }) + "\n" });
// Every file under a folder, relative, so a test can say nothing was written.
function listing(dir) {
const out = [];
const walk = (d) => {
for (const e of fs.readdirSync(d, { withFileTypes: true })) {
const p = path.join(d, e.name);
if (e.isDirectory()) walk(p);
else out.push(path.relative(dir, p).split(path.sep).join("/"));
}
};
walk(dir);
return out.sort();
}
// A dashboard session opened from `dir`, the way an agent opens one.
function dashboard(t, dir) {
const opened = cli(["open", "--workflow", "dashboard", "--no-open"], { cwd: dir }).json;
const s = { ...opened, ...sessionUrl(opened.url) };
s.post = (pathname, body, headers = {}) =>
fetch(`${s.base}${pathname}`, {
method: "POST",
headers: { "content-type": "application/json", cookie: s.cookie, connection: "close", ...headers },
body: typeof body === "string" ? body : JSON.stringify(body ?? {}),
});
s.get = (pathname) => fetch(`${s.base}${pathname}`, { headers: { cookie: s.cookie, connection: "close" } });
t.after(() => cli(["stop", "--session", s.sid, "--force"], { cwd: dir }));
return s;
}
/* ------------------------------------------------------------ the scan */
test("scan.learning: not set up, off, on and paused, with the waiting count", (t) => {
const none = project();
const s1 = dashboard(t, none);
assert.deepEqual(readState(s1.session).scan.learning, { state: "not-set-up", pausedSince: null, waiting: 0, oldestDays: 0 });
const off = project(SETTINGS("off"));
assert.equal(readState(dashboard(t, off).session).scan.learning.state, "off");
const on = project(SETTINGS("on"));
const noted = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000 - 60000).toISOString();
writeWaiting(on, { id: "20261111-120000-abcdef", type: "lesson", text: "A lesson.", noted });
writeWaiting(on, { id: "20261112-120000-abcdef", type: "lesson", text: "Another.", noted: new Date().toISOString() });
assert.deepEqual(readState(dashboard(t, on).session).scan.learning, { state: "on", pausedSince: null, waiting: 2, oldestDays: 2 });
const paused = project(SETTINGS("on"));
const pause = writePause(paused, true, "2026-11-13T09:00:00.000Z");
const scan = readState(dashboard(t, paused).session).scan.learning;
assert.equal(scan.state, "paused");
assert.equal(scan.pausedSince, pause.since);
});
test("scan.learning is absent for a settings format this console does not know", (t) => {
const dir = project({ ".plan2code/settings.json": JSON.stringify({ format: 99, learning: "on" }) });
const scan = readState(dashboard(t, dir).session).scan;
assert.ok(scan, "the dashboard still scans");
assert.equal("learning" in scan, false, "no learning field, so the page draws no row");
});
test("a failure in Learning's core never fails the scan", () => {
const boom = () => {
throw new Error("the core broke");
};
assert.equal(learningScan(project(), { read: boom }), null);
assert.equal(learningScan(project(), { read: () => ({ state: "unknown", waiting: { count: 1 } }) }), null);
});
test("an unreadable learning store reads as empty: on, not paused, nothing waiting", (t) => {
// A file where the store's folder should be: every read under it fails, and
// the core treats that as an empty store rather than throwing.
const dir = project(SETTINGS("on"));
const store = storeDir(dir);
fs.mkdirSync(path.dirname(store), { recursive: true });
fs.writeFileSync(store, "not a folder");
t.after(() => fs.rmSync(store, { force: true }));
const s = dashboard(t, dir);
assert.deepEqual(readState(s.session).scan.learning, { state: "on", pausedSince: null, waiting: 0, oldestDays: 0 });
});
test("the scan reads without pruning: an old waiting item stays on disk", (t) => {
const dir = project(SETTINGS("on"));
const old = new Date(Date.now() - 40 * 24 * 60 * 60 * 1000).toISOString();
writeWaiting(dir, { id: "20261001-120000-aaaaaa", type: "lesson", text: "Old.", noted: old });
const learning = readState(dashboard(t, dir).session).scan.learning;
assert.equal(learning.waiting, 0, "an item past 30 days is not counted");
assert.ok(fs.existsSync(path.join(storeDir(dir), "waiting", "20261001-120000-aaaaaa.json")), "the console deleted nothing");
});
/* ----------------------------------------------------------- the pause */
test("POST /learning/pause: a foreign Origin is 403 and a bad body is 400", async (t) => {
const s = dashboard(t, project(SETTINGS("on")));
assert.equal((await s.post("/learning/pause", { paused: true }, { origin: "http://evil.example" })).status, 403);
assert.equal((await s.post("/learning/pause", "{not json")).status, 400);
const bad = await s.post("/learning/pause", { paused: "yes" });
assert.equal(bad.status, 400);
assert.deepEqual(await bad.json(), { error: "bad-request" });
});
test("POST /learning/pause is 409 when the project is not on", async (t) => {
for (const files of [{}, SETTINGS("off")]) {
const s = dashboard(t, project(files));
const res = await s.post("/learning/pause", { paused: true });
assert.equal(res.status, 409);
assert.deepEqual(await res.json(), { error: "not-on" });
}
});
test("POST /learning/pause writes pause.json on this machine, nothing in the project, and patches the scan", async (t) => {
const dir = project(SETTINGS("on"));
const before = listing(dir);
const s = dashboard(t, dir);
const res = await s.post("/learning/pause", { paused: true });
assert.equal(res.status, 200);
const body = await res.json();
assert.equal(body.ok, true);
assert.equal(body.learning.state, "paused");
const pauseFile = path.join(storeDir(dir), "pause.json");
assert.ok(pauseFile.startsWith(LEARNING_DIR), "the pause lives under the learning store");
assert.equal(JSON.parse(fs.readFileSync(pauseFile, "utf8")).paused, true);
assert.equal(readState(s.session).scan.learning.state, "paused", "the row repaints from the patched scan");
assert.deepEqual(listing(dir), before, "nothing was written inside the project");
const back = await (await s.post("/learning/pause", { paused: false })).json();
assert.equal(back.learning.state, "on");
assert.equal(fs.existsSync(pauseFile), false);
assert.equal(readState(s.session).scan.learning.state, "on");
});
/* ------------------------------------------------------ the read routes */
test("GET /learning/state answers the scan's object, worked out now", async (t) => {
const dir = project(SETTINGS("on"));
const s = dashboard(t, dir);
writeWaiting(dir, { id: "20261113-120000-bbbbbb", type: "lesson", text: "New.", noted: new Date().toISOString() });
const res = await s.get("/learning/state");
assert.equal(res.status, 200);
assert.deepEqual(await res.json(), { state: "on", pausedSince: null, waiting: 1, oldestDays: 0 });
const unknown = dashboard(t, project({ ".plan2code/settings.json": "{}" }));
assert.deepEqual(await (await unknown.get("/learning/state")).json(), {});
});
test("GET /learning/lessons: general first, then the rest by name; no sub-folders or links out", async (t) => {
const dir = project({
...SETTINGS("on"),
".plan2code/lessons/web-console.md": "# Web console\n\nA lesson.\n",
".plan2code/lessons/general.md": "# General\n\nAnother.\n",
".plan2code/lessons/activities.md": "No heading here.\n",
".plan2code/lessons/notes.txt": "not markdown\n",
".plan2code/lessons/deeper/inside.md": "# Inside\n",
});
// A link pointing outside the folder is never followed.
const outside = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "p2c-learn-out-")), "secret.md");
fs.writeFileSync(outside, "# Secret\n");
let linked = true;
try {
fs.symlinkSync(outside, path.join(dir, ".plan2code", "lessons", "linked.md"), "file");
} catch {
linked = false; // Windows without the symlink right: the rest still holds
}
const s = dashboard(t, dir);
const res = await s.get("/learning/lessons");
assert.equal(res.status, 200);
const { files } = await res.json();
assert.deepEqual(
files.map((f) => f.name),
["general.md", "activities.md", "web-console.md"]
);
assert.equal(files[0].title, "General");
assert.equal(files[1].title, "activities", "no heading: the file's name");
assert.match(files[2].text, /A lesson\./);
if (linked) assert.equal(files.some((f) => f.name === "linked.md"), false, "the link out was not followed");
const empty = dashboard(t, project(SETTINGS("on")));
assert.deepEqual(await (await empty.get("/learning/lessons")).json(), { files: [] });
});
/* ------------------------------------------------- the action and reply */
test("a Learning action reaches the agent whole, and a launch keeps fromBanner", () => {
for (const what of ["review", "switch-on", "switch-off", "move-log", "remove"]) {
const action = learningAction(what);
assert.deepEqual(action, { i: "__learning", type: "learning", do: what });
assert.deepEqual(sessionActions({ actions: [action] }), [{ i: "__learning", do: what }]);
assert.ok(learningReply(what).length > 0, `${what} has a reply`);
assert.doesNotMatch(learningReply(what), /—/);
}
assert.throws(() => learningAction("delete-everything"));
const launch = { i: "__launch", type: "launch", skill: "plan2code-quick-task", workflow: "quick-task", fromBanner: true };
assert.equal(sessionActions({ actions: [launch] })[0].fromBanner, true);
});
test("the waiting banner's line shows only while lessons wait and Learning is on or not set up", () => {
assert.equal(learningBannerText({ state: "on", waiting: 3, oldestDays: 2 }), "3 lessons are waiting for your review (oldest 2 days).");
assert.equal(learningBannerText({ state: "not-set-up", waiting: 1, oldestDays: 1 }), "1 lesson is waiting for your review (oldest 1 day).");
assert.equal(learningBannerText({ state: "on", waiting: 0, oldestDays: 0 }), "");
assert.equal(learningBannerText({ state: "paused", waiting: 4, oldestDays: 0 }), "");
assert.equal(learningBannerText({ state: "off", waiting: 4, oldestDays: 0 }), "");
assert.equal(learningBannerText(undefined), "");
});
/* ---------------------------------------------- the lessons card, end to end */
test("the lessons card from lessons.mjs list goes up on the dashboard, and a Keep comes back as a Keep line and a decisions file decide takes", async (t) => {
const dir = project(SETTINGS("on"));
writeWaiting(dir, { id: "20261113-120000-abcdef", type: "lesson", text: "Run a page test alone first.", why: "A full run hides the race.", kind: "command", about: ["scripts/node-test.mjs"], source: "said", noted: new Date().toISOString() });
const lessons = (args) => {
const res = spawnSync(process.execPath, [LESSONS, ...args], { cwd: dir, env: ENV, encoding: "utf8" });
return { code: res.status, json: JSON.parse(res.stdout || "null"), stderr: res.stderr };
};
const list = lessons(["list"]);
assert.equal(list.code, 0, list.stderr);
const card = list.json.card;
assert.equal(card.kind, "lessons");
assert.deepEqual(card.rows.map((r) => [r.id, r.type, r.choices]), [["20261113-120000-abcdef", "lesson", ["Keep", "Reword", "Drop"]]]);
const s = dashboard(t, dir);
const posted = postPatch(s, { items: [card], agent: { status: "waiting" } }, { cwd: dir });
assert.equal(posted.status, 0, posted.stderr);
const item = readState(s.session).items.find((i) => i.id === card.id);
assert.equal(item.status, "open", "the dashboard takes the lessons card");
// What the page's Send carries: the answer, and the reply its words make.
const v = { type: "answer", kind: "lessons", decisions: [{ id: card.rows[0].id, choice: "Keep" }] };
const reply = `${card.title}: ${indentReply(lessonsReply(item, v))}`;
const res = await s.post("/submit", { actions: [{ i: card.id, ...v }], reply });
assert.equal(res.status, 200);
const waited = cli(["wait", "--session", s.sid, "--seconds", "5"], { cwd: dir });
assert.equal(waited.status, 0, waited.stderr);
const lines = waited.json.reply.split("\n").map((l) => l.trim());
assert.ok(lines.some((l) => l === "Keep: Run a page test alone first."), waited.json.reply);
// The Decisions line is the file lessons.mjs decide takes, unchanged.
const json = lines.find((l) => l.startsWith("Decisions: ")).slice("Decisions: ".length);
const file = path.join(s.session, "decisions.json");
fs.writeFileSync(file, json);
const decided = lessons(["decide", "--file", file]);
assert.equal(decided.code, 0, decided.stderr);
assert.match(decided.json.closing, /^Kept 1\./, JSON.stringify(decided.json));
assert.match(fs.readFileSync(path.join(dir, ".plan2code", "lessons", "general.md"), "utf8"), /Run a page test alone first\./);
});
+201 -5
View File
@@ -93,6 +93,14 @@ import {
verdictText,
lastOpenCard,
nextOpenAfter,
answerLines,
lessonDecision,
lessonEditStart,
lessonReworded,
lessonLines,
lessonMissing,
lessonsReply,
loopLessonsLine,
} from "../src/web-console/public/answers.js";
import { chatView } from "../src/web-console/public/chat.js";
import { ACCENTS, DEFAULT_ACCENT, RETIRED_ACCENTS, accentId } from "../src/web-console/public/palette.js";
@@ -581,6 +589,23 @@ test("pruneStaged drops only the picks a re-posted card no longer offers, withou
assert.deepEqual(pruneStaged(items, { u1: staged.u1 }), { staged: { u1: staged.u1 }, dropped: [] });
});
test("pruneStaged drops a multi pick the re-posted card now locks, and leaves a choice's locked field alone", () => {
const items = [
{ id: "m1", kind: "multi", options: [{ k: "1", text: "a" }, { k: "2", text: "b", locked: true }] },
{ id: "m2", kind: "multi", options: [{ k: "1", text: "a", locked: true }] },
{ id: "c1", kind: "choice", options: [{ k: "A", text: "a", locked: true }] },
];
const out = pruneStaged(items, {
m1: { type: "answer", kind: "multi", ks: ["1", "2"] },
m2: { type: "answer", kind: "multi", ks: ["1"] },
c1: { type: "answer", kind: "choice", k: "A" },
});
assert.deepEqual(out.dropped.sort(), ["m1", "m2"]);
assert.deepEqual(out.staged.m1.ks, ["1"], "the locked key goes, the other stays");
assert.equal("m2" in out.staged, false, "a multi left with only a locked pick goes");
assert.deepEqual(out.staged.c1.k, "A", "only a multi draws locked rows");
});
test("document helpers: the extension allow-list, the picker's accept, sizes, and the kind of an old entry", () => {
assert.equal(MAX_ATTACHMENTS, 5);
assert.equal(MAX_DOC_BYTES, 10 * 1024 * 1024);
@@ -1592,6 +1617,176 @@ test("validate: fill only as \"note\", only on a text item", () => {
assert.ok(validate(item({ fill: true })).some((p) => p.startsWith(message)));
});
test("validate: a lessons item takes rows each with a type and its own choices, and nothing chosen", () => {
const row = (extra = {}) => ({ id: "w1", type: "lesson", text: "Run a page test alone first.", choices: ["Keep", "Reword", "Drop"], ...extra });
const item = (extra) => ({ id: "lessons", kind: "lessons", title: "Lessons to keep", status: "open", ...extra });
const one = (extra) => validate({ items: [item(extra)] });
assert.deepEqual(one({ opening: "You are on main: kept lessons will be uncommitted changes here.", rows: [row({ why: "A full run hides it.", origin: "You said this.", note: "", flags: [], refused: null, area: "General", areas: ["General"] })] }), []);
assert.deepEqual(
one({ rows: ["lesson", "doubt", "gone", "agents-fix", "log-line", "area"].map((type, i) => row({ id: `w${i}`, type })) }),
[],
"every row type the list gives"
);
const firstAsk = { lesson: { id: "w1", text: "x" }, sentences: ["a", "b", "c"], yes: "Switch Learning on", no: "Not for this project", later: "Later." };
assert.deepEqual(one({ firstAsk }), [], "a first ask needs no rows");
const refused = (extra, field) => {
const problems = one(extra);
assert.ok(problems.some((p) => p.includes(field)), `${field}: ${problems.join(" | ")}`);
};
refused({}, "rows: is empty");
refused({ rows: [] }, "rows: is empty");
refused({ rows: [row({ choices: [] })] }, 'row "w1" choices');
refused({ rows: [row({ choices: undefined })] }, 'row "w1" choices');
refused({ rows: [row({ type: "rule" })] }, 'row "w1" type');
refused({ rows: [row({ choice: "Keep" })] }, 'row "w1" choice: is not allowed');
refused({ rows: [row({ selected: true })] }, 'row "w1" selected: is not allowed');
refused({ firstAsk: { ...firstAsk, sentences: ["a", "b"] } }, "firstAsk");
const two = validate({ items: [item({ rows: [row()] }), item({ id: "lessons-2", rows: [row()] })] });
assert.ok(two.some((p) => p.includes("2 lessons cards are open at once")), two.join(" | "));
const answered = validate({ items: [item({ rows: [row()], status: "answered" }), item({ id: "lessons-2", rows: [row()] })] });
assert.deepEqual(answered, [], "an answered card does not count");
});
test("validate: a lesson's own words never get the lessons card refused, but the card's own text still can", () => {
const marker = "TASK_" + "COMPLETE";
const words = ["Requirements 12 and 13 are checked by check-versions.mjs.", "Risk 3 is the slow blame on Windows.", `Never print ${marker} in a spec file.`, "The grill step reads the map first."];
const rows = words.map((text, i) => ({ id: `w${i}`, type: "lesson", text, why: text, origin: "You said this.", choices: ["Keep", "Reword", "Drop"] }));
rows.push({ id: "log1", type: "log-line", text: words[0], lessons: [words[1]], choices: ["Move", "Reword and move", "Leave"] });
rows.push({ id: "fix1", type: "agents-fix", text: words[2], before: words[1], after: words[2], file: "AGENTS.md", choices: ["Apply", "Reword", "Drop"] });
const item = (extra) => ({ id: "lessons", kind: "lessons", title: "Lessons to keep", status: "open", rows, ...extra });
assert.deepEqual(validate({ items: [item()] }), [], "rows are the project's words");
const firstAsk = { lesson: { id: "w1", text: words[1], why: words[0] }, sentences: ["a", "b", "c"], yes: "Switch Learning on", no: "Not for this project", later: "Later." };
assert.deepEqual(validate({ items: [item({ rows: undefined, firstAsk })] }), [], "so is the first ask's lesson");
// What the agent wrote around them is still held to the rules.
assert.ok(validate({ items: [item({ body: words[1] })] }).some((p) => p.includes("Risk 3")), "the body");
assert.ok(validate({ items: [item({ rows: undefined, firstAsk: { ...firstAsk, sentences: ["a", "b", words[0]] } })] }).some((p) => p.includes("Requirements 12")), "a first-ask sentence");
// Any other kind of card with the same words is refused as before.
assert.ok(validate({ items: [{ id: "q1", kind: "notice", title: "A note", body: words[1], status: "open" }] }).length > 0);
});
test("validate: the dashboard refuses question cards but draws the lessons card", () => {
const rows = [{ id: "w1", type: "lesson", text: "x", choices: ["Keep", "Reword", "Drop"] }];
assert.deepEqual(validate({ workflow: "dashboard", items: [{ id: "lessons", kind: "lessons", title: "Lessons to keep", status: "open", rows }] }), []);
assert.ok(validate({ workflow: "dashboard", items: [{ id: "q1", kind: "text", title: "Name", status: "open" }] }).some((p) => p.includes("the dashboard draws no question cards")));
});
test("validate: a multi's pick-list fields are checked only when present, each refusal naming the field", () => {
const opt = (k, extra = {}) => ({ k, text: `pkg ${k}`, ...extra });
const multi = (options, extra = {}) => validate({ items: [{ id: "picks", kind: "multi", title: "Updates to apply", status: "open", options, ...extra }] });
const refused = (problems, ...parts) => {
assert.ok(
problems.some((p) => p.startsWith('item "picks"') && parts.every((part) => p.includes(part))),
`${parts.join(" + ")}: ${problems.join(" | ")}`
);
};
// Accepted: none of the fields (Dead Code's shape), then every field at its edge.
assert.deepEqual(multi([opt("A"), opt("B")], { presets: [{ label: "Both", ks: ["A", "B"] }] }), []);
assert.deepEqual(
multi(
[
opt("A", { group: "Safe", batch: "npm-root", more: "x".repeat(4096) }),
opt("B", { group: "S".repeat(40), batch: "npm-root", locked: false }),
opt("C", { locked: true, more: "Needs Node 22." }),
],
{ counter: { rounds: "check rounds" }, presets: [{ label: "All safe", ks: ["A", "B"] }] }
),
[]
);
// Refused: each field out of shape.
refused(multi([opt("A", { group: "" })]), "options:", 'option "A"', '"group"', "1 to 40");
refused(multi([opt("A", { group: "G".repeat(41) })]), 'option "A"', '"group"');
refused(multi([opt("A", { group: 3 })]), 'option "A"', '"group"');
refused(multi([opt("A", { more: "x".repeat(4097) })]), 'option "A"', '"more"', "4 KB");
refused(multi([opt("A", { more: "é".repeat(2049) })]), 'option "A"', '"more"'); // 4098 bytes, 2049 characters
refused(multi([opt("A", { more: ["x"] })]), 'option "A"', '"more"');
refused(multi([opt("A", { batch: 7 })]), 'option "A"', '"batch"');
refused(multi([opt("A", { batch: "" })]), 'option "A"', '"batch"');
refused(multi([opt("A", { locked: "yes" })]), 'option "A"', '"locked"');
refused(multi([opt("A")], { counter: { rounds: 2 } }), "counter:", '"rounds"');
refused(multi([opt("A")], { counter: "check rounds" }), "counter:", '"rounds"');
refused(multi([opt("A")], { counter: {} }), "counter:");
refused(
multi([opt("A"), opt("B", { locked: true })], { presets: [{ label: "Everything", ks: ["A", "B"] }] }),
"presets:",
'preset "Everything"',
'"B"',
"locked"
);
const notMulti = validate({ items: [{ id: "picks", kind: "choice", title: "Updates to apply", status: "open", options: [opt("A")], counter: { rounds: "check rounds" } }] });
refused(notMulti, "counter:", "only a multi");
// Every refusal carries the field done right, as the other rules do.
for (const p of multi([opt("A", { group: "" })])) assert.match(p, /\{/);
});
test("lessons answers: a line per decision, what was left waiting, and the decisions file's JSON", () => {
const item = {
id: "lessons",
kind: "lessons",
title: "Lessons to keep",
rows: [
{ id: "a", type: "lesson", text: "Old words", why: "Because", area: "General", choices: ["Keep", "Reword", "Drop"] },
{ id: "b", type: "agents-fix", text: "new", file: ".agents-docs/x.md", before: "old", after: "new", choices: ["Apply", "Reword", "Drop"] },
{ id: "c", type: "doubt", text: "Saved", choices: ["Keep", "Reword", "Retire"] },
{ id: "d", type: "log-line", text: "A log line", choices: ["Move", "Reword and move", "Leave in the log"] },
],
};
const decisions = [
lessonDecision(item.rows[0], "Reword", { text: " New words ", why: "Because", area: "Web console" }),
lessonDecision(item.rows[1], "Apply"),
lessonDecision(item.rows[2], "Retire"),
];
assert.deepEqual(decisions, [
{ id: "a", choice: "Reword", text: "New words", why: "Because", area: "Web console" },
{ id: "b", choice: "Apply" },
{ id: "c", choice: "Retire" },
]);
const v = { decisions };
assert.deepEqual(lessonLines(item, v), ["Reword: New words", "Apply: .agents-docs/x.md", "Retire: Saved", "1 left waiting"]);
assert.deepEqual(answerLines(item, v), lessonLines(item, v));
const reply = lessonsReply(item, v).split("\n");
assert.equal(reply[0], "3 decided, 1 left waiting");
assert.equal(reply[1], "Reword: New words");
assert.deepEqual(JSON.parse(reply.find((l) => l.startsWith("Decisions: ")).slice("Decisions: ".length)), decisions);
assert.deepEqual(lessonLines(item, { decisions: [] }), ["4 left waiting"], "nothing chosen leaves everything waiting");
assert.deepEqual(lessonLines(item, { firstAsk: "yes" }), ["Switch Learning on"]);
assert.deepEqual(lessonLines(item, { firstAsk: "no" }), ["Not for this project"]);
// A refused row kept after its words changed goes as a Reword; unchanged, Keep stays Keep.
const bad = { id: "r", type: "lesson", text: "key AKIA...", refused: { pattern: "aws-access-key", part: "AKIA" }, choices: ["Reword", "Drop"] };
assert.deepEqual(lessonDecision(bad, "Keep", { text: "Keys live in the vault." }), { id: "r", choice: "Reword", text: "Keys live in the vault." });
assert.deepEqual(lessonDecision(bad, "Keep", { text: bad.text }), { id: "r", choice: "Keep" });
// An emptied Why goes as "", so decide does not keep the old one.
assert.deepEqual(lessonDecision(item.rows[0], "Reword", { text: "Old words", why: "" }), { id: "a", choice: "Reword", text: "Old words", why: "" });
// A log line's Reword and move goes as the lessons decide takes, one per lesson it becomes.
const log = { id: "log:1", type: "log-line", text: "A log line", lessons: ["First.", "Second."], choices: ["Move", "Reword and move", "Leave in the log"] };
assert.deepEqual(lessonEditStart(log).lessons, ["First.", "Second."], "the edit starts from the lessons, not the line");
assert.deepEqual(lessonDecision(log, "Reword and move", { lessons: ["First, reworded.", "Second."], why: "Seen twice." }), {
id: "log:1",
choice: "Reword and move",
lessons: [
{ text: "First, reworded.", why: "Seen twice." },
{ text: "Second.", why: "Seen twice." },
],
});
assert.equal(lessonMissing(log, lessonDecision(log, "Reword and move", { lessons: ["", "Second."] })), "The lesson");
assert.equal(lessonReworded(log, lessonEditStart(log)), false, "the seed is never a reword");
const fix = { id: "f", type: "agents-fix", text: "new", refused: { pattern: "x", part: "x" }, choices: ["Reword", "Drop"] };
assert.equal(lessonReworded(fix, lessonEditStart(fix)), false, "a fix with no after: the seed matches its words");
// A reword left empty names the missing field.
assert.equal(lessonMissing(item.rows[0], lessonDecision(item.rows[0], "Reword", { text: " " })), "The lesson");
assert.equal(lessonMissing(item.rows[0], lessonDecision(item.rows[0], "Keep")), "");
});
test("the loop stop card's lessons line shows only while lessons wait and Learning is on or not set up", () => {
assert.equal(loopLessonsLine({ state: "on", waiting: 2 }), "2 lessons are waiting for your review. Open the dashboard to review them.");
assert.equal(loopLessonsLine({ state: "not-set-up", waiting: 1 }), "1 lesson is waiting for your review. Open the dashboard to review them.");
for (const l of [null, {}, { state: "on", waiting: 0 }, { state: "off", waiting: 3 }, { state: "paused", waiting: 3 }]) assert.equal(loopLessonsLine(l), "");
});
test("attachmentName: slug of the original name, 8 characters of the upload id, the upload's own extension", () => {
const up = (uuid, ext) => path.join(HOME, "sessions", "x", "uploads", `${uuid}${ext}`);
const a = up("3f2b9c1e-8a4d-4f6e-9b7a-2c5d1e0f4a6b", ".jpg");
@@ -2093,8 +2288,8 @@ test("workspace cursor never moves backwards, and only changes past it are pendi
}
});
test("subagents: only the sixteen opted-in workflows offer the switch", () => {
for (const w of ["init", "init-update", "pathfinder", "plan", "revise-plan", "document", "implement", "implement-review", "quick-task", "review", "finalize", "xray", "diagnose", "pr-prep", "test", "dead-code"]) {
test("subagents: only the seventeen opted-in workflows offer the switch", () => {
for (const w of ["init", "init-update", "pathfinder", "plan", "revise-plan", "document", "implement", "implement-review", "quick-task", "review", "finalize", "xray", "diagnose", "pr-prep", "test", "dead-code", "deps"]) {
assert.equal(offered(w), true, w);
assert.ok(defaultInstruction(w).length > 0, `${w} has a default instruction`);
}
@@ -2102,7 +2297,7 @@ test("subagents: only the sixteen opted-in workflows offer the switch", () => {
assert.equal(offered(w), false, String(w));
assert.equal(defaultInstruction(w), "");
}
assert.equal(Object.keys(SUBAGENT_WORKFLOWS).length, 16);
assert.equal(Object.keys(SUBAGENT_WORKFLOWS).length, 17);
assert.deepEqual(defaultSetting("review"), { workflow: "review", on: true, instruction: null, max: 3, strength: "balanced" });
assert.equal(defaultSetting("changelog").on, false, "a skill without the switch is never on");
assert.equal(effectiveInstruction({ workflow: "review", instruction: " " }), defaultInstruction("review"));
@@ -2392,7 +2587,7 @@ test("meter: the weights and labels built from the skill list are the ones writt
"pathfinder-chart": 2, "pathfinder-question": 0, "pathfinder-research": 1,
plan: 2, "revise-plan": 1, document: 2, "implement-phase": 2, "implement-review-phase": 3,
review: 2, "quick-task": 1, init: 2, "init-update": 2, finalize: 1, handoff: 0, git: 1,
"git-commits": 0, "git-conflict": 1, changelog: 1, xray: 1, diagnose: 1, "pr-prep": 1, test: 1, "dead-code": 1,
"git-commits": 0, "git-conflict": 1, changelog: 1, xray: 1, diagnose: 1, "pr-prep": 1, test: 1, "dead-code": 1, deps: 1,
"ui-prototype-round": 1,
});
assert.deepEqual({ ...LAUNCH_LABELS }, {
@@ -2401,6 +2596,7 @@ test("meter: the weights and labels built from the skill list are the ones writt
"init-update": "Init update started", finalize: "Finalize started", git: "Git started",
changelog: "Changelog started", xray: "X-ray started", diagnose: "Diagnose started",
"pr-prep": "PR Prep started", test: "Test started", "dead-code": "Dead Code started",
deps: "Update Dependencies started",
});
assert.deepEqual({ ...RUN_LABELS }, {
"pathfinder-chart": "Pathfinder map written", "pathfinder-question": "Pathfinder question settled",
@@ -2410,7 +2606,7 @@ test("meter: the weights and labels built from the skill list are the ones writt
"quick-task": "Quick task built", init: "Init run", "init-update": "Init update run",
finalize: "Finalize run", handoff: "Handoff written", git: "Git run", "git-commits": "Commits in Git",
"git-conflict": "Git conflict help", changelog: "Changelog run", xray: "X-ray run", diagnose: "Diagnose run",
"pr-prep": "PR Prep run", test: "Test run", "dead-code": "Dead Code run",
"pr-prep": "PR Prep run", test: "Test run", "dead-code": "Dead Code run", deps: "Update Dependencies run",
"ui-prototype-round": "Prototype round drawn",
});
for (const t of [WEIGHTS, LAUNCH_LABELS, RUN_LABELS]) assert.ok(Object.isFrozen(t));
+35
View File
@@ -245,6 +245,30 @@ test("each bad loopOutcome field is refused with a message naming it", () => {
assert.deepEqual(tryPatch(loopState(), { loopOutcome: edge }).problems, [], "100 characters, 50 entries and 200 characters are the limits, not over them");
});
test("loopOutcome: a failed report may carry one next step for the person, and it is bounded like the other prose", () => {
const failed = goodOutcome();
Object.assign(failed, { result: "failed", reason: "findings", nextStep: "Fix the unreadable range in deps.mjs, then press Continue building" });
const ok = tryPatch(loopState(), { loopOutcome: failed });
assert.deepEqual(ok.problems, []);
assert.equal(ok.next.loopOutcome.nextStep, failed.nextStep);
assert.deepEqual(tryPatch(loopState(), { loopOutcome: goodOutcome() }).problems, [], "it stays optional");
const cases = [
["a two-line next step", "one\ntwo", /loopOutcome\.nextStep must be one line of 1 to 300 characters/],
["a 301-character next step", "n".repeat(301), /loopOutcome\.nextStep must be one line of 1 to 300 characters/],
["an empty next step", "", /loopOutcome\.nextStep must be one line/],
["a completion marker in the next step", "All set, PHASE_COMPLETE", /loopOutcome\.nextStep: contains a loop completion marker/],
];
for (const [what, value, expected] of cases) {
const o = goodOutcome();
Object.assign(o, { result: "failed", reason: "tests", nextStep: value });
const { problems } = tryPatch(loopState(), { loopOutcome: o });
assert.ok(problems.some((p) => expected.test(p)), `${what}: ${JSON.stringify(problems)}`);
}
const edge = goodOutcome();
Object.assign(edge, { result: "failed", reason: "tests", nextStep: "n".repeat(300) });
assert.deepEqual(tryPatch(loopState(), { loopOutcome: edge }).problems, [], "300 characters is the limit, not over it");
});
test("an unfixed finding's title and file are one line, as in the fixed and skipped lists", () => {
const o = goodOutcome();
o.review.unfixed = [{ level: "suggestion", title: "Name\nthe timer", file: "src/x.js\nsrc/y.js" }];
@@ -489,6 +513,17 @@ test("loopEnd: a short reason and a recommended button are stored, and both stay
assert.deepEqual(tryPatch(loopState(), { loopEnd: goodEnd() }).problems, [], "an older app sends neither");
});
test("loopEnd: the advice for the person is stored, optional, one line of up to 300 characters", () => {
const { problems, next } = tryPatch(loopState(), { loopEnd: goodEnd({ advice: "Fix the failing test, then press Continue building." }) });
assert.deepEqual(problems, []);
assert.equal(next.loopEnd.advice, "Fix the failing test, then press Continue building.");
assert.deepEqual(tryPatch(loopState(), { loopEnd: goodEnd() }).problems, [], "an older app sends none");
for (const advice of ["one\ntwo", "a".repeat(301), ""]) {
const bad = tryPatch(loopState(), { loopEnd: goodEnd({ advice }) });
assert.ok(bad.problems.some((p) => /loopEnd\.advice must be one line of 1 to 300 characters/.test(p)), JSON.stringify(bad.problems));
}
});
test("loopEnd: an unknown evidence id, a push in can, and the other bad fields are refused, each named", () => {
const cases = [
["an unknown evidence id", goodEnd({ evidence: "nope" }), /loopEnd\.evidence must be the id of a doc on the page/],
+485
View File
@@ -0,0 +1,485 @@
// Page tests for Learning on the dashboard: the row in its four states and two
// places, the paused tint, Pause for me with no agent, the More menu, the
// waiting banner and the controls that gray out when no agent can answer; and
// the lessons card: each row's own choices, Reword, a refused row, a flagged
// row, the first ask, Review from the banner and the loop stop card's line. Run
// with: node --test scripts/test-web-console-page-learning.mjs
//
// Each test drives the real console in a real Chrome or Edge through
// scripts/page-test-helpers.mjs, in a throwaway project whose
// .plan2code/settings.json sets the state.
import test from "node:test";
import assert from "node:assert/strict";
import { pageSuite, openSession, tempProject, textOf, styleOf, stylesOf, itemCard, sendAndCollect, settled } from "./page-test-helpers.mjs";
import { cli, until } from "./web-console-test-helpers.mjs";
import { writePause, writeWaiting } from "../src/web-console/learning.mjs";
const suite = pageSuite(test);
const SETTINGS = (learning) => ({ ".plan2code/settings.json": JSON.stringify({ format: 1, learning }) + "\n" });
const PROJECT = (learning) => ({ "AGENTS.md": "# AGENTS.md\n\nA small demo project.\n", ...(learning ? SETTINGS(learning) : {}) });
const MENU = { menu: { note: "Nothing on disk yet." }, agent: { status: "waiting" } };
// The dashboard as a person first sees it, past the intro and the Welcome.
async function toTheMenu(s) {
const skip = s.page.getByRole("button", { name: "Skip the intro" });
await skip.click();
await skip.waitFor({ state: "hidden" });
const main = s.page.locator("#main");
await main.getByRole("heading", { name: "What are we doing today?" }).waitFor();
const welcomeDone = s.page.getByRole("button", { name: "Start building" });
if (await welcomeDone.isVisible()) {
await welcomeDone.click();
await welcomeDone.waitFor({ state: "hidden" });
}
return main;
}
async function dashboard(t, files, before) {
const project = tempProject(files);
if (before) before(project);
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project });
const main = await toTheMenu(s);
return { s, main, project };
}
// Where the row sits among the dashboard's own blocks, read in one go.
const placeOf = (main) =>
main.locator(".dash").evaluate((dash) => {
const kids = [...dash.children];
const at = (sel) => kids.findIndex((k) => k.matches(sel));
const groups = kids.map((k, i) => (k.matches("section.dash-group") ? i : -1)).filter((i) => i >= 0);
return {
row: at("section.learn-row"),
rows: dash.querySelectorAll("section.learn-row").length,
toggle: at("label.dash-toggle"),
firstGroup: groups[0],
lastGroup: groups[groups.length - 1],
tip: at(".approval-tip"),
};
});
for (const [state, pill] of [
["not-set-up", "Not set up"],
["off", "Off"],
]) {
test(`${state}: the row sits under the picker with its pill and Switch on`, async (t) => {
const { main } = await dashboard(t, PROJECT(state === "not-set-up" ? null : state));
const row = main.locator("section.learn-row");
await row.waitFor();
const where = await placeOf(main);
assert.equal(where.rows, 1);
assert.equal(where.row, where.toggle + 1, "directly after the hide-unavailable toggle");
assert.ok(where.row < where.firstGroup, "above the card groups");
assert.equal((await row.locator(".learn-pill").textContent()).trim(), pill);
assert.equal(await row.getByRole("button", { name: "Switch on" }).isEnabled(), true);
if (state === "not-set-up") {
assert.match(await textOf(row), /Plan2Code can keep lessons about this codebase, approved by you\./);
}
});
}
test("paused: the row is under the picker, amber, and says since when", async (t) => {
const { main } = await dashboard(t, PROJECT("on"), (p) => writePause(p, true, "2026-11-13T12:00:00.000Z"));
const row = main.locator("section.learn-row");
await row.waitFor();
const where = await placeOf(main);
assert.equal(where.row, where.toggle + 1);
assert.equal((await row.locator(".learn-pill").textContent()).trim(), "Paused for you");
assert.match(await textOf(row), /Paused since Nov 1[23]/);
const sw = row.getByRole("switch", { name: "Pause for me" });
assert.equal(await sw.getAttribute("aria-checked"), "true");
// The amber tint: the line's border and the pill share the hold color, and
// the line has a background the plain row does not.
const line = row.locator(".learn-line");
const looks = await stylesOf(line, ["border-top-color", "background-color"]);
assert.equal(looks["border-top-color"], await styleOf(row.locator(".learn-pill"), "color"));
assert.notEqual(looks["background-color"], "rgba(0, 0, 0, 0)");
});
test("on: the row is after the last card group, before the tip, with no count of saved lessons", async (t) => {
const { main } = await dashboard(t, {
...PROJECT("on"),
".plan2code/lessons/general.md": "# General\n\n- One.\n- Two.\n- Three.\n",
});
const row = main.locator("section.learn-row");
await row.waitFor();
const where = await placeOf(main);
assert.equal(where.row, where.lastGroup + 1, "after the last card group");
assert.equal(where.tip, where.row + 1, "before the approval tip");
const text = await textOf(row);
assert.equal((await row.locator(".learn-pill").textContent()).trim(), "On");
assert.doesNotMatch(text, /\d/, `no count in the row: ${text}`);
assert.equal(await main.getByText(/\d+\s+(saved\s+)?lessons?\s+(saved|kept)/i).count(), 0, "no count anywhere");
await row.getByRole("button", { name: "Open the lessons" }).click();
const dlg = main.page().locator("#learn-lessons-modal");
await dlg.getByText("General", { exact: true }).first().waitFor();
assert.match(await textOf(dlg), /The project's lessons \(\.plan2code\/lessons\/, saved with the repository\)/);
});
test("Pause for me repaints the row with no agent listening, both ways", async (t) => {
const { s, main } = await dashboard(t, PROJECT("on"));
const bottom = main.locator("section.learn-row.is-bottom");
await bottom.getByRole("switch", { name: "Pause for me" }).click();
// Nothing collects a send here: the server saved the pause and pushed the scan.
const top = main.locator("section.learn-row.is-top.is-paused");
await top.waitFor();
assert.equal(await bottom.count(), 0);
assert.equal(await top.getByRole("switch").getAttribute("aria-checked"), "true");
await top.getByRole("switch", { name: "Pause for me" }).click();
await main.locator("section.learn-row.is-bottom.is-on").waitFor();
assert.equal(s.wait(1).code, 10, "no send reached the agent");
});
test("More opens upward and closes on Escape and on a click outside", async (t) => {
const { s, main } = await dashboard(t, PROJECT("on"));
const row = main.locator("section.learn-row.is-bottom");
const more = row.getByRole("button", { name: /More/ });
const menu = row.getByRole("menu");
assert.equal(await menu.isVisible(), false);
await more.click();
await menu.waitFor();
assert.equal(await more.getAttribute("aria-expanded"), "true");
const [m, b] = [await menu.boundingBox(), await more.boundingBox()];
assert.ok(m.y + m.height <= b.y + 1, `the menu opens above its button: ${JSON.stringify({ m, b })}`);
assert.deepEqual(await menu.getByRole("menuitem").allInnerTexts(), [
"Switch off for this project",
"Move the failure log into lessons",
"Remove all lessons…",
]);
// Keyboard reachable: the first item has focus, and the arrows move it.
await until(async () => (await menu.getByRole("menuitem").first().evaluate((n) => n === document.activeElement)), 2000);
await s.page.keyboard.press("ArrowDown");
assert.equal(await menu.getByRole("menuitem").nth(1).evaluate((n) => n === document.activeElement), true);
await s.page.keyboard.press("Escape");
await menu.waitFor({ state: "hidden" });
await more.click();
await menu.waitFor();
await main.getByRole("heading", { name: "What are we doing today?" }).click();
await menu.waitFor({ state: "hidden" });
});
test("Remove all lessons asks in the page first, then sends the Learning action", async (t) => {
const { s, main } = await dashboard(t, PROJECT("on"));
const row = main.locator("section.learn-row.is-bottom");
await row.getByRole("button", { name: /More/ }).click();
await row.getByRole("menuitem", { name: "Remove all lessons…" }).click();
const dlg = s.page.locator("#learn-remove-modal");
await dlg.waitFor();
assert.match(await textOf(dlg), /Remove all saved lessons from this project\? Learning stays on\./);
await dlg.getByRole("button", { name: "Remove all lessons" }).click();
const got = s.wait(10);
assert.equal(got.code, 0, "the send reached the agent");
assert.deepEqual(got.actions, [{ i: "__learning", type: "learning", do: "remove" }]);
});
test("the banner shows only with lessons waiting, directly above the title", async (t) => {
const noted = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000 - 60000).toISOString();
const { s, main } = await dashboard(t, PROJECT("on"), (p) => {
writeWaiting(p, { id: "20261111-120000-cccccc", type: "lesson", text: "A lesson.", noted });
writeWaiting(p, { id: "20261112-120000-cccccc", type: "lesson", text: "Another.", noted: new Date().toISOString() });
});
const banner = main.locator(".learn-banner");
await banner.waitFor();
assert.equal(await banner.getAttribute("role"), "status");
assert.match(await textOf(banner), /2 lessons are waiting for your review \(oldest 2 days\)/);
const order = await banner.evaluate((n) => [n.nextElementSibling.className, n.nextElementSibling.nextElementSibling.className]);
assert.deepEqual(order, ["card-kicker", "dash-title"], "nothing between the banner and the title");
await banner.getByRole("button", { name: "Review" }).click();
const got = s.wait(10);
assert.equal(got.code, 0);
assert.deepEqual(got.actions, [{ i: "__learning", type: "learning", do: "review" }]);
const quiet = await dashboard(t, PROJECT("on"));
await quiet.main.locator("section.learn-row").waitFor();
assert.equal(await quiet.main.locator(".learn-banner").count(), 0, "no banner with nothing waiting");
const paused = await dashboard(t, PROJECT("on"), (p) => {
writePause(p, true);
writeWaiting(p, { id: "20261112-120000-dddddd", type: "lesson", text: "Waits.", noted: new Date().toISOString() });
});
await paused.main.locator("section.learn-row.is-paused").waitFor();
assert.equal(await paused.main.locator(".learn-banner").count(), 0, "hidden while paused");
});
test("a launch from a dashboard showing lessons waiting carries fromBanner", async (t) => {
const { s, main } = await dashboard(t, PROJECT("on"), (p) =>
writeWaiting(p, { id: "20261113-120000-eeeeee", type: "lesson", text: "Waits.", noted: new Date().toISOString() })
);
await main.locator(".learn-banner").waitFor();
const card = main.getByRole("button").filter({ has: s.page.locator("code", { hasText: /^\/plan2code-1-plan$/ }) });
await card.click();
await main.getByRole("button", { name: "Start Plan" }).click();
const got = s.wait(10);
assert.equal(got.code, 0);
const launch = got.actions.find((a) => a.i === "__launch");
assert.equal(launch.fromBanner, true);
});
test("agent-run controls gray out while the page has lost the console", async (t) => {
const { s, main } = await dashboard(t, PROJECT(null));
const row = main.locator("section.learn-row");
const on = row.getByRole("button", { name: "Switch on" });
assert.equal(await on.isEnabled(), true);
cli(["stop", "--session", s.sid, "--force"], { cwd: s.project });
await s.page.waitForFunction(() => document.getElementById("planny").classList.contains("is-gone"), null, { timeout: 20000 });
await until(async () => !(await on.isEnabled()), 5000);
assert.equal(await on.isEnabled(), false);
assert.ok((await on.getAttribute("title")) || "", "the grayed control says why");
});
/* ------------------------------------------------------ the lessons card */
// One row of each type, as lessons.mjs list's card gives them.
const ROWS = [
{ id: "w-lesson", type: "lesson", text: "Run a page test alone first.", why: "A full run hides the race.", origin: "You said this.", note: "", flags: [], refused: null, area: "General", areas: ["General", "Web console"], kind: "command", about: ["scripts/node-test.mjs"], choices: ["Keep", "Reword", "Drop"] },
{ id: "w-doubt", type: "doubt", heading: "This lesson may no longer be true:", text: "The handler does one thing.", found: "It now does three.", why: "", origin: "This lesson may no longer be true: It now does three.", note: "", flags: [], refused: null, area: "General", areas: ["General"], choices: ["Keep", "Reword", "Retire"] },
{ id: "w-fix", type: "agents-fix", file: "AGENTS.md", before: "Run npm test.", after: "Run the targeted suites.", text: "Run the targeted suites.", why: "", origin: "A fix to AGENTS.md, replacing: Run npm test.", note: "", flags: [], refused: null, area: "", choices: ["Apply", "Reword", "Drop"] },
{ id: "log:abc", type: "log-line", text: "Never fix CRLF by hand.", lessons: ["Run npm run fix:eol for line endings."], why: "", origin: "From the failure log in AGENTS.md.", note: "", flags: [], refused: null, area: "", choices: ["Move", "Reword and move", "Leave in the log"] },
{ id: "w-area", type: "area", text: "Activities", name: "Activities", paths: ["src/web-console/public/activities/**"], why: "Paths: src/web-console/public/activities/**", origin: "", note: "Noted on feature/x.", flags: [], refused: null, area: "Activities", choices: ["Create", "Rename", "Drop"] },
];
const CARD = (rows = ROWS, extra = {}) => ({
id: "lessons",
kind: "lessons",
title: "Lessons to keep",
body: "Choose for each one. Nothing is kept unless you choose it, and anything you leave keeps waiting.",
opening: null,
rows,
...extra,
});
async function lessonsCard(t, card = CARD()) {
const s = await openSession(await suite.browser(), { t, workflow: "review", payload: { items: [card], agent: { status: "waiting" } } });
const c = itemCard(s.page, card.id);
await c.locator(card.firstAsk ? ".lessons-first-lesson" : ".lessons-row").first().waitFor();
await settled(s.page, "#main");
return { s, card: c };
}
const rowOf = (card, id) => card.locator(`.lessons-row[data-row="${id}"]`);
const choicesOf = (row) => row.locator(".lessons-choices button");
const replyLines = (got) => got.reply.split("\n").map((l) => l.trim());
test("lessons card: each row shows its own choice words, and nothing is chosen", async (t) => {
const { card } = await lessonsCard(t);
const want = {
"w-lesson": ["Keep", "Reword", "Drop"],
"w-doubt": ["Keep", "Reword", "Retire"],
"w-fix": ["Apply", "Reword", "Drop"],
"log:abc": ["Move", "Reword and move", "Leave in the log"],
"w-area": ["Create", "Rename", "Drop"],
};
for (const [id, words] of Object.entries(want)) {
const row = rowOf(card, id);
assert.deepEqual(await choicesOf(row).allInnerTexts(), words, id);
assert.deepEqual(await choicesOf(row).evaluateAll((bs) => bs.map((b) => b.getAttribute("aria-pressed"))), words.map(() => "false"), `${id}: nothing chosen`);
assert.equal(await row.locator(".lessons-choices").getAttribute("role"), "group", `${id}: its choices are a group`);
}
const doubt = await textOf(rowOf(card, "w-doubt"));
assert.match(doubt, /This lesson may no longer be true:/);
assert.match(doubt, /It now does three\./);
assert.match(await textOf(rowOf(card, "w-fix")), /Before\s+Run npm test\.\s+After\s+Run the targeted suites\./i);
assert.match(await textOf(rowOf(card, "log:abc")), /It would become this lesson:\s+Run npm run fix:eol for line endings\./);
assert.match(await textOf(rowOf(card, "w-lesson")), /You said this\./);
assert.match(await textOf(rowOf(card, "w-area")), /Noted on feature\/x\./);
});
test("lessons card: Keep on one row sends only that row, and the rest are left waiting", async (t) => {
const { s, card } = await lessonsCard(t);
await rowOf(card, "w-lesson").getByRole("button", { name: "Keep" }).click();
await card.locator(".lessons-summary", { hasText: "1 chosen, 4 left waiting." }).waitFor();
assert.equal(await rowOf(card, "w-lesson").getByRole("button", { name: "Keep" }).getAttribute("aria-pressed"), "true");
const got = await sendAndCollect(s);
assert.deepEqual(got.actions.find((a) => a.i === "lessons").decisions, [{ id: "w-lesson", choice: "Keep" }]);
assert.ok(replyLines(got).includes("Keep: Run a page test alone first."), got.reply);
assert.match(got.reply, /1 decided, 4 left waiting/);
await itemCard(s.page, "lessons").locator(".answered-values", { hasText: "4 left waiting" }).waitFor();
});
test("lessons card: a choice keeps the keyboard on its button, and a note typed beside a Reword goes with the answer", async (t) => {
const { s, card } = await lessonsCard(t);
const keep = rowOf(card, "w-doubt").getByRole("button", { name: "Keep" });
await keep.focus();
await s.page.keyboard.press("Enter");
await rowOf(card, "w-doubt").getByRole("button", { name: "Keep", pressed: true }).waitFor();
assert.equal(await s.page.evaluate(() => document.activeElement && document.activeElement.textContent), "Keep", "focus stays on the pressed choice");
await s.page.keyboard.press("Tab");
assert.equal(await s.page.evaluate(() => document.activeElement && document.activeElement.textContent), "Reword", "Tab moves on within the row");
await rowOf(card, "w-lesson").getByRole("button", { name: "Reword" }).click();
const text = rowOf(card, "w-lesson").getByLabel("The lesson");
await text.waitFor();
const note = card.locator(".md-host .cm-content").last();
await note.click();
await note.pressSequentially("Checked with the team.");
await text.fill("");
await text.fill("Run one page test file alone.");
const got = await sendAndCollect(s);
const action = got.actions.find((a) => a.i === "lessons");
assert.equal(action.text, "Checked with the team.", "the note survived the emptied field");
assert.equal(action.decisions.find((d) => d.id === "w-lesson").text, "Run one page test file alone.");
});
test("lessons card: choosing again clears a row, and Leave them all waiting sends nothing chosen", async (t) => {
const { s, card } = await lessonsCard(t);
await rowOf(card, "w-lesson").getByRole("button", { name: "Keep" }).click();
await rowOf(card, "w-lesson").getByRole("button", { name: "Keep", pressed: true }).waitFor();
await rowOf(card, "w-lesson").getByRole("button", { name: "Keep" }).click();
await rowOf(card, "w-lesson").getByRole("button", { name: "Keep", pressed: false }).waitFor();
await card.getByRole("button", { name: "Leave them all waiting" }).click();
await card.getByRole("button", { name: "Leave them all waiting", pressed: true }).waitFor();
const got = await sendAndCollect(s);
assert.deepEqual(got.actions.find((a) => a.i === "lessons").decisions, []);
assert.match(got.reply, /0 decided, 5 left waiting/);
});
test("lessons card: Reword edits the sentence and the area, and the answer carries them", async (t) => {
const { s, card } = await lessonsCard(t);
await rowOf(card, "w-lesson").getByRole("button", { name: "Reword" }).click();
const edit = rowOf(card, "w-lesson").locator(".lessons-edit");
await edit.waitFor();
const text = edit.getByLabel("The lesson");
assert.equal(await text.inputValue(), "Run a page test alone first.", "it opens on the row's own words");
await text.fill("");
await card.locator(".lessons-error", { hasText: "The lesson is empty" }).waitFor();
assert.equal(await s.page.locator("#btn-send").isDisabled(), true, "an empty lesson keeps Send off");
await text.fill("Run one page test file alone before the full run.");
await edit.getByLabel("Saved in").selectOption("Web console");
assert.equal(await card.locator(".lessons-error").isHidden(), true);
const got = await sendAndCollect(s);
assert.deepEqual(got.actions.find((a) => a.i === "lessons").decisions, [
{ id: "w-lesson", choice: "Reword", text: "Run one page test file alone before the full run.", why: "A full run hides the race.", area: "Web console" },
]);
assert.ok(replyLines(got).includes("Reword: Run one page test file alone before the full run."), got.reply);
});
test("lessons card: a refused row's Keep stays off until Reword changes its words", async (t) => {
const refusedRow = { ...ROWS[0], id: "w-bad", text: "The key is AKIA…", refused: { pattern: "aws-access-key", part: "AKIA" }, choices: ["Reword", "Drop"] };
const { s, card } = await lessonsCard(t, CARD([refusedRow]));
const row = rowOf(card, "w-bad");
assert.match(await textOf(row), /Refused: part of it looks like a secret \(it starts “AKIA”\)/);
assert.equal(await row.getByRole("button", { name: "Keep" }).isDisabled(), true);
await row.getByRole("button", { name: "Reword" }).click();
const text = row.getByLabel("The lesson");
await text.waitFor();
assert.equal(await row.getByRole("button", { name: "Keep" }).isDisabled(), true, "unchanged words keep it off");
await text.fill("Keys live in the team vault, never in the code.");
await until(async () => !(await row.getByRole("button", { name: "Keep" }).isDisabled()), 3000);
await row.getByRole("button", { name: "Keep" }).click();
await row.getByRole("button", { name: "Keep", pressed: true }).waitFor();
const got = await sendAndCollect(s);
assert.deepEqual(got.actions.find((a) => a.i === "lessons").decisions, [
{ id: "w-bad", choice: "Reword", text: "Keys live in the team vault, never in the code.", why: "A full run hides the race." },
]);
});
test("lessons card: a refused row's Keep still chooses after its words go back and are reworded again", async (t) => {
const refusedRow = { ...ROWS[0], id: "w-bad", text: "The key is AKIA…", refused: { pattern: "aws-access-key", part: "AKIA" }, choices: ["Reword", "Drop"] };
const { s, card } = await lessonsCard(t, CARD([refusedRow]));
const row = rowOf(card, "w-bad");
const keep = () => row.getByRole("button", { name: "Keep" });
await row.getByRole("button", { name: "Reword" }).click();
const text = row.getByLabel("The lesson");
await text.waitFor();
await text.fill("Keys live in the team vault.");
await until(async () => !(await keep().isDisabled()), 3000);
await keep().click();
await row.getByRole("button", { name: "Keep", pressed: true }).waitFor();
// Back to the refused words: Keep cannot stand, and the row goes back to Reword without a redraw.
await text.fill("The key is AKIA…");
await row.getByRole("button", { name: "Reword", pressed: true }).waitFor();
assert.equal(await keep().isDisabled(), true);
await text.fill("Keys live in the team vault, never in the code.");
await until(async () => !(await keep().isDisabled()), 3000);
await keep().click();
await row.getByRole("button", { name: "Keep", pressed: true }).waitFor();
assert.equal(await row.getByLabel("The lesson").count(), 1, "the row stays open, chosen");
const got = await sendAndCollect(s);
assert.deepEqual(got.actions.find((a) => a.i === "lessons").decisions, [
{ id: "w-bad", choice: "Reword", text: "Keys live in the team vault, never in the code.", why: "A full run hides the race." },
]);
});
test("lessons card: a flagged row says what was flagged", async (t) => {
const flagged = { ...ROWS[0], id: "w-flag", flags: [{ pattern: "email", part: "a@b.c" }] };
const { card } = await lessonsCard(t, CARD([flagged]));
const flag = rowOf(card, "w-flag").locator(".lessons-flag");
assert.equal(await textOf(flag), "Holds what looks like an email address (“a@b.c”). Keep only if that is intended.");
assert.notEqual(await styleOf(flag, "background-color"), "rgba(0, 0, 0, 0)", "the warning stands out from the row");
});
test("lessons card: the first ask shows the lesson before what Learning is, and answers yes", async (t) => {
const firstAsk = {
lesson: { id: "w1", text: "Run a page test alone first.", why: "A full run hides the race.", kind: "command" },
sentences: ["Plan2Code can keep lessons like this with the repository.", "Nothing is saved without your approval.", "Lessons are about the code, never about you."],
yes: "Switch Learning on",
no: "Not for this project",
later: "You can change this later on the dashboard.",
};
const { s, card } = await lessonsCard(t, { id: "first-ask", kind: "lessons", title: "Keep lessons?", firstAsk });
const order = await card.evaluate((c) => {
const all = [...c.querySelectorAll("*")];
return { lesson: all.indexOf(c.querySelector(".lessons-first-lesson")), about: all.indexOf(c.querySelector(".lessons-first-about")) };
});
assert.ok(order.lesson >= 0 && order.lesson < order.about, `the lesson comes first: ${JSON.stringify(order)}`);
assert.equal(await card.locator(".lessons-row").count(), 0, "no rows yet");
assert.match(await textOf(card), /You can change this later on the dashboard\./);
await card.getByRole("button", { name: "Switch Learning on" }).click();
await card.getByRole("button", { name: "Switch Learning on", pressed: true }).waitFor();
const got = await sendAndCollect(s);
assert.equal(got.actions.find((a) => a.i === "first-ask").firstAsk, "yes");
assert.match(got.reply, /Keep lessons\?: Switch Learning on/);
});
test("lessons card: Review on the banner leads to the card over the dashboard, with no skill launched", async (t) => {
const { s, main } = await dashboard(t, PROJECT("on"), (p) =>
writeWaiting(p, { id: "20261113-120000-ffffff", type: "lesson", text: "Run a page test alone first.", noted: new Date().toISOString() })
);
await main.locator(".learn-banner").getByRole("button", { name: "Review" }).click();
const got = s.wait(10);
assert.deepEqual(got.actions, [{ i: "__learning", type: "learning", do: "review" }]);
// The dashboard agent posts the card from lessons.mjs list, still as the dashboard.
s.post({ items: [CARD([{ ...ROWS[0], id: "20261113-120000-ffffff" }])], agent: { status: "waiting" } });
const dlg = s.page.locator("#lessons-modal");
await dlg.locator(".lessons-row").waitFor();
assert.equal(await main.getByRole("heading", { name: "What are we doing today?" }).count(), 1, "the menu stays under it");
assert.equal(await dlg.getByRole("button", { name: "Send to Plan2Code" }).isDisabled(), true, "nothing chosen yet");
// An emptied Reword field holds the dialog's Send off, as the footer's Send is held elsewhere.
await dlg.getByRole("button", { name: "Reword" }).click();
const text = dlg.getByLabel("The lesson");
await text.waitFor();
assert.equal(await dlg.getByRole("button", { name: "Send to Plan2Code" }).isDisabled(), false, "a reword ready to go");
await text.fill("");
await until(async () => await dlg.getByRole("button", { name: "Send to Plan2Code" }).isDisabled(), 3000);
await dlg.getByRole("button", { name: "Keep" }).click();
await dlg.getByRole("button", { name: "Keep", pressed: true }).waitFor();
await dlg.getByRole("button", { name: "Send to Plan2Code" }).click();
const sent = s.wait(10);
assert.equal(sent.code, 0);
assert.equal(sent.actions.some((a) => a.i === "__launch"), false, "no skill launched");
assert.deepEqual(sent.actions.find((a) => a.i === "lessons").decisions, [{ id: "20261113-120000-ffffff", choice: "Keep" }]);
await dlg.waitFor({ state: "hidden" });
// The agent runs decide and posts the menu back, waiting again: the answered card stays closed.
s.post({ menu: { note: "Kept 1 lesson." }, agent: { status: "waiting" } });
await main.getByText("Kept 1 lesson.").waitFor();
assert.equal(await dlg.isVisible(), false, "the answered card does not open again");
});
test("the loop stop card says when lessons are waiting", async (t) => {
const project = tempProject(PROJECT("on"));
writeWaiting(project, { id: "20261113-120000-999999", type: "lesson", text: "Waits.", noted: new Date().toISOString() });
const s = await openSession(await suite.browser(), {
t,
workflow: "implement",
open: ["--loop"],
env: { PLAN2CODE_IN_APP: "1" },
payload: { title: "demo: Phase 1", headline: { stage: "Build", cleared: 1, total: 2 }, agent: { status: "working", activity: "Task 2 of 2" } },
project,
});
s.post({ loopEnd: { kind: "stopped", line: "Phase 2 stopped", phases: [], uncommitted: [], can: ["dashboard"] }, agent: { status: "waiting" } });
const line = s.page.locator(".loop-end .loop-lessons");
await line.waitFor();
assert.equal(await textOf(line), "1 lesson is waiting for your review. Open the dashboard to review them.");
});
+41
View File
@@ -328,6 +328,47 @@ test("a stopped loop leads with its short reason and puts the long line under it
assert.equal(old.heading, HARD_STOP.line, "an older app without a reason keeps its line as the heading");
});
test("a stop shows why in a danger strip and what to do next under it, before the buttons", async (t) => {
const s = await openSetup(t);
const advice = "Fix the unreadable range in deps.mjs, then press Continue building.";
const seen = await s.page.evaluate(async (end) => {
const m = await import(new URL("screens/ending.js", document.baseURI).href);
const card = m.renderLoopEnd(end);
const why = card.querySelector(".loop-why");
const next = card.querySelector(".loop-advice");
const order = [...card.children].map((c) => c.className || c.tagName);
return { why: why?.textContent ?? null, next: next?.textContent ?? null, order };
}, { ...HARD_STOP, advice });
assert.equal(seen.why, HARD_STOP.line, "the reason strip holds the full line");
assert.equal(seen.next, `What to do next: ${advice}`);
const at = (cls) => seen.order.findIndex((c) => String(c).includes(cls));
assert.ok(at("loop-why") < at("loop-advice") && at("loop-advice") < at("loop-end-actions"), seen.order.join(" > "));
const old = await drawStop(s, { ...HARD_STOP, reason: undefined, advice: undefined });
assert.equal(old.line, null, "an older app without a reason keeps its line as the heading and draws no strip");
const finished = await s.page.evaluate(async () => {
const m = await import(new URL("screens/ending.js", document.baseURI).href);
const card = m.renderLoopEnd({ kind: "finished", line: "All 1 phases built", phases: [], uncommitted: [], can: ["finalize", "dashboard"], advice: "never shown" });
return Boolean(card.querySelector(".loop-why, .loop-advice"));
});
assert.equal(finished, false, "a finish has no reason to give");
});
test("a doc blockquote opening with [!CAUTION] or [!TIP] becomes a colored alert box with the marker removed", async (t) => {
const s = await openSetup(t);
const seen = await s.page.evaluate(async () => {
const { md } = await import(new URL("render.js", document.baseURI).href);
const root = md("> [!CAUTION]\n> **Why it stopped:** a test failed\n\n> [!TIP]\n> **What to do next:** fix it\n\n> a plain quote");
const boxes = [...root.querySelectorAll("blockquote")].map((q) => ({ cls: q.className, text: q.textContent.trim() }));
return boxes;
});
assert.equal(seen.length, 3);
assert.ok(seen[0].cls.includes("md-alert") && seen[0].cls.includes("md-alert-caution"), seen[0].cls);
assert.ok(seen[1].cls.includes("md-alert-tip"), seen[1].cls);
assert.equal(seen[2].cls, "md-quote", "an ordinary quote is unchanged");
assert.equal(seen[0].text.includes("[!CAUTION]"), false, "the marker is not shown");
assert.ok(seen[0].text.startsWith("Why it stopped: a test failed"), seen[0].text);
});
test("every stop-screen button carries one plain line saying what it does", async (t) => {
const s = await openSetup(t);
const seen = await drawStop(s, HARD_STOP);
+12
View File
@@ -155,6 +155,17 @@ test("pointer: __review names building-review.md", async () => {
}
});
test("pointer: __learning names console-launches.md", async () => {
const s = fresh({ workflow: "dashboard", items: [], menu: { note: "Nothing yet." } });
try {
const { out } = await send(s, [{ i: "__learning", type: "learning", do: "switch-on" }]);
assert.deepEqual(out.read, [file("console-launches.md")]);
assert.deepEqual(out.session, [{ i: "__learning", do: "switch-on" }], "the action reaches the agent whole");
} finally {
done(s);
}
});
test("pointer: a review card answered with a verdict names building-review.md", async () => {
const s = fresh({ workflow: "implement" });
try {
@@ -252,6 +263,7 @@ test("pointersForSend: the whole table", () => {
assert.deepEqual(pointersForSend(act({ i: "__stop" }), empty, noFlags), ["stop"]);
assert.deepEqual(pointersForSend(act({ i: "__stop", handoff: true }), empty, noFlags), ["stop"]);
assert.deepEqual(pointersForSend(act({ i: "__review" }), empty, noFlags), ["review"]);
assert.deepEqual(pointersForSend(act({ i: "__learning", type: "learning", do: "remove" }), empty, noFlags), ["learning"]);
const reviewCard = { items: [{ id: "signoff", kind: "review" }] };
assert.deepEqual(pointersForSend(act({ i: "signoff", type: "answer", verdict: "review" }), reviewCard, noFlags), ["review"]);
assert.deepEqual(pointersForSend(act({ i: "signoff", type: "answer", answer: { verdict: "approve" } }), reviewCard, noFlags), ["review"]);
+5 -1
View File
@@ -469,6 +469,10 @@ test("cleanup finds old sessions and strays in both folders, and keeps every pro
// 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);
@@ -485,7 +489,7 @@ test("cleanup finds old sessions and strays in both folders, and keeps every pro
"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"]) assert.equal(items.some((i) => i.id === id), false, `${id} 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");
+6 -3
View File
@@ -693,16 +693,18 @@ test("the favicon is served as an SVG with a PNG fallback and the page points at
/* ---------------------------------------------------------------- help */
test("help: 21 tabs with unique ids", () => {
assert.equal(HELP_TABS.length, 21);
assert.equal(new Set(HELP_TABS.map((t) => t.id)).size, 21);
test("help: 23 tabs with unique ids", () => {
assert.equal(HELP_TABS.length, 23);
assert.equal(new Set(HELP_TABS.map((t) => t.id)).size, 23);
assert.ok(Object.isFrozen(HELP_TABS) && HELP_TABS.every((t) => Object.isFrozen(t)), "the tab list is frozen");
const ids = HELP_TABS.map((t) => t.id);
assert.equal(ids.indexOf("learning"), ids.indexOf("dashboard") + 1, "Learning comes right after The dashboard");
assert.equal(ids.indexOf("loop"), ids.indexOf("build") + 1, "Implementation Loop comes right after Watching a build");
assert.equal(HELP_TABS[ids.indexOf("loop")].label, "Implementation Loop");
assert.equal(ids.indexOf("git"), ids.indexOf("loop") + 1, "The git board comes right after Implementation Loop");
assert.equal(HELP_TABS[ids.indexOf("git")].label, "The git board");
assert.equal(helpTabFor({ workflow: "git" }), "git");
assert.equal(ids.indexOf("deps"), ids.indexOf("git") + 1, "Update dependencies comes right after The git board");
assert.equal(ids.indexOf("activities"), ids.indexOf("ask") + 1, "Activities comes right after Ask a quick question");
assert.equal(HELP_TABS[ids.indexOf("activities")].label, "Activities");
const tpl = helpTemplate();
@@ -800,6 +802,7 @@ test("help: helpTabFor opens on the tab for where the person is", () => {
[{ workflow: "quick-task" }, "build"],
[{ workflow: "git" }, "git"],
[{ workflow: "git", view: "ask" }, "ask"],
[{ workflow: "deps" }, "deps"],
[{ workflow: "git", dashboard: true }, "dashboard"],
[{ workflow: "plan", view: "questions" }, "about"],
[{ view: undefined }, "about"],
+1 -1
View File
@@ -189,7 +189,7 @@ test("shape: no page module sets a style attribute from script", () => {
// no routes of its own: its buttons are sends (`__git`), through /submit.
const ROUTE_ORDER = [
"/health", "/s/", "/handover", "/", "SERVABLE", "/overview", "/agents-doc", "/prototypes", "/prototype", "/handoff", "/version", "/state", "/events", "/draft",
"/looks", "/looks", "/subagents", "/pr-host", "/models", "/models", "/agents", "/agents", "/agents/test", "/agents/use-path", "/cleanup", "/upload",
"/looks", "/looks", "/subagents", "/learning/pause", "/learning/state", "/learning/lessons", "/pr-host", "/models", "/models", "/agents", "/agents", "/agents/test", "/agents/use-path", "/cleanup", "/upload",
"/notepad", "/notepad/text", "/notepad/image", "/notepad/thumb", "/notepad/image/delete", "/notepad/tab",
"/notepad/tab/rename", "/notepad/tab/delete", "/notepad/tab/order", "/notepad/tab/last", "/notepad/tab/sent", "/notepad/images/",
"/attachments/", "/shots/", "/uploads/", "/submit", "/open-link", "/open-prototype", "/chat", "/chat/decision", "/workspace",
+1 -1
View File
@@ -498,7 +498,7 @@ test("every console workflow has its notes, and its skill's Interface reads them
init: "init", "init-update": "init", pathfinder: "pathfinder", plan: "plan", "revise-plan": "revise-plan",
document: "document", implement: "implement", "implement-review": "implement", "quick-task": "quick-task",
review: "review", finalize: "finalize", handoff: "handoff", changelog: "changelog", git: "git", xray: "xray",
diagnose: "diagnose", "pr-prep": "pr-prep", test: "test", "dead-code": "dead-code", "ui-prototype": "ui-prototype",
diagnose: "diagnose", "pr-prep": "pr-prep", test: "test", "dead-code": "dead-code", deps: "deps", "ui-prototype": "ui-prototype",
};
const skills = fs.readdirSync(path.join(ROOT, "src")).filter((f) => /^plan2code(-.*)?\.md$/.test(f));
for (const f of skills) {
+5 -1
View File
@@ -55,6 +55,10 @@ export const HANDOFFS_DIR = path.join(HOME, "handoffs");
// real folder (notepadsDir() reads the variable on every call).
export const NOTEPADS_DIR = path.join(HOME, "notepads");
process.env.PLAN2CODE_NOTEPADS_DIR = NOTEPADS_DIR;
// Learning's store on this machine (~/.plan2code/learning) likewise, set for
// this process too so a test importing learning.mjs never reaches the real one.
export const LEARNING_DIR = path.join(HOME, "learning");
process.env.PLAN2CODE_LEARNING_DIR = LEARNING_DIR;
// A spawned console server or CLI must not inherit relocation vars (an
// exported GIT_DIR would redirect the board's reads), SSH markers (they set
// `remote` in open output) or leftover PLAN2CODE_* knobs.
@@ -78,7 +82,7 @@ for (const k of AMBIENT_ENV_KEYS) delete scrubbed[k];
// cannot open. An empty file is the portable "no global config".
const EMPTY_GITCONFIG = path.join(HOME, "empty-gitconfig");
fs.writeFileSync(EMPTY_GITCONFIG, "");
export const ENV = { ...scrubbed, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_MODELS_DIR: MODELS_DIR, PLAN2CODE_HANDOFFS_DIR: HANDOFFS_DIR, PLAN2CODE_NOTEPADS_DIR: NOTEPADS_DIR, PLAN2CODE_NO_BROWSER: "1", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: EMPTY_GITCONFIG };
export const ENV = { ...scrubbed, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_MODELS_DIR: MODELS_DIR, PLAN2CODE_HANDOFFS_DIR: HANDOFFS_DIR, PLAN2CODE_NOTEPADS_DIR: NOTEPADS_DIR, PLAN2CODE_LEARNING_DIR: LEARNING_DIR, PLAN2CODE_NO_BROWSER: "1", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: EMPTY_GITCONFIG };
// Every server these tests start runs the release check at boot. A fresh
// cached failure keeps the whole suite off the network and bannerless.
fs.writeFileSync(path.join(HOME, "update-check.json"), JSON.stringify({ checkedAt: Date.now(), latest: null }));