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

+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;
}