Grade every waiting lesson with a separate check before the lessons card asks for approval

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-27 23:19:42 -08:00
1 parent b06a4cb4ab
commit 1345aa0a95
36 files changed
+2812 -139

No files matched your search

+1 -1
View File
@@ -26,7 +26,7 @@ The ✕ on a chip (after the page's two-step confirm) sends `session:[{"i":"__de
## A Learning action
The Learning row and banner send `session:[{"i":"__learning","do":"switch-on"}]` (`do` is `review`, `switch-on`, `switch-off`, `move-log` or `remove`; Remove was confirmed on the page). No hop: you stay the dashboard. Run `lessons.mjs` as the dashboard skill's "A Learning action arrives" says (a `review` while Learning is not set up is `list --first-ask` and the first ask, before anything is kept; the lessons card is the only question this page shows), then `open --resume <sid> --no-open --workflow dashboard` and post the menu again with `--wait`. Pause for me never reaches you: the page saves it itself. A `__launch` with `fromBanner: true` came from a dashboard showing lessons waiting.
The Learning row and banner send `session:[{"i":"__learning","do":"switch-on"}]` (`do` is `review`, `switch-on`, `switch-off`, `move-log`, `remove` or `tidy`; Remove was confirmed on the page). No hop: you stay the dashboard. Run `lessons.mjs` as the dashboard skill's "A Learning action arrives" says (a `review` while Learning is not set up is `list --first-ask` and the first ask, before anything is kept; the lessons card is the only question this page shows), then `open --resume <sid> --no-open --workflow dashboard` and post the menu again with `--wait`. Pause for me never reaches you: the page saves it itself. A `__launch` with `fromBanner: true` came from a dashboard showing lessons waiting.
## A strength suggestion
+78 -1
View File
@@ -126,6 +126,49 @@ export function writePause(cwd, paused, now) {
return { paused: true, since };
}
/* ------------------------------------------------------------ follow counts */
/** One line per "Following a lesson" moment, on this machine only. */
function followsFile(cwd) {
return path.join(storeDir(cwd), "follows.ndjson");
}
/**
* Append one follow: `{"lesson":"<area>/<slug>","at":"<ISO>","skill":"<name>"}`.
* The file is only ever appended to, so two runs at once cannot lose a count.
*/
export function recordFollow(cwd, { lesson, skill }, now) {
const file = followsFile(cwd);
ensureDir(path.dirname(file));
const line = JSON.stringify({ lesson: String(lesson), at: toDate(now).toISOString(), skill: String(skill) });
fs.appendFileSync(file, line + "\n");
}
/** `{ <lesson id>: { count, last } }`, summed on read; an unreadable line is skipped. */
export function followCounts(cwd) {
let text;
try {
text = fs.readFileSync(followsFile(cwd), "utf8");
} catch {
return {};
}
const counts = {};
for (const raw of text.split("\n")) {
if (!raw.trim()) continue;
let row;
try {
row = JSON.parse(raw);
} catch {
continue;
}
if (!row || typeof row.lesson !== "string" || typeof row.at !== "string" || Number.isNaN(Date.parse(row.at))) continue;
const c = counts[row.lesson] || (counts[row.lesson] = { count: 0, last: row.at });
c.count += 1;
if (Date.parse(row.at) > Date.parse(c.last)) c.last = row.at;
}
return counts;
}
/* ------------------------------------------------------ the waiting store */
const pad = (n) => String(n).padStart(2, "0");
@@ -232,9 +275,42 @@ export function learningState(cwd = process.cwd(), now, { prune = true } = {}) {
/* ------------------------------------------------------- the console's view */
// Where the dashboard starts to nudge a tidy-up: general.md holds at most 25
// lessons (GENERAL_MAX in lessons.mjs, which the installed console does not
// carry), so 22 is close; an area file has no cap, so 30 is a long file.
export const NEAR_CAP_GENERAL = 22;
export const NEAR_CAP_AREA = 30;
/**
* Whether the project's saved lessons are crowded: general.md at 22 or more,
* or any other area file at 30 or more (counted as `### ` headings). Reads
* only; a missing folder or an unreadable file counts as not crowded.
*/
export function lessonsNearCap(cwd = process.cwd()) {
const dir = path.join(worktreeOf(cwd), ".plan2code", "lessons");
let names;
try {
names = fs.readdirSync(dir);
} catch {
return false;
}
for (const name of names) {
if (!name.endsWith(".md")) continue;
let text;
try {
text = fs.readFileSync(path.join(dir, name), "utf8");
} catch {
continue;
}
const count = text.split(/\r?\n/).filter((l) => l.startsWith("### ")).length;
if (count >= (name === "general.md" ? NEAR_CAP_GENERAL : NEAR_CAP_AREA)) return true;
}
return false;
}
/**
* What the dashboard's scan carries as `scan.learning`:
* `{ state, pausedSince, waiting, oldestDays }`, or null when the state is
* `{ state, pausedSince, waiting, oldestDays, nearCap }`, or null when the state is
* `unknown` (a settings format this console does not know: the page then
* draws no row) or when the core fails, so a broken store never fails `open`.
* Reads without pruning: the console server writes nothing here but the pause.
@@ -254,5 +330,6 @@ export function learningScan(cwd = process.cwd(), { now, read = learningState }
pausedSince: s.pausedSince || null,
waiting: Number.isInteger(waiting.count) ? waiting.count : 0,
oldestDays: Number.isInteger(waiting.oldestDays) ? waiting.oldestDays : 0,
nearCap: s.state === "on" && lessonsNearCap(cwd),
};
}
+54 -3
View File
@@ -856,9 +856,12 @@ export const ITEM_KINDS = new Set([
// type and its choices, and nothing arrives already chosen (FR-14, FR-15).
// `gone` is a saved lesson whose files no longer exist: the list offers it
// with a doubt's words.
export const LESSON_ROW_TYPES = ["lesson", "doubt", "gone", "agents-fix", "log-line", "area"];
const LESSON_ROW_TEXT = ["why", "kind", "area", "origin", "note", "before", "after", "found", "heading", "file", "name"];
const LESSON_ROW_LISTS = ["about", "areas", "flags", "lessons", "paths"];
// `tidy` is a proposed change to saved lessons (merge, reword, retire or
// move): `change` names it, `targets` the lessons it touches, and a merge or
// reword carries its new `wording` and that wording's `wordingWhy`.
export const LESSON_ROW_TYPES = ["lesson", "doubt", "gone", "agents-fix", "tidy", "log-line", "area"];
const LESSON_ROW_TEXT = ["why", "kind", "area", "origin", "note", "before", "after", "found", "heading", "file", "name", "change", "wording", "wordingWhy"];
const LESSON_ROW_LISTS = ["about", "areas", "flags", "lessons", "paths", "targets"];
const LESSONS_RIGHT = {
kind: "lessons",
rows: [{ id: "w1", type: "lesson", text: "Run a page test with node scripts/node-test.mjs <file>.", choices: ["Keep", "Reword", "Drop"] }],
@@ -868,6 +871,49 @@ const FIRST_ASK_RIGHT = {
firstAsk: { lesson: { id: "w1", text: "..." }, sentences: ["...", "...", "..."], yes: "Switch Learning on", no: "Not for this project", later: "..." },
};
// What the check found, as lessons.mjs list puts it on a row (`check`) and on
// the card (`checked`), and the two words a row's `tag` may carry.
export const LESSON_ROW_TAGS = ["Checked in an earlier run", "Not checked yet"];
const LESSON_CHECK_KEYS = ["fails", "doubts", "passed", "suggestion"];
const CHECK_RIGHT = { check: { fails: [{ test: "Search", reason: "It matches 3 files." }], doubts: [], passed: 3, suggestion: "A shorter wording." } };
const CHECKED_RIGHT = { checked: { how: "helper", count: 6, seconds: 40 } };
const isCount = (n) => Number.isInteger(n) && n >= 0;
function lessonCheckProblems(check, name, at) {
if (!isPlainObject(check)) return [rule(at, name, "must be the { fails, doubts, passed, suggestion? } lessons.mjs gave", CHECK_RIGHT)];
const problems = [];
for (const key of Object.keys(check)) {
if (!LESSON_CHECK_KEYS.includes(key)) problems.push(rule(at, `${name} "${key}"`, `is not a field of a check. Use ${LESSON_CHECK_KEYS.join(", ")}`, CHECK_RIGHT));
}
for (const key of ["fails", "doubts"]) {
const list = check[key];
if (list == null) continue;
if (!Array.isArray(list) || list.length > 4) {
problems.push(rule(at, `${name} ${key}`, "must be an array of at most 4 { test, reason } entries", CHECK_RIGHT));
continue;
}
list.forEach((e, i) => {
const ok = isPlainObject(e) && typeof e.test === "string" && typeof e.reason === "string" && e.reason.length <= 240;
if (!ok) problems.push(rule(at, `${name} ${key}[${i}]`, "must be { test, reason }, two strings, the reason at most 240 characters", CHECK_RIGHT));
});
}
if (check.passed != null && !(Number.isInteger(check.passed) && check.passed >= 0 && check.passed <= 4)) {
problems.push(rule(at, `${name} passed`, "must be a whole number from 0 to 4", CHECK_RIGHT));
}
if (check.suggestion != null && (typeof check.suggestion !== "string" || check.suggestion.length > 200)) {
problems.push(rule(at, `${name} suggestion`, "must be a string of at most 200 characters, or left out", CHECK_RIGHT));
}
return problems;
}
function lessonsCheckedProblems(checked, at) {
const how = isPlainObject(checked) && ["helper", "same-agent"].includes(checked.how);
const ran = how && isCount(checked.count) && isCount(checked.seconds) && Object.keys(checked).every((k) => ["how", "count", "seconds"].includes(k));
const failed = isPlainObject(checked) && typeof checked.failed === "string" && checked.failed.length <= 200 && Object.keys(checked).length === 1;
if (ran || failed) return [];
return [rule(at, "checked", 'must be { how: "helper" or "same-agent", count, seconds } (whole numbers), or { failed } with a reason of at most 200 characters', CHECKED_RIGHT)];
}
// What is wrong with a lessons item, as rule() sentences.
function lessonsProblems(item, at) {
const problems = [];
@@ -923,7 +969,12 @@ function lessonsProblems(item, at) {
if (row.refused != null && !isPlainObject(row.refused)) {
problems.push(rule(at, `${name} refused`, "must be the { pattern, part } lessons.mjs gave, or null", { refused: { pattern: "aws-access-key", part: "AKIA" } }));
}
if (row.check != null) problems.push(...lessonCheckProblems(row.check, `${name} check`, at));
if (row.tag != null && !LESSON_ROW_TAGS.includes(row.tag)) {
problems.push(rule(at, `${name} tag`, `must be one of ${LESSON_ROW_TAGS.map((t) => `"${t}"`).join(", ")}, or left out`, { tag: LESSON_ROW_TAGS[0] }));
}
});
if (item.checked != null) problems.push(...lessonsCheckedProblems(item.checked, at));
// The agent's answer to Ask for suggestions, readable by the page: row id to
// one of that row's own choice words. It outlines a button; it never picks.
const sug = item.suggested;
+28 -12
View File
@@ -191,11 +191,11 @@ export function answerLines(item, v) {
// 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" };
export const LESSON_KEEP_WORD = { lesson: "Keep", doubt: "Keep", gone: "Keep", "agents-fix": "Apply", tidy: "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" };
export const LESSON_EDIT_WORD = { lesson: "Reword", doubt: "Reword", gone: "Reword", "agents-fix": "Reword", tidy: "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" };
@@ -211,12 +211,17 @@ export function lessonEditField(row) {
// 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 edit fields' first values: the row as it stands, or its text replaced by
* `prefill` (a suggested wording) when one is given.
*/
export function lessonEditStart(row, prefill) {
const given = typeof prefill === "string" && prefill.trim() ? prefill : null;
if (row.type === "agents-fix") return { after: given ?? lessonOriginal(row) };
if (row.type === "area") return { name: given ?? lessonOriginal(row), paths: [...(row.paths || [])] };
if (row.type === "log-line") return { lessons: given ? [given] : logLessons(row), why: row.why || "", area: row.area || "" };
if (row.type === "tidy") return { text: given ?? lessonOriginal(row), why: row.wordingWhy || "", area: row.area || "" };
return { text: given ?? lessonOriginal(row), why: row.why || "", area: row.area || "" };
}
/**
@@ -227,6 +232,8 @@ 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");
// A tidy row's words are the new wording, not the sentence describing the change.
if (row.type === "tidy") return row.wording || "";
return row.text || "";
}
@@ -267,7 +274,8 @@ export function lessonDecision(row, choice, edit = {}) {
}
return out;
}
const why = typeof edit.why === "string" ? edit.why.trim() : row.why || "";
const baseWhy = row.type === "tidy" ? row.wordingWhy || "" : row.why || "";
const why = typeof edit.why === "string" ? edit.why.trim() : baseWhy;
const area = typeof edit.area === "string" && edit.area && edit.area !== (row.area || "") ? edit.area : "";
if (row.type === "log-line") {
const texts = typed.split("\n");
@@ -275,7 +283,7 @@ export function lessonDecision(row, choice, edit = {}) {
}
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 (why || (typeof edit.why === "string" && baseWhy)) out.why = why;
if (area) out.area = area;
return out;
}
@@ -294,7 +302,7 @@ export function lessonMissing(row, decision) {
/** The words one decision reads as: "Keep: <text>", "Reword: <new text>", "Apply: <file>". */
export function lessonDecisionLine(row, d) {
const shown =
d.choice === "Apply"
d.choice === "Apply" && !(row && row.type === "tidy")
? (row && row.file) || "AGENTS.md"
: Array.isArray(d.lessons)
? d.lessons.map((l) => (l && l.text) || "").join(" / ")
@@ -982,13 +990,14 @@ export function deleteReply(spec) {
// 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"];
export const LEARNING_ACTIONS = ["review", "switch-on", "switch-off", "move-log", "remove", "tidy"];
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.",
tidy: "Tidy up the saved lessons: propose merges, rewords, retires and moves.",
};
export function learningAction(what) {
if (!LEARNING_ACTIONS.includes(what)) throw new Error("unknown Learning action: " + what);
@@ -1016,6 +1025,13 @@ export function learningBannerText(learning) {
return `${n} ${n === 1 ? "lesson is" : "lessons are"} waiting for your review (oldest ${d} ${d === 1 ? "day" : "days"}).`;
}
// The tidy-up nudge's line, or "" when it shows nothing: the saved lessons are
// near their limit (the scan's nearCap) and Learning is on.
export function learningNearCapText(learning) {
if (!learning || learning.state !== "on" || learning.nearCap !== true) return "";
return "Lessons are nearing their limit. Tidy up?";
}
// 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
+70
View File
@@ -41,6 +41,7 @@ import {
lessonDecision,
lessonMissing,
lessonEditStart,
lessonEditField,
lessonReworded,
startsTicked,
} from "../answers.js";
@@ -1825,6 +1826,8 @@ function buildLessons(card, item, staged) {
};
if (item.opening) card.appendChild(el("p", "lessons-opening", item.opening));
const how = lessonsCheckedLine(item.checked);
if (how) card.appendChild(el("p", "lessons-checked", how));
const list = el("ul", "lessons-rows");
for (const row of item.rows || []) list.appendChild(lessonRow(item, row, draft, commit));
card.appendChild(list);
@@ -1850,6 +1853,61 @@ function buildLessons(card, item, staged) {
commentField(card, item, "Anything to add?");
}
const plural = (n, one) => `${n} ${one}${n === 1 ? "" : "s"}`;
// The card's one how-checked line, or "" when the card carries none.
function lessonsCheckedLine(checked) {
if (!checked || typeof checked !== "object") return "";
if (typeof checked.failed === "string") return `The check could not run: ${checked.failed}`;
const by = checked.how === "helper" ? "a fresh helper that could only read" : checked.how === "same-agent" ? "the same agent that noted them" : "";
if (!by) return "";
return `Checked ${plural(checked.count, "lesson")} in ${plural(checked.seconds, "second")} by ${by}`;
}
// What the check found on one row: each Fail then each Doubt on a line of its
// own, then a quiet pass line. Nothing at all for a row the check never saw.
function lessonCheckLines(li, item, row, draft, commit) {
const check = row.check;
if (!check || typeof check !== "object") return;
const fails = Array.isArray(check.fails) ? check.fails : [];
const doubts = Array.isArray(check.doubts) ? check.doubts : [];
const box = el("div", "lesson-checks");
for (const [word, list] of [["Fail", fails], ["Doubt", doubts]]) {
for (const e of list) {
const line = el("p", "lesson-check " + word.toLowerCase());
line.appendChild(el("span", "lesson-check-word", word));
line.appendChild(document.createTextNode(` ${e.test}: ${e.reason}`));
box.appendChild(line);
}
}
const found = fails.length + doubts.length;
// With all four tests flagged there is nothing left that passed.
if (!found || check.passed !== 0) box.appendChild(el("p", "lesson-check-pass", found && Number.isInteger(check.passed) ? `Passed the other ${check.passed}` : "Passed the check"));
if (check.suggestion) {
const sug = el("p", "lesson-suggestion");
sug.appendChild(el("span", null, `Suggested wording: ${check.suggestion}`));
const use = el("button", "btn sm", "Use this wording");
use.type = "button";
use.id = `lesson-use-${item.id}-${row.id}`;
use.addEventListener("click", () => {
// Picks Reword and opens it on the suggestion; what is sent is a
// normal Reword of whatever the person leaves in the box.
const word = LESSON_EDIT_WORD[row.type];
draft.picks[row.id] = (row.choices || []).includes(word) ? word : "Reword";
draft.leaveAll = false;
// Only the words change: a Why or Area already typed stays.
const start = lessonEditStart(row, check.suggestion);
const key = lessonEditField(row).key;
draft.edits[row.id] = { ...(draft.edits[row.id] || start), [key]: start[key] };
commit(true);
document.getElementById(use.id)?.focus();
});
sug.appendChild(use);
box.appendChild(sug);
}
li.appendChild(box);
}
// 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] || "";
@@ -1868,6 +1926,16 @@ function lessonRow(item, row, draft, commit) {
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 === "tidy") {
li.appendChild(el("p", "lessons-text", row.text));
// A merge or reword replaces lessons already saved: show them, so the change reads whole.
const was = (row.targets || []).filter((t) => t && t.text);
if ((row.change === "merge" || row.change === "reword") && was.length) {
li.appendChild(el("p", "lessons-heading", row.change === "merge" ? "It replaces these lessons:" : "It replaces this wording:"));
const ul = el("ul", "lessons-become");
for (const t of was) ul.appendChild(el("li", null, t.text));
li.appendChild(ul);
}
} else if (row.type === "log-line") {
li.appendChild(el("p", "lessons-text", row.text));
const become = (row.lessons || []).filter(Boolean);
@@ -1885,6 +1953,8 @@ function lessonRow(item, row, draft, commit) {
// 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));
if (row.tag) li.appendChild(el("p", "lessons-tag", row.tag));
lessonCheckLines(li, item, row, draft, commit);
for (const f of Array.isArray(row.flags) ? row.flags : []) {
const what = FLAG_WORDS[f && f.pattern] || "something personal";
+25 -15
View File
@@ -12,6 +12,7 @@ import {
loopDriving,
learningBusyNow,
LEARNING_BUSY_MS,
learningBusyLimit,
} from "../selectors.js";
import { whenTitle, whenWords } from "../labels.js";
import { hooks, page, redraw, saveNow } from "../state.js";
@@ -49,6 +50,7 @@ import {
learningAction,
learningReply,
learningBannerText,
learningNearCapText,
noteSwitchShows,
noteTabEmpty,
defaultNoteTicks,
@@ -1440,16 +1442,17 @@ function learningBanner(sc) {
const busy = learningBusyNow(state);
// Review pressed, or the choices just saved: the banner says what the agent
// is doing, in the same place, so the wait is never silent.
const working = busy && (busy.what === "review" || busy.what === "decide") ? busy : null;
const working = busy && (busy.what === "review" || busy.what === "decide" || busy.what === "tidy") ? busy : null;
const text = learningBannerText(sc && sc.learning);
if (!text && !working) return null;
const nudge = learningNearCapText(sc && sc.learning);
if (!text && !nudge && !working) return null;
const banner = el("div", "callout is-info dash-nudge learn-banner");
banner.setAttribute("role", "status");
if (working) {
banner.classList.add("is-busy");
banner.setAttribute("aria-busy", "true");
const line = el("span", "dash-nudge-text learn-busy");
line.append(el("span", "spinner tiny"), document.createTextNode(working.what === "review" ? "Opening lessons…" : "Saving your lessons…"));
line.append(el("span", "spinner tiny"), document.createTextNode(working.what === "review" ? "Opening lessons…" : working.what === "tidy" ? "Looking over your lessons…" : "Saving your lessons…"));
banner.appendChild(line);
if (working.what === "review") {
const review = el("button", "btn sm primary", "Review");
@@ -1459,14 +1462,21 @@ function learningBanner(sc) {
}
return banner;
}
banner.appendChild(el("span", "dash-nudge-text", text));
const review = el("button", "btn sm 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);
// Each line is its own row with its own button: lessons waiting, and lessons near their limit.
const row = (words, label, what, primary) => {
const r = el("div", "learn-banner-row");
r.appendChild(el("span", "dash-nudge-text", words));
const b = el("button", "btn sm" + (primary ? " primary" : ""), label);
b.type = "button";
b.disabled = Boolean(why);
if (why) b.title = why;
b.addEventListener("click", () => sendLearning(what));
r.appendChild(b);
banner.appendChild(r);
};
if (text) row(text, "Review", "review", true);
if (nudge) row(nudge, "Tidy up", "tidy", !text);
return banner;
}
@@ -1478,7 +1488,7 @@ function learningBanner(sc) {
function watchLearningBusy(busy) {
const timer = setInterval(() => {
if (page.learningBusy !== busy) return clearInterval(timer);
if (Date.now() - busy.at > LEARNING_BUSY_MS) {
if (Date.now() - busy.at > learningBusyLimit(busy)) {
clearInterval(timer);
page.learningBusy = null;
redraw();
@@ -1493,8 +1503,8 @@ function watchLearningBusy(busy) {
if (!busy.seen && Date.now() - busy.at < 3000) return;
clearInterval(timer);
page.learningBusy = null;
if (busy.what === "review") {
const none = hooks.banner("No lessons are waiting any more.", "info");
if (busy.what === "review" || busy.what === "tidy") {
const none = hooks.banner(busy.what === "tidy" ? "Nothing to tidy up right now." : "No lessons are waiting any more.", "info");
setTimeout(() => hooks.clearBanner(none), 4000);
}
redraw();
@@ -1523,13 +1533,13 @@ export async function sendLearning(what) {
// the agent answers.
const sc = scan();
const from = sc && sc.learning && sc.learning.state;
if ((what === "switch-on" || what === "switch-off" || what === "review") && from) {
if ((what === "switch-on" || what === "switch-off" || what === "review" || what === "tidy") && from) {
const busy = { what, from, at: Date.now(), seen: false };
page.learningBusy = busy;
redraw();
// One redraw at the limit, so an action the agent never answers stops spinning.
setTimeout(redraw, LEARNING_BUSY_MS + 500);
if (what === "review") watchLearningBusy(busy);
if (what === "review" || what === "tidy") watchLearningBusy(busy);
}
try {
const res = await fetch("/submit", {
+46 -4
View File
@@ -155,6 +155,7 @@ function moreMenu() {
};
list.append(
item("Switch off for this project", () => hooks.sendLearning("switch-off")),
item("Tidy up lessons", () => hooks.sendLearning("tidy")),
item("Move the failure log into lessons", () => hooks.sendLearning("move-log")),
item("Remove all lessons…", () => openRemoveConfirm(), " is-danger")
);
@@ -504,6 +505,49 @@ function openRemoveConfirm() {
dlg.showModal();
}
// The same slug lessons.mjs gives a lesson's heading (slugOf), so a lesson's id
// is `<file name without .md>/<slug>` here as there.
function slugOf(text) {
return String(text || "")
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 60)
.replace(/-+$/, "");
}
/** "Followed 12 times, last on Nov 20", "Followed once, last on Nov 20" or "Not followed yet". */
function followLine(entry) {
if (!entry || !(entry.count > 0)) return "Not followed yet";
const last = shortDate(entry.last);
const times = entry.count === 1 ? "once" : `${entry.count} times`;
return `Followed ${times}${last ? ", last on " + last : ""}`;
}
// One file's text through the page's Markdown, a quiet follow line under each
// lesson's heading (a "### " line).
function appendLessonText(part, file, follows) {
const area = String(file.name || "").replace(/\.md$/i, "");
const chunks = String(file.text || "").split(/\r?\n(?=### )/);
const add = (text) => {
if (!text.trim()) return;
const div = el("div", "md");
mdInto(div, text);
part.appendChild(div);
};
for (const chunk of chunks) {
const m = /^### (.+?)\s*(?:\r?\n|$)/.exec(chunk);
if (!m) {
add(chunk);
continue;
}
add(m[0]);
const line = el("p", "learn-follow", followLine(follows[`${area}/${slugOf(m[1])}`]));
part.appendChild(line);
add(chunk.slice(m[0].length));
}
}
// Open the lessons: every lesson file, read-only, through the page's Markdown.
async function openLessons() {
let dlg = document.getElementById("learn-lessons-modal");
@@ -525,7 +569,7 @@ async function openLessons() {
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();
const { files, follows } = await res.json();
body.replaceChildren();
if (!files || !files.length) {
body.appendChild(el("p", "md-p", "No lessons are saved in this project yet."));
@@ -534,9 +578,7 @@ async function openLessons() {
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);
appendLessonText(part, f, follows || {});
body.appendChild(part);
}
} catch {
+12 -2
View File
@@ -15,6 +15,16 @@ export const WORKING_GRACE_MS = 5 * 60 * 1000;
// How long a Learning action may show as working before the page gives up
// waiting for the agent (it normally answers in a second or two).
export const LEARNING_BUSY_MS = 30000;
// Review and Tidy up first grade every waiting lesson (check-input, a checker,
// check-record), which often takes longer than LEARNING_BUSY_MS: while the
// agent is still working on one, the page waits up to this long instead.
export const LEARNING_CHECK_MS = 5 * 60 * 1000;
/** How long a Learning action may stay busy: LEARNING_CHECK_MS for a Review or Tidy up the agent is still working on, else LEARNING_BUSY_MS. */
export function learningBusyLimit(busy) {
const checking = (busy.what === "review" || busy.what === "tidy") && (page.pendingResult || agentWorking());
return checking ? LEARNING_CHECK_MS : LEARNING_BUSY_MS;
}
/**
* The Learning action the person just pressed while the agent works on it, or
@@ -31,9 +41,9 @@ export function learningBusyNow(state) {
page.learningBusy = null;
return null;
};
if (Date.now() - busy.at > LEARNING_BUSY_MS) return end();
if (Date.now() - busy.at > learningBusyLimit(busy)) return end();
if ((busy.what === "switch-on" || busy.what === "switch-off") && busy.from !== state) return end();
if (busy.what === "review" && ((page.S && page.S.items) || []).some((i) => i && i.kind === "lessons" && isOpen(i))) return end();
if ((busy.what === "review" || busy.what === "tidy") && ((page.S && page.S.items) || []).some((i) => i && i.kind === "lessons" && isOpen(i))) return end();
return busy;
}
@@ -112,6 +112,8 @@
/* Lessons waiting: the banner nearest the title, in the accent tint. */
.dash-nudge.learn-banner { border-left-width: 4px; }
.learn-banner .btn { margin-left: auto; }
/* Two lines in one banner (lessons waiting, lessons near their limit): each its own row. */
.learn-banner-row { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 14px; flex: 1 1 100%; }
/* 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); }
@@ -120,6 +122,8 @@
A lesson's title is a long heading: balanced wrapping (tokens.css) halves it, so fill each line. */
.learn-lessons-file .md { max-width: none; }
.learn-lessons-file .md-h { text-wrap: wrap; }
/* One quiet line under a lesson's heading: how often it was followed. */
.learn-follow { margin: 2px 0 6px; font-size: var(--fs-sm); color: var(--ink-3); }
/* The lessons card (cards.js buildLessons): one block per item, none chosen at first. */
.lessons-opening { margin: 14px 0 0; font-size: var(--fs-md); color: var(--ink-3); }
@@ -138,6 +142,15 @@
.lessons-found { font-size: var(--fs-md); color: var(--ink-2); }
.lessons-origin,
.lessons-note { font-size: var(--fs-sm); color: var(--ink-3); }
.lessons-tag { font-size: var(--fs-sm); color: var(--ink-3); font-style: italic; }
.lessons-checked { margin: 6px 0 0; font-size: var(--fs-sm); color: var(--ink-3); }
.lesson-checks { margin: 0 0 6px; }
.lesson-checks p { margin: 0 0 4px; font-size: var(--fs-md); }
.lesson-check-word { font-weight: 700; margin-right: 2px; }
.lesson-check.fail { color: var(--warn); }
.lesson-check.doubt { color: var(--stage); }
.lesson-checks .lesson-check-pass { color: var(--ink-3); font-size: var(--fs-sm); }
.lesson-suggestion { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; color: var(--ink-2); }
.lessons-fix blockquote {
margin: 0 0 8px;
padding: 6px 10px;
+4 -2
View File
@@ -52,7 +52,7 @@ import { cleanSetting, offered } from "./public/subagents.js";
import { DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, accentId, cardWidth } from "./public/palette.js";
import { SERVABLE, TYPES, asset } from "./static.mjs";
import { handoffsDir, isHandoffId } from "./handoffs.mjs";
import { learningScan, learningState, writePause } from "./learning.mjs";
import { followCounts, learningScan, learningState, writePause } from "./learning.mjs";
import { linkToOpen, openFile, openLink } from "./open-link.mjs";
import {
NotepadError,
@@ -743,7 +743,9 @@ function readLessonFiles(worktree) {
}
function learningLessons(req, res, ctx) {
return json(res, 200, { files: readLessonFiles(ctx.worktree() || ctx.project) }, { "cache-control": "no-store" });
const project = ctx.worktree() || ctx.project;
// follows: how often each saved lesson was followed, read from this machine's store.
return json(res, 200, { files: readLessonFiles(project), follows: followCounts(project) }, { "cache-control": "no-store" });
}
// What an unknown git host is, for the git board's pull-request link. Saved