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

+459 -13
View File
@@ -18,7 +18,7 @@
// bit of a saved tally (the host's memo), so the start and end screens can
// say how much is still out there to find.
import { drawPill } from "./pills.js";
import { drawPill, LIVES, livesText } from "./pills.js";
// The step at the starting length of three cells, in ms. The snake speeds up as
// it grows (see stepMs), so this is the slowest step a round begins at.
@@ -110,6 +110,35 @@ const BOSS_BONUS = 5;
const deepFreeze = (o) => Object.freeze(Object.fromEntries(Object.entries(o).map(([k, v]) => [k, Object.freeze(v)])));
// Lives: a round starts with START_LIVES and a crash costs one (the snake is
// put back mid-board, riding out GRACE_MS of free passage). Reaching each
// score in LIFE_MARKS earns one back, then one for every LIFE_EVERY points
// past the last mark, up to MAX_LIVES; past the cap the mark still moves on.
// Beating a boss earns one as well.
export const START_LIVES = 3;
export const MAX_LIVES = 9;
export const LIFE_MARKS = Object.freeze([100, 250, 450, 700]);
export const LIFE_EVERY = 300;
export const GRACE_MS = 2500;
// The score at which the n-th bonus life (counting from 0) is earned.
export const lifeMark = (n) => (n < LIFE_MARKS.length ? LIFE_MARKS[n] : LIFE_MARKS[LIFE_MARKS.length - 1] + (n - LIFE_MARKS.length + 1) * LIFE_EVERY);
// The bosses, by the level whose start brings them. A boss holds a square of
// `size` cells and wanders the board, and the food is its orbs: each one
// eaten costs it a hit point, and the regular food and the level count wait
// until it is beaten. Touching it is a crash. Each has its own trick: the
// Golem stomps rocks down around the snake, the Comet Queen calls comets, the
// Thunder Toad leaps and lands where a warning ring showed.
export const BOSSES = deepFreeze({
4: { id: "golem", name: "Grumpy Golem", sub: "Eat its orbs. Mind the falling rocks", color: "#8f877c", size: 3, hp: 4, moveMs: 520, actMs: 4200 },
6: { id: "queen", name: "Comet Queen", sub: "Eat its orbs. She throws comets", color: "#a466ff", size: 3, hp: 5, moveMs: 330, actMs: 5200 },
8: { id: "toad", name: "Thunder Toad", sub: "Eat its orbs. Dodge the landing ring", color: "#3fae5a", size: 3, hp: 6, moveMs: 0, actMs: 2800 },
});
const BOSS_KILL_POINTS = 12;
const BOSSES_BY_ID = Object.freeze(Object.fromEntries(Object.values(BOSSES).map((b) => [b.id, b])));
const TOAD_WARN_MS = 900;
// The power-ups. A timed one lasts `ms`; Shield and Scissors act at once.
export const POWERS = deepFreeze({
shield: { name: "Shield", blurb: "Shrug off one crash", color: "#1fb6d9" },
@@ -277,9 +306,19 @@ function taken(round) {
(round.coins || []).forEach(add);
(round.portals || []).forEach(add);
(round.comets || []).forEach(add);
bossCells(round.boss).forEach(add);
return cells;
}
// The cells a boss covers, and whether one of them is c.
function bossCells(b, at = b) {
const cells = [];
if (!b) return cells;
for (let dy = 0; dy < b.size; dy++) for (let dx = 0; dx < b.size; dx++) cells.push({ x: at.x + dx, y: at.y + dy });
return cells;
}
export const onBoss = (b, c) => Boolean(b) && c.x >= b.x && c.y >= b.y && c.x < b.x + b.size && c.y < b.y + b.size;
// A free cell at random, listed row by row, among those `ok` allows; null
// when there is none.
function pickFree(round, random, ok = () => true) {
@@ -326,7 +365,7 @@ export function placeBoss(round, random = Math.random) {
// Three cells mid-board heading right, food somewhere else, nothing scored,
// and nothing else on the board yet.
export function newRound(size = GRID, random = Math.random) {
export function newRound(size = GRID, random = Math.random, lives = START_LIVES) {
const mid = Math.floor(size / 2);
const round = {
size,
@@ -355,6 +394,12 @@ export function newRound(size = GRID, random = Math.random) {
spawnMs: FIRST_SPAWN_MS,
chaosMs: 0,
crashed: null,
lives,
// The next bonus life is at lifeMark(lifeAt); grace is the free passage left after a lost life.
lifeAt: 0,
grace: 0,
boss: null,
infinite: false,
// What happened since the game last looked, for its sounds and sparks.
events: [],
};
@@ -514,9 +559,139 @@ function levelUp(round, random) {
if (level === 5 || level === 7 || level === 9) addComet(round, random);
if (level >= CHAOS_LEVEL) dropRocks(round, 2, random);
if (level === CHAOS_LEVEL) round.chaosMs = CHAOS_FIRST_MS;
if (BOSSES[level]) startFight(round, random);
}
/* ------------------------------------------------------------- bosses */
// A boss takes the board: out of the head's reach, off the snake, with the
// food turned into its first orb.
function startFight(round, random) {
const spec = BOSSES[round.level];
const head = round.snake[0];
const used = taken(round);
const spots = [];
for (let y = 0; y <= round.size - spec.size; y++) {
for (let x = 0; x <= round.size - spec.size; x++) {
const cells = bossCells({ size: spec.size }, { x, y });
const mid = { x: x + 1, y: y + 1 };
if (near(head, mid) >= 9 && !cells.some((c) => used.has(c.y * round.size + c.x))) spots.push({ x, y });
}
}
if (!spots.length) return;
const at = pickOf(spots, random);
round.boss = { id: spec.id, name: spec.name, sub: spec.sub, color: spec.color, size: spec.size, hp: spec.hp, max: spec.hp, x: at.x, y: at.y, tx: null, ty: null, moveMs: spec.moveMs, actMs: spec.actMs, leap: null, hurt: 0 };
round.rocks = round.rocks.filter((r) => !onBoss(round.boss, r));
round.food = placeFood(round, random);
if (round.food) round.food.orb = true;
round.events.push({ type: "fight", x: at.x + 1, y: at.y + 1, id: spec.id, name: spec.name, sub: spec.sub, color: spec.color });
}
// An orb eaten: the boss loses a hit point, and at none it is beaten, which
// pays out, grows the snake and earns a life.
function hitBoss(round, random) {
const b = round.boss;
const at = round.snake[0];
round.combo = round.comboMs > 0 ? Math.min(MAX_COMBO, round.combo + 1) : 1;
round.comboMs = COMBO_MS;
b.hp -= 1;
b.hurt = 450;
let points = round.combo * multiplier(round);
round.events.push({ type: "bossHit", x: at.x, y: at.y, hp: b.hp, max: b.max, combo: round.combo, points });
if (b.hp <= 0) {
const bonus = BOSS_KILL_POINTS * round.level * multiplier(round);
points += bonus;
round.grow += 3;
if (round.lives < MAX_LIVES) round.lives += 1;
round.events.push({ type: "bossDown", x: b.x + 1, y: b.y + 1, name: b.name, color: b.color, points: bonus, lives: round.lives });
round.boss = null;
round.comets = [];
}
round.score += points;
round.food = placeFood(round, random);
if (round.boss && round.food) round.food.orb = true;
}
// A boss moving one cell toward a waypoint: blocked by the body, a crash into
// the head (once the grace is over), and never over the food.
function moveBoss(round, random) {
const b = round.boss;
if (b.tx == null || (b.tx === b.x && b.ty === b.y)) {
b.tx = Math.floor(random() * (round.size - b.size + 1));
b.ty = Math.floor(random() * (round.size - b.size + 1));
return null;
}
const dx = b.tx - b.x;
const dy = b.ty - b.y;
const to = Math.abs(dx) >= Math.abs(dy) && dx !== 0 ? { x: b.x + Math.sign(dx), y: b.y } : { x: b.x, y: b.y + Math.sign(dy) };
const cells = bossCells(b, to);
const blocked = cells.some((c) => round.snake.slice(1).some((s) => same(s, c)) || (round.food && onFood(round.food, c)));
if (blocked) {
b.tx = null;
return null;
}
b.x = to.x;
b.y = to.y;
if (cells.some((c) => same(c, round.snake[0])) && !(round.grace > 0)) return crash(round, "boss", random);
return null;
}
// The boss's own trick, once its timer runs out.
function bossAct(round, random) {
const b = round.boss;
const head = round.snake[0];
if (b.id === "golem") {
dropRocks(round, 3, random);
round.events.push({ type: "bossAct", id: b.id, x: b.x + 1, y: b.y + 1 });
} else if (b.id === "queen") {
addComet(round, random);
round.events.push({ type: "bossAct", id: b.id, x: b.x + 1, y: b.y + 1 });
} else if (b.id === "toad" && !b.leap) {
// It aims where the head is heading.
const ax = head.x + round.dir.x * 3;
const ay = head.y + round.dir.y * 3;
const clamp = (v) => Math.max(0, Math.min(round.size - b.size, v - 1));
b.leap = { x: clamp(ax), y: clamp(ay), warn: TOAD_WARN_MS };
round.events.push({ type: "bossAct", id: b.id, x: b.x + 1, y: b.y + 1 });
}
}
// A boss's time passing: its hurt flash, its walk, its trick and the toad's
// landing. "crash" when it ends the round.
function ageBoss(round, ms, random) {
const b = round.boss;
b.hurt = Math.max(0, b.hurt - ms);
if (b.moveMs) {
b.walk = (b.walk || 0) + ms;
while (b.walk >= b.moveMs && round.boss) {
b.walk -= b.moveMs;
if (moveBoss(round, random) === "crash") return "crash";
}
}
if (b.leap) {
b.leap.warn -= ms;
if (b.leap.warn <= 0) {
const { x, y } = b.leap;
b.leap = null;
b.actMs = BOSSES_BY_ID[b.id].actMs;
b.x = x;
b.y = y;
round.events.push({ type: "land", x: x + 1, y: y + 1 });
round.rocks = round.rocks.filter((r) => !onBoss(b, r));
if (onBoss(b, round.snake[0]) && !(round.grace > 0)) return crash(round, "boss", random);
}
return null;
}
b.actMs -= ms;
if (b.actMs <= 0) {
b.actMs = BOSSES_BY_ID[b.id].actMs + random() * 1200;
bossAct(round, random);
}
return null;
}
function eat(round, random) {
if (round.boss) return hitBoss(round, random);
const at = round.snake[0];
const boss = Boolean(round.food && round.food.boss);
round.combo = round.comboMs > 0 ? Math.min(MAX_COMBO, round.combo + 1) : 1;
@@ -535,6 +710,17 @@ function eat(round, random) {
while (round.level < level) levelUp(round, random);
}
// A bonus life at each LIFE_MARK score, up to MAX_LIVES: past the cap the
// mark still moves on, so a life is never saved up for later.
export function awardLives(round) {
while (round.score >= lifeMark(round.lifeAt)) {
round.lifeAt += 1;
if (round.lives >= MAX_LIVES) continue;
round.lives += 1;
round.events.push({ type: "bonusLife", lives: round.lives, x: round.snake[0].x, y: round.snake[0].y });
}
}
// Magnet: food and coins in reach slide a cell toward the head each step.
function pull(round) {
const head = round.snake[0];
@@ -557,14 +743,60 @@ function pull(round) {
round.coins.forEach(slide);
}
function crash(round, by) {
// A crash costs a life: with one to spare the snake is put back mid-board
// ("hit"), else the round is over ("crash"). Never takes a life while
// round.infinite is set.
function crash(round, by, random = Math.random) {
const at = round.snake[0];
if (round.infinite || round.lives > 1) {
if (!round.infinite) round.lives -= 1;
round.events.push({ type: "life", by, x: at.x, y: at.y, lives: round.lives });
respawn(round, random);
return "hit";
}
round.lives = 0;
round.crashed = by;
round.events.push({ type: "crash", by, x: round.snake[0].x, y: round.snake[0].y });
round.events.push({ type: "crash", by, x: at.x, y: at.y });
return "crash";
}
// A shield takes the hit in place of the snake.
// Puts the snake back mid-board, three cells heading right, with its length
// and everything else kept, GRACE_MS of free passage, and the middle of the
// board cleared of rocks, comets, portals, a boss and food.
function respawn(round, random) {
const mid = Math.floor(round.size / 2);
const clear = (c) => Math.abs(c.x - mid) <= 5 && Math.abs(c.y - mid) <= 3;
round.snake = [{ x: mid, y: mid }, { x: mid - 1, y: mid }, { x: mid - 2, y: mid }];
round.prev = null;
round.dir = DIRS.right;
round.queue = [];
round.slide = 0;
round.grow = 0;
round.grace = GRACE_MS;
round.rocks = round.rocks.filter((r) => !clear(r));
round.comets = round.comets.filter((c) => !clear(c));
round.items = round.items.filter((i) => !clear(i));
if (round.runner && clear(round.runner)) round.runner = null;
if (round.portals && round.portals.some(clear)) openPortals(round, random);
const b = round.boss;
if (b) {
if (bossCells(b).some(clear)) b.x = b.x < mid ? 1 : round.size - b.size - 1;
b.leap = null;
b.tx = null;
}
if (round.food && foodCells(round.food).some(clear)) {
const bites = round.food.bites;
const moved = round.food.boss ? placeBoss(round, random) : placeFood(round, random);
if (moved && round.food.boss && moved.boss) moved.bites = bites;
if (moved && round.food.orb) moved.orb = true;
round.food = moved;
}
}
// The free passage after a lost life: a hit is taken like a shield's, but
// nothing is used up.
function shielded(round, at) {
if (round.grace > 0) return true;
if (!(round.shield > 0)) return false;
round.shield -= 1;
round.events.push({ type: "shield", x: at.x, y: at.y });
@@ -575,6 +807,12 @@ function shielded(round, at) {
// way pushed to round.events. A crash leaves the snake where it was, so the
// last frame shows what it hit.
export function step(round, random = Math.random) {
const what = stepOnce(round, random);
awardLives(round);
return what;
}
function stepOnce(round, random) {
if (round.queue.length) {
// On ice a turn slides on for ICE_STEPS steps before it takes.
if (icy(round) && round.slide < ICE_STEPS) round.slide += 1;
@@ -594,7 +832,7 @@ export function step(round, random = Math.random) {
}
if (next.x < 0 || next.y < 0 || next.x >= round.size || next.y >= round.size) {
// Ghost and a shield both wrap the snake to the far side.
if (!active(round, "ghost") && !shielded(round, head)) return crash(round, "wall");
if (!active(round, "ghost") && !shielded(round, head)) return crash(round, "wall", random);
next = { x: (next.x + round.size) % round.size, y: (next.y + round.size) % round.size };
}
const food = round.food;
@@ -604,18 +842,19 @@ export function step(round, random = Math.random) {
const body = eating || round.grow > 0 ? round.snake : round.snake.slice(0, -1);
const rock = round.rocks.findIndex((r) => !(r.warn > 0) && same(r, next));
if (rock >= 0) {
if (!shielded(round, next)) return crash(round, "rock");
if (!shielded(round, next)) return crash(round, "rock", random);
round.rocks.splice(rock, 1);
const points = 3 * multiplier(round);
round.score += points;
round.events.push({ type: "smash", x: next.x, y: next.y, points });
}
if (onBoss(round.boss, next)) return crash(round, "boss", random);
const comet = round.comets.findIndex((c) => !(c.warn > 0) && same(c, next));
if (comet >= 0) {
if (!shielded(round, next)) return crash(round, "comet");
if (!shielded(round, next)) return crash(round, "comet", random);
round.comets.splice(comet, 1);
}
if (body.some((c) => same(c, next)) && !shielded(round, next)) return crash(round, "self");
if (body.some((c) => same(c, next)) && !shielded(round, next)) return crash(round, "self", random);
round.prev = round.snake;
round.snake = [next, ...body];
if (!eating && round.grow > 0) round.grow -= 1;
@@ -660,7 +899,7 @@ export function step(round, random = Math.random) {
// A comet moves one cell on the diagonal, bouncing off the walls and rocks.
// Into the head it is a crash; into the body it cuts the tail off there.
function moveComet(round, c) {
function moveComet(round, c, random) {
let nx = c.x + c.dx;
let ny = c.y + c.dy;
if (nx < 0 || nx >= round.size) {
@@ -683,7 +922,7 @@ function moveComet(round, c) {
c.y = ny;
const hit = round.snake.findIndex((s) => same(s, c));
if (hit === 0) {
if (!shielded(round, c)) return crash(round, "comet");
if (!shielded(round, c)) return crash(round, "comet", random);
round.comets.splice(round.comets.indexOf(c), 1);
return null;
}
@@ -705,6 +944,14 @@ function moveComet(round, c) {
// CHAOS_LEVEL, a surprise now and then happens on its own. "crash" when a
// comet hits the head, else null.
export function age(round, ms, random = Math.random) {
const what = ageOnce(round, ms, random);
awardLives(round);
return what;
}
function ageOnce(round, ms, random) {
if (round.grace > 0) round.grace = Math.max(0, round.grace - ms);
if (round.boss && ageBoss(round, ms, random) === "crash") return "crash";
for (const kind of Object.keys(round.effects)) {
round.effects[kind] -= ms;
if (round.effects[kind] <= 0) {
@@ -765,7 +1012,7 @@ export function age(round, ms, random = Math.random) {
c.ms += ms;
while (c.ms >= COMET_MS && round.comets.includes(c)) {
c.ms -= COMET_MS;
if (moveComet(round, c) === "crash") return "crash";
if (moveComet(round, c, random) === "crash") return "crash";
}
}
return null;
@@ -1409,6 +1656,111 @@ function drawDark(ctx, round, cell, head, clock) {
}
}
// A boss: its own body and face over a pair of eyes that follow the head. A
// hit flashes it white, and the toad's landing is shown as a ring that fills.
function drawBossMonster(ctx, round, cell, clock) {
const b = round.boss;
if (!b) return;
const head = round.snake[0];
if (b.leap) {
const p = 1 - b.leap.warn / TOAD_WARN_MS;
const lx = b.leap.x * cell;
const ly = b.leap.y * cell;
const lw = b.size * cell;
ctx.fillStyle = `rgba(226, 85, 63, ${0.12 + 0.3 * p})`;
ctx.fillRect(lx, ly, lw, lw);
ctx.strokeStyle = "#e2553f";
ctx.lineWidth = Math.max(2, cell * 0.12);
ctx.setLineDash([cell * 0.3, cell * 0.2]);
ctx.strokeRect(lx + 1, ly + 1, lw - 2, lw - 2);
ctx.setLineDash([]);
}
const hurt = b.hurt > 0 && Math.floor(b.hurt / 70) % 2 === 0;
const w = b.size * cell;
const jig = b.hurt > 0 ? (Math.random() - 0.5) * cell * 0.12 : 0;
const bob = Math.sin(clock / 260) * cell * 0.06;
const x = b.x * cell + jig;
const y = b.y * cell + bob;
const body = hurt ? "#ffffff" : b.color;
const dark = "rgba(0, 0, 0, 0.45)";
ctx.lineWidth = Math.max(2, cell * 0.1);
ctx.strokeStyle = dark;
ctx.fillStyle = body;
if (b.id === "golem") {
roundRect(ctx, x + cell * 0.1, y + cell * 0.1, w - cell * 0.2, w - cell * 0.2, cell * 0.45);
ctx.fill();
ctx.stroke();
ctx.lineWidth = Math.max(1, cell * 0.07);
ctx.beginPath();
ctx.moveTo(x + w * 0.62, y + w * 0.12);
ctx.lineTo(x + w * 0.54, y + w * 0.3);
ctx.lineTo(x + w * 0.66, y + w * 0.4);
ctx.moveTo(x + w * 0.2, y + w * 0.78);
ctx.lineTo(x + w * 0.34, y + w * 0.66);
ctx.lineTo(x + w * 0.3, y + w * 0.56);
ctx.stroke();
} else if (b.id === "queen") {
ctx.globalAlpha = 0.55;
for (const side of [-1, 1]) {
ctx.beginPath();
if (typeof ctx.ellipse === "function") ctx.ellipse(x + w / 2 + side * w * 0.5, y + w * 0.45 + Math.sin(clock / 120) * cell * 0.1, w * 0.22, w * 0.38, side * 0.4, 0, Math.PI * 2);
else ctx.arc(x + w / 2 + side * w * 0.5, y + w * 0.45, w * 0.25, 0, Math.PI * 2);
ctx.fillStyle = "#d9c2ff";
ctx.fill();
}
ctx.globalAlpha = 1;
ctx.fillStyle = body;
ctx.beginPath();
ctx.arc(x + w / 2, y + w / 2 + cell * 0.1, w * 0.46, 0, Math.PI * 2);
ctx.fill();
ctx.stroke();
const cw = cell * 0.55;
const cy = y + w * 0.1;
ctx.fillStyle = GOLD;
ctx.beginPath();
ctx.moveTo(x + w / 2 - cw, cy);
ctx.lineTo(x + w / 2 - cw, cy - cw * 0.8);
ctx.lineTo(x + w / 2 - cw * 0.5, cy - cw * 0.35);
ctx.lineTo(x + w / 2, cy - cw);
ctx.lineTo(x + w / 2 + cw * 0.5, cy - cw * 0.35);
ctx.lineTo(x + w / 2 + cw, cy - cw * 0.8);
ctx.lineTo(x + w / 2 + cw, cy);
ctx.closePath();
ctx.fill();
} else {
ctx.beginPath();
if (typeof ctx.ellipse === "function") ctx.ellipse(x + w / 2, y + w * 0.58, w * 0.48, w * 0.4, 0, 0, Math.PI * 2);
else ctx.arc(x + w / 2, y + w * 0.58, w * 0.44, 0, Math.PI * 2);
ctx.fill();
ctx.stroke();
for (const [px, py] of [[0.25, 0.7], [0.72, 0.74], [0.5, 0.85]]) dot(ctx, x + w * px, y + w * py, cell * 0.14, "rgba(0, 0, 0, 0.2)");
}
// Eyes that follow the head.
const eyeY = b.id === "toad" ? y + w * 0.3 : y + w * 0.4;
const ang = Math.atan2(head.y - (b.y + b.size / 2), head.x - (b.x + b.size / 2));
for (const side of [-1, 1]) {
const cx = x + w / 2 + side * w * 0.2;
dot(ctx, cx, eyeY, cell * 0.3, "#ffffff");
dot(ctx, cx + Math.cos(ang) * cell * 0.12, eyeY + Math.sin(ang) * cell * 0.12, cell * 0.14, "#1d1a17");
}
// A scowl for the golem and the queen, a wide mouth for the toad.
ctx.strokeStyle = "#1d1a17";
ctx.lineWidth = Math.max(2, cell * 0.1);
ctx.beginPath();
if (b.id === "toad") {
ctx.moveTo(x + w * 0.22, y + w * 0.62);
ctx.quadraticCurveTo(x + w / 2, y + w * 0.82, x + w * 0.78, y + w * 0.62);
} else {
ctx.moveTo(x + w * 0.2, eyeY - cell * 0.4);
ctx.lineTo(x + w * 0.42, eyeY - cell * 0.22);
ctx.moveTo(x + w * 0.8, eyeY - cell * 0.4);
ctx.lineTo(x + w * 0.58, eyeY - cell * 0.22);
ctx.moveTo(x + w * 0.35, y + w * 0.72);
ctx.lineTo(x + w * 0.65, y + w * 0.72);
}
ctx.stroke();
}
function pill(ctx, x, y, h, text, color, fill = 1) {
ctx.font = `800 ${Math.round(h * 0.62)}px system-ui, -apple-system, "Segoe UI", sans-serif`;
const w = h * 0.7 + text.length * h * 0.42;
@@ -1424,6 +1776,7 @@ function drawHud(ctx, round, cell) {
let x = cell * 0.25;
const y = cell * 0.2;
x += pill(ctx, x, y, h, `LV ${round.level}`, levelColor(round.level)) + 6;
x += pill(ctx, x, y, h, livesText(round.infinite ? Infinity : round.lives), LIVES) + 6;
if (round.combo > 1) x += pill(ctx, x, y, h, `x${round.combo} COMBO`, GOLD, round.comboMs / COMBO_MS) + 6;
if (round.shield > 0) x += pill(ctx, x, y, h, round.shield > 1 ? "SHIELD x2" : "SHIELD", POWERS.shield.color) + 6;
if (icy(round)) x += pill(ctx, x, y, h, "ICE", THEMES[ICE_LEVEL].tint) + 6;
@@ -1432,6 +1785,22 @@ function drawHud(ctx, round, cell) {
if (!spec || !EFFECT_LABELS[kind]) continue;
x += pill(ctx, x, y, h, EFFECT_LABELS[kind], spec.color, left / spec.ms) + 6;
}
// The boss's name and a block for each hit point, on a row of their own.
const b = round.boss;
if (b) {
const y2 = y + h + 4;
let bx = cell * 0.25;
bx += pill(ctx, bx, y2, h, b.name.toUpperCase(), b.color) + 6;
const bw = h * 0.9;
for (let i = 0; i < b.max; i++) {
ctx.fillStyle = i < b.hp ? b.color : "rgba(0, 0, 0, 0.5)";
ctx.strokeStyle = "#1d1a17";
ctx.lineWidth = 1;
roundRect(ctx, bx + i * (bw + 3), y2, bw, h, h * 0.25);
ctx.fill();
ctx.stroke();
}
}
}
// A banner is a light strip BANNER_ROWS cells tall. It opens on the half of
@@ -1737,11 +2106,68 @@ function create({ canvas, tone = () => {}, hum = () => {}, music = () => {}, onS
tone("hit", 0.8);
} else if (e.by === "rock") tone("smash", 1);
else if (e.by === "comet") tone("blast", 1);
else if (e.by === "boss") tone("boom", 1);
else tone("squish", 1);
burst(at, colors.snake, 40, 10);
burst(at, colors.head, 16, 6);
shake(450, 0.35);
flash("#e2553f", 320);
} else if (e.type === "life") {
// A crash that was not the last: the same noise as one, then a heart lost.
if (e.by === "wall") tone("thud", 1);
else if (e.by === "rock") tone("smash", 1);
else if (e.by === "comet") tone("blast", 1);
else if (e.by === "boss") tone("boom", 1);
else tone("squish", 1);
tone("hit", 0.8);
burst(at, colors.snake, 40, 10);
burst(at, colors.head, 16, 6);
shake(450, 0.35);
flash("#e2553f", 320);
banner(round.infinite ? "Ouch!" : "Life lost", round.infinite ? "Endless lives" : e.lives === 1 ? "One life left" : `${e.lives} lives left`, LIVES, 1500);
} else if (e.type === "bonusLife") {
tone("extraLife", 0.9);
sfx.later.push({ ms: 260, play: () => tone("sparkle", 0.6) });
burst(at, LIVES, 30, 8);
float(at, "+1 LIFE", LIVES);
banner("Extra life!", `${e.lives} lives`, LIVES, 1500);
} else if (e.type === "fight") {
tone("mystery");
tone("bossIntro", 0.9);
sfx.later.push({ ms: 400, play: () => tone("riser", 0.6) });
shake(500, 0.3);
flash(e.color, 500);
burst(at, e.color, 40, 9);
banner(e.name, e.sub, e.color, 2800);
} else if (e.type === "bossHit") {
tone("snakeBite", 0.9, scaleStep(e.max - e.hp));
tone("boom", 0.8);
burst(at, round.boss ? round.boss.color : GOLD, 24, 8);
float(at, e.hp > 0 ? `+${e.points} ${e.hp} left` : `+${e.points}`, GOLD);
shake(220, 0.18);
} else if (e.type === "bossDown") {
tone("explode", 1);
tone("fanfare", 0.9);
tone("snakeBossDown", 0.9);
sfx.later.push({ ms: 500, play: () => tone("cheer", 0.6) });
burst(at, e.color, 80, 12);
burst(at, GOLD, 40, 10);
shake(700, 0.4);
flash(GOLD, 600);
float(at, `+${e.points}`, GOLD);
banner(`${e.name} beaten!`, e.lives >= MAX_LIVES ? "Bonus points" : "Bonus life", GOLD, 2400);
} else if (e.type === "bossAct") {
if (e.id === "golem") {
tone("rumbleLong", 0.8);
shake(260, 0.2);
} else if (e.id === "queen") tone("snakeCometWarn", 0.7);
else tone("warn", 0.8);
burst(at, round.boss ? round.boss.color : GOLD, 14, 6);
} else if (e.type === "land") {
tone("boom", 1);
tone("rumbleLong", 0.6);
burst(at, "#3fae5a", 40, 10);
shake(380, 0.3);
}
};
@@ -1919,8 +2345,20 @@ function create({ canvas, tone = () => {}, hum = () => {}, music = () => {}, onS
if (fx.shake > 0) ctx.translate((Math.random() - 0.5) * 2 * fx.shakeMag * cell, (Math.random() - 0.5) * 2 * fx.shakeMag * cell);
drawBoard(ctx, round, cell, colors, clock);
drawThings(ctx, round, cell, colors, clock);
if (round.boss && round.food && round.food.orb) {
const r = cell * (0.62 + 0.08 * Math.sin(clock / 140));
ctx.strokeStyle = round.boss.color;
ctx.lineWidth = Math.max(2, cell * 0.1);
ctx.beginPath();
ctx.arc((round.food.x + 0.5) * cell, (round.food.y + 0.5) * cell, r, 0, Math.PI * 2);
ctx.stroke();
}
drawBossMonster(ctx, round, cell, clock);
const t = state === "running" ? Math.min(1, elapsed / pace(round)) : 1;
// Free passage after a lost life: the snake flickers.
if (round.grace > 0 && Math.floor(clock / 110) % 2 === 0) ctx.globalAlpha = 0.4;
const head = drawSnake(ctx, round, cell, colors, clock, t, state === "over" && Boolean(round.crashed));
ctx.globalAlpha = 1;
if (active(round, "lightsOut")) drawDark(ctx, round, cell, head, clock);
for (const p of fx.parts) {
ctx.globalAlpha = Math.max(0, p.life / p.max);
@@ -1949,7 +2387,7 @@ function create({ canvas, tone = () => {}, hum = () => {}, music = () => {}, onS
const start = () => {
colors = null;
round = newRound();
round = newRound(GRID, Math.random, START_LIVES);
deck = dealMusic(Math.random, opener);
opener = deck[0];
elapsed = 0;
@@ -1981,6 +2419,14 @@ function create({ canvas, tone = () => {}, hum = () => {}, music = () => {}, onS
get score() {
return round.score;
},
// For the tests only: the window never reads it.
get round() {
return round;
},
// Endless lives for this round (the Activities window's code), or not.
cheat(on) {
round.infinite = Boolean(on);
},
get state() {
return state;
},
+198 -5
View File
@@ -177,9 +177,161 @@ export function answerLines(item, v) {
if (Array.isArray(v.rows) && v.rows.length) {
out.push(`${v.rows.length} steps, in the order you set`);
}
if (item && item.kind === "lessons") out.push(...lessonLines(item, v));
return out;
}
/* ------------------------------------------------------ the lessons card */
// The choice that keeps a row as it stands, per row type (FR-15). A refused
// row cannot take it until it is reworded.
export const LESSON_KEEP_WORD = { lesson: "Keep", doubt: "Keep", gone: "Keep", "agents-fix": "Apply", "log-line": "Move", area: "Create" };
// The choices that open the row for editing.
export const LESSON_EDIT_WORDS = new Set(["Reword", "Reword and move", "Rename"]);
// The edit word per row type: what a refused row's keep word goes back to.
export const LESSON_EDIT_WORD = { lesson: "Reword", doubt: "Reword", gone: "Reword", "agents-fix": "Reword", "log-line": "Reword and move", area: "Rename" };
// The first ask's answers, as the agent reads them.
export const FIRST_ASK_WORDS = { yes: "Switch Learning on", no: "Not for this project" };
/** The field a row's edit must fill, and the label that names it. */
export function lessonEditField(row) {
if (row && row.type === "agents-fix") return { key: "after", label: "The new wording" };
if (row && row.type === "area") return { key: "name", label: "The area's name" };
if (row && row.type === "log-line") return { key: "lessons", label: "The lesson" };
return { key: "text", label: "The lesson" };
}
// The lessons a failure log line would become, or the line itself when the
// list gave none (a refused line comes masked and with none).
const logLessons = (row) => (Array.isArray(row.lessons) && row.lessons.length ? row.lessons.map(String) : [row.text || ""]);
/** The edit fields' first values: the row as it stands. */
export function lessonEditStart(row) {
if (row.type === "agents-fix") return { after: lessonOriginal(row) };
if (row.type === "area") return { name: lessonOriginal(row), paths: [...(row.paths || [])] };
if (row.type === "log-line") return { lessons: logLessons(row), why: row.why || "", area: row.area || "" };
return { text: lessonOriginal(row), why: row.why || "", area: row.area || "" };
}
/**
* The row's own words, the ones its edit starts from and is compared with to
* tell whether it was reworded. A log line's lessons are joined by newlines.
*/
export function lessonOriginal(row) {
if (row.type === "agents-fix") return row.after || row.text || "";
if (row.type === "area") return row.name || row.text || "";
if (row.type === "log-line") return logLessons(row).join("\n");
return row.text || "";
}
/** The edit's words in the same form as lessonOriginal, or the original when untouched. */
function lessonTyped(row, edit) {
const field = lessonEditField(row).key;
if (field === "lessons") return Array.isArray(edit.lessons) ? edit.lessons.map((t) => String(t).trim()).join("\n") : lessonOriginal(row);
return typeof edit[field] === "string" ? edit[field].trim() : lessonOriginal(row);
}
/** Whether a row's edit changed its words. */
export function lessonReworded(row, edit = {}) {
return lessonTyped(row, edit) !== lessonOriginal(row);
}
/**
* One decision as lessons.mjs decide takes it: `{ id, choice }` plus what the
* choice needs from the row's edits (`edit`, the person's typed values). A
* refused row kept after a reword goes as a Reword, since its words changed.
* Only values that differ from the row are sent for an area's paths or a
* lesson's area; `why` goes whenever it is not empty or was emptied. A log
* line's "Reword and move" goes as `lessons: [{ text, why?, area? }]`; the
* agent adds each `about` (End step 6).
*/
export function lessonDecision(row, choice, edit = {}) {
const typed = lessonTyped(row, edit);
const keepWord = LESSON_KEEP_WORD[row.type];
let pick = choice;
if (row.refused && choice === keepWord && typed !== lessonOriginal(row)) pick = LESSON_EDIT_WORD[row.type];
const d = { id: row.id, choice: pick };
if (!LESSON_EDIT_WORDS.has(pick)) return d;
if (row.type === "agents-fix") return { ...d, after: typed };
if (row.type === "area") {
const out = { ...d, name: typed };
if (Array.isArray(edit.paths)) {
const paths = edit.paths.map((p) => String(p).trim()).filter(Boolean);
if (paths.join(",") !== (row.paths || []).join(",")) out.paths = paths;
}
return out;
}
const why = typeof edit.why === "string" ? edit.why.trim() : row.why || "";
const area = typeof edit.area === "string" && edit.area && edit.area !== (row.area || "") ? edit.area : "";
if (row.type === "log-line") {
const texts = typed.split("\n");
return { ...d, lessons: texts.map((text) => ({ text, ...(why ? { why } : {}), ...(area ? { area } : {}) })) };
}
const out = { ...d, text: typed };
// An emptied Why is sent as "", so decide does not keep the old one.
if (why || (typeof edit.why === "string" && row.why)) out.why = why;
if (area) out.area = area;
return out;
}
/** What is still missing before a row's decision can go, or "" when nothing is. */
export function lessonMissing(row, decision) {
if (!decision || !LESSON_EDIT_WORDS.has(decision.choice)) return "";
const { key, label } = lessonEditField(row);
if (key === "lessons") {
const list = Array.isArray(decision.lessons) ? decision.lessons : [];
return list.length && list.every((l) => String((l && l.text) || "").trim()) ? "" : label;
}
return String(decision[key] || "").trim() ? "" : label;
}
/** The words one decision reads as: "Keep: <text>", "Reword: <new text>", "Apply: <file>". */
export function lessonDecisionLine(row, d) {
const shown =
d.choice === "Apply"
? (row && row.file) || "AGENTS.md"
: Array.isArray(d.lessons)
? d.lessons.map((l) => (l && l.text) || "").join(" / ")
: d.after || d.name || d.text || (row ? (row.type === "area" ? row.name || row.text : row.text) : "") || d.id;
return `${d.choice}: ${shown}`;
}
/**
* The lessons card's answer as lines: one per decision, then how many were
* left waiting; or the first ask's answer.
*/
export function lessonLines(item, v) {
if (!v) return [];
if (v.firstAsk === "yes" || v.firstAsk === "no") return [FIRST_ASK_WORDS[v.firstAsk]];
if (!Array.isArray(v.decisions)) return [];
const rows = Array.isArray(item && item.rows) ? item.rows : [];
const byRow = new Map(rows.map((r) => [r.id, r]));
const out = v.decisions.map((d) => lessonDecisionLine(byRow.get(d.id), d));
const left = rows.filter((r) => !v.decisions.some((d) => d.id === r.id)).length;
if (left) out.push(`${left} left waiting`);
else if (!out.length) out.push("Nothing chosen");
return out;
}
/**
* What the agent reads for the lessons card: the lines above, and the
* decisions exactly as lessons.mjs decide takes them, on one `Decisions:`
* line, so the console and the terminal write the same decisions file.
*/
export function lessonsReply(item, v) {
if (!v) return "";
if (!Array.isArray(v.decisions)) return [...lessonLines(item, v), ...(v.text ? [v.text] : [])].join("\n");
const rows = Array.isArray(item && item.rows) ? item.rows : [];
const byRow = new Map(rows.map((r) => [r.id, r]));
const left = rows.filter((r) => !v.decisions.some((d) => d.id === r.id)).length;
// The count leads, so each decision starts a line of its own under the card's title.
const lines = [`${v.decisions.length} decided${left ? `, ${left} left waiting` : ""}`];
for (const d of v.decisions) lines.push(lessonDecisionLine(byRow.get(d.id), d));
lines.push(`Decisions: ${JSON.stringify(v.decisions)}`);
if (v.text) lines.push(v.text);
return lines.join("\n");
}
/**
* A single-choice answer, which is one thing or the other and never both.
*
@@ -698,7 +850,7 @@ export function cardAvailability(entry, scan, sel, lookup = stateFor) {
return ON;
}
// Always on; a diagnosed bug is the one spec Quick Task is the next step for.
// Always on; a diagnosed bug and an upgrade brief are the specs Quick Task is the next step for.
if (rule.states === "any") return next ? { ...ON, next } : ON;
// A building spec whose only unfinished tasks are blocked, each with a
// written reason (the scan's finalizeReady), is ready for Finalize too.
@@ -758,8 +910,8 @@ export function toggleNoteTick(ticked, id) {
/**
* The spec a card's launch carries: the picker's selection for the cards that
* take a spec, and for Quick Task only a diagnosed bug, whose write-up it reads
* first, or a folder holding only saved prototypes (files on disk with a
* take a spec, and for Quick Task only a diagnosed bug or an upgrade brief
* waiting to be applied, whose write-up it reads first, or a folder holding only saved prototypes (files on disk with a
* `prototypes` count), which it builds from. A mid-pipeline spec with
* prototypes is Implement's to build. Every other card launches untargeted.
*/
@@ -768,7 +920,7 @@ export function launchTarget(entry, sel) {
if (entry.spec) return sel;
if (entry.skill !== "plan2code-quick-task") return null;
const prototypeOnly = sel.state === "unrecognized" && sel.prototypes > 0;
return sel.state === "diagnosed" || prototypeOnly ? sel : null;
return sel.state === "diagnosed" || sel.state === "upgrade" || prototypeOnly ? sel : null;
}
export function cardPresentation(entry, scan, sel, menu = {}) {
@@ -821,6 +973,43 @@ export function deleteReply(spec) {
return `Delete the spec folder ${spec.dir}/ for good, right here in this session.`;
}
// A Learning control on the dashboard (screens/learning-row.js and the
// waiting banner). No hop: the dashboard agent runs lessons.mjs for it. Plain
// wording, no em dashes: these lines are read by the agent.
export const LEARNING_ACTIONS = ["review", "switch-on", "switch-off", "move-log", "remove"];
const LEARNING_REPLIES = {
review: "Review the waiting lessons.",
"switch-on": "Switch Learning on for this project.",
"switch-off": "Switch Learning off for this project.",
"move-log": "Move the failure log into lessons.",
remove: "Remove all saved lessons from this project. Learning stays on.",
};
export function learningAction(what) {
if (!LEARNING_ACTIONS.includes(what)) throw new Error("unknown Learning action: " + what);
return { i: "__learning", type: "learning", do: what };
}
export function learningReply(what) {
return LEARNING_REPLIES[what] || "";
}
/**
* The Implementation Loop's stop card's line about waiting lessons (FR-13),
* from /learning/state, or "" when none wait or Learning is off or paused.
*/
export function loopLessonsLine(learning) {
if (!learning || !(learning.waiting > 0) || (learning.state !== "on" && learning.state !== "not-set-up")) return "";
const n = learning.waiting;
return `${n} ${n === 1 ? "lesson is" : "lessons are"} waiting for your review. Open the dashboard to review them.`;
}
// The waiting banner's line, or "" when it shows nothing: lessons waiting and
// Learning on or not set up (hidden while paused or off).
export function learningBannerText(learning) {
if (!learning || !(learning.waiting > 0) || (learning.state !== "on" && learning.state !== "not-set-up")) return "";
const n = learning.waiting;
const d = Number.isInteger(learning.oldestDays) ? learning.oldestDays : 0;
return `${n} ${n === 1 ? "lesson is" : "lessons are"} waiting for your review (oldest ${d} ${d === 1 ? "day" : "days"}).`;
}
// What the delete dialog says about the spec, from the scan alone. `touched`
// stays a number: the page formats it in the person's own locale.
// A handoff on the dashboard (scan.handoffs). The page sends only the id; the
@@ -1069,7 +1258,11 @@ export function pruneStaged(items, staged) {
for (const [id, v] of Object.entries(out)) {
const item = byId.get(id);
if (!item || !v || typeof v !== "object" || (item.kind !== "choice" && item.kind !== "multi")) continue;
const keys = new Set((item.options || []).map((o) => o && o.k));
// A multi's locked option is shown, never picked: a tick staged before a
// re-post locked it goes like a key the card no longer offers.
const keys = new Set(
(item.options || []).filter((o) => o && !(item.kind === "multi" && o.locked === true)).map((o) => o && o.k)
);
const next = { ...v };
let lost = false;
if (item.kind === "choice" && next.k && !keys.has(next.k)) {
+4 -2
View File
@@ -22,8 +22,9 @@ import {
adopt, askSuggestions, banner, connect, fillSky, fitGrowBox, loadState, markSent, maybeWelcome, render, renderFooter,
renderSidebar, renderWhere, save, startClock, startLooks, stagedPayload, syncWorkspaceScope,
wakeHoldsChime, wireAsk, wireCards, wireChrome, wireCleanup, wireDashboard, wireDocs, wireEnding,
wireActivities, wireLoopSetup, wireHelp, launchSkill, openHelpOn, openLoopSetup, wireLooks, wireNotepad, wirePrefs, wireWorkspace,
wireActivities, wireLoopSetup, wireHelp, launchSkill, sendLearning, renderLearningRow, learningBlocked, openHelpOn, openLoopSetup, wireLooks, wireNotepad, wirePrefs, wireWorkspace,
openPrefs, markSaved, confirmUnsaved, loadAgentsView, wireAgentsView, hasUnsaved, unsavedName, saveOpen, discardOpen, focusOpen,
renderCard, send, refreshLessonsSend,
} from "./screens/core.js";
import { sound } from "./sound.js";
@@ -36,8 +37,9 @@ import { sound } from "./sound.js";
// and the few calls a screen makes into another are handed to state.js first.
onSave(save);
useHooks({
launchSkill, openHelpOn, openLoopSetup, askSuggestions, banner, fitGrowBox, markSent, maybeWelcome, renderFooter, renderSidebar, renderWhere, stagedPayload, syncWorkspaceScope,
launchSkill, sendLearning, renderLearningRow, learningBlocked, openHelpOn, openLoopSetup, askSuggestions, banner, fitGrowBox, markSent, maybeWelcome, renderFooter, renderSidebar, renderWhere, stagedPayload, syncWorkspaceScope,
openPrefs, markSaved, confirmUnsaved, loadAgentsView, wireAgentsView, hasUnsaved, unsavedName, saveOpen, discardOpen, focusOpen,
renderCard, send, refreshLessonsSend,
});
const boot = bootData();
+3
View File
@@ -20,10 +20,12 @@ export const HELP_TABS = Object.freeze([
tab("notes", "Notes and attachments", false),
tab("docs", "Documents and printing", false),
tab("dashboard", "The dashboard", true),
tab("learning", "Learning", false),
tab("meter", "Session meter", false),
tab("build", "Watching a build", false),
tab("loop", "Implementation Loop", true),
tab("git", "The git board", false),
tab("deps", "Update dependencies", false),
tab("subagents", "Helpers (subagents)", false),
tab("ask", "Ask a quick question", false),
tab("activities", "Activities", false),
@@ -52,6 +54,7 @@ export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow,
if (dashboard) return "dashboard";
if (v === "overview" || v === "map" || v === "draft" || v.startsWith("doc:")) return "docs";
if (workflow === "git") return "git";
if (workflow === "deps") return "deps";
if (HELP_BUILD_WORKFLOWS.has(workflow)) return "build";
return "about";
}
+211 -10
View File
@@ -446,6 +446,13 @@
<circle cx="14.5" cy="11" r="1.5" />
<path d="M10 19v2M12 19v2M14 19v2" />
</symbol>
<!-- Update dependencies: a package box with an arrow rising out of it. -->
<symbol id="ci-deps" viewBox="0 0 24 24" fill="none">
<path d="M4 10l8 4 8-4" />
<path d="M4 10v8l8 4 8-4v-8" />
<path d="M12 14v8" />
<path d="M12 2v8M9 5l3-3 3 3" />
</symbol>
<!-- UI Prototype: a framed screen with three sliders. -->
<symbol id="ci-ui-prototype" viewBox="0 0 24 24" fill="none">
<rect x="3" y="4" width="18" height="16" rx="2" />
@@ -974,6 +981,29 @@
</g>
</g>
</svg>
<!-- Update dependencies: he holds up a package box and an arrow rises
out of it, his star following it up. -->
<svg class="pose pose-deps" data-pose="deps" viewBox="0 4 240 216" aria-hidden="true" focusable="false">
<ellipse class="shadow" cx="126" cy="198" rx="44" ry="5" />
<g class="bob">
<g class="dp-arrow">
<path class="lt" d="M187 102 L187 78" />
<path class="lt" d="M179 86 L187 78 L195 86" />
</g>
<path class="dp-box" d="M170 112 L187 104 L204 112 L204 132 L187 140 L170 132 Z" />
<path class="lt" d="M170 112 L187 120 L204 112 M187 120 L187 140" />
<g transform="translate(-14 0)">
<rect class="fl foot f1" x="94" y="179" width="20" height="10" rx="5" />
<rect class="fl foot f2" x="126" y="179" width="20" height="10" rx="5" />
<rect class="sh" x="80" y="72" width="80" height="108" rx="16" />
<path class="ln" d="M80 126 L66 150" /><circle class="fl" cx="66" cy="150" r="5.5" />
<g class="dp-look"><path class="ey blink" d="M126 86 L129.64 94.98 L139.31 95.67 L131.9 101.92 L134.23 111.33 L126 106.2 L117.77 111.33 L120.1 101.92 L112.69 95.67 L122.36 94.98 Z" /></g>
<path class="es" d="M110 120 Q122 129 134 120" />
<line class="ln" x1="160" y1="126" x2="180" y2="134" />
<circle class="fl" cx="184" cy="134" r="5.5" />
</g>
</g>
</svg>
<!-- Agent setup: waving hello at a terminal window, its prompt waiting
for the command line that brings an agent. -->
<svg class="pose pose-setup" data-pose="setup" viewBox="0 4 240 216" aria-hidden="true" focusable="false">
@@ -1046,6 +1076,10 @@
<rect x="4" y="13" width="7" height="7" rx="1.5" />
<rect x="13" y="13" width="7" height="7" rx="1.5" />
</symbol>
<symbol id="hi-learning" viewBox="0 0 24 24" fill="none">
<path d="M9 18h6M10 21h4" />
<path d="M12 3a6 6 0 0 0-3.5 10.9c.6.5 1 1.2 1 2V16h5v-.1c0-.8.4-1.5 1-2A6 6 0 0 0 12 3z" />
</symbol>
<symbol id="hi-meter" viewBox="0 0 24 24" fill="none">
<circle cx="12" cy="12" r="8" />
<path d="M12 4a8 8 0 0 1 7.6 10.5" />
@@ -1065,6 +1099,12 @@
<circle cx="18" cy="7" r="2" />
<path d="M6 7v10M18 9a7 7 0 0 1-7 7H6" />
</symbol>
<symbol id="hi-deps" viewBox="0 0 24 24" fill="none">
<path d="M4 10l8 4 8-4" />
<path d="M4 10v8l8 4 8-4v-8" />
<path d="M12 14v8" />
<path d="M12 2v8M9 5l3-3 3 3" />
</symbol>
<symbol id="hi-subagents" viewBox="0 0 24 24" fill="none">
<circle cx="7" cy="12" r="3.5" />
<circle cx="18" cy="5" r="2" />
@@ -2142,7 +2182,120 @@
</p>
</section>
<!-- Tab 11: Session meter -->
<!-- Tab 11: Learning -->
<section class="help-panel" data-tab="learning">
<h3>Learning</h3>
<p class="help-lead">
Plan2Code can learn your codebase as your team works in it. A step
offers what it learned at the end of a run; you choose what to keep,
and the next run, yours or a teammate's, starts out knowing it.
</p>
<h4>What a lesson is</h4>
<p>
A lesson is one sentence about the code, with why it holds, a kind
(a correction, a convention, how something works, or a command) and
the files it is about. Lessons are about the code, never about you.
</p>
<div class="help-example">
<p><strong>A game's saved number goes through the flat keys in looks.json, never browser storage.</strong></p>
<p>Why: you corrected this while fixing Bounce Road's best score.</p>
<p>About: <code>src/web-console/public/activities/</code></p>
</div>
<h4>The four states</h4>
<p>
The dashboard's Learning row says which one the project is in:
</p>
<ul>
<li>
<strong>Not set up</strong>: nobody has chosen yet. Runs read
nothing, and the first time a run learns something it asks whether
to switch Learning on, showing that lesson.
</li>
<li>
<strong>Off</strong>: the team said no for this project. Runs
work as they did before Learning.
</li>
<li>
<strong>On</strong>: runs read the lessons that fit the files they
work on, and the steps that build, review, test, diagnose or explain code offer
what they learned at the end.
</li>
<li>
<strong>Paused for you</strong>: Learning stays on for the team,
but your own runs neither read nor offer lessons until you switch
<strong>Pause for me</strong> back. Nobody else is affected.
</li>
</ul>
<p>
On and Off are the team's choice and travel with the repository;
the pause is yours alone. <strong>More</strong> on the row switches
Learning off, moves the failure log in <code>AGENTS.md</code> into
lessons, or removes all lessons. When lessons are waiting, a banner
above the title offers <strong>Review</strong>.
</p>
<h4>Choosing what to keep</h4>
<p>
At the end of a run each item gets its own choice, in words that fit
it. Nothing is picked for you.
</p>
<table>
<thead>
<tr>
<th>The item</th>
<th>Its choices</th>
</tr>
</thead>
<tbody>
<tr>
<td>A new lesson</td>
<td>Keep, Reword, Drop</td>
</tr>
<tr>
<td>A saved lesson the step doubts</td>
<td>Keep, Reword, Retire</td>
</tr>
<tr>
<td>A fix to <code>AGENTS.md</code></td>
<td>Apply, Reword, Drop</td>
</tr>
<tr>
<td>A failure log line</td>
<td>Move, Reword and move, Leave in the log</td>
</tr>
<tr>
<td>A new area of code</td>
<td>Create, Rename, Drop</td>
</tr>
</tbody>
</table>
<p>
Nothing is saved without your approval, and nothing is committed for
you: what you keep shows up as changed files, to commit with the rest
of the work. A lesson you have not decided on yet stays waiting for
30 days.
</p>
<h4>Where lessons are kept</h4>
<table>
<thead>
<tr>
<th>Where</th>
<th>What it holds</th>
</tr>
</thead>
<tbody>
<tr>
<td>The project's lessons (<code>.plan2code/lessons/</code>, saved with the repository)</td>
<td>The lessons your team kept, one file per area of code plus a general one, and the Learning switch beside them. Commit it; it is how your teammates get them.</td>
</tr>
<tr>
<td>On this machine only (<code>~/.plan2code/</code>)</td>
<td>Lessons waiting for your review and your own pause. Never shared.</td>
</tr>
</tbody>
</table>
</section>
<!-- Tab 12: Session meter -->
<section class="help-panel" data-tab="meter">
<h3>Session meter</h3>
<p class="help-lead">
@@ -2197,7 +2350,7 @@
</p>
</section>
<!-- Tab 12: Watching a build -->
<!-- Tab 13: Watching a build -->
<section class="help-panel" data-tab="build">
<h3>Watching a build</h3>
<p class="help-lead">
@@ -2413,7 +2566,7 @@
</p>
</section>
<!-- Tab 13: The git board -->
<!-- Tab 14: The git board -->
<section class="help-panel" data-tab="git">
<h3>The git board</h3>
<p class="help-lead">
@@ -2537,7 +2690,54 @@
</p>
</section>
<!-- Tab 14: Helpers (subagents) -->
<!-- Tab 15: Update dependencies -->
<section class="help-panel" data-tab="deps">
<h3>Update dependencies</h3>
<p>
The <strong>Update dependencies</strong> card clears a dependency
backlog in one sitting. It scans every manifest in the project (npm,
pnpm and Yarn, Cargo, pip and uv, Go and .NET), labels each update,
applies the ones you pick in batches, runs your install and checks
after each batch, and puts back whatever breaks.
</p>
<h4>The labels</h4>
<ul>
<li><strong>Safe</strong>: in range, notes read, nothing breaking found. All Safe is the suggested pick.</li>
<li><strong>Check first</strong>: a bigger jump or notes it could not read. Applied one at a time, with its own checks.</li>
<li><strong>Warning</strong>: the notes say something your code uses changed. Tick it to write an upgrade brief instead of applying it.</li>
<li><strong>Held back</strong> and <strong>Not scanned</strong>: shown for the record, never picked.</li>
</ul>
<h4>The pick list</h4>
<ul>
<li>Rows are grouped by label. Open a row to read its notes, the breaking lines and where your code calls the package.</li>
<li>The count under the list says how many check rounds your picks take.</li>
<li>Nothing is updated until you send.</li>
</ul>
<h4>When a batch breaks</h4>
<p>
A batch whose install or checks fail is put back exactly as it was
found and reinstalled, then narrowed down to the pick that broke it.
That pick is marked failed with its output; the rest go on. Stopping
mid-run keeps the batches that passed.
</p>
<h4>Upgrade briefs</h4>
<p>
A ticked Warning writes <code>specs/&lt;package&gt;-upgrade/UPGRADE-&lt;date&gt;.md</code>.
The dashboard shows that folder as <strong>Upgrade ready</strong>, with
Quick task and Plan lit: Quick task applies it, Plan plans a big one.
Once Quick task has applied it and its checks pass, the folder shows as
<strong>Upgrade done</strong>, offered for archiving, and deleted after
one confirm like a fixed bug.
</p>
<h4>What it never does</h4>
<p>
It never commits, installs a tool, edits your source code or updates
anything you did not pick. The changed manifests and lockfiles wait
for you to commit.
</p>
</section>
<!-- Tab 16: Helpers (subagents) -->
<section class="help-panel" data-tab="subagents">
<h3>Helpers (subagents)</h3>
<p>
@@ -2624,7 +2824,7 @@
</ul>
</section>
<!-- Tab 15: Ask a quick question -->
<!-- Tab 17: Ask a quick question -->
<section class="help-panel" data-tab="ask">
<h3>Ask a quick question</h3>
<p class="help-lead">
@@ -2728,7 +2928,7 @@
</p>
</section>
<!-- Tab 16: Activities -->
<!-- Tab 18: Activities -->
<section class="help-panel" data-tab="activities">
<h3>Activities</h3>
<p class="help-lead">
@@ -3197,7 +3397,7 @@
</p>
</section>
<!-- Tab 17: Stopping and finishing -->
<!-- Tab 19: Stopping and finishing -->
<section class="help-panel" data-tab="finishing">
<h3>Stopping and finishing</h3>
<p class="help-lead">
@@ -3304,7 +3504,7 @@
</p>
</section>
<!-- Tab 18: Keyboard and preferences -->
<!-- Tab 20: Keyboard and preferences -->
<section class="help-panel" data-tab="prefs">
<h3>Keyboard and preferences</h3>
<p class="help-lead">
@@ -3535,7 +3735,7 @@
</ul>
</section>
<!-- Tab 19: Setting up an agent -->
<!-- Tab 21: Setting up an agent -->
<section class="help-panel" data-tab="setup">
<h3>Setting up an agent</h3>
<p class="help-lead">
@@ -3587,7 +3787,7 @@
</p>
</section>
<!-- Tab 20: Privacy and where things are saved -->
<!-- Tab 22: Privacy and where things are saved -->
<section class="help-panel" data-tab="privacy">
<h3>Privacy and where things are saved</h3>
<p class="help-lead">
@@ -4227,6 +4427,7 @@
</dialog>
<footer class="footer">
<div class="pick-count-live" id="pick-count-live" aria-live="polite"></div>
<div class="footer-summary" id="footer-summary" aria-live="polite">
Nothing to send yet.
</div>
+22 -1
View File
@@ -192,6 +192,25 @@ export function runHint(text) {
return COMMAND_WORDS.test(firstLine) ? "hint" : null;
}
const ALERT_MARK = /^\[!(CAUTION|TIP)\][ \t]*\n?/;
/**
* "caution" or "tip" when a blockquote's first words are `[!CAUTION]` or
* `[!TIP]`, and the marker is taken out of the tokens so it is not drawn;
* null for an ordinary quote.
*/
function alertKind(tokens) {
const first = Array.isArray(tokens) ? tokens[0] : null;
if (!first || first.type !== "paragraph" || !Array.isArray(first.tokens)) return null;
const lead = first.tokens[0];
if (!lead || lead.type !== "text" || typeof lead.text !== "string") return null;
const found = ALERT_MARK.exec(lead.text);
if (!found) return null;
lead.text = lead.text.slice(found[0].length);
if (!lead.text) first.tokens.shift();
return found[1].toLowerCase();
}
function blockInto(parent, tokens) {
for (const t of tokens || []) {
switch (t.type) {
@@ -218,7 +237,9 @@ function blockInto(parent, tokens) {
break;
}
case "blockquote": {
const q = el("blockquote", "md-quote");
// A quote that opens with `[!CAUTION]` or `[!TIP]` is a colored alert box.
const alert = alertKind(t.tokens);
const q = el("blockquote", alert ? `md-quote md-alert md-alert-${alert}` : "md-quote");
blockInto(q, t.tokens);
parent.appendChild(q);
break;
+438 -5
View File
@@ -35,6 +35,13 @@ import {
verdictText,
handoffText,
finishPaused,
LESSON_KEEP_WORD,
LESSON_EDIT_WORDS,
LESSON_EDIT_WORD,
lessonDecision,
lessonMissing,
lessonEditStart,
lessonReworded,
} from "../answers.js";
import { el, md } from "../render.js";
import {
@@ -353,6 +360,9 @@ export function renderCard(item) {
(loopLock ? " is-loop-" + loopLock : "")
);
// The pick count's fixed live node speaks only for a card that counts.
if (!(item.kind === "multi" && item.counter && isOpen(item))) announceCount("");
// Which question this card is for, so a render can tell whether the card it
// is replacing is the same one (keep the scroll) or a different one (start
// at the top).
@@ -770,6 +780,7 @@ function otherField(card, item, staged) {
// the pager kept pointing the wrong way while the footer said "1 ready".
function stagedChanged() {
hooks.renderFooter();
hooks.refreshLessonsSend();
hooks.renderSidebar();
renderStagedMarks();
}
@@ -920,12 +931,55 @@ function clearRow(card, item) {
card.appendChild(row);
}
// Which `more` bodies are open, by question and option key, so a redraw (every
// tick is one) leaves an opened row open. Page memory only: a reload starts
// with every row closed.
const openMore = new Set();
const moreKey = (item, o) => `${item.id}\u0000${o.k}`;
// The keys a multi may never send: a locked row is shown, never picked.
function lockedKeys(item) {
return new Set((item.options || []).filter((o) => o && o.locked === true).map((o) => o.k));
}
// "N picked, M <label>": M counts the distinct `batch` values among the ticked
// options, and an option with no `batch` counts as a round of its own.
function multiCount(item, ks) {
const picked = new Set(ks || []);
const rounds = new Set();
let n = 0;
for (const o of item.options || []) {
if (!o || !picked.has(o.k) || o.locked === true) continue;
n++;
rounds.add(typeof o.batch === "string" ? "b\u0000" + o.batch : "k\u0000" + o.k);
}
return { picked: n, rounds: rounds.size };
}
function buildMulti(card, item, staged) {
const chosen = new Set((staged && staged.ks) || []);
const locked = lockedKeys(item);
const chosen = new Set(((staged && staged.ks) || []).filter((k) => !locked.has(k)));
const grouped = (item.options || []).some((o) => o && typeof o.group === "string" && o.group);
const list = el("ul", "options");
let lastGroup;
for (const [i, o] of (item.options || []).entries()) {
const on = chosen.has(o.k);
const li = el("li", "option" + (on ? " is-picked" : ""));
// A heading before the first option of each run sharing a group, in the
// order sent. A run with no group gets none, as a list with no groups does.
if (grouped) {
const g = typeof o.group === "string" && o.group ? o.group : null;
if (g && g !== lastGroup) {
const head = el("li", "option-group-row");
head.setAttribute("role", "presentation");
head.appendChild(el("h4", "option-group", g));
list.appendChild(head);
}
lastGroup = g;
}
const isLocked = o.locked === true;
const on = !isLocked && chosen.has(o.k);
const hasMore = typeof o.more === "string" && Boolean(o.more);
// "is-held", not "is-locked": that class is the settled record's (lockedOptions).
const li = el("li", "option" + (on ? " is-picked" : "") + (isLocked ? " is-held" : "") + (hasMore ? " has-more" : ""));
const label = el("label");
label.style.display = "contents";
@@ -935,9 +989,14 @@ function buildMulti(card, item, staged) {
box.value = o.k;
box.checked = on;
box.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
if (isLocked) {
box.disabled = true;
box.setAttribute("aria-disabled", "true");
}
box.addEventListener("change", () => {
if (isLocked) return;
const cur = page.local.staged[item.id];
const next = new Set((cur && cur.ks) || []);
const next = new Set(((cur && cur.ks) || []).filter((k) => !locked.has(k)));
if (box.checked) next.add(o.k);
else next.delete(o.k);
// Unticking the last box keeps what is written in "Anything else".
@@ -962,21 +1021,77 @@ function buildMulti(card, item, staged) {
label.appendChild(box);
label.appendChild(body);
li.appendChild(label);
// A row that opens: the button sits outside the label, so pressing it
// never toggles the tick, and the tick never opens the row.
if (hasMore) {
const key = moreKey(item, o);
const open = openMore.has(key);
const bodyId = `more-${item.id}-${o.k || i}`;
const toggle = el("button", "option-more-btn", open ? "Less" : "More");
toggle.type = "button";
// Stable across redraws, so the click handler can find the new button.
toggle.id = `more-btn-${item.id}-${o.k || i}`;
toggle.setAttribute("aria-expanded", String(open));
toggle.setAttribute("aria-controls", bodyId);
// The name starts with the visible word, so "click Less" finds it.
toggle.setAttribute("aria-label", `${open ? "Less" : "More"} about ${o.text}`);
toggle.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
if (openMore.has(key)) openMore.delete(key);
else openMore.add(key);
const id = toggle.id;
// The redraw rebuilds the card, and withFocus keeps focus only on
// fields, so put it back on the new button by hand.
redraw();
const again = document.getElementById(id);
if (again) again.focus();
});
li.appendChild(toggle);
if (open) {
const more = md(o.more, "md option-more");
more.id = bodyId;
li.appendChild(more);
}
}
list.appendChild(li);
}
card.appendChild(list);
card.appendChild(el("p", "help", "Pick as many as apply."));
renderPresets(card, item, staged);
renderCounter(card, item, chosen);
otherField(card, item, staged);
}
// The live pick and round count a long pick list carries (`counter`), so the
// person sees how many check rounds their ticks will cost before sending.
// Every tick, preset and clear stages, and staging redraws the card, so the
// count is always the one for the ticks on screen.
function renderCounter(card, item, chosen) {
const c = item.counter;
if (!c || typeof c !== "object" || typeof c.rounds !== "string" || !c.rounds) return;
const { picked, rounds } = multiCount(item, [...chosen]);
const text = `${picked} picked, ${rounds} ${c.rounds}`;
card.appendChild(el("p", "option-counter", text));
// The card is rebuilt on every tick, and a live region announces only a
// node already on the page: speak through the one fixed node in index.html.
announceCount(text);
}
function announceCount(text) {
const live = document.getElementById("pick-count-live");
if (live && live.textContent !== text) live.textContent = text;
}
// Shortcuts that tick a named set in one go, for a long list where the usual
// answers are groups ("the serious ones", "all of them"): the review's fix
// list is the case it exists for. A preset only ticks boxes. The answer is
// still the ticks, so they can adjust after pressing one, and what reaches the
// agent is the same list it would have got from ticking by hand.
function renderPresets(card, item, staged) {
const known = new Set((item.options || []).map((o) => o.k));
// A locked option is never part of a preset, whatever the preset names.
const known = new Set((item.options || []).filter((o) => o && o.locked !== true).map((o) => o.k));
const presets = (Array.isArray(item.presets) ? item.presets : [])
.map((p) => ({ label: String((p && p.label) || "").trim(), ks: ((p && p.ks) || []).filter((k) => known.has(k)) }))
.filter((p) => p.label && p.ks.length);
@@ -1607,6 +1722,323 @@ function buildList(card, item, staged) {
commentField(card, item, "Anything else about this breakdown?", false, quick);
}
/* ------------------------------------------------------ the lessons card */
// What the person has chosen on a lessons card, kept as a draft beside the
// staged answer: the pick and any edits per row, and whether they chose to
// leave everything waiting. The staged answer is built from it, and is held
// back while an edit is missing a required field.
const lessonsKey = (item) => "lessons-" + item.id;
function lessonsDraft(item) {
const raw = page.local.drafts[lessonsKey(item)];
let d = null;
try {
d = raw ? JSON.parse(raw) : null;
} catch {
d = null;
}
const picks = d && d.picks && typeof d.picks === "object" ? d.picks : {};
const edits = d && d.edits && typeof d.edits === "object" ? d.edits : {};
return { picks, edits, leaveAll: Boolean(d && d.leaveAll) };
}
// The answer the draft stands for, or null with the field still missing.
function lessonsAnswer(item, draft) {
const rows = item.rows || [];
const decisions = [];
let missing = "";
for (const row of rows) {
const choice = draft.picks[row.id];
if (!choice) continue;
const d = lessonDecision(row, choice, draft.edits[row.id] || {});
const gap = lessonMissing(row, d);
if (gap && !missing) missing = `${gap} is empty on “${row.text || row.id}”. Write it, or choose another option.`;
decisions.push(d);
}
if (missing) return { value: null, missing };
// Nothing chosen yet: only a typed note stays staged, as it would on any card.
if (!decisions.length && !draft.leaveAll) return { value: lessonsNote(item, null), missing: "" };
return { value: lessonsNote(item, { type: "answer", kind: "lessons", decisions }), missing: "" };
}
// withNote, also reading the note box's draft: while a field is empty the
// staged answer is taken back, note and all, and the box still shows the note.
function lessonsNote(item, value) {
const cur = page.local.staged[item.id];
const text = (cur && cur.text) || String(page.local.drafts["note-" + item.id] || "").trim();
if (!text) return value;
return value ? { ...value, text } : { type: "answer", kind: item.kind, text };
}
// What the draft leaves: "2 chosen, 1 left waiting."
function lessonsSummary(item, draft) {
const rows = item.rows || [];
const chosen = rows.filter((r) => draft.picks[r.id]).length;
const left = rows.length - chosen;
if (!chosen) return draft.leaveAll ? `Nothing chosen: all ${left} stay waiting.` : `Nothing chosen yet. ${left} waiting.`;
return `${chosen} chosen${left ? `, ${left} left waiting` : ""}.`;
}
const FLAG_WORDS = {
email: "an email address",
handle: "a handle (@name)",
"person-name": "a person's name",
};
function buildLessons(card, item, staged) {
if (item.firstAsk) return buildFirstAsk(card, item, staged);
const draft = lessonsDraft(item);
const summary = el("p", "lessons-summary");
summary.setAttribute("role", "status");
const error = el("p", "field-error lessons-error");
error.hidden = true;
// Save the draft and stage what it stands for. A pick redraws the card; an
// edit being typed does not, so the caret stays where it is.
const commit = (redrawCard) => {
setDraft(lessonsKey(item), JSON.stringify(draft));
const { value, missing } = lessonsAnswer(item, draft);
error.hidden = !missing;
error.textContent = missing;
summary.textContent = lessonsSummary(item, draft);
if (redrawCard) return stage(item.id, value);
stageQuiet(item.id, value);
stagedChanged();
};
if (item.opening) card.appendChild(el("p", "lessons-opening", item.opening));
const list = el("ul", "lessons-rows");
for (const row of item.rows || []) list.appendChild(lessonRow(item, row, draft, commit));
card.appendChild(list);
const { missing } = lessonsAnswer(item, draft);
error.hidden = !missing;
error.textContent = missing;
summary.textContent = lessonsSummary(item, draft);
card.appendChild(error);
const foot = el("div", "lessons-foot");
foot.appendChild(summary);
// Sending with nothing chosen is allowed: everything keeps waiting (FR-14).
const leave = el("button", "btn tiny" + (draft.leaveAll ? " primary" : ""), "Leave them all waiting");
leave.type = "button";
leave.setAttribute("aria-pressed", String(draft.leaveAll));
leave.addEventListener("click", () => {
draft.leaveAll = !draft.leaveAll;
if (draft.leaveAll) draft.picks = {};
commit(true);
});
foot.appendChild(leave);
card.appendChild(foot);
commentField(card, item, "Anything to add?");
}
// One waiting item: what it is, why, where it came from, and its own choices.
function lessonRow(item, row, draft, commit) {
const pick = draft.picks[row.id] || "";
const li = el("li", "lessons-row is-" + row.type + (pick ? " is-chosen" : ""));
li.dataset.row = row.id;
if (row.type === "doubt" || row.type === "gone") {
li.appendChild(el("p", "lessons-heading", row.heading || (row.type === "doubt" ? "This lesson may no longer be true:" : "Its files no longer exist.")));
li.appendChild(el("p", "lessons-text", row.text));
if (row.found) li.appendChild(el("p", "lessons-found", "Found: " + row.found));
} else if (row.type === "agents-fix") {
li.appendChild(el("p", "lessons-heading", "A fix to " + (row.file || "AGENTS.md")));
const pair = el("div", "lessons-fix");
pair.appendChild(el("p", "lessons-fix-label", "Before"));
pair.appendChild(el("blockquote", "lessons-before", row.before || "(a new line)"));
pair.appendChild(el("p", "lessons-fix-label", "After"));
pair.appendChild(el("blockquote", "lessons-after", row.after || row.text || ""));
li.appendChild(pair);
} else if (row.type === "log-line") {
li.appendChild(el("p", "lessons-text", row.text));
const become = (row.lessons || []).filter(Boolean);
if (become.length) {
li.appendChild(el("p", "lessons-heading", become.length === 1 ? "It would become this lesson:" : "It would become these lessons:"));
const ul = el("ul", "lessons-become");
for (const t of become) ul.appendChild(el("li", null, t));
li.appendChild(ul);
}
} else {
li.appendChild(el("p", "lessons-text", row.text));
}
if (row.why && row.type !== "area") li.appendChild(el("p", "lessons-why", "Why: " + row.why));
if (row.type === "area") li.appendChild(el("p", "lessons-why", row.why || "Paths: " + (row.paths || []).join(", ")));
// The doubt's and the fix's origin repeat what is drawn above them.
if (row.origin && !["doubt", "gone", "agents-fix"].includes(row.type)) li.appendChild(el("p", "lessons-origin", row.origin));
if (row.note) li.appendChild(el("p", "lessons-note", row.note));
for (const f of Array.isArray(row.flags) ? row.flags : []) {
const what = FLAG_WORDS[f && f.pattern] || "something personal";
li.appendChild(el("p", "lessons-flag", `Holds what looks like ${what}${f && f.part ? ` (“${f.part}”)` : ""}. Keep only if that is intended.`));
}
const reworded = lessonReworded(row, draft.edits[row.id] || {});
const keepWord = LESSON_KEEP_WORD[row.type];
if (row.refused) {
const part = row.refused.part ? ` (it starts “${row.refused.part}”)` : "";
li.appendChild(el("p", "lessons-refused", `Refused: part of it looks like a secret${part}. Reword it to ${keepWord.toLowerCase()} it.`));
}
// The choices, in the order given; a refused row shows its keep word
// unavailable until the words change.
const choices = [...(row.choices || [])];
if (row.refused && keepWord && !choices.includes(keepWord)) choices.unshift(keepWord);
const group = el("div", "lessons-choices");
group.setAttribute("role", "group");
group.setAttribute("aria-label", "Choices for: " + (row.text || row.id));
choices.forEach((word, i) => {
const on = pick === word;
const b = el("button", "btn small" + (on ? " primary" : ""), word);
b.type = "button";
b.id = `lesson-${item.id}-${row.id}-${i}`;
b.setAttribute("aria-pressed", String(on));
if (row.refused && word === keepWord && !reworded) {
b.disabled = true;
b.title = "Reword it first: part of it was refused.";
}
b.addEventListener("click", () => {
// Read the pick as the click lands: a refused row's typing can move it
// from Keep to Reword without a redraw.
const on = draft.picks[row.id] === word;
if (on) delete draft.picks[row.id];
else draft.picks[row.id] = word;
if (!on) draft.leaveAll = false;
// Opening an edit starts from the row's own words.
if (!on && LESSON_EDIT_WORDS.has(word) && !draft.edits[row.id]) draft.edits[row.id] = lessonEditStart(row);
commit(true);
// The redraw replaced the button; keep the keyboard where it was.
document.getElementById(b.id)?.focus();
});
group.appendChild(b);
});
li.appendChild(group);
// Reword (or Rename): the row opens in place with its words editable. A
// refused row keeps its reworded words while Keep is chosen, so Keep goes as
// a Reword of the new words.
const editing = LESSON_EDIT_WORDS.has(pick) || (row.refused && pick === keepWord);
if (editing) li.appendChild(lessonEditor(item, row, draft, commit));
return li;
}
function lessonEditor(item, row, draft, commit) {
const box = el("div", "lessons-edit");
if (!draft.edits[row.id]) draft.edits[row.id] = lessonEditStart(row);
const edit = draft.edits[row.id];
const base = `lesson-edit-${item.id}-${row.id}`;
const keepWord = LESSON_KEEP_WORD[row.type];
const input = (key, label, value, onValue) => {
const wrap = el("div", "field lessons-field");
const id = `${base}-${key}`;
const lab = el("label", null, label);
lab.htmlFor = id;
const field = el("input", "lessons-input");
field.type = "text";
field.id = id;
field.value = value || "";
field.addEventListener("input", () => {
onValue(field.value);
// A refused row's keep word becomes available the moment its words
// change; the rest of the card stays as it is, so the caret stays.
if (row.refused) {
const keep = [...box.parentNode.querySelectorAll(".lessons-choices button")].find((b) => b.textContent === keepWord);
if (keep) {
keep.disabled = !lessonReworded(row, edit);
if (keep.disabled) keep.title = "Reword it first: part of it was refused.";
else keep.removeAttribute("title");
// Back to the refused words: Keep cannot stand, so the row goes back to its edit word.
if (keep.disabled && draft.picks[row.id] === keepWord) {
draft.picks[row.id] = LESSON_EDIT_WORD[row.type];
keep.classList.remove("primary");
keep.setAttribute("aria-pressed", "false");
const editBtn = [...box.parentNode.querySelectorAll(".lessons-choices button")].find((b) => b.textContent === draft.picks[row.id]);
if (editBtn) {
editBtn.classList.add("primary");
editBtn.setAttribute("aria-pressed", "true");
}
}
}
}
commit(false);
});
wrap.append(lab, field);
return wrap;
};
if (row.type === "agents-fix") {
box.appendChild(input("after", "The new wording", edit.after, (v) => (edit.after = v)));
} else if (row.type === "area") {
box.appendChild(input("name", "The area's name", edit.name, (v) => (edit.name = v)));
box.appendChild(
input("paths", "Its paths (comma-separated)", (edit.paths || []).join(", "), (v) => (edit.paths = v.split(",").map((p) => p.trim()).filter(Boolean)))
);
} else {
if (row.type === "log-line") {
const list = Array.isArray(edit.lessons) ? edit.lessons : (edit.lessons = lessonEditStart(row).lessons);
list.forEach((t, i) =>
box.appendChild(input(`lesson-${i}`, list.length > 1 ? `Lesson ${i + 1}` : "The lesson", t, (v) => (list[i] = v)))
);
} else {
box.appendChild(input("text", "The lesson", edit.text, (v) => (edit.text = v)));
}
box.appendChild(input("why", "Why", edit.why, (v) => (edit.why = v)));
const areas = [...(Array.isArray(row.areas) ? row.areas : [])];
if (row.area && !areas.includes(row.area)) areas.unshift(row.area);
if (areas.length) {
const wrap = el("div", "field lessons-field");
const id = `${base}-area`;
const lab = el("label", null, "Saved in");
lab.htmlFor = id;
const sel = el("select", "lessons-select");
sel.id = id;
for (const a of areas) {
const o = el("option", null, a);
o.value = a;
if (a === (edit.area || row.area)) o.selected = true;
sel.appendChild(o);
}
sel.addEventListener("change", () => {
edit.area = sel.value;
commit(false);
});
wrap.append(lab, sel);
box.appendChild(wrap);
}
}
return box;
}
// The first ask (FR-30): the real lesson first, then what Learning is in three
// sentences, then the two answers and the line saying it can change later.
function buildFirstAsk(card, item, staged) {
const fa = item.firstAsk;
const lesson = el("div", "lessons-first-lesson");
lesson.appendChild(el("p", "lessons-text", (fa.lesson && fa.lesson.text) || ""));
if (fa.lesson && fa.lesson.why) lesson.appendChild(el("p", "lessons-why", "Why: " + fa.lesson.why));
card.appendChild(lesson);
const about = el("div", "lessons-first-about");
for (const s of fa.sentences || []) about.appendChild(md(s, "md"));
card.appendChild(about);
const row = el("div", "btn-row");
for (const [answer, label] of [
["yes", fa.yes],
["no", fa.no],
]) {
const on = staged && staged.firstAsk === answer;
const b = el("button", "btn" + (on ? " primary" : answer === "yes" ? " is-approve" : ""), label);
b.type = "button";
b.setAttribute("aria-pressed", String(Boolean(on)));
b.addEventListener("click", () => stage(item.id, withNote(item, on ? null : { type: "answer", kind: "lessons", firstAsk: answer })));
row.appendChild(b);
}
card.appendChild(row);
if (fa.later) card.appendChild(el("p", "help lessons-later", fa.later));
commentField(card, item, "Anything to add?");
}
const PHASE_WORKFLOWS = ["plan", "revise-plan"];
const COMBINE_PHASES =
"Combine phases where possible to simplify and reduce the total number of phases, while still keeping a clear separation of concerns.";
@@ -1672,6 +2104,7 @@ const BUILDERS = {
checklist: buildChecklist,
menu: buildMenu,
list: buildList,
lessons: buildLessons,
};
// The listeners that keep the cards honest, wired once at start-up: the fade at
+12 -3
View File
@@ -25,6 +25,7 @@ import {
finishPaused,
handoffText,
indentReply,
lessonsReply,
noteAction,
noteReplyLines,
progressTotal,
@@ -84,9 +85,11 @@ import { mountAgentsView } from "./agents-view.js";
// What the entry needs from the screens at start-up, handed on from here: only
// the core imports a screen.
export { launchSkill, wakeHoldsChime, wireDashboard } from "./dashboard.js";
export { launchSkill, sendLearning, wakeHoldsChime, wireDashboard } from "./dashboard.js";
export { renderLearningRow, learningBlocked, refreshLessonsSend } from "./learning-row.js";
import { renderLessonsDialog } from "./learning-row.js";
export { fillSky } from "./starting.js";
export { fitGrowBox, wireCards } from "./cards.js";
export { fitGrowBox, wireCards, renderCard } from "./cards.js";
export { wireDocs } from "./docs.js";
export { wireAsk } from "./ask.js";
export { syncWorkspaceScope, wireWorkspace } from "./workspace.js";
@@ -1753,8 +1756,11 @@ function paintMain(main) {
renderDashboard(main);
}
} else renderDashboard(main);
// Review from the Learning banner: the lessons card, over the menu.
renderLessonsDialog(!page.local.launching && !page.loopSetup && !page.dashPick);
return;
}
renderLessonsDialog(false);
// The git board stays up after every action until Done with git. The
// agent's confirm and result cards sit in the board's cardSlot, under the
@@ -2097,7 +2103,8 @@ export function markSent({ sentIds, sentNotes = {}, summaries, values }) {
// even when an answer on the same item went. The sent images' files stay
// on disk for the agent; the sweep cleans them up.
for (const id of sentIds) {
for (const prefix of ["other-", "text-", "note-"]) delete page.local.drafts[prefix + id];
// `lessons-` is the lessons card's picks: a later card must start with nothing chosen.
for (const prefix of ["other-", "text-", "note-", "lessons-"]) delete page.local.drafts[prefix + id];
if (sentNotes[id]) {
clearSentNote(id, sentNotes[id]);
} else if (!page.local.images[id]) {
@@ -2279,6 +2286,8 @@ const STATE_WORDS = { done: "all done", blocked: "blocked", help: "need help", d
function tokenFor(item, v) {
const map = item.token || {};
if (v.skipped) return v.text ? `skip; ${v.text}` : "skip";
// The lessons card: a line per decision and the decisions file's JSON.
if (item.kind === "lessons") return lessonsReply(item, v);
const parts = [];
if (v.k) parts.push(map[v.k] || v.k);
if (Array.isArray(v.ks) && v.ks.length) parts.push(v.ks.map((k) => map[k] || k).join(", "));
+68 -4
View File
@@ -43,6 +43,9 @@ import {
deleteHandoffReply,
deleteAction,
deleteReply,
learningAction,
learningReply,
learningBannerText,
noteSwitchShows,
noteTabEmpty,
defaultNoteTicks,
@@ -198,6 +201,10 @@ export function renderDashboard(main) {
notice.append(open, dismiss);
wrap.appendChild(notice);
}
// Lessons waiting for review: last of the banners, so it sits nearest the
// title (the others are more urgent). Hidden while paused or off.
const learnBanner = learningBanner(scan());
if (learnBanner) wrap.appendChild(learnBanner);
wrap.appendChild(el("p", "card-kicker", "Plan2Code"));
wrap.appendChild(el("h2", "dash-title", "What are we doing today?"));
// The agent's note reads the spec the picker opened on (the same "initial"
@@ -243,6 +250,10 @@ export function renderDashboard(main) {
return;
}
wrap.appendChild(hideUnavailableToggle());
// Learning while it needs the person (not set up, off, paused): under the
// picker. Never while a handoff preview shows (returned above).
const learnTop = hooks.renderLearningRow(scan(), "top");
if (learnTop) wrap.appendChild(learnTop);
// Only when this tab's own pick moved: another tab changing the scope
// sends a frame here too, and re-asserting this tab's pick on every render
// had two dashboards trade the workspace back and forth without end.
@@ -276,6 +287,9 @@ export function renderDashboard(main) {
el("p", "dash-empty", "Nothing fits this pick right now. Turn off the toggle above to see every workflow.")
);
}
// Learning while on: after the last card group, before the approval tip.
const learnBottom = hooks.renderLearningRow(scan(), "bottom");
if (learnBottom) wrap.appendChild(learnBottom);
wrap.appendChild(approvalTip());
// Mid wake-up: the groups wait hidden until the glide lets them rise in,
// and the note shows only as far as it has been typed. Once the entrance
@@ -1149,9 +1163,12 @@ export async function launchSkill(entry) {
};
// The picker's spec goes to the skill being launched, not to the card:
// cards that take no spec (utilities, setup) launch untargeted even while
// a spec is selected, save Quick Task on a diagnosed bug or a folder of
// saved prototypes (launchTarget).
// a spec is selected, save Quick Task on a diagnosed bug, an upgrade brief
// or a folder of saved prototypes (launchTarget).
if (target) action.spec = target.dir;
// Launched from a dashboard showing lessons waiting: the skill's Start reads
// with --from-banner (shared-references/lessons.md).
if (learningBannerText(scan() && scan().learning)) action.fromBanner = true;
// A Notebook tab picked in the pane rides the hop in this page only, never
// on the action: the launched skill's `fill: "note"` box is filled from it
// (core.js), and the agent reads it only when that box is sent.
@@ -1253,14 +1270,15 @@ function openHandoffDelete(h) {
function openDeleteConfirm(spec) {
if (!isDeletableSpecDir(spec.dir) || page.gone || page.pendingResult || page.local.launching || page.local.deleting) return;
deleteTarget = spec;
// A finished spec (a fixed bug): one confirm, and a warning that says so.
// A finished spec (a fixed bug, a done upgrade): one confirm, and a warning that says so.
const fixed = Boolean(stateFor(spec.state)?.finished);
const done = spec.state === "upgraded" ? "The upgrade is done, so this only clears the brief. " : "The bug is fixed, so this only clears the write-up. ";
$("delete-title").textContent = "Delete this spec?";
const warn = $("delete-warn");
if (!deleteWarnDefault) deleteWarnDefault = [...warn.childNodes].map((n) => n.cloneNode(true));
warn.replaceChildren(
...(fixed
? ["The bug is fixed, so this only clears the write-up. ", el("code", "", "specs/"), " is not tracked by git, so it cannot be brought back."]
? [done, el("code", "", "specs/"), " is not tracked by git, so it cannot be brought back."]
: deleteWarnDefault.map((n) => n.cloneNode(true)))
);
warn.hidden = false;
@@ -1372,6 +1390,52 @@ async function sendDelete(spec) {
}
}
// The Learning banner above the title, or null: only while lessons wait and
// Learning is on or not set up. Review sends the __learning action.
function learningBanner(sc) {
const text = learningBannerText(sc && sc.learning);
if (!text) return null;
const banner = el("div", "dash-nudge learn-banner");
banner.setAttribute("role", "status");
banner.appendChild(el("span", "dash-nudge-text", text));
const review = el("button", "btn small primary", "Review");
review.type = "button";
const why = hooks.learningBlocked();
review.disabled = Boolean(why);
if (why) review.title = why;
review.addEventListener("click", () => sendLearning("review"));
banner.appendChild(review);
return banner;
}
// A Learning control that changes the project: a __learning action to the
// dashboard agent, posted the way sendDelete() posts. No hop: the agent runs
// lessons.mjs, rescans and posts the menu again.
export async function sendLearning(what) {
if (hooks.learningBlocked()) return;
try {
const res = await fetch("/submit", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: [learningAction(what)], reply: learningReply(what) }),
});
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
if (!res.ok) throw new Error(String(res.status));
page.pendingResult = true;
saveNow();
} catch (err) {
if (err && err.pending) page.pendingResult = true;
hooks.banner(
err && err.pending
? "Your last pick is still being picked up, so that could not go yet. Try again in a moment."
: "That did not go through. Nothing changed; try again.",
"warn"
);
} finally {
redraw();
}
}
// The dialogs' buttons, wired once at start-up: the update notice's Done, the
// handoff preview's close, and the delete dialog's Cancel, name box and go.
export function wireDashboard() {
+31 -1
View File
@@ -29,6 +29,7 @@ import {
DASHBOARD_REPLY,
COMMIT_REPLY,
CHANGELOG_REPLY,
loopLessonsLine,
} from "../answers.js";
import { hooks, page, saveNow, redraw } from "../state.js";
@@ -168,6 +169,24 @@ let loopPressed = null;
// app for a second agent. Keyed by the ending it was pressed on.
let askUpFor = null;
// The waiting-lessons line under a loop stop's reason (FR-13): fetched once per
// ending from /learning/state, then drawn; a failed fetch adds nothing.
let loopLessons = { key: null, line: "" };
function loopLessonsFor(key) {
if (loopLessons.key === key) return loopLessons.line;
loopLessons = { key, line: "" };
fetch("/learning/state", { cache: "no-store" })
.then((res) => (res.ok ? res.json() : null))
.then((learning) => {
const line = loopLessonsLine(learning);
if (loopLessons.key !== key || !line) return;
loopLessons.line = line;
redraw();
})
.catch(() => {});
return "";
}
// Whether the stop screen's Details is open, kept across redraws (keyed like askUpFor).
let loopDetailsOpen = null;
@@ -226,7 +245,18 @@ export function renderLoopEnd(end) {
// long, goes under it rather than in the heading.
const reason = !finished && typeof end.reason === "string" && end.reason ? end.reason : "";
card.appendChild(el("h2", "loop-end-heading", finished ? "Every phase is built" : reason || end.line));
if ((finished || reason) && end.line) card.appendChild(el("p", "loop-line", end.line));
// On a stop the full line is the colored reason, and the advice sits under it.
if ((finished || reason) && end.line) card.appendChild(el("p", finished ? "loop-line" : "loop-line loop-why", end.line));
if (!finished && typeof end.advice === "string" && end.advice) {
const next = el("p", "loop-advice");
next.appendChild(el("strong", null, "What to do next: "));
next.appendChild(document.createTextNode(end.advice));
card.appendChild(next);
}
if (!finished) {
const lessons = loopLessonsFor(loopEndKey(end));
if (lessons) card.appendChild(el("p", "loop-line loop-lessons", lessons));
}
const evidence = end.evidence && docs().find((d) => d.id === end.evidence);
if (evidence) {
@@ -0,0 +1,374 @@
// Plan2Code Web Console - Learning's row on the dashboard: one slim line in four
// states and two places, built from the saved prototype (specs/project-learning
// prototypes/learning-row.html, variant A). Under the spec picker while it needs
// the person (not set up, off, paused); after the last card group while on.
//
// Pause for me is the one control that needs no agent: it posts to
// /learning/pause and the server pushes the new scan. Everything that changes
// the project goes to the dashboard agent as a __learning action (sendLearning
// in dashboard.js, reached through hooks: a screen never imports another),
// and is disabled whenever a card would be.
import { page, redraw, hooks } from "../state.js";
import { el, mdInto, lightDismiss } from "../render.js";
import { postJson } from "../net.js";
import { sendState } from "../send-state.js";
import { loopDriving, isOpen, stagedCount } from "../selectors.js";
const TOP_STATES = new Set(["not-set-up", "off", "paused"]);
const PILLS = {
"not-set-up": { text: "Not set up", cls: "" },
off: { text: "Off", cls: "" },
on: { text: "On", cls: " is-on" },
paused: { text: "Paused for you", cls: " is-hold" },
};
// The More menu stays open across the dashboard's redraws until it is closed.
let moreOpen = false;
// A pause post in flight: the switch holds until the pushed state lands.
let pausing = false;
/** "Nov 13", the way the page's other short dates read. */
function shortDate(iso) {
const at = new Date(iso);
if (!iso || Number.isNaN(at.getTime())) return "";
return at.toLocaleDateString(undefined, { month: "short", day: "numeric" });
}
/**
* Why an agent-run control is unavailable, or "" when it can be pressed: the
* same conditions that disable a dashboard card (dashCard()).
*/
export function learningBlocked() {
if (page.gone) return "Plan2Code is not answering right now.";
if (page.pendingResult) return "Plan2Code is still picking up your last choice.";
if (page.local && page.local.launching) return "A workflow is starting.";
if (loopDriving()) return "The Implementation Loop is running.";
return "";
}
function agentButton(text, cls, what) {
const b = el("button", cls, text);
b.type = "button";
const why = learningBlocked();
b.disabled = Boolean(why);
if (why) b.title = why;
b.addEventListener("click", () => {
if (!learningBlocked()) hooks.sendLearning(what);
});
return b;
}
function pauseSwitch(paused) {
const b = el("button", "learn-switch" + (paused ? " is-on" : ""));
b.type = "button";
b.setAttribute("role", "switch");
b.setAttribute("aria-checked", paused ? "true" : "false");
b.disabled = pausing || Boolean(page.gone);
if (page.gone) b.title = "The console is not reachable right now.";
const track = el("span", "learn-track");
track.setAttribute("aria-hidden", "true");
b.append(track, document.createTextNode("Pause for me"));
b.addEventListener("click", async () => {
if (pausing) return;
pausing = true;
redraw();
const { status } = await postJson("/learning/pause", { paused: !paused });
pausing = false;
if (status !== 200) {
hooks.banner(
status === 409 ? "Learning is no longer on for this project, so there is nothing to pause." : "The pause did not go through. Try again.",
"warn"
);
}
redraw();
});
return b;
}
function closeMore(focusButton) {
if (!moreOpen) return;
moreOpen = false;
redraw();
if (focusButton) queueMicrotask(() => document.querySelector(".learn-row .learn-more-btn")?.focus());
}
function moreMenu() {
const wrap = document.createDocumentFragment();
const btn = el("button", "learn-link learn-more-btn", "More ▴");
btn.type = "button";
btn.setAttribute("aria-haspopup", "menu");
btn.setAttribute("aria-expanded", moreOpen ? "true" : "false");
btn.addEventListener("click", () => {
moreOpen = !moreOpen;
redraw();
if (moreOpen) queueMicrotask(() => document.querySelector(".learn-more [role=menuitem]:not([aria-disabled=true])")?.focus());
});
btn.addEventListener("keydown", (e) => {
if (e.key === "ArrowUp" || e.key === "ArrowDown") {
e.preventDefault();
moreOpen = true;
redraw();
queueMicrotask(() => document.querySelector(".learn-more [role=menuitem]")?.focus());
}
});
const list = el("ul", "learn-more");
list.setAttribute("role", "menu");
list.setAttribute("aria-label", "More Learning actions");
list.hidden = !moreOpen;
const why = learningBlocked();
const item = (text, act, cls = "") => {
const li = el("li", "learn-more-item" + cls, text);
li.setAttribute("role", "menuitem");
li.tabIndex = -1;
if (why) {
li.setAttribute("aria-disabled", "true");
li.title = why;
}
const run = () => {
if (learningBlocked()) return;
moreOpen = false;
act();
redraw();
};
li.addEventListener("click", run);
li.addEventListener("keydown", (e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
run();
}
});
return li;
};
list.append(
item("Switch off for this project", () => hooks.sendLearning("switch-off")),
item("Move the failure log into lessons", () => hooks.sendLearning("move-log")),
item("Remove all lessons…", () => openRemoveConfirm(), " is-danger")
);
list.addEventListener("keydown", (e) => {
const items = [...list.querySelectorAll("[role=menuitem]")];
const at = items.indexOf(document.activeElement);
if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
closeMore(true);
} else if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
const step = e.key === "ArrowDown" ? 1 : -1;
items[(at + step + items.length) % items.length]?.focus();
} else if (e.key === "Home" || e.key === "End") {
e.preventDefault();
(e.key === "Home" ? items[0] : items[items.length - 1])?.focus();
} else if (e.key === "Tab") {
closeMore(false);
}
});
wrap.append(btn, list);
return wrap;
}
// One listener for the page's life: a click outside the row, or Escape
// anywhere, closes an open More menu.
let outsideWired = false;
function wireOutside() {
if (outsideWired) return;
outsideWired = true;
document.addEventListener("pointerdown", (e) => {
if (moreOpen && !(e.target instanceof Element && e.target.closest(".learn-more, .learn-more-btn"))) closeMore(false);
});
document.addEventListener("keydown", (e) => {
if (moreOpen && e.key === "Escape") closeMore(true);
});
}
/* ------------------------------------------------------------- the dialogs */
/**
* Review from the dashboard (FR-18): the dashboard agent posts the lessons
* card while the workflow is still `dashboard`, and its page draws no question
* cards, so the card is shown here, in a dialog over the menu, built by the
* same builder as on any other page (reached through hooks). It opens while an
* open lessons item waits for the person and closes once it is sent or
* answered. `on` is false off the dashboard menu, which closes it.
*/
export function renderLessonsDialog(on) {
const items = (page.S && Array.isArray(page.S.items) && page.S.items) || [];
const item = on ? items.find((i) => i && i.kind === "lessons" && isOpen(i)) : null;
// Any send closes it for good: a dashboard lessons card is never asked
// again, and once the agent collects the send and goes back to waiting, the
// page no longer counts it in flight while the card may still read open.
const sent = item && ((page.local.sent && page.local.sent[item.id]?.value) || item.submitted);
let dlg = document.getElementById("lessons-modal");
if (!item || sent) {
if (dlg && dlg.open) dlg.close();
return;
}
if (!dlg) {
dlg = el("dialog", "modal lessons-dialog");
dlg.id = "lessons-modal";
dlg.setAttribute("aria-label", "Lessons to review");
// Not light-dismissed, and Escape does not close it: the agent is waiting
// on this card, and the dialog is the only place it is drawn. Leave them
// all waiting, then Send, is the way out.
dlg.addEventListener("cancel", (e) => e.preventDefault());
document.body.appendChild(dlg);
}
const scroll = dlg.scrollTop;
const card = hooks.renderCard(item);
const actions = el("div", "modal-actions");
const go = el("button", "btn primary", "Send to Plan2Code");
go.type = "button";
go.id = "lessons-send";
go.addEventListener("click", () => hooks.send());
actions.appendChild(go);
if (stagedCount() > 1) actions.appendChild(el("p", "help", "Anything else ready to send goes with it."));
dlg.replaceChildren(card, actions);
refreshLessonsSend();
if (!dlg.open) dlg.showModal();
dlg.scrollTop = scroll;
}
/**
* The dialog's Send, set again whenever what is staged changes, including the
* quiet staging of typing (a Reword field emptied, a note): on only while the
* lessons card holds an answer and a send can go.
*/
export function refreshLessonsSend() {
const go = document.getElementById("lessons-send");
if (!go) return;
const items = (page.S && Array.isArray(page.S.items) && page.S.items) || [];
const item = items.find((i) => i && i.kind === "lessons" && isOpen(i));
go.disabled = !item || !page.local.staged[item.id] || sendState().disabled;
}
function dialog(id, cls, title) {
let dlg = document.getElementById(id);
if (dlg) return dlg;
dlg = el("dialog", "modal " + cls);
dlg.id = id;
dlg.setAttribute("aria-labelledby", id + "-title");
const h = el("h2", null, title);
h.id = id + "-title";
dlg.appendChild(h);
document.body.appendChild(dlg);
lightDismiss(dlg);
return dlg;
}
// Remove all lessons asks first, in the style of the spec delete dialog.
function openRemoveConfirm() {
let dlg = document.getElementById("learn-remove-modal");
if (!dlg) {
dlg = dialog("learn-remove-modal", "learn-remove", "Remove all lessons?");
dlg.appendChild(el("p", "modal-blurb", "Remove all saved lessons from this project? Learning stays on."));
const actions = el("div", "modal-actions");
const keep = el("button", "btn ghost", "Keep them");
keep.type = "button";
keep.addEventListener("click", () => dlg.close());
const go = el("button", "btn danger is-on", "Remove all lessons");
go.type = "button";
go.id = "learn-remove-go";
go.addEventListener("click", () => {
dlg.close();
if (!learningBlocked()) hooks.sendLearning("remove");
});
actions.append(keep, go);
dlg.appendChild(actions);
}
dlg.showModal();
}
// Open the lessons: every lesson file, read-only, through the page's Markdown.
async function openLessons() {
let dlg = document.getElementById("learn-lessons-modal");
if (!dlg) {
dlg = dialog("learn-lessons-modal", "handoff-read learn-lessons", "The project's lessons");
const where = el("p", "modal-blurb learn-lessons-where");
mdInto(where, "The project's lessons (`.plan2code/lessons/`, saved with the repository)");
const body = el("div", "handoff-body md learn-lessons-body");
const actions = el("div", "modal-actions");
const close = el("button", "btn ghost", "Close");
close.type = "button";
close.addEventListener("click", () => dlg.close());
actions.appendChild(close);
dlg.append(where, body, actions);
}
const body = dlg.querySelector(".learn-lessons-body");
body.replaceChildren(el("p", "md-p", "Reading…"));
dlg.showModal();
try {
const res = await fetch("/learning/lessons", { cache: "no-store" });
if (res.status !== 200) throw new Error(String(res.status));
const { files } = await res.json();
body.replaceChildren();
if (!files || !files.length) {
body.appendChild(el("p", "md-p", "No lessons are saved in this project yet."));
return;
}
for (const f of files) {
const part = el("section", "learn-lessons-file");
part.appendChild(el("p", "learn-lessons-name", f.name));
const text = el("div", "md");
mdInto(text, f.text || "");
part.appendChild(text);
body.appendChild(part);
}
} catch {
body.replaceChildren(el("p", "md-p", "The lessons could not be read."));
}
}
/* ----------------------------------------------------------------- the row */
/**
* The Learning row for `position` ("top" or "bottom"), or null: the top place
* takes Not set up, Off and Paused, the bottom place takes On, and no row is
* drawn when the scan carries no `learning` (an unknown settings format).
*/
export function renderLearningRow(scan, position) {
const learning = scan && scan.learning;
if (!learning || !PILLS[learning.state]) return null;
const top = TOP_STATES.has(learning.state);
if ((position === "top") !== top) return null;
if (position !== "top" && position !== "bottom") return null;
wireOutside();
const state = learning.state;
const row = el("section", `learn-row is-${position} is-${state}`);
row.setAttribute("aria-label", "Learning");
row.dataset.learning = state;
const line = el("div", "learn-line");
line.appendChild(el("span", "learn-label", "Learning"));
const pill = PILLS[state];
line.appendChild(el("span", "learn-pill" + pill.cls, pill.text));
const controls = el("span", "learn-controls");
if (state === "not-set-up") {
line.appendChild(el("span", "learn-say", "Plan2Code can keep lessons about this codebase, approved by you."));
controls.appendChild(agentButton("Switch on", "btn small primary", "switch-on"));
} else if (state === "off") {
line.appendChild(el("span", "learn-say", "Off for this project."));
controls.appendChild(agentButton("Switch on", "btn small", "switch-on"));
} else if (state === "paused") {
const since = shortDate(learning.pausedSince);
line.appendChild(
el(
"span",
"learn-say",
`On for this project. Paused ${since ? "since " + since : "for you"}: your runs are not reading or offering lessons.`
)
);
controls.appendChild(pauseSwitch(true));
} else {
line.appendChild(el("span", "learn-say", "On for this project."));
controls.appendChild(pauseSwitch(false));
const open = el("button", "learn-link", "Open the lessons");
open.type = "button";
open.addEventListener("click", openLessons);
controls.appendChild(open);
controls.appendChild(moreMenu());
}
line.appendChild(controls);
row.appendChild(line);
if (state !== "on") moreOpen = false;
return row;
}
@@ -21,6 +21,10 @@
flex-direction: column;
}
.modal.activities[open] { display: flex; }
/* While the picker is showing, the two columns of rows only need so much room:
wider and the name and blurb sit far from their score. A game keeps the
whole window. */
.modal.activities:has(#activities-picker:not([hidden])) { max-width: 1100px; }
.modal.activities h2,
.modal.activities .modal-blurb,
.modal.activities .modal-actions { flex: none; }
@@ -714,6 +714,12 @@
.loop-end-phases code { font-family: var(--mono); font-size: 12px; }
.loop-end-files { margin: 0; padding-left: 18px; font-family: var(--mono); font-size: 12px; color: var(--ink-2); }
.loop-end-heading, .loop-end .loop-line { overflow-wrap: anywhere; }
.loop-end .loop-why, .loop-end .loop-advice {
padding: 9px 13px; border-left: 4px solid var(--warn); border-radius: 0 6px 6px 0;
background: var(--warn-soft); color: var(--ink); font-size: 14px; line-height: 1.5; max-width: 75ch; margin: 0;
}
.loop-end .loop-advice { border-left-color: var(--accent); background: var(--accent-soft); }
.loop-end .loop-advice strong { color: var(--accent); }
/* Each button with one plain line under it saying what it does. */
.loop-end-actions { display: grid; grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); gap: 12px; }
.loop-end-choice { display: grid; gap: 6px; align-content: start; justify-items: start; }
+4
View File
@@ -86,6 +86,10 @@
padding: 1px 5px;
overflow-wrap: anywhere;
}
/* Help, "Learning": one example lesson, set apart like a quoted card. */
.help-panel .help-example { margin: 0 0 12px; padding: 10px 12px; background: var(--panel-2); border: 1px solid var(--rule); border-left-width: 4px; border-radius: var(--radius); }
.help-panel .help-example p { margin: 0 0 4px; }
.help-panel .help-example p:last-child { margin-bottom: 0; }
/* Help, "When something looks stuck": a calm callout and a symptom / cause / action list. */
.help-panel .help-callout {
display: flex; align-items: flex-start; gap: 12px;
+198
View File
@@ -0,0 +1,198 @@
/* Learning on the dashboard: the slim row (screens/learning-row.js) and the
waiting banner. From the saved prototype's variant A
(specs/project-learning/prototypes/learning-row.html), on the page's own
tokens: the prototype's hold color is --stage, its border --rule. */
/* The row. Under the spec picker while it needs the person (not set up, off,
paused); after the last card group while on. */
.learn-row { position: relative; }
.learn-row.is-top { margin: 0 0 22px; }
.learn-row.is-bottom { margin: 4px 0 18px; }
.learn-line {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px 12px;
padding: 8px 12px;
border-top: 1px solid var(--rule);
border-bottom: 1px solid var(--rule);
font-size: 14px;
color: var(--ink);
}
/* Paused for you: the amber tint, so a paused person sees it at a glance. */
.learn-row.is-paused .learn-line {
background: var(--stage-soft);
border: 1px solid var(--stage);
border-radius: calc(var(--radius) * 0.7);
}
.learn-label { font-weight: 650; }
.learn-pill {
font-size: 10.5px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
padding: 2px 8px;
border: 1px solid var(--rule-2);
border-radius: 999px;
color: var(--ink-3);
}
.learn-pill.is-on { color: var(--accent); border-color: var(--accent); }
.learn-pill.is-hold { color: var(--stage); border-color: var(--stage); }
.learn-say { flex: 1 1 14em; min-width: 0; color: var(--ink-3); }
.learn-row.is-paused .learn-say { color: var(--ink); }
.learn-controls { margin-left: auto; display: flex; align-items: center; gap: 12px; }
.learn-controls .btn { margin: 0; }
/* Pause for me: a sliding switch. Amber while paused. */
.learn-switch {
display: inline-flex;
align-items: center;
gap: 8px;
font: inherit;
min-height: 24px;
padding: 0;
background: none;
border: 0;
color: var(--ink);
cursor: pointer;
}
.learn-switch:disabled { opacity: 0.45; cursor: not-allowed; }
.learn-track {
position: relative;
flex: none;
width: 34px;
height: 20px;
box-sizing: border-box;
border-radius: 999px;
background: var(--bg);
border: 1px solid var(--rule-2);
}
.learn-track::after {
content: "";
position: absolute;
top: 2px;
left: 2px;
width: 14px;
height: 14px;
border-radius: 50%;
background: var(--ink-3);
transition: left 0.15s ease;
}
.learn-switch.is-on .learn-track { background: var(--stage); border-color: var(--stage); }
.learn-switch.is-on .learn-track::after { left: 16px; background: var(--panel); }
.learn-switch:hover:not(:disabled) .learn-track { border-color: var(--accent); }
.learn-link {
font: inherit;
font-size: 13px;
min-height: 24px;
padding: 0 4px;
background: none;
border: 0;
color: var(--accent);
text-decoration: underline;
cursor: pointer;
}
.learn-link:hover { text-decoration-thickness: 2px; }
.learn-switch:focus-visible,
.learn-link:focus-visible,
.learn-more-item:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
/* More: at the bottom of the page, so it opens upward. */
.learn-more {
position: absolute;
right: 0;
bottom: 100%;
z-index: 5;
min-width: 17em;
margin: 0 0 4px;
padding: 4px;
list-style: none;
text-align: left;
background: var(--panel);
border: 1px solid var(--rule);
border-radius: calc(var(--radius) * 0.7);
box-shadow: var(--shadow);
font-size: 13.5px;
color: var(--ink);
}
.learn-more[hidden] { display: none; }
.learn-more-item { padding: 7px 10px; border-radius: calc(var(--radius) * 0.5); cursor: pointer; }
.learn-more-item:hover,
.learn-more-item:focus { background: var(--accent-soft); outline: none; }
.learn-more-item.is-danger { color: var(--warn); border-top: 1px solid var(--rule); border-top-left-radius: 0; border-top-right-radius: 0; }
.learn-more-item[aria-disabled="true"] { opacity: 0.45; cursor: not-allowed; }
.learn-more-item[aria-disabled="true"]:hover { background: none; }
/* Lessons waiting: the banner nearest the title, in the accent tint. */
.dash-nudge.learn-banner { border-left-width: 4px; }
.learn-banner .btn { margin: 0 0 0 auto; }
/* Open the lessons: each file under its own name. */
.learn-lessons-file + .learn-lessons-file { margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--rule); }
.learn-lessons-name { margin: 0 0 6px; font-family: var(--mono); font-size: 12.5px; color: var(--ink-3); }
/* The lessons card (screens/cards.js buildLessons): one block per waiting
item, each with its own choices and nothing chosen at first. */
.lessons-opening { margin: 14px 0 0; font-size: 13.5px; color: var(--ink-3); }
.lessons-rows { list-style: none; margin: 14px 0 0; padding: 0; display: grid; gap: 12px; }
.lessons-row {
padding: 12px 14px;
border: 1px solid var(--rule);
border-radius: calc(var(--radius) * 0.7);
background: var(--panel);
}
.lessons-row.is-chosen { border-color: var(--accent); }
.lessons-row p { margin: 0 0 6px; }
.lessons-heading { font-size: 12.5px; font-weight: 650; color: var(--ink-2); }
.lessons-text { font-weight: 600; color: var(--ink); }
.lessons-why,
.lessons-found { font-size: 13.5px; color: var(--ink-2); }
.lessons-origin,
.lessons-note { font-size: 12.5px; color: var(--ink-3); }
.lessons-fix-label { font-size: 11.5px; font-weight: 700; letter-spacing: 0.06em; text-transform: uppercase; color: var(--ink-3); }
.lessons-fix blockquote {
margin: 0 0 8px;
padding: 6px 10px;
border-left: 3px solid var(--rule-2);
font-family: var(--mono);
font-size: 12.5px;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.lessons-fix .lessons-after { border-left-color: var(--accent); }
.lessons-become { margin: 0 0 6px; padding-left: 18px; font-size: 13.5px; }
/* Flagged and refused: said in words, not only in color. */
.lessons-flag,
.lessons-refused {
padding: 5px 9px;
border-radius: calc(var(--radius) * 0.5);
font-size: 13px;
background: var(--stage-soft);
color: var(--ink);
}
.lessons-refused { background: var(--warn-soft); color: var(--warn); }
.lessons-choices { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
.lessons-choices .btn { margin: 0; }
.lessons-edit { margin-top: 10px; display: grid; gap: 8px; }
.lessons-field { margin: 0; }
.lessons-input,
.lessons-select { width: 100%; box-sizing: border-box; }
.lessons-error { margin: 10px 0 0; }
.lessons-foot { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; margin-top: 12px; }
.lessons-summary { margin: 0; font-size: 13.5px; color: var(--ink-2); }
.lessons-foot .btn { margin: 0 0 0 auto; }
.lessons-first-lesson {
margin: 14px 0 0;
padding: 12px 14px;
border-left: 4px solid var(--accent);
background: var(--accent-soft);
border-radius: calc(var(--radius) * 0.5);
}
.lessons-first-lesson p { margin: 0 0 4px; }
.lessons-first-about { margin: 12px 0 0; }
.lessons-later { margin-top: 8px; }
/* Review from the dashboard: the same card in a dialog over the menu. */
.modal.lessons-dialog { width: min(720px, calc(100vw - 32px)); }
.lessons-dialog .card { margin: 0; box-shadow: none; border: 0; padding: 0; }