From 1345aa0a95b24a0d898b3bd177076f44416f640e Mon Sep 17 00:00:00 2001 From: Justin Parker Date: Fri, 27 Nov 2026 23:19:42 -0800 Subject: [PATCH] Grade every waiting lesson with a separate check before the lessons card asks for approval AI Assisted --- .agents-docs/AGENTS-architecture-console.md | 4 +- .agents-docs/AGENTS-architecture-install.md | 3 +- .../AGENTS-architecture-skill-scripts.md | 2 +- .readme/web-console-internals.md | 4 +- .readme/web-console.md | 2 +- AGENTS.md | 4 +- install.js | 25 +- scripts/capture-screenshots.mjs | 2 +- scripts/test-script-lessons.mjs | 1157 ++++++++++++++++- scripts/test-web-console-learning.mjs | 86 +- scripts/test-web-console-logic.mjs | 51 +- scripts/test-web-console-page-learning.mjs | 161 ++- scripts/test-web-console-skills.mjs | 3 +- src/plan2code-0-pathfinder.md | 2 +- src/plan2code-1-plan.md | 2 +- src/plan2code-1b-revise-plan.md | 2 +- src/plan2code-2-document.md | 2 +- src/plan2code-4-finalize.md | 2 +- src/plan2code-dead-code.md | 2 +- src/plan2code-pr-prep.md | 2 +- src/plan2code-ui-prototype.md | 2 +- src/plan2code.md | 3 +- src/shared-references/helper-strength.md | 3 +- src/shared-references/lesson-check.md | 71 + src/shared-references/lessons.md | 22 +- src/skill-scripts/lessons.mjs | 961 +++++++++++++- src/web-console/console-launches.md | 2 +- src/web-console/learning.mjs | 79 +- src/web-console/patches.mjs | 57 +- src/web-console/public/answers.js | 40 +- src/web-console/public/screens/cards.js | 70 + src/web-console/public/screens/dashboard.js | 40 +- .../public/screens/learning-row.js | 50 +- src/web-console/public/selectors.js | 14 +- src/web-console/public/styles/learning.css | 13 + src/web-console/routes.mjs | 6 +- 36 files changed, 2812 insertions(+), 139 deletions(-) create mode 100644 src/shared-references/lesson-check.md diff --git a/.agents-docs/AGENTS-architecture-console.md b/.agents-docs/AGENTS-architecture-console.md index bf5baef..39c44ae 100644 --- a/.agents-docs/AGENTS-architecture-console.md +++ b/.agents-docs/AGENTS-architecture-console.md @@ -18,7 +18,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web | `open-link.mjs` | the desktop app's webview opens no new windows, so the page there sends links off the console (`linkLeavesPage()` in `public/app-bridge.js`: http or https on another origin, caught in `wireChrome()`) to `POST /open-link`. `linkToOpen()` takes http and https only (400 otherwise); `openLink()` starts the default browser with the link as one argument, never through a shell (`rundll32 url.dll,FileProtocolHandler` on Windows, `open` on macOS, `$BROWSER` or `xdg-open` elsewhere) and skips it under `PLAN2CODE_NO_BROWSER`. When that fails the page shows the link with a Copy button to paste into a browser | | `loop-setup.mjs` | the Implementation Loop's setup, remembered per project in `~/.plan2code/console/loop-setup.json` (one entry per folded project folder, schema 1): defaults, validation and the read and write the `/loop-setup` route uses. The app reads the same file itself for the quick check, so the page never carries that command | | `spec-carry.mjs` | the spec a desktop app's New Session carries to the fresh dashboard: one short-lived `~/.plan2code/console/spec-carry.json` (`{project, spec, at}`), written by `restart_brief::leave_spec` in the app from the old session's `specDir` (or, from a dashboard, its picker's `specSel` in the draft), taken once by `POST /spec-carry` (`takeSpecCarry`: same folded project, under ten minutes old, one folder under `specs/`) and used by `loadSpecCarry()` in `selectors.js` only when the new picker lists that spec | -| `cmd-post-wait.mjs` | `post` and `wait`: publish a patch, then collect what the person sent. `sessionActions()` hands the send's `__` actions to the agent whole: `__delete`, a `__launch` with its `fromBanner` (sent from a dashboard showing lessons waiting), and `__learning` with every field (`{ "i": "__learning", "do": ... }`, `do` one of `LEARNING_ACTIONS` in `public/answers.js`: `review`, `switch-on`, `switch-off`, `move-log` or `remove`). `__learning` is not a hop: the dashboard agent runs `lessons.mjs`, resumes as the dashboard and posts the menu again, and `pointers.mjs` names `console-launches.md` for it. Pause for me never reaches the agent (`POST /learning/pause`) | +| `cmd-post-wait.mjs` | `post` and `wait`: publish a patch, then collect what the person sent. `sessionActions()` hands the send's `__` actions to the agent whole: `__delete`, a `__launch` with its `fromBanner` (sent from a dashboard showing lessons waiting), and `__learning` with every field (`{ "i": "__learning", "do": ... }`, `do` one of `LEARNING_ACTIONS` in `public/answers.js`: `review`, `switch-on`, `switch-off`, `move-log`, `remove` or `tidy`). `__learning` is not a hop: the dashboard agent runs `lessons.mjs`, resumes as the dashboard and posts the menu again, and `pointers.mjs` names `console-launches.md` for it. Pause for me never reaches the agent (`POST /learning/pause`) | | `cmd-small.mjs` | the small commands: keep, forget, delete-spec, handoff, delete-handoff, status and stop; `handoff new` refuses an unknown `--workflow` the same way `open` does | | `files.mjs` | where the console's files live, how they are written safely, and the argument parser both command lines share | | `agents.mjs` | the rules of `~/.plan2code/agents.json` (see "Agents file" in [the install file](./AGENTS-architecture-install.md)), console side: `normalizeAgents()` reads the file into clean entries and warnings, never throwing; `validateForSave()` checks what User Preferences sends and names the first bad entry and field; `makeId()`, `buildArgs()` (the command line from an entry) and `resolveCommand()` (where a command runs from, never running it). Served by `GET` / `POST /agents` and `POST /agents/test` in `routes.mjs` | @@ -40,7 +40,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web | loop setup `phaseStrength` / `strengths` | `loop-setup.mjs` keeps the per-project toggle and, per spec folder, a list of `{n, name, strength}` picks, pruned as specs finish and phases move (twin: `LoopSetup` in `loop_driver.rs`). `loop_driver.rs` starts a phase with `AgentManager::start_phase_on(prompt, model, effort, env)` and sets `PLAN2CODE_LOOP_STRENGTH` (thrifty, balanced or best) in its environment, which `cmd-open.mjs` reads to give the phase's helpers the same Helper strength line; a retry goes one step up with `models::next_strength` (Rust twin of `nextStrength`; a Match my session phase stays) | | `git-repo.mjs` | the one read-only reader of a git repository: the worktree status (`countPending()`, behind `pendingFiles()`), the branch table, the default branch, a merge or rebase in progress, the remotes and their web addresses, the last fetch and the pull-request link; `snapshot()` is what `open` and every `reread` store as `state.git`. Every git call carries `GIT_OPTIONAL_LOCKS=0`, so a background look never takes the index lock. Imported by `cmd-open.mjs`, `cmd-post-wait.mjs` and `sessions.mjs`; the git skill's `git.mjs` reaches it through `common.mjs` | | `handoffs.mjs` | the handoff store, the only code that names, lists, marks, deletes and sweeps handoffs, all in `~/.plan2code/handoffs/` (`PLAN2CODE_HANDOFFS_DIR` for tests; `PLAN2CODE_NOW` pins its clock): `newHandoff()` claims `YYYY-MM-DD-HHmm-handoff` (`-2`, `-3` on a clash, the `.json` created exclusively) and writes only `.json` (`{ v: 1, id, title, worktree, project, spec, workflow, skill, written, fromStop, usedAt }`), the agent writing `.md`; `listHandoffs(worktree)` (unused, same worktree, `.md` present, newest first, title and Next task read off the document); `readHandoffMeta()`, `markHandoffUsed()`; `removeHandoff()` (`HANDOFF_ID` only, regular files, never a link, realpath inside the folder, throws on any refusal); `staleHandoffs()` / `removeHandoffs()` for the sweep | -| `learning.mjs` | Learning's core, shared with the `lessons.mjs` skill script: the one `learningState()` (not set up, off, on, paused, unknown), the repository key, the tracked `.plan2code/settings.json` read, and the two stores on this machine under `~/.plan2code/learning//` (`pause.json`, `waiting/.json`; `PLAN2CODE_LEARNING_DIR` moves them for tests); `learningScan()` is the dashboard's `scan.learning`, read without pruning. Never writes into a project | +| `learning.mjs` | Learning's core, shared with the `lessons.mjs` skill script: the one `learningState()` (not set up, off, on, paused, unknown), the repository key, the tracked `.plan2code/settings.json` read, and the stores on this machine under `~/.plan2code/learning//` (`pause.json`, `waiting/.json`, `checks/`, and the append-only `follows.ndjson` that `followCounts()` sums on read; `PLAN2CODE_LEARNING_DIR` moves them for tests); `learningScan()` is the dashboard's `scan.learning`, read without pruning, with `nearCap` while Learning is On and general lessons reach 22 of 25 or an area file 30. Never writes into a project | | `notepads.mjs` | the notebook store (the feature is named Notebook; its code, routes and storage folder keep the name `notepad`), the only code that names, reads, writes and removes notebooks, one per folder Plan2Code runs in, in `~/.plan2code/notepads/-<12 hex>/` (`PLAN2CODE_NOTEPADS_DIR` for tests), split into named tabs: `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order, last, tabs: { id: { name, created, sent? } } }`) and `tabs//note.md` with `tabs//images/`. `notepadKey()` (the folder's basename slug and the first 12 hex of `sha256(foldKey(folder))`), `listTabs()` / `defaultTabId()`, `readNotepad(folder, tab)` (never creates or writes anything; `{ tabs, last, tab }` with the tab's `text`, `savedAt` and `images` repeated at the top), the tab changes `createTab()` / `renameTab()` / `reorderTabs()` / `setLastTab()` / `deleteTab()` (index first, then the folder; names pass `normalizeTabName()`, `TAB_NAME_MAX` 40, any case compared by `nameKey()`, `NOTEPAD_MAX_TABS` 20), `saveNote(folder, tab, text)` (1 MB cap, atomic), `addImage()` / `addThumb()` / `removeImage()` (JPEG bytes only, 200 pictures per tab, UUID names), `imagePath()` (regular files whose realpath stays inside the folder), `staleNotepads(now, maxAgeMs)` (the real folders directly under it named like a key, never a link or a file, whose newest file is at least `maxAgeMs` old, as `{ key, folder, path }` with `folder` from `meta.json` or null), `removeNotepad(key)` (the key checked against `NOTEPAD_KEY_RE`, the path kept inside the notepads folder by `path.relative`, a link refused, then the whole folder removed; User Preferences, Cleanup is its only caller) and `NotepadError` (`code` and `status`, turned into `{ error }` by the `/notepad` routes). **Migration:** a notepad in the first shape (`note.md` and `images/` at the top) reads as one virtual tab, Notes (`LEGACY_TAB_ID`), and writes nothing; its first write moves the files into `tabs//` and writes `tabs.json` last, every step safe to run again after a crash. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders on the next write. Every write runs under a `notepad.lock` in the notepad's folder. The agent CLI never imports it: nothing in a notepad reaches the agent | | `picker.mjs` | the per-OS native folder picker behind **Browse…** (`pickerCommand()` → `{ command, args, env }` or `null`; `pickFolder()` runs it with async `spawn`, so the server keeps serving while the dialog is open). Copied from `src/launcher/plan2code.js` (self-contained CommonJS, so it cannot be shared) with the prompt as a parameter; a drift test keeps the two in step | | `update-check.mjs` | the dashboard's release check, server-only (never in `SERVABLE`): `compareVersions()` (numeric X.Y.Z, `null` otherwise), `latestTag()` (the highest `refs/tags/vX.Y.Z`, peeled `^{}` and pre-release tags skipped), `checkForUpdate({ installed, cacheFile, now, run })` (never throws) and `runLsRemote()` (`git ls-remote --tags` on the repo: no shell, `GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`, SSH `BatchMode` when `GIT_SSH_COMMAND` is unset, `windowsHide`, killed at 10 s; git authenticates itself, the console never touches a credential). The answer, failures included, is cached for an hour in `~/.plan2code/console/update-check.json` (`UPDATE_CHECK_FILE`, in `PROTECTED_CONSOLE_FILES` so no sweep removes it). `server.mjs` starts it after the ready line and never awaits it; `stateFrame()` carries `update: { installed, latest }` only when a newer release exists (its `latest` is part of `haveKey()`, so a page that connected first still gets it), and `GET /version` returns `{ version, latest }`. Tests seed a fresh cached failure in every console home, so no test server reaches the network. The `plan2code` launcher reads the same cache for its terminal release notice (a copy of this module sits in `~/.plan2code/bin/`) | diff --git a/.agents-docs/AGENTS-architecture-install.md b/.agents-docs/AGENTS-architecture-install.md index 34018ee..6a41f50 100644 --- a/.agents-docs/AGENTS-architecture-install.md +++ b/.agents-docs/AGENTS-architecture-install.md @@ -17,7 +17,8 @@ plan2code/ │ │ └── trail.md # Every-response map visual + pathed resume command │ ├── shared-references/ # Reference files shared across skills │ │ ├── building-habits.md # Find the cause, test first, pin behavior (quick-task, implement, implement-review, test) -│ │ ├── helper-strength.md # How strong a model and how much effort each helper gets (init, init-update, pathfinder, plan, revise-plan, document, quick-task, implement, implement-review, review, finalize, xray, diagnose, pr-prep, test) +│ │ ├── helper-strength.md # How strong a model and how much effort each helper gets (dashboard, for the lesson check only, init, init-update, pathfinder, plan, revise-plan, document, quick-task, implement, implement-review, review, finalize, xray, diagnose, pr-prep, test) +│ │ ├── lesson-check.md # Learning: the lesson checker's brief, four tests, verdicts and reasons, never edits (dashboard, implement, implement-review, review, quick-task, xray, diagnose, test) │ │ ├── lessons.md # Learning: the fixed words and when a skill runs each `lessons.mjs` command (dashboard, pathfinder, plan, revise-plan, document, implement, implement-review, review, finalize, quick-task, xray, diagnose, pr-prep, test, dead-code, ui-prototype) │ │ ├── review-in-build.md # The review a building skill runs on its own work (quick-task, implement, implement-review, review, finalize, dead-code) │ │ └── test-runs.md # Choosing what tests to run: targeted per task and phase, full suite only where the plan puts it (document, implement, implement-review, quick-task, review, finalize, pr-prep, test, dead-code) diff --git a/.agents-docs/AGENTS-architecture-skill-scripts.md b/.agents-docs/AGENTS-architecture-skill-scripts.md index 479d921..d38a4ff 100644 --- a/.agents-docs/AGENTS-architecture-skill-scripts.md +++ b/.agents-docs/AGENTS-architecture-skill-scripts.md @@ -34,7 +34,7 @@ Anything a workflow step decides with one correct answer (parsing a spec's check | `changelog-state.mjs` (own) | changelog | `state`, `bump`, `set-package-version`: the default branch's version, whether the branch's entry can be extended (not released, not on another branch), the file's heading style, the gap since the entry was last touched; only `set-package-version` writes, and only the version field | | `git.mjs` (own) | git | `state`, `plan`, `branch-check`, `init-check`, `delete-check`, `cleanup-list`, `conflicts`, `pr-url`, `classify-error`: the repo snapshot, each action's exact command and confirm text (shared by the terminal and the board), branch-name, delete, cleanup and git init checks, a stopped rebase's conflicts, the pull-request link and git's errors sorted into kinds with a next step. Read-only: the agent runs every command it prints, and `guard()` refuses force push, hook skipping, amend, remote delete and blanket add | | `ui-prototype.mjs` (shared, with `ui-prototype-round.mjs`, `ui-prototype-page.mjs`, `ui-prototype-drafts.mjs`, `ui-prototype-block.mjs`) | ui-prototype, pathfinder, plan, revise-plan, quick-task (ride-along) | `sweep` (drafts older than 30 days), `new-round`, `assemble` (the page from `round.json`, the variant files and the shell in `references/ui-prototype-shell/`, images and fonts embedded; exit 4 `round-mismatch` when a drafts round's `round.json` names another `name` or `round` than its folder), `check` (the contract's rules, the three image rules `image-type`, `image-size` and `image-missing`, and the size ceiling), `open` (the default browser), `read-block` (a pasted choice block from stdin into fields) and `save` (the pair `specs//prototypes/.html` and `.md`, then that prototype's drafts removed). Writes only under `~/.plan2code/prototypes//` and, on `save`, the spec's `prototypes/`; never writes project code, never opens a page outside the drafts or `specs/`, never fetches anything over the network. The helper modules are imported only by `ui-prototype.mjs` | -| `lessons.mjs` | dashboard, pathfinder, plan, revise-plan, document, implement(-review), review, finalize, quick-task, xray, diagnose, pr-prep, test, dead-code, ui-prototype | Learning's one script. Every answer carries `state` (`not-set-up`, `off`, `on`, `paused`, `unknown`) and `active`, decided only by `learningState()` in the bundled `web-console/learning.mjs`, which it loads at run time through `consoleModule("learning.mjs")` (exit 3 `no-console` without it), so the dashboard and the skills never disagree. `state` (the state, since when Paused for you, the waiting count, whether AGENTS.md exists, whether on the default branch) / `switch on\|off` (the team switch) / `pause on\|off` (Paused for you, refused unless On) / `read` (the lessons for the named paths and the branch's changed files, `marked` when their About files changed since, with a `run` handle so a later read hands over only new areas) / `note` (a lesson, an area, a doubt or an AGENTS.md fix, checked, then held as waiting; nothing while Off or Paused for you; a secret exits 5) / `check` (the secret refusal and the email, handle and person-name flags; reads only) / `list` (the approval list of everything waiting, new failure log lines, the first-ask card) / `decide` (applies the person's choices, or `--first-ask yes\|no`; a test map row fix carries `row` on its list item and is reworded with `row` or with `after` as its one table line, read back by `rowFromLine()` in `test-map.mjs`, and every row is validated and secret-checked again at Apply) / `log-lines` (failure log lines added since Learning was first switched on) / `areas --suggest` (first areas from the test map) / `report` (lessons per area, the oldest, marked and gone ones) / `remove --confirm` (deletes every saved lesson). Writes only the project's `.plan2code/settings.json` and `.plan2code/lessons/.md`, the pointer line and upkeep sentence in the project's `AGENTS.md`, its failure log lines (moved into lessons, marked `(kept in the log)`, or added on a first-ask no), accepted fixes to `AGENTS.md` or an `.agents-docs/` file, and, through the core, the pause and the waiting lessons on this machine only, in `~/.plan2code/learning//`. Never stages or commits | +| `lessons.mjs` | dashboard, pathfinder, plan, revise-plan, document, implement(-review), review, finalize, quick-task, xray, diagnose, pr-prep, test, dead-code, ui-prototype | Learning's one script. Every answer carries `state` (`not-set-up`, `off`, `on`, `paused`, `unknown`) and `active`, decided only by `learningState()` in the bundled `web-console/learning.mjs`, which it loads at run time through `consoleModule("learning.mjs")` (exit 3 `no-console` without it), so the dashboard and the skills never disagree. `state` (the state, since when Paused for you, the waiting count, whether AGENTS.md exists, whether on the default branch) / `switch on\|off` (the team switch) / `pause on\|off` (Paused for you, refused unless On) / `read` (the lessons for the named paths and the branch's changed files, `marked` when their About files changed since, with a `run` handle so a later read hands over only new areas) / `note` (a lesson, an area, a doubt, an AGENTS.md fix or a `tidy` proposal (`--change merge|reword|retire|move --targets `), checked, then held as waiting; nothing while Off or Paused for you; a secret exits 5; a lesson may carry a literal search, `--shows-in --match should|never --text-match `, its glob at most 120 characters and three `**`; a correction or convention needs `--why`; an inferred lesson from a read-only skill is refused) / `check-input [--tidy]` (the waiting lessons for the lesson check, oldest first and at most 10, each with its search already run and its named files hashed; a search looks only at the files git tracks or leaves unignored, listed once per command, so ignored build output is never searched; check files over a day old are pruned first) / `check-record --file` (validates the checker's verdicts, four tests of Pass, Doubt or Fail each with a reason, and stores them on the waiting items; exit 4 names the fault) / `follow --lesson --skill ` (one line in `follows.ndjson` per "Following a lesson") / `tidy-input` (every saved lesson with its follow count and mark, for the tidy-up coach) / `check` (the secret refusal and the email, handle and person-name flags; reads only) / `list` (the approval list of everything waiting, new failure log lines, the first-ask card; with `--check ` the rows carry the verdicts, the outline and the how-checked line, `--check-failed` says why the check did not run) / `decide` (applies the person's choices, or `--first-ask yes\|no`; a test map row fix carries `row` on its list item and is reworded with `row` or with `after` as its one table line, read back by `rowFromLine()` in `test-map.mjs`, and every row is validated and secret-checked again at Apply) / `log-lines` (failure log lines added since Learning was first switched on) / `areas --suggest` (first areas from the test map) / `report` (lessons per area, the oldest, marked and gone ones) / `remove --confirm` (deletes every saved lesson). Writes only the project's `.plan2code/settings.json` and `.plan2code/lessons/.md`, the pointer line and upkeep sentence in the project's `AGENTS.md`, its failure log lines (moved into lessons, marked `(kept in the log)`, or added on a first-ask no), accepted fixes to `AGENTS.md` or an `.agents-docs/` file, and, through the core, the pause, the waiting lessons (with their verdicts), `checks/` and `follows.ndjson` on this machine only, in `~/.plan2code/learning//`. `read` also writes there: a marked lesson whose search no longer matches becomes a waiting doubt. Never stages or commits | | `changes.mjs` | implement, implement-review, quick-task | The sign-off page's Changes tab. `start --session ` snapshots the working tree (tracked, modified and new files, never ignored ones) into a git tree object through a temporary index and `git write-tree`, so the real index, HEAD, branches and working tree stay as they were, and writes the tree id to `/changes-start.json`; a rerun replaces it. `diff --session [--cap 524288]` snapshots the tree now, compares it with the start tree and writes `/changes.diff` (unified, `git diff --no-color -M` headers; over the cap it is cut at a file boundary with a notice, every file still named; a file that may hold a secret keeps its name and counts, its lines hidden; the counts of hidden and cut files travel as `# counts: ` trailer lines (tab separated fields) that the page applies to files with no lines of their own), printing `{ ok, files, added, removed, truncated, hidden, file }`. Exit 3 for no repository, no snapshot or a snapshot git no longer has, 4 when git cannot snapshot. Work done before `start` never shows, and nothing has to be committed. The notes for Implement and Quick task (`notes/implement.md`, `notes/quick-task.md`) say when to run each; the page draws the result as a `diff` doc block | **Shared reference for `lessons.mjs`:** `src/shared-references/lessons.md` ships as `references/lessons.md` (through `additionalReferences`) to the same fifteen skills and the dashboard. It is the prose half of Learning: the fixed words (Learning, lesson, waiting; Not set up, Off, On, Paused for you), when a skill runs each command (Start, While working, End, unattended runs, Learning off), and that a failed call means one "Lessons could not be read this run." and carrying on without lessons. diff --git a/.readme/web-console-internals.md b/.readme/web-console-internals.md index 4e96e70..f17310b 100644 --- a/.readme/web-console-internals.md +++ b/.readme/web-console-internals.md @@ -169,8 +169,8 @@ origin. | `POST /open-prototype` | `{ spec, name }`: opens one `.html` from `/prototypes/` in the person's default browser. 404 for any other name, 500 when no browser could start. | | `GET /handoff?id=` | *Read it all*: the handoff's `.md` from `~/.plan2code/handoffs/`, as `text/markdown` with `cache-control: no-store`. A dashboard only, and only an id its own scan listed: a used, unknown or malformed id is 404. | | `POST /learning/pause` | Pause for me: `{ paused: boolean }` (origin-checked; anything else is 400 `bad-request`, and 409 `not-on` unless Learning is On or Paused for you). Writes the personal pause on this machine only (`pause.json` under `~/.plan2code/learning//`), the server's only write for Learning, and repaints the row with no agent. | -| `GET /learning/state` | The Learning row's state worked out now, `{ state, pausedSince, waiting, oldestDays }` (`{}` when the project's settings file is from a format it cannot read), with `cache-control: no-store`. | -| `GET /learning/lessons` | Open the lessons, read only: `{ files: [{ name, title, text }] }` from the project's lessons (`.plan2code/lessons/`, saved with the repository), `general.md` first, then the other `.md` files in name order (plain files only, at most 100 of 512 KB each), with `cache-control: no-store`. | +| `GET /learning/state` | The Learning row's state worked out now, `{ state, pausedSince, waiting, oldestDays, nearCap }` (`{}` when the project's settings file is from a format it cannot read), with `cache-control: no-store`. | +| `GET /learning/lessons` | Open the lessons, read only: `{ files: [{ name, title, text }], follows: { : { count, last } } }` (follows from this machine's `follows.ndjson`, for the reader's "Followed N times" line) from the project's lessons (`.plan2code/lessons/`, saved with the repository), `general.md` first, then the other `.md` files in name order (plain files only, at most 100 of 512 KB each), with `cache-control: no-store`. | | `GET /workspace` | The Workspace dialog's list: folders, `missing`, `remote` and the agent's folder `issues`. `?check=1` re-checks every folder on disk first. | | `POST /workspace/add` | `{ path, name?, description? }`. The path is resolved against the folder the session started in (`~` expanded) and must be a folder: 400 `not-a-folder`, `duplicate` (with its `name`; compared case-insensitively on Windows and macOS), `bad-name`, or `name-taken` with a `suggest`. Answers the new entry, `nested: true` when it sits inside another folder in the list. | | `POST /workspace/edit` | `{ id, name?, description? }`. Renames or re-describes one folder: 400 `bad-name` / `name-taken`, 404 `unknown`. | diff --git a/.readme/web-console.md b/.readme/web-console.md index 5bb33bf..1af8874 100644 --- a/.readme/web-console.md +++ b/.readme/web-console.md @@ -113,7 +113,7 @@ The easy way in is the dashboard: type `/plan2code` in your agent, or run `plan2 - **Specs and their states.** The picker at the top chooses the spec. A diagnosed bug reads *Bug diagnosed* (Quick task suggested, Plan lit), then *Bug fixed* once Quick task has fixed it; a held-back upgrade from Update dependencies reads *Upgrade ready*, then *Upgrade done*. A finished one can be archived, or deleted from its chip. - **Handoffs.** Handoffs this folder has not picked up follow the specs as dashed chips. Select one to preview it, then **Pick it up here**, **Read it all**, **Copy for a new conversation** or **Delete**. They live in `~/.plan2code/handoffs/`, written by *Stop with a handoff* (below) and by the Handoff skill. - **Git and the utilities.** **Git** opens a board with three tabs (Changes, Branches, Sync) and asks before every push, publish and delete; outside a repository it offers to start one. **Codebase X-ray**, **Diagnose a bug** and **Update dependencies** are always available too. -- **Learning.** A row shows *Not set up*, *Off*, *On* or *Paused for you*; **Pause for me** pauses it for you alone. A banner offers **Review** while lessons are waiting. Kept lessons go to `.plan2code/lessons/` in the project; waiting lessons and your pause stay on this machine, and nothing is committed for you. +- **Learning.** A row shows *Not set up*, *Off*, *On* or *Paused for you*; **Pause for me** pauses it for you alone. A banner offers **Review** while lessons are waiting. Before you see them, each waiting lesson is checked against the code by a separate reader, and the card shows any Doubt or Fail with its reason (and, where it helps, a better wording to use); you still decide. The lessons reader shows how often each lesson was followed. **More, Tidy up lessons** (and a banner nudge once general lessons reach 22 of 25, or an area file 30) has the agent propose merges, rewords, retires and moves, one change each, checked like any lesson and applied only on your **Apply**. Kept lessons go to `.plan2code/lessons/` in the project; waiting lessons and your pause stay on this machine, and nothing is committed for you. - **Planny wakes up.** A fresh dashboard starts with him asleep; click to wake him (**Skip** or Escape skips it, and reduced motion shows the awake dashboard at once). Or start any step by its command (the full list is in the README's [Prefer the terminal?](../README.md#prefer-the-terminal) section), and add `--web` to open the console without being asked: `/plan2code-1-plan --web plan a lunch voting app`. Without it, the first question is "In your browser (suggested)" or "Here in the terminal". The page opens straight away at a `127.0.0.1` address, with a starting screen while the skill reads your project. You can switch to the terminal at any point: the files under `specs/` are the same either way. diff --git a/AGENTS.md b/AGENTS.md index b8b7618..3b5e7b6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,11 +36,11 @@ Details: [Status line](./.agents-docs/AGENTS-architecture-statusline.md) ## Web Console -Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) installed once under `~/.plan2code/console//` (`installSharedConsole` in `install.js`) and reached from every skill through a forwarding stub, `src/web-console-stub/console.mjs`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review, and in Implement, Implement + Review and Quick task a **Changes** tab: a `diff` doc block fed by the `changes.mjs` skill script, parsed by `public/diff-parse.js` and drawn by `public/diff-view.js`), build progress, the living document, a spec's saved prototypes (a **Prototypes** tab: an `.md` read in place, an `.html` opened in the default browser), an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (a Save, Share, Review, Tidy path, one task card for the step you are on, and the Changes, Branches and Sync tabs folded into **All branches and tools**; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, private: the agent reads a tab only when you start Pathfinder, Plan, Quick task, Diagnose, UI Prototype or Revise plan from the dashboard with it and send the box it fills (an idea box marked `fill: "note"`, up to five ticked pictures attached), which then marks the tab sent via `POST /notepad/tab/sent`; the agent CLI never imports the store; removed only through Cleanup once a month untouched), **Activities** behind the top bar's die (thirteen small games, Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, listed in `public/activities.js` with one module per game under `public/activities/` (Ghoul Rush is its own folder of modules, `public/activities/ghoul-rush/`) and a card line (`blurb`) each, a picker of game rows in two columns, ordered Recently played or A to Z (saved in `activityOrder`), with never-picked games under Not played yet, once two are listed, that plays one game at a time (another pick drops the last game's round), driven by `screens/activities.js` (keys, key releases for a game with `release()`, canvas pointer events for a game with `pointer()`, one frame timer), paused whenever the person's turn comes and resumed only by the person (while that pause's banner is up, only by its **Unpause game** button), best scores in flat `activityBest` keys in `looks.json` (and the time each game was last picked in `activityPlayed`) (lowest wins for a game that sets `lowerIsBetter`; Mini golf opens on a dashboard of its six 18-hole courses, one file each under `public/activities/golf-course-.js`, and keeps a best per course, `activityBestGolf`), and one number a game may keep between sessions in `activityMemo` (Snake's tally of surprises found, Light Trails' furthest arena, Bug Hunt's tally of finds, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's most stages cleared in a run, Flock Dash's furthest stage), never shown to the agent), a built-in 23-topic Help, the app-only **Implementation Loop** (a dashboard card and a setup screen drawn by the page, `public/screens/loop-setup.js`; the last setup remembered per project in `~/.plan2code/console/loop-setup.json`, owned by `loop-setup.mjs`; a page that locks while `state.loop.driving` is set, until the app posts `loopEnd`; a skill run with `--loop` reports a `loopOutcome` instead of asking for sign-off, per `notes/loop.md`), a first-run Welcome, User Preferences (gear: four tabs, Appearance, Agents & models, System and Sounds & activities, on the `public/tabs.js` helper Help also uses, with `public/prefs.js`, `screens/prefs-dialog.js` and `screens/agents-view.js`), an agent-less **setup** page (the `setup` workflow `plan2code` or the desktop app opens when no agent can run: each built-in's found / outside-PATH / missing state from `agent-lookup.mjs`, install lines, Check again, Use it from here, starter templates and Start, which hands the tab to the new agent through a token-guarded `POST /handover` and a `move` event; the app shows it in its window from a Set up an agent button instead) and a bug/idea link to GitHub issues. On opted-in skills (every workflow but the dashboard, setup, Changelog, Git, Handoff and UI Prototype) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`), and a Helper strength choice (Balanced, Thrifty, Best, Match my session; rules in `src/shared-references/helper-strength.md`, shipped in the seventeen helper skills); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; task files are read through `spec-files.mjs` (shared with the `specs.mjs` skill script), and the rule for which hops start the page clean is `startsClean()` in `public/hops.js`. The agent contract is a card plus pointers: `console.md` (the card) once per conversation, then a topic file (`console-*.md` such as `console-docs.md`, `notes/.md`, `building*.md`) only when the console names it in its own `read` output, once per session per topic (remembered in `pointers.json` in the session folder, owned by `pointers.mjs`); the console refuses the slips it can see (a `stop` with no `finish`, a `finish` while `stopWarning` is set, with `stop --force` for a dead page) instead of the docs repeating each rule. Byte budgets for the card, every notes file and a sample session's outputs run in `npm test` (`scripts/test-console-wire-budgets.mjs`). The server never writes into a project; the one thing it deletes there is an old `specs--completed/` the person picks in Cleanup, and only when git tracks it (an untracked one is refused, with the reason on the page). +Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) installed once under `~/.plan2code/console//` (`installSharedConsole` in `install.js`) and reached from every skill through a forwarding stub, `src/web-console-stub/console.mjs`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review, and in Implement, Implement + Review and Quick task a **Changes** tab: a `diff` doc block fed by the `changes.mjs` skill script, parsed by `public/diff-parse.js` and drawn by `public/diff-view.js`), build progress, the living document, a spec's saved prototypes (a **Prototypes** tab: an `.md` read in place, an `.html` opened in the default browser), an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (a Save, Share, Review, Tidy path, one task card for the step you are on, and the Changes, Branches and Sync tabs folded into **All branches and tools**; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, private: the agent reads a tab only when you start Pathfinder, Plan, Quick task, Diagnose, UI Prototype or Revise plan from the dashboard with it and send the box it fills (an idea box marked `fill: "note"`, up to five ticked pictures attached), which then marks the tab sent via `POST /notepad/tab/sent`; the agent CLI never imports the store; removed only through Cleanup once a month untouched), **Activities** behind the top bar's die (thirteen small games, Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, listed in `public/activities.js` with one module per game under `public/activities/` (Ghoul Rush is its own folder of modules, `public/activities/ghoul-rush/`) and a card line (`blurb`) each, a picker of game rows in two columns, ordered Recently played or A to Z (saved in `activityOrder`), with never-picked games under Not played yet, once two are listed, that plays one game at a time (another pick drops the last game's round), driven by `screens/activities.js` (keys, key releases for a game with `release()`, canvas pointer events for a game with `pointer()`, one frame timer), paused whenever the person's turn comes and resumed only by the person (while that pause's banner is up, only by its **Unpause game** button), best scores in flat `activityBest` keys in `looks.json` (and the time each game was last picked in `activityPlayed`) (lowest wins for a game that sets `lowerIsBetter`; Mini golf opens on a dashboard of its six 18-hole courses, one file each under `public/activities/golf-course-.js`, and keeps a best per course, `activityBestGolf`), and one number a game may keep between sessions in `activityMemo` (Snake's tally of surprises found, Light Trails' furthest arena, Bug Hunt's tally of finds, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's most stages cleared in a run, Flock Dash's furthest stage), never shown to the agent), a built-in 23-topic Help, the app-only **Implementation Loop** (a dashboard card and a setup screen drawn by the page, `public/screens/loop-setup.js`; the last setup remembered per project in `~/.plan2code/console/loop-setup.json`, owned by `loop-setup.mjs`; a page that locks while `state.loop.driving` is set, until the app posts `loopEnd`; a skill run with `--loop` reports a `loopOutcome` instead of asking for sign-off, per `notes/loop.md`), a first-run Welcome, User Preferences (gear: four tabs, Appearance, Agents & models, System and Sounds & activities, on the `public/tabs.js` helper Help also uses, with `public/prefs.js`, `screens/prefs-dialog.js` and `screens/agents-view.js`), an agent-less **setup** page (the `setup` workflow `plan2code` or the desktop app opens when no agent can run: each built-in's found / outside-PATH / missing state from `agent-lookup.mjs`, install lines, Check again, Use it from here, starter templates and Start, which hands the tab to the new agent through a token-guarded `POST /handover` and a `move` event; the app shows it in its window from a Set up an agent button instead) and a bug/idea link to GitHub issues. On opted-in skills (every workflow but the dashboard, setup, Changelog, Git, Handoff and UI Prototype) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`), and a Helper strength choice (Balanced, Thrifty, Best, Match my session; rules in `src/shared-references/helper-strength.md`, shipped in every skill that starts helpers); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; task files are read through `spec-files.mjs` (shared with the `specs.mjs` skill script), and the rule for which hops start the page clean is `startsClean()` in `public/hops.js`. The agent contract is a card plus pointers: `console.md` (the card) once per conversation, then a topic file (`console-*.md` such as `console-docs.md`, `notes/.md`, `building*.md`) only when the console names it in its own `read` output, once per session per topic (remembered in `pointers.json` in the session folder, owned by `pointers.mjs`); the console refuses the slips it can see (a `stop` with no `finish`, a `finish` while `stopWarning` is set, with `stop --force` for a dead page) instead of the docs repeating each rule. Byte budgets for the card, every notes file and a sample session's outputs run in `npm test` (`scripts/test-console-wire-budgets.mjs`). The server never writes into a project; the one thing it deletes there is an old `specs--completed/` the person picks in Cleanup, and only when git tracks it (an untracked one is refused, with the reason on the page). One agent list and one lookup rule serve the launcher, the console and the app: `src/launcher/agents.json` (the built-ins and starter templates with per-OS install data) and `src/web-console/agent-lookup.mjs` (`loadAgentList()` and `findAgent()`, both copied by `install.js` into `~/.plan2code/bin/`); the app carries a Rust twin held to the same cases by `scripts/fixtures/agent-lookup-cases.json`. -**Learning** (lessons about a codebase, kept with it): the dashboard draws a Learning row (Not set up, Off, On or Paused for you, with a Pause for me switch and a More menu) and, while lessons are waiting, a banner with Review, both from the scan's `learning` field (`public/screens/learning-row.js`, `public/styles/learning.css`); skills ask for approval through the `lessons` card kind. The server's only write for it is the personal pause, on this machine only (`POST /learning/pause`, under `~/.plan2code/learning/`); every change to the project's Learning files (`.plan2code/settings.json` and `.plan2code/lessons/`) goes through the `lessons.mjs` skill script, which shares one core with the scan, `src/web-console/learning.mjs`. +**Learning** (lessons about a codebase, kept with it): the dashboard draws a Learning row (Not set up, Off, On or Paused for you, with a Pause for me switch and a More menu) and, while lessons are waiting, a banner with Review (plus a Tidy up nudge from the scan's `nearCap`; More, Tidy up lessons sends the `tidy` action, which writes `tidy` waiting items the same card applies), both from the scan's `learning` field (`public/screens/learning-row.js`, `public/styles/learning.css`); skills ask for approval through the `lessons` card kind. Before that card, every waiting lesson is graded by a separate check, a fresh read-only helper where the agent has one, else a labeled second pass by the same agent (`src/shared-references/lesson-check.md`; `lessons.mjs check-input` prepares, the checker judges, `check-record` stores), and the card shows each Doubt or Fail with its reason; follows ("Following a lesson") are counted on this machine only, in `follows.ndjson`, for the lessons reader. The server's only write for it is the personal pause, on this machine only (`POST /learning/pause`, under `~/.plan2code/learning/`); every change to the project's Learning files (`.plan2code/settings.json` and `.plan2code/lessons/`) goes through the `lessons.mjs` skill script, which shares one core with the scan, `src/web-console/learning.mjs`. Building or changing an Activities game: follow the game rules in [Activities](./.agents-docs/AGENTS-architecture-activities.md) ("Building an Activities game": lives in the solid lives pill, the endless-lives code (`cheat(on)`) in every game with lives, banners placed away from the player and see-through over what matters, pausing left to the window). Details: [Web console server and contract](./.agents-docs/AGENTS-architecture-console.md), [page](./.agents-docs/AGENTS-architecture-console-page.md), [design points](./.agents-docs/AGENTS-architecture-console-design.md), [Activities](./.agents-docs/AGENTS-architecture-activities.md) (and the Ghoul Rush and Bounce Road files it links) [.readme/web-console.md](./.readme/web-console.md) (the user guide), [.readme/activities.md](./.readme/activities.md) and [.readme/web-console-internals.md](./.readme/web-console-internals.md) (routes, security, driving it by hand, refreshing screenshots) Why the agent-facing console docs are shaped as they are (the card, pointers, refusals): [Web Console Contract](./.agents-docs/AGENTS-web-console-contract.md); it never ships. diff --git a/install.js b/install.js index d3df7e5..cec15cd 100644 --- a/install.js +++ b/install.js @@ -170,7 +170,9 @@ const SOURCE_PROMPTS = [ scripts: ['lessons.mjs', 'glob.mjs', 'test-map.mjs'], additionalReferences: [ { source: 'web-console', target: 'web-console' }, - { source: 'shared-references/lessons.md', target: 'lessons.md' } + { source: 'shared-references/lessons.md', target: 'lessons.md' }, + { source: 'shared-references/helper-strength.md', target: 'helper-strength.md' }, + { source: 'shared-references/lesson-check.md', target: 'lesson-check.md' } ] }, { @@ -240,7 +242,8 @@ const SOURCE_PROMPTS = [ { source: 'plan2code-review-references' }, { source: 'plan2code-ui-prototype.md', target: 'ui-prototype.md' }, { source: 'plan2code-ui-prototype-references' }, - { source: 'shared-references/lessons.md', target: 'lessons.md' } + { source: 'shared-references/lessons.md', target: 'lessons.md' }, + { source: 'shared-references/lesson-check.md', target: 'lesson-check.md' } ] }, { @@ -310,7 +313,8 @@ const SOURCE_PROMPTS = [ { source: 'shared-references/test-runs.md', target: 'test-runs.md' }, { source: 'plan2code-review.md', target: 'review.md' }, { source: 'plan2code-review-references' }, - { source: 'shared-references/lessons.md', target: 'lessons.md' } + { source: 'shared-references/lessons.md', target: 'lessons.md' }, + { source: 'shared-references/lesson-check.md', target: 'lesson-check.md' } ] }, { @@ -329,7 +333,8 @@ const SOURCE_PROMPTS = [ { source: 'shared-references/test-runs.md', target: 'test-runs.md' }, { source: 'plan2code-review.md', target: 'review.md' }, { source: 'plan2code-review-references' }, - { source: 'shared-references/lessons.md', target: 'lessons.md' } + { source: 'shared-references/lessons.md', target: 'lessons.md' }, + { source: 'shared-references/lesson-check.md', target: 'lesson-check.md' } ] }, { @@ -347,7 +352,8 @@ const SOURCE_PROMPTS = [ { source: 'shared-references/review-in-build.md', target: 'review-in-build.md' }, { source: 'shared-references/helper-strength.md', target: 'helper-strength.md' }, { source: 'shared-references/test-runs.md', target: 'test-runs.md' }, - { source: 'shared-references/lessons.md', target: 'lessons.md' } + { source: 'shared-references/lessons.md', target: 'lessons.md' }, + { source: 'shared-references/lesson-check.md', target: 'lesson-check.md' } ] }, { @@ -392,7 +398,8 @@ const SOURCE_PROMPTS = [ additionalReferences: [ { source: 'web-console', target: 'web-console' }, { source: 'shared-references/helper-strength.md', target: 'helper-strength.md' }, - { source: 'shared-references/lessons.md', target: 'lessons.md' } + { source: 'shared-references/lessons.md', target: 'lessons.md' }, + { source: 'shared-references/lesson-check.md', target: 'lesson-check.md' } ] }, { @@ -409,7 +416,8 @@ const SOURCE_PROMPTS = [ { source: 'web-console', target: 'web-console' }, { source: 'shared-references/building-habits.md', target: 'building-habits.md' }, { source: 'shared-references/helper-strength.md', target: 'helper-strength.md' }, - { source: 'shared-references/lessons.md', target: 'lessons.md' } + { source: 'shared-references/lessons.md', target: 'lessons.md' }, + { source: 'shared-references/lesson-check.md', target: 'lesson-check.md' } ] }, { @@ -444,7 +452,8 @@ const SOURCE_PROMPTS = [ { source: 'shared-references/test-runs.md', target: 'test-runs.md' }, { source: 'shared-references/building-habits.md', target: 'building-habits.md' }, { source: 'shared-references/helper-strength.md', target: 'helper-strength.md' }, - { source: 'shared-references/lessons.md', target: 'lessons.md' } + { source: 'shared-references/lessons.md', target: 'lessons.md' }, + { source: 'shared-references/lesson-check.md', target: 'lesson-check.md' } ] }, { diff --git a/scripts/capture-screenshots.mjs b/scripts/capture-screenshots.mjs index b6b256e..2b4bc3f 100644 --- a/scripts/capture-screenshots.mjs +++ b/scripts/capture-screenshots.mjs @@ -351,7 +351,7 @@ function makeLearningProject() { const note = (text, kind, about) => spawnSync( process.execPath, - [path.join(ROOT, "src", "skill-scripts", "lessons.mjs"), "note", "--type", "lesson", "--text", text, "--kind", kind, "--about", about, "--source", "said", "--skill", "implement"], + [path.join(ROOT, "src", "skill-scripts", "lessons.mjs"), "note", "--type", "lesson", "--text", text, "--kind", kind, "--about", about, "--source", "said", "--skill", "implement", ...(kind === "convention" ? ["--why", "An offset skips rows when the list changes between pages."] : [])], { cwd: project, env: ENV, encoding: "utf8" } ); note("Every list endpoint pages with a cursor, never an offset.", "convention", "src/tasks"); diff --git a/scripts/test-script-lessons.mjs b/scripts/test-script-lessons.mjs index e8aaea8..7904b3b 100644 --- a/scripts/test-script-lessons.mjs +++ b/scripts/test-script-lessons.mjs @@ -7,6 +7,7 @@ import { test, after } from "node:test"; import assert from "node:assert/strict"; +import crypto from "node:crypto"; import fs from "node:fs"; import path from "node:path"; import { spawnSync } from "node:child_process"; @@ -363,6 +364,76 @@ test("lessons record: parse and render round trip byte for byte, LF and CRLF", ( assert.equal(record.parseAreaFile(AREA_TEXT.replace(/\n/g, "\r\n")).eol, "\r\n"); }); +const SEARCH_TEXT = [ + "# Web console", + "Paths: src/web-console/**", + "", + "### Keep the flat keys", + "- Kind: convention", + "- About: src/web-console/server.mjs", + "- Why: a nested key was lost once.", + "- Shows in: src/web-console/**/*.js | never matches | localStorage.setItem", + "- Noted: 2026-11-01, Implement, checked 2026-11-10, kept over the check", + "", + "### Run the page test alone", + "- Kind: command", + "- About: scripts/a.mjs", + "- Shows in: scripts/*.mjs | should match | node-test.mjs", + "- Noted: 2026-11-02, Quick Task, kept over the check", + "", + "### An old block with no new fields", + "- Kind: how-it-works", + "- About: src/a.js", + "- Noted: 2026-11-03, Review", + "", +].join("\n"); + +test("lessons record: a search line and the kept-over-the-check mark parse and round trip, LF and CRLF", () => { + for (const text of [SEARCH_TEXT, SEARCH_TEXT.replace(/\n/g, "\r\n"), SEARCH_TEXT.replace(/\n$/, "")]) { + const area = record.parseAreaFile(text); + assert.equal(record.renderAreaFile(area), text); + const [a, b, c] = area.blocks; + assert.deepEqual(a.search, { glob: "src/web-console/**/*.js", match: "never", text: "localStorage.setItem" }); + assert.equal(a.noted, "2026-11-01, Implement"); + assert.equal(a.checked, "2026-11-10"); + assert.equal(a.keptOverCheck, true); + assert.deepEqual(b.search, { glob: "scripts/*.mjs", match: "should", text: "node-test.mjs" }); + assert.equal(b.checked, null); + assert.equal(b.keptOverCheck, true); + assert.equal(c.search, undefined); + assert.equal(c.keptOverCheck, undefined); + // A fresh render of the parsed block writes the same lines (LF only here). + if (!text.includes("\r")) assert.deepEqual(record.renderBlock(a), a.lines.slice(0, record.renderBlock(a).length)); + } +}); + +test("lessons record: a Shows in line that does not parse stays in the block and is reported", () => { + const text = ["# A", "", "### One", "- Kind: command", "- About: a.js", "- Shows in: a.js | maybe | x", "- Noted: 2026-11-01, I", ""].join("\n"); + const area = record.parseAreaFile(text); + assert.equal(area.blocks[0].search, undefined); + assert.deepEqual(area.blocks[0].badLines, ["- Shows in: a.js | maybe | x"]); + assert.equal(record.renderAreaFile(area), text); +}); + +test("lessons record: this repository's general.md round trips byte for byte", () => { + const file = path.join(import.meta.dirname, "..", ".plan2code", "lessons", "general.md"); + const text = fs.readFileSync(file, "utf8"); + assert.equal(record.renderAreaFile(record.parseAreaFile(text)), text); +}); + +test("lessons record: searchProblems checks the glob, the match words and the text", () => { + assert.deepEqual(record.searchProblems({ glob: "src/**/*.js", match: "should", text: "export default" }), []); + const bad = (search) => record.searchProblems(search).length; + assert.ok(bad({ glob: "../x/**", match: "should", text: "a" })); + assert.ok(bad({ glob: "src\\a.js", match: "should", text: "a" })); + assert.ok(bad({ glob: "/abs/a.js", match: "should", text: "a" })); + assert.ok(bad({ glob: "src/**", match: "sometimes", text: "a" })); + assert.ok(bad({ glob: "src/**", match: "never", text: "" })); + assert.ok(bad({ glob: "src/**", match: "never", text: "a | b" })); + assert.ok(bad({ glob: "src/**", match: "never", text: "a".repeat(121) })); + assert.equal(bad({ glob: "src/**", match: "never", text: "a".repeat(120) }), 0); +}); + test("lessons record: an insert lands at its alphabetical place and leaves every other line alone", () => { for (const eolText of ["\n", "\r\n"]) { const text = AREA_TEXT.replace(/\n/g, eolText); @@ -489,7 +560,7 @@ const waitingFiles = (store) => .filter((f) => /waiting[\\/][^\\/]+\.json$/.test(f)) : []; -const lesson = (text, extra = []) => ["note", "--type", "lesson", "--text", text, "--kind", "convention", "--about", "src/a.js", "--source", "said", "--skill", "Implement", ...extra]; +const lesson = (text, extra = []) => ["note", "--type", "lesson", "--text", text, "--kind", "convention", "--about", "src/a.js", "--source", "said", "--skill", "Implement", "--why", "The tests say so.", ...extra]; test("lessons note: each rule refuses with exit 4 invalid-lesson", () => { const dir = repo(); @@ -499,20 +570,24 @@ test("lessons note: each rule refuses with exit 4 invalid-lesson", () => { ["201 characters", lesson("a".repeat(201))], ["unknown kind", ["note", "--type", "lesson", "--text", "One rule", "--kind", "rule", "--about", "src/a.js", "--source", "said", "--skill", "I"]], ["a correction with no why", ["note", "--type", "lesson", "--text", "One rule", "--kind", "correction", "--about", "src/a.js", "--source", "said", "--skill", "I"]], - ["four files", ["note", "--type", "lesson", "--text", "One rule", "--kind", "convention", "--about", "a.js,b.js,c.js,d.js", "--source", "said", "--skill", "I"]], - ["a path with ..", ["note", "--type", "lesson", "--text", "One rule", "--kind", "convention", "--about", "../outside.js", "--source", "said", "--skill", "I"]], - ["inferred with no seen files", ["note", "--type", "lesson", "--text", "One rule", "--kind", "convention", "--about", "src/a.js", "--source", "inferred", "--skill", "I"]], + ["four files", ["note", "--type", "lesson", "--text", "One rule", "--kind", "convention", "--why", "The tests say so.", "--about", "a.js,b.js,c.js,d.js", "--source", "said", "--skill", "I"], "about"], + ["a path with ..", ["note", "--type", "lesson", "--text", "One rule", "--kind", "convention", "--why", "The tests say so.", "--about", "../outside.js", "--source", "said", "--skill", "I"], "about"], + ["inferred with no seen files", ["note", "--type", "lesson", "--text", "One rule", "--kind", "convention", "--why", "The tests say so.", "--about", "src/a.js", "--source", "inferred", "--skill", "I"], "seen"], ]; - for (const [what, args] of cases) { + for (const [what, args, field] of cases) { const r = L(dir, args, store); assert.equal(r.code, 4, `${what}: ${r.stdout}`); assert.equal(r.json.error, "invalid-lesson", what); assert.ok(r.json.problems.length >= 1, what); + // A case that names its field must fail on that rule, not on another it trips by accident. + if (field) assert.deepEqual([...new Set(r.json.problems.map((p) => p.field))], [field], `${what}: ${r.stdout}`); } assert.equal(L(dir, lesson("Call `a.b()` first. Then `c()`, as in `x. Y`"), store).code, 4, "a second sentence outside code still counts"); assert.equal(L(dir, lesson("Call `x. Y` before the build"), store).code, 0, "a stop inside a code span is not a sentence end"); write(dir, "src/web/a.js", ""); - assert.equal(L(dir, ["note", "--type", "lesson", "--text", "One rule", "--kind", "convention", "--about", "src/web,src/a.js", "--source", "said", "--skill", "I"], store).code, 4, "a folder stands alone"); + const folder = L(dir, ["note", "--type", "lesson", "--text", "One rule", "--kind", "convention", "--why", "The tests say so.", "--about", "src/web,src/a.js", "--source", "said", "--skill", "I"], store); + assert.equal(folder.code, 4, "a folder stands alone"); + assert.deepEqual(folder.json.problems.map((p) => p.field), ["about"], "a folder stands alone, and only that is wrong"); }); test("lessons note: a refused secret exits 5 and writes nothing anywhere", () => { @@ -543,13 +618,81 @@ test("lessons note: a refused secret exits 5 and writes nothing anywhere", () => assert.deepEqual(waitingFiles(store), [], "the waiting folder stays empty"); }); +const SEARCH = ["--shows-in", "src/**/*.js", "--match", "never", "--text-match", "localStorage"]; + +test("lessons note: a full search is stored on the waiting item", () => { + const dir = repo(); + const store = learningDir(); + settings(dir, { format: 1, learning: "on" }); + const r = L(dir, lesson("Use the flat keys", SEARCH), store); + assert.equal(r.code, 0, r.stdout); + assert.equal(r.json.noted, true); + const file = waitingFiles(store)[0]; + const item = JSON.parse(fs.readFileSync(path.join(store, file), "utf8")); + assert.deepEqual(item.search, { glob: "src/**/*.js", match: "never", text: "localStorage" }); + const plain = L(dir, lesson("Use another rule"), store); + assert.equal(plain.code, 0, plain.stdout); + const other = waitingFiles(store).find((f) => f !== file); + assert.equal(JSON.parse(fs.readFileSync(path.join(store, other), "utf8")).search, undefined); +}); + +test("lessons note: a partial or malformed search, or a convention with no why, exits 4", () => { + const dir = repo(); + const store = learningDir(); + const cases = [ + ["only --shows-in", lesson("A rule", ["--shows-in", "src/**"])], + ["--shows-in and --match", lesson("A rule", ["--shows-in", "src/**", "--match", "should"])], + ["only --text-match", lesson("A rule", ["--text-match", "x"])], + ["a glob with ..", lesson("A rule", ["--shows-in", "../x/**", "--match", "should", "--text-match", "x"])], + ["a text with a pipe", lesson("A rule", ["--shows-in", "src/**", "--match", "should", "--text-match", "a | b"])], + ["a bad match word", lesson("A rule", ["--shows-in", "src/**", "--match", "maybe", "--text-match", "x"])], + ["a convention with no why", ["note", "--type", "lesson", "--text", "A rule", "--kind", "convention", "--about", "src/a.js", "--source", "said", "--skill", "I"]], + ]; + for (const [what, args] of cases) { + const r = L(dir, args, store); + assert.equal(r.code, 4, `${what}: ${r.stdout}`); + assert.equal(r.json.error, "invalid-lesson", what); + } + assert.ok(L(dir, cases[0][1], store).json.problems[0].message.includes("--match"), "a partial set names the missing flags"); + assert.equal(L(dir, ["note", "--type", "lesson", "--text", "A rule", "--kind", "correction", "--about", "src/a.js", "--source", "said", "--skill", "I"], store).code, 4, "a correction still needs a why"); + assert.equal(L(dir, ["note", "--type", "lesson", "--text", "A rule", "--kind", "command", "--about", "src/a.js", "--source", "said", "--skill", "I"], store).code, 0, "a command needs none"); + assert.deepEqual(waitingFiles(store).length, 1, "only the command was held"); +}); + +test("lessons note: a secret-shaped search text exits 5 and writes nothing", () => { + const dir = repo(); + const store = learningDir(); + const [bad] = SECRETS["github-token"]; + const r = L(dir, lesson("A rule", ["--shows-in", "src/**", "--match", "never", "--text-match", bad]), store); + assert.equal(r.code, 5, r.stdout); + assert.equal(r.json.error, "secret"); + assert.ok(!r.stdout.includes(bad)); + assert.deepEqual(waitingFiles(store), []); +}); + +test("lessons note: an inferred lesson from a read-only skill is refused, and said or another skill is accepted", () => { + const dir = repo(); + const store = learningDir(); + const inferred = (skill) => ["note", "--type", "lesson", "--text", "A rule", "--kind", "command", "--about", "src/a.js", "--source", "inferred", "--seen", "src/a.js", "--skill", skill]; + for (const skill of ["plan", "plan2code-1-plan", "finalize", "dead-code", "Dead Code", "PR Prep", "UI Prototype", "Revise plan"]) { + const r = L(dir, inferred(skill), store); + assert.equal(r.code, 5, `${skill}: ${r.stdout}`); + assert.equal(r.json.error, "inferred-from-read-only"); + } + assert.deepEqual(waitingFiles(store), [], "nothing was written"); + const said = L(dir, ["note", "--type", "lesson", "--text", "A rule", "--kind", "command", "--about", "src/a.js", "--source", "said", "--skill", "plan"], store); + assert.equal(said.code, 0, said.stdout); + assert.equal(L(dir, inferred("quick-task"), store).code, 0); +}); + test("lessons note: a skill name with a line break or over 40 characters is refused", () => { const dir = repo(); const store = learningDir(); for (const skill of ["Implement\n### Injected heading", "x".repeat(41)]) { - const r = L(dir, ["note", "--type", "lesson", "--text", "One rule", "--kind", "convention", "--about", "src/a.js", "--source", "said", "--skill", skill], store); + const r = L(dir, ["note", "--type", "lesson", "--text", "One rule", "--kind", "convention", "--why", "The tests say so.", "--about", "src/a.js", "--source", "said", "--skill", skill], store); assert.equal(r.code, 4, r.stdout); assert.equal(r.json.error, "invalid-lesson"); + assert.deepEqual(r.json.problems.map((p) => p.field), ["skill"], r.stdout); } assert.deepEqual(waitingFiles(store), []); }); @@ -725,7 +868,7 @@ test("lessons list: origin lines, the other-branch note and the main-branch open write(dir, "src/only-here.js", "x\n"); g("add", "-A"); g("commit", "-q", "-m", "feature file"); - L(dir, ["note", "--type", "lesson", "--text", "Keep it short", "--kind", "convention", "--about", "src/only-here.js", "--source", "inferred", "--seen", "src/only-here.js,src/b.js", "--skill", "Implement"], store); + L(dir, ["note", "--type", "lesson", "--text", "Keep it short", "--kind", "convention", "--about", "src/only-here.js", "--source", "inferred", "--seen", "src/only-here.js,src/b.js", "--skill", "Implement", "--why", "The tests say so."], store); const onFeature = L(dir, ["list"], store).json; assert.equal(onFeature.opening, null, "not on the default branch"); assert.equal(onFeature.items[0].note, ""); @@ -805,7 +948,7 @@ test("lessons decide: two branches keeping different lessons in one area merge w g("commit", "-q", "-m", "area"); const keepOn = (branch, text) => { g("checkout", "-q", "-b", branch, "main"); - L(dir, ["note", "--type", "lesson", "--text", text, "--kind", "convention", "--about", "src/web-console/a.mjs", "--source", "said", "--skill", "Implement"], store); + L(dir, ["note", "--type", "lesson", "--text", text, "--kind", "convention", "--about", "src/web-console/a.mjs", "--source", "said", "--skill", "Implement", "--why", "The tests say so."], store); assert.equal(decide(dir, store, [{ id: ids(dir, store)[0], choice: "Keep" }]).json.results[0].outcome, "kept"); g("commit", "-q", "-am", branch); }; @@ -838,8 +981,8 @@ test("lessons decide: a lesson whose proposed area is dropped lands in a matchin settings(dir, { format: 1, learning: "on" }); write(dir, ".plan2code/lessons/source.md", "# Source\nPaths: src/**\n"); L(dir, ["note", "--type", "area", "--name", "Web", "--paths", "src/web/**", "--skill", "Implement"], store); - L(dir, ["note", "--type", "lesson", "--text", "Web lesson", "--kind", "convention", "--about", "src/web/a.js", "--source", "said", "--skill", "Implement", "--area", "Web"], store); - L(dir, ["note", "--type", "lesson", "--text", "Docs lesson", "--kind", "convention", "--about", "docs/a.md", "--source", "said", "--skill", "Implement", "--area", "Web"], store); + L(dir, ["note", "--type", "lesson", "--text", "Web lesson", "--kind", "convention", "--about", "src/web/a.js", "--source", "said", "--skill", "Implement", "--why", "The tests say so.", "--area", "Web"], store); + L(dir, ["note", "--type", "lesson", "--text", "Docs lesson", "--kind", "convention", "--about", "docs/a.md", "--source", "said", "--skill", "Implement", "--why", "The tests say so.", "--area", "Web"], store); const listed = L(dir, ["list"], store).json; assert.deepEqual( listed.rounds.map((round) => round.type), @@ -868,7 +1011,7 @@ test("lessons decide: Create then Keep into the new area, Rename, and unknown id settings(dir, { format: 1, learning: "on" }); L(dir, ["note", "--type", "area", "--name", "Web", "--paths", "src/web/**", "--skill", "Implement"], store); L(dir, ["note", "--type", "area", "--name", "Docs", "--paths", "docs/**", "--skill", "Implement"], store); - L(dir, ["note", "--type", "lesson", "--text", "Web lesson", "--kind", "convention", "--about", "src/web/a.js", "--source", "said", "--skill", "Implement"], store); + L(dir, ["note", "--type", "lesson", "--text", "Web lesson", "--kind", "convention", "--about", "src/web/a.js", "--source", "said", "--skill", "Implement", "--why", "The tests say so."], store); const [web, docs, one] = idsOf(dir, store, "Web", "Docs", "Web lesson"); const r = decide(dir, store, [ { id: one, choice: "Keep" }, @@ -1396,17 +1539,35 @@ test("lessons decide: a doubt kept moves the checked date and nothing else, and assert.equal(marks(dir)[LESSON_ID].marked, false, "the block's own line moved past the edit"); }); +test("lessons decide: a kept lesson carries its search into the file, and a Reword keeps a saved search", () => { + const dir = markA(); + const store = learningDir(); + settings(dir, { format: 1, learning: "on" }); + const n = L(dir, lesson("Page with a cursor everywhere", ["--about", "src/app.js", "--shows-in", "src/**/*.js", "--match", "never", "--text-match", "offset="]), store); + assert.equal(n.code, 0, n.stdout); + const kept = decide(dir, store, [{ id: ids(dir, store)[0], choice: "Keep" }]); + assert.equal(kept.json.results[0].outcome, "kept", JSON.stringify(kept.json.results)); + const area = fs.readdirSync(path.join(dir, ".plan2code", "lessons")).map((f) => read(dir, `.plan2code/lessons/${f}`)).join("\n"); + assert.match(area, /- Shows in: src\/\*\*\/\*\.js \| never matches \| offset=\n- Noted: /); + write(dir, WEB_FILE, "# Web\nPaths: src/**\n\n### Keep the handler small\n- Kind: command\n- About: src/app.js\n- Shows in: src/** | should match | handler\n- Noted: 2026-11-01, Implement, kept over the check\n"); + L(dir, doubt(LESSON_ID), store); + const doubtId = L(dir, ["list"], store).json.items.find((i) => i.type === "doubt").id; + const r = decide(dir, store, [{ id: doubtId, choice: "Reword", text: "Keep the handler tiny" }]); + assert.equal(r.json.results[0].outcome, "reworded", JSON.stringify(r.json.results)); + assert.match(read(dir, WEB_FILE), /- Shows in: src\/\*\* \| should match \| handler\n/); +}); + test("lessons decide: Reword a doubted lesson re-sorts it, and Retire empties and removes the area file", () => { const dir = markA(); const store = learningDir(); settings(dir, { format: 1, learning: "on" }); write(dir, WEB_FILE, WEB_AREA + "\n### Name the handler after its route\n- Kind: convention\n- About: src/app.js\n- Noted: 2026-11-02, Implement\n"); L(dir, doubt(LESSON_ID), store); - const reworded = decide(dir, store, [{ id: ids(dir, store)[0], choice: "Reword", text: "Answer from one small handler" }]); + const reworded = decide(dir, store, [{ id: ids(dir, store)[0], choice: "Reword", text: "Answer from one small handler", why: "One handler per route kept them apart." }]); assert.equal(reworded.json.results[0].outcome, "reworded", JSON.stringify(reworded.json.results)); assert.equal(reworded.json.results[0].lesson, "web/answer-from-one-small-handler"); assert.deepEqual(read(dir, WEB_FILE).match(/^### .*$/gm), ["### Answer from one small handler", "### Name the handler after its route"]); - assert.match(read(dir, WEB_FILE), /### Answer from one small handler\n- Kind: convention\n- About: src\/app.js\n- Noted: 2026-11-01, Implement, checked 2026-08-03\n/); + assert.match(read(dir, WEB_FILE), /### Answer from one small handler\n- Kind: convention\n- About: src\/app.js\n- Why: One handler per route kept them apart.\n- Noted: 2026-11-01, Implement, checked 2026-08-03\n/); fs.rmSync(path.join(dir, "src/app.js")); const gone = L(dir, ["list"], store).json.items.map((i) => i.id); @@ -2143,7 +2304,7 @@ test("lessons.md: every line it tells a skill to print is a line the script prin // "Noted for the end of the run: ", from a real note. const [noted] = pick("Noted for the end of the run: "); - const note = L(dir, ["note", "--type", "lesson", "--text", "Draw the page from the state object", "--kind", "convention", "--about", "src/web/page.js", "--source", "said", "--skill", "Implement"], store); + const note = L(dir, ["note", "--type", "lesson", "--text", "Draw the page from the state object", "--kind", "convention", "--about", "src/web/page.js", "--source", "said", "--skill", "Implement", "--why", "The tests say so."], store); assert.equal(note.code, 0, note.stderr); assert.equal(note.json.line, noted.replace("", "Draw the page from the state object")); @@ -2168,10 +2329,974 @@ test("lessons.mjs: no output string says pending or queued (the fixed word is wa const outputs = [L(dir, ["state"], store), L(dir, ["list", "--first-ask"], store)]; settings(dir, { format: 1, learning: "on" }); outputs.push( - L(dir, ["note", "--type", "lesson", "--text", "Draw the page from the state object", "--kind", "convention", "--about", "README.md", "--source", "said", "--skill", "Implement"], store), + L(dir, ["note", "--type", "lesson", "--text", "Draw the page from the state object", "--kind", "convention", "--about", "README.md", "--source", "said", "--skill", "Implement", "--why", "The tests say so."], store), L(dir, ["read"], store), L(dir, ["list"], store), L(dir, ["remove"], store) ); for (const out of outputs) assert.doesNotMatch(out.stdout + out.stderr, BANNED); }); + +/* ------------------------------------------------------------ the check */ + +const sha = (text) => crypto.createHash("sha256").update(text).digest("hex"); + +// Run `fn` with the learning store pointed at `store`, for the core's calls. +function inStore(store, fn) { + const before = process.env.PLAN2CODE_LEARNING_DIR; + process.env.PLAN2CODE_LEARNING_DIR = store; + try { + return fn(); + } finally { + if (before === undefined) delete process.env.PLAN2CODE_LEARNING_DIR; + else process.env.PLAN2CODE_LEARNING_DIR = before; + } +} + +// A waiting lesson written through the core, into a given store. `noted` is a Date. +const putLesson = (dir, store, id, noted, fields = {}) => + inStore(store, () => core.writeWaiting(dir, { id, type: "lesson", text: `Lesson ${id}`, why: "A reason.", kind: "correction", about: ["src/a.js"], source: "said", skill: "Implement", noted: noted.toISOString(), ...fields })); + +// The waiting item as stored now (its check included). +const storedItem = (dir, store, id) => inStore(store, () => core.listWaiting(dir, nowDate(), { prune: false }).find((w) => w.id === id)); + +const checkFilesIn = (dir, store) => + inStore(store, () => { + const d = path.join(core.storeDir(dir), "checks"); + return fs.existsSync(d) ? fs.readdirSync(d) : []; + }); + +const passAll = (over = {}) => { + const t = (verdict = "Pass", reason = "It holds.") => ({ verdict, reason }); + return { true: t(), worth: t(), overlap: t(), clear: t(), ...over }; +}; + +const recordFile = (body) => { + const file = path.join(tmp("lessons-check"), "verdicts.json"); + fs.writeFileSync(file, JSON.stringify(body)); + return file; +}; + +// A learning-on repository with src/a.js, ready for waiting lessons. +function checkRepo() { + const dir = repo(); + const store = learningDir(); + settings(dir, { format: 1, learning: "on" }); + write(dir, "src/a.js", "export const a = 1;\n"); + return { dir, store }; +} + +test("lessons check-input: 12 waiting lessons give 10 oldest first and 2 in notChecked", () => { + const { dir, store } = checkRepo(); + const order = []; + for (let i = 0; i < 12; i++) { + const id = `w${String(i).padStart(2, "0")}`; + putLesson(dir, store, id, daysBefore(20 - i)); + order.push(id); + } + const r = L(dir, ["check-input"], store); + assert.equal(r.code, 0, r.stderr); + assert.equal(r.json.cap, 10); + assert.deepEqual(r.json.lessons.map((l) => l.id), order.slice(0, 10)); + assert.deepEqual(r.json.notChecked, order.slice(10)); + assert.match(r.json.checkId, /^[a-z0-9]+-[0-9a-f]{4}$/); + assert.equal(checkFilesIn(dir, store).length, 1, "the run's check file is written"); +}); + +test("lessons check-input: check files over a day old are pruned, newer ones and other files are kept", () => { + const { dir, store } = checkRepo(); + const old = `${(Date.now() - 2 * 24 * 60 * 60 * 1000).toString(36)}-abcd.json`; + const recent = `${(Date.now() - 60 * 1000).toString(36)}-beef.json`; + inStore(store, () => { + const d = path.join(core.storeDir(dir), "checks"); + fs.mkdirSync(d, { recursive: true }); + for (const name of [old, recent, "notes.txt"]) fs.writeFileSync(path.join(d, name), "{}"); + }); + putLesson(dir, store, "w01", daysBefore(3)); + const r = L(dir, ["check-input"], store); + assert.equal(r.code, 0, r.stderr); + const left = checkFilesIn(dir, store); + assert.ok(!left.includes(old), "an abandoned check from two days ago is gone"); + assert.ok(left.includes(recent) && left.includes("notes.txt"), "a check from a minute ago and a file of another shape stay"); + assert.ok(left.includes(`${r.json.checkId}.json`), "this run's check file is written"); +}); + +test("lessons check-input: a file lesson is read whole with its hash, and context lists saved and other waiting lessons", () => { + const { dir, store } = checkRepo(); + write(dir, "AGENTS.md", "# A\n"); + write(dir, ".plan2code/lessons/general.md", "# General\n\n### Saved one\n- Kind: how-it-works\n- About: src/a.js\n- Noted: 2026-01-01, Implement\n"); + putLesson(dir, store, "w01", daysBefore(3)); + const r = L(dir, ["check-input"], store); + assert.deepEqual(r.json.lessons[0].files, [{ path: "src/a.js", hash: sha("export const a = 1;\n"), read: "whole" }]); + assert.equal(r.json.lessons[0].budgetHit, undefined); + assert.equal(r.json.context.agentsMd, "AGENTS.md"); + assert.deepEqual(r.json.context.saved, [{ id: "general/saved-one", text: "Saved one" }]); + assert.deepEqual(r.json.context.waiting, []); + // Beyond the cap, a lesson is context rather than checked. + for (let i = 0; i < 11; i++) putLesson(dir, store, `x${String(i).padStart(2, "0")}`, daysBefore(2)); + const more = L(dir, ["check-input"], store).json; + assert.equal(more.lessons.length, 10); + assert.equal(more.context.waiting.length, 2); +}); + +test("lessons check-input: a folder lesson stops at 6 files or 60 KB with budgetHit, preferring files that share words", () => { + const { dir, store } = checkRepo(); + for (let i = 0; i < 8; i++) write(dir, `src/many/f${i}.js`, `// ${i}\n`); + write(dir, "src/many/zebra-parser.js", "// z\n"); + putLesson(dir, store, "w01", daysBefore(5), { text: "The zebra parser never trims", about: ["src/many"] }); + for (let i = 0; i < 3; i++) write(dir, `src/big/b${i}.txt`, "x".repeat(31000)); + putLesson(dir, store, "w02", daysBefore(4), { text: "Big files", about: ["src/big"] }); + write(dir, "src/small/s0.js", "// s\n"); + putLesson(dir, store, "w03", daysBefore(3), { text: "Small folder", about: ["src/small"] }); + const [many, big, small] = L(dir, ["check-input"], store).json.lessons; + assert.equal(many.files.length, 6); + assert.equal(many.budgetHit, true); + assert.ok(many.files.every((f) => f.read === "sampled")); + assert.equal(many.files[0].path, "src/many/zebra-parser.js", "the file sharing words with the lesson comes first"); + assert.equal(big.files.length, 2, "two 31000 byte files pass the 60 KB budget"); + assert.equal(big.budgetHit, true); + assert.equal(small.files.length, 1); + assert.equal(small.budgetHit, undefined); +}); + +test("lessons check-input: a lesson whose stored check still holds is skipped, and one whose file changed is due again", () => { + const { dir, store } = checkRepo(); + putLesson(dir, store, "w01", daysBefore(5), { check: { tests: passAll(), how: "helper", files: { "src/a.js": sha("export const a = 1;\n") }, checked: new Date().toISOString(), seconds: 3 } }); + putLesson(dir, store, "w02", daysBefore(4)); + assert.deepEqual(L(dir, ["check-input"], store).json.lessons.map((l) => l.id), ["w02"]); + write(dir, "src/a.js", "export const a = 2;\n"); + assert.deepEqual(L(dir, ["check-input"], store).json.lessons.map((l) => l.id), ["w01", "w02"]); +}); + +test("lessons search: hits carry file and line, matching is case-exact, node_modules, .git, skills/ and gitignored files are skipped", () => { + const dir = repo(); + write(dir, "src/a.js", "const a = 1;\n\nlocalStorage.setItem('k', 1);\n"); + write(dir, "src/b.txt", "no match here\n"); + write(dir, "node_modules/x/index.js", "localStorage\n"); + write(dir, ".git/hooks/x.js", "localStorage\n"); + write(dir, "skills/y/z.js", "localStorage\n"); + write(dir, "src/big.js", "localStorage " + "x".repeat(600 * 1024)); + write(dir, "src/bin.js", "localStorage\0\n"); + const found = record.runSearch(dir, { glob: "**/*.js", match: "never", text: "localStorage" }); + assert.equal(found.matched, true); + assert.deepEqual(found.hits, [{ file: "src/a.js", line: 3 }]); + assert.equal(found.filesSearched, 1); + assert.equal(record.runSearch(dir, { glob: "**/*.js", match: "never", text: "localstorage" }).matched, false, "case-exact"); + const none = record.runSearch(dir, { glob: "src/**", match: "should", text: "absent text" }); + assert.deepEqual({ matched: none.matched, hits: none.hits }, { matched: false, hits: [] }); + write(dir, ".gitignore", "build/\n"); + write(dir, "build/gen.js", "localStorage\n"); + assert.deepEqual(record.runSearch(dir, { glob: "**/*.js", match: "never", text: "localStorage" }).hits, [{ file: "src/a.js", line: 3 }], "a gitignored file is never searched"); + const listed = record.searchFiles(dir); + assert.ok(!listed.includes("build/gen.js") && listed.includes("src/a.js"), "the listing leaves ignored files out and keeps untracked ones"); + assert.deepEqual(record.runSearch(dir, { glob: "build/*.js", match: "never", text: "localStorage" }, ["build/gen.js"]).hits, [{ file: "build/gen.js", line: 1 }], "a list handed in is searched as given"); + for (let i = 0; i < 30; i++) write(dir, `src/many/m${i}.js`, "localStorage\n"); + assert.equal(record.runSearch(dir, { glob: "src/many/*.js", match: "never", text: "localStorage" }).hits.length, 20, "at most 20 hits"); +}); + +test("lessons check-input: a lesson with a search carries its searchResult", () => { + const { dir, store } = checkRepo(); + write(dir, "src/c.js", "localStorage.getItem('x');\n"); + putLesson(dir, store, "w01", daysBefore(5), { search: { glob: "src/**/*.js", match: "never", text: "localStorage" } }); + putLesson(dir, store, "w02", daysBefore(4)); + const [a, b] = L(dir, ["check-input"], store).json.lessons; + assert.deepEqual(a.searchResult, { matched: true, hits: [{ file: "src/c.js", line: 1 }], filesSearched: 2 }); + assert.equal(b.searchResult, undefined); +}); + +test("lessons check-record: a good record stores check on each item and removes the check file", () => { + const { dir, store } = checkRepo(); + putLesson(dir, store, "w01", daysBefore(5)); + putLesson(dir, store, "w02", daysBefore(4)); + const input = L(dir, ["check-input"], store).json; + const file = recordFile({ + checkId: input.checkId, + how: "helper", + verdicts: [ + { id: "w01", tests: passAll({ clear: { verdict: "Doubt", reason: "It could name the file." } }), suggestion: "Use the flat keys for saved numbers" }, + { id: "w02", tests: passAll() }, + ], + }); + const r = L(dir, ["check-record", "--file", file], store); + assert.equal(r.code, 0, r.stdout + r.stderr); + assert.equal(r.json.recorded, 2); + const one = storedItem(dir, store, "w01").check; + assert.equal(one.how, "helper"); + assert.equal(one.suggestion, "Use the flat keys for saved numbers"); + assert.equal(one.tests.clear.verdict, "Doubt"); + assert.deepEqual(one.files, { "src/a.js": sha("export const a = 1;\n") }); + assert.ok(Number.isFinite(Date.parse(one.checked)) && Number.isInteger(one.seconds)); + assert.equal(storedItem(dir, store, "w02").check.suggestion, undefined); + assert.deepEqual(checkFilesIn(dir, store), [], "the check file is gone"); + assert.equal(L(dir, ["check-record", "--file", file], store).code, 4, "a check records once"); +}); + +test("lessons check-record: each malformed verdict exits 4 naming the fault and stores nothing", () => { + const { dir, store } = checkRepo(); + putLesson(dir, store, "w01", daysBefore(5)); + const { checkId } = L(dir, ["check-input"], store).json; + const bad = (body, pattern) => { + const r = L(dir, ["check-record", "--file", recordFile({ checkId, how: "helper", verdicts: [{ id: "w01", tests: passAll() }], ...body })], store); + assert.equal(r.code, 4, r.stdout); + assert.match(r.json.problems.map((p) => p.message).join(" "), pattern); + assert.equal(storedItem(dir, store, "w01").check, undefined, "nothing stored"); + }; + bad({ checkId: "zzz-0000" }, /checkId/); + bad({ checkId: "../x" }, /checkId/); + bad({ how: "robot" }, /how must be helper or same-agent/); + bad({ verdicts: [{ id: "nope", tests: passAll() }] }, /not in this check's lessons/); + bad({ verdicts: [{ id: "w01", tests: { true: { verdict: "Pass", reason: "Ok." } } }] }, /w01\.worth is missing/); + bad({ verdicts: [{ id: "w01", tests: passAll({ worth: { verdict: "Maybe", reason: "Ok." } }) }] }, /worth\.verdict must be Pass, Doubt or Fail/); + bad({ verdicts: [{ id: "w01", tests: passAll({ worth: { verdict: "Pass", reason: "" } }) }] }, /worth\.reason is empty/); + bad({ verdicts: [{ id: "w01", tests: passAll({ worth: { verdict: "Pass", reason: "It holds. It also helps." } }) }] }, /one sentence/); + bad({ verdicts: [{ id: "w01", tests: passAll({ worth: { verdict: "Pass", reason: "x".repeat(201) } }) }] }, /at most 200/); + bad({ verdicts: [{ id: "w01", tests: passAll() }, { id: "w01", tests: passAll() }] }, /more than one verdict/); + bad({ verdicts: [{ id: "w01", tests: passAll({ worth: { verdict: "Pass", reason: 7 } }) }] }, /worth\.reason must be one sentence of text/); + const secretReason = "Uses " + "ghp_" + "a1B2".repeat(8) + " in the file."; + const leaked = L(dir, ["check-record", "--file", recordFile({ checkId, how: "helper", verdicts: [{ id: "w01", tests: passAll({ worth: { verdict: "Pass", reason: secretReason } }) }] })], store); + assert.equal(leaked.code, 4); + assert.match(leaked.json.problems[0].message, /secret-shaped/); + assert.doesNotMatch(leaked.stdout + leaked.stderr, /ghp_/, "the secret is never echoed"); + assert.equal(L(dir, ["check-record", "--file", path.join(tmp("lessons-check"), "missing.json")], store).code, 3); +}); + +test("lessons check-record: a secret-shaped or invalid suggestion is dropped with a warning, the record still lands", () => { + const { dir, store } = checkRepo(); + putLesson(dir, store, "w01", daysBefore(5)); + putLesson(dir, store, "w02", daysBefore(4)); + const { checkId } = L(dir, ["check-input"], store).json; + const secret = "Use the token " + "ghp_" + "a1B2".repeat(8); + const r = L(dir, ["check-record", "--file", recordFile({ checkId, how: "same-agent", verdicts: [{ id: "w01", tests: passAll(), suggestion: secret }, { id: "w02", tests: passAll(), suggestion: "Two sentences. Not allowed." }] })], store); + assert.equal(r.code, 0, r.stdout); + assert.equal(r.json.recorded, 2); + assert.equal(r.json.problems.length, 2); + assert.doesNotMatch(r.stdout + r.stderr, /ghp_/, "the secret is never echoed"); + assert.equal(storedItem(dir, store, "w01").check.suggestion, undefined); + assert.equal(storedItem(dir, store, "w02").check.suggestion, undefined); + assert.equal(storedItem(dir, store, "w01").check.how, "same-agent"); +}); + +// Four waiting lessons, three of them checked the way End does (w04 left out). +function checkedList() { + const { dir, store } = checkRepo(); + putLesson(dir, store, "w01", daysBefore(5), { text: "Fails a test" }); + putLesson(dir, store, "w02", daysBefore(4), { text: "Passes all" }); + putLesson(dir, store, "w03", daysBefore(3), { text: "Doubts only" }); + putLesson(dir, store, "w04", daysBefore(2), { text: "Never checked" }); + const input = L(dir, ["check-input"], store).json; + const file = recordFile({ + checkId: input.checkId, + how: "helper", + verdicts: [ + { id: "w01", tests: passAll({ true: { verdict: "Fail", reason: "The file does not say so." } }), suggestion: "Say what the file says" }, + { id: "w02", tests: passAll() }, + { id: "w03", tests: passAll({ clear: { verdict: "Doubt", reason: "It could be sharper." } }) }, + ], + }); + const r = L(dir, ["check-record", "--file", file], store); + assert.equal(r.code, 0, r.stdout); + return { dir, store, input }; +} + +test("lessons list: fresh verdicts become row fields and outlines, a Fail suggests Drop, all Pass Keep, Doubts nothing", () => { + const { dir, store } = checkedList(); + const r = L(dir, ["list", "--check", `${(Date.now() - 3_600_000).toString(36)}-abcd`], store).json; + const row = (id) => r.card.rows.find((x) => x.id === id); + assert.deepEqual(row("w01").check.fails, [{ test: "True against the code", reason: "The file does not say so." }]); + assert.equal(row("w01").check.suggestion, "Say what the file says"); + assert.deepEqual(row("w03").check.doubts, [{ test: "Clear enough", reason: "It could be sharper." }]); + assert.equal(row("w02").check.passed, 4); + assert.deepEqual(r.card.suggested, { w01: "Drop", w02: "Keep" }); + assert.equal(row("w01").tag, undefined); + assert.equal(row("w04").tag, "Not checked yet"); + assert.equal(row("w04").check, undefined); + assert.deepEqual(Object.keys(r.card.checked), ["how", "count", "seconds"]); + assert.equal(r.card.checked.count, 3); + assert.equal(r.card.checked.how, "helper"); + const items = r.rounds.find((x) => x.type === "lesson").items; + assert.equal(items.find((i) => i.id === "w01").check.fails.length, 1, "terminal rounds carry the same fields"); + assert.equal(items.find((i) => i.id === "w04").tag, "Not checked yet"); +}); + +test("lessons list: --check tags an older verdict, --check-failed says the check could not run", () => { + const { dir, store } = checkedList(); + const later = `${(Date.now() + 3_600_000).toString(36)}-abcd`; + const r = L(dir, ["list", "--check", later, "--check-failed", "The helper timed out"], store).json; + assert.equal(r.card.rows.find((x) => x.id === "w02").tag, "Checked in an earlier run"); + assert.deepEqual(r.card.checked, { failed: "The helper timed out" }); + const earlier = L(dir, ["list", "--check", `${(Date.now() - 3_600_000).toString(36)}-abcd`], store).json; + assert.equal(earlier.card.rows.find((x) => x.id === "w02").tag, undefined, "a verdict newer than the run's check has no tag"); +}); + +test("lessons list: editing a named file drops the verdict and tags the row Not checked yet", () => { + const { dir, store } = checkedList(); + write(dir, "src/a.js", "export const a = 99;\n"); + const r = L(dir, ["list"], store).json; + for (const id of ["w01", "w02", "w03"]) { + const row = r.card.rows.find((x) => x.id === id); + assert.equal(row.check, undefined); + assert.equal(row.tag, "Not checked yet"); + } + assert.equal(r.card.suggested, undefined); + assert.equal(r.card.checked, undefined); +}); + +test("lessons decide: Keep over a Fail writes kept over the check, Keep over a pass does not", () => { + const { dir, store } = checkedList(); + const r = decide(dir, store, [{ id: "w01", choice: "Keep" }, { id: "w02", choice: "Keep" }]); + assert.equal(r.code, 0, r.stdout); + const text = fs.readdirSync(path.join(dir, ".plan2code", "lessons")).map((f) => read(dir, `.plan2code/lessons/${f}`)).join("\n"); + const noted = text.split("\n").filter((l) => l.startsWith("- Noted:")); + assert.equal(noted.length, 2); + assert.equal(noted.filter((l) => /kept over the check/.test(l)).length, 1); + assert.match(text, /### Fails a test\n(?:- [^\n]*\n)*- Noted: [^\n]*, kept over the check/); + assert.doesNotMatch(text, /### Passes all\n(?:- [^\n]*\n)*- Noted: [^\n]*kept over the check/); +}); + +test("lessons list and decide: a stored check of the wrong shape counts as not checked and never crashes", () => { + const { dir, store } = checkRepo(); + const hash = sha("export const a = 1;\n"); + const stamp = () => new Date().toISOString(); + putLesson(dir, store, "w01", daysBefore(5), { text: "No tests object", check: { files: { "src/a.js": hash }, how: "helper", checked: stamp(), seconds: 1 } }); + putLesson(dir, store, "w02", daysBefore(4), { text: "A null test", check: { tests: { ...passAll(), worth: null }, files: { "src/a.js": hash }, how: "helper", checked: stamp(), seconds: 1 } }); + putLesson(dir, store, "w03", daysBefore(3), { text: "A path that climbs out", check: { tests: passAll(), files: { "../x": hash }, how: "helper", checked: stamp(), seconds: 1 } }); + const r = L(dir, ["list"], store); + assert.equal(r.code, 0, r.stderr); + for (const row of r.json.card.rows) { + assert.equal(row.tag, "Not checked yet", row.id); + assert.equal(row.check, undefined); + } + assert.deepEqual(L(dir, ["check-input"], store).json.lessons.map((l) => l.id), ["w01", "w02", "w03"], "each is due a check again"); + const d = decide(dir, store, [{ id: "w01", choice: "Keep" }, { id: "w02", choice: "Keep" }]); + assert.equal(d.code, 0, d.stderr); + assert.doesNotMatch(read(dir, ".plan2code/lessons/general.md"), /kept over the check/); +}); + +test("lessons decide: Reword over a Fail also writes kept over the check", () => { + const { dir, store } = checkedList(); + const r = decide(dir, store, [{ id: "w01", choice: "Reword", text: "Say what the file says", why: "The file does." }]); + assert.equal(r.code, 0, r.stdout); + assert.equal(r.json.results[0].outcome, "reworded"); + const text = fs.readdirSync(path.join(dir, ".plan2code", "lessons")).map((f) => read(dir, `.plan2code/lessons/${f}`)).join("\n"); + assert.match(text, /### Say what the file says\n(?:- [^\n]*\n)*- Noted: [^\n]*, kept over the check/); +}); + +test("lessons check brief: the dashboard and the seven noting skills ship lesson-check.md, no read-only skill does", () => { + const shipsBrief = (skill) => fs.existsSync(path.join(SKILLS, skill, "references", "lesson-check.md")); + for (const skill of ["plan2code", "plan2code-3-implement", "plan2code-3-implement-review", "plan2code-quick-task", "plan2code-diagnose", "plan2code-xray", "plan2code-review", "plan2code-test"]) { + assert.ok(shipsBrief(skill), `${skill} ships references/lesson-check.md`); + } + const noting = new Set(["plan2code", "plan2code-3-implement", "plan2code-3-implement-review", "plan2code-quick-task", "plan2code-diagnose", "plan2code-xray", "plan2code-review", "plan2code-test"]); + for (const skill of fs.readdirSync(SKILLS)) { + if (!noting.has(skill) && fs.statSync(path.join(SKILLS, skill)).isDirectory()) assert.ok(!shipsBrief(skill), `${skill} does not ship lesson-check.md`); + } +}); + +/* ------------------------------------------- read raises doubts for marked lessons */ + +const SEARCH_AREA = (search, why = "A reason.") => `# Web\nPaths: src/**\n\n### Keep the handler small\n- Kind: convention\n- About: src/app.js\n${why ? `- Why: ${why}\n` : ""}${search ? `- Shows in: ${search}\n` : ""}- Noted: 2026-11-01, Implement\n`; +// Learning on; the lesson committed with src/app.js, then (when `edit` is set) an edit to that file in a later commit, which marks it. +const doubtRepo = (name, area, edit) => + copyFixture(name, name, (dir) => { + const g = gitInit(dir); + write(dir, ".plan2code/settings.json", JSON.stringify({ format: 1, learning: "on" })); + write(dir, "README.md", "# Fixture\n"); + write(dir, "src/app.js", "export const app = 1;\n"); + write(dir, WEB_FILE, area); + commitAll(g, "lesson"); + if (edit) { + write(dir, "src/app.js", edit); + commitAll(g, "edit"); + } + }); +const waitingDoubts = (store) => + waitingFiles(store) + .map((f) => JSON.parse(fs.readFileSync(path.join(store, f), "utf8"))) + .filter((w) => w.type === "doubt"); + +test("lessons read: a marked lesson whose never-matches search now hits raises one waiting doubt, and a second read raises none", () => { + const dir = doubtRepo("doubt-never", SEARCH_AREA("src/** | never matches | forbidden("), "export const app = forbidden(1);\n"); + const store = learningDir(); + const first = L(dir, ["read", "--paths", "src/app.js"], store); + assert.equal(first.code, 0, first.stderr); + assert.match(first.json.line, /Raised 1 doubt: its search no longer matches\.$/); + assert.equal(first.json.raised.length, 1); + const doubts = waitingDoubts(store); + assert.equal(doubts.length, 1); + assert.equal(doubts[0].target, LESSON_ID); + assert.match(doubts[0].found, /^Its search no longer matches: 1 line now holds the text, the first in src\/app\.js at line 1\.$/); + const second = L(dir, ["read", "--paths", "src/app.js"], store); + assert.equal(second.json.raised, undefined); + assert.doesNotMatch(second.json.line, /Raised/); + assert.equal(waitingDoubts(store).length, 1); +}); + +test("lessons read: a marked should-match search with no hit raises a doubt", () => { + const dir = doubtRepo("doubt-should", SEARCH_AREA("src/** | should match | handler"), "export const app = 2;\n"); + const store = learningDir(); + const r = L(dir, ["read", "--paths", "src/app.js"], store); + assert.match(r.json.line, /Raised 1 doubt: its search no longer matches\./); + assert.match(waitingDoubts(store)[0].found, /^Its search no longer matches: nothing in the searched files holds the text now\.$/); +}); + +test("lessons read: an unmarked lesson's search never runs, even when it would contradict the lesson", () => { + const dir = doubtRepo("doubt-unmarked", SEARCH_AREA("src/** | never matches | export const"), null); + const store = learningDir(); + const r = L(dir, ["read", "--paths", "src/app.js"], store); + assert.equal(r.code, 0, r.stderr); + assert.equal(r.json.areas[0].lessons[0].marked, false); + assert.equal(r.json.raised, undefined); + assert.deepEqual(waitingFiles(store), []); +}); + +test("lessons read: a marked lesson whose search still agrees raises nothing", () => { + const dir = doubtRepo("doubt-agrees", SEARCH_AREA("src/** | never matches | forbidden("), "export const app = 2;\n"); + const store = learningDir(); + const r = L(dir, ["read", "--paths", "src/app.js"], store); + assert.equal(r.json.areas[0].lessons[0].marked, true); + assert.equal(r.json.raised, undefined); + assert.deepEqual(waitingFiles(store), []); +}); + +test("lessons read: a marked convention with no Why raises a Needs a Why doubt once, and Reword carries the Why", () => { + const dir = doubtRepo("doubt-why", SEARCH_AREA(null, ""), "export const app = 2;\n"); + const store = learningDir(); + const r = L(dir, ["read", "--paths", "src/app.js"], store); + assert.match(r.json.line, /Raised 1 doubt: a convention needs its Why\.$/); + const doubts = waitingDoubts(store); + assert.equal(doubts.length, 1); + assert.match(doubts[0].found, /^Needs a Why/); + assert.equal(L(dir, ["read", "--paths", "src/app.js"], store).json.raised, undefined); + const listed = L(dir, ["list"], store).json.items.find((i) => i.type === "doubt"); + assert.deepEqual(listed.choices, ["Keep", "Reword", "Retire"]); + const done = decide(dir, store, [{ id: listed.id, choice: "Reword", text: "Keep the handler small", why: "Small handlers are easy to test." }]); + assert.equal(done.code, 0, done.stdout); + assert.equal(done.json.results[0].outcome, "reworded"); + assert.match(read(dir, WEB_FILE), /- Why: Small handlers are easy to test\./); +}); + +test("lessons read: one doubt per lesson, so a search doubt means no Needs a Why doubt beside it", () => { + const dir = doubtRepo("doubt-one", SEARCH_AREA("src/** | never matches | forbidden(", ""), "export const app = forbidden(1);\n"); + const store = learningDir(); + const r = L(dir, ["read", "--paths", "src/app.js"], store); + assert.equal(r.json.raised.length, 1); + assert.equal(waitingDoubts(store).length, 1); + assert.match(waitingDoubts(store)[0].found, /^Its search/); +}); + +/* ---------------------------------------------- teach it now: said lessons from read-only skills */ + +test("lessons note: from a read-only skill, said is written waiting and inferred exits 5 end to end", () => { + const dir = repo(); + const store = learningDir(); + settings(dir, { format: 1, learning: "on" }); + const said = L(dir, ["note", "--type", "lesson", "--text", "Never edit the generated skills folder by hand", "--kind", "correction", "--about", "skills/", "--source", "said", "--why", "Builds overwrite it.", "--skill", "pathfinder"], store); + assert.equal(said.code, 0, said.stdout); + assert.match(said.json.line, /^Noted for the end of the run: Never edit the generated skills folder by hand$/); + assert.equal(waitingFiles(store).length, 1); + const inferred = L(dir, ["note", "--type", "lesson", "--text", "Another fact", "--kind", "how-it-works", "--about", "src/a.js", "--source", "inferred", "--seen", "src/a.js", "--skill", "pathfinder"], store); + assert.equal(inferred.code, 5, inferred.stdout); + assert.equal(inferred.json.error, "inferred-from-read-only"); + assert.equal(waitingFiles(store).length, 1, "the refused lesson wrote nothing"); +}); + +test("lessons note: the same words noted again with a Why replace the waiting item, not add a second", () => { + const dir = repo(); + const store = learningDir(); + settings(dir, { format: 1, learning: "on" }); + const args = (extra) => ["note", "--type", "lesson", "--text", "Run the lint step before the build", "--kind", "convention", "--about", "package.json", "--source", "said", "--skill", "plan", ...extra]; + // A convention needs its Why at note time, so the first note is a command lesson with the same words. + const first = L(dir, ["note", "--type", "lesson", "--text", "Run the lint step before the build", "--kind", "command", "--about", "package.json", "--source", "said", "--skill", "plan"], store); + assert.equal(first.code, 0, first.stdout); + const again = L(dir, args(["--why", "The build hides lint errors."]), store); + assert.equal(again.code, 0, again.stdout); + assert.equal(again.json.id, first.json.id); + const files = waitingFiles(store); + assert.equal(files.length, 1); + const item = JSON.parse(fs.readFileSync(path.join(store, files[0]), "utf8")); + assert.equal(item.why, "The build hides lint errors."); + assert.equal(item.kind, "convention"); +}); + +test("lessons read: a hit in a very long path still raises a doubt, naming the line without the path", () => { + const long = "src/" + "deep-folder-name/".repeat(8) + "file.js"; + const dir = copyFixture("doubt-long", "doubt-long", (d) => { + const g = gitInit(d); + write(d, ".plan2code/settings.json", JSON.stringify({ format: 1, learning: "on" })); + write(d, "src/app.js", "export const app = 1;\n"); + write(d, long, "ok\n"); + write(d, WEB_FILE, SEARCH_AREA("src/** | never matches | forbidden(")); + commitAll(g, "lesson"); + write(d, long, "forbidden(1)\n"); + commitAll(g, "edit"); + write(d, "src/app.js", "export const app = 2;\n"); + commitAll(g, "edit app"); + }); + const store = learningDir(); + const r = L(dir, ["read", "--paths", "src/app.js"], store); + assert.equal(r.json.raised.length, 1, r.stdout); + const found = waitingDoubts(store)[0].found; + assert.ok(found.length <= 200); + assert.match(found, /^Its search no longer matches: 1 line now holds the text, the first at line 1 of a searched file.$/); +}); + +test("lessons note: the same words from another skill do not replace a waiting item", () => { + const dir = repo(); + const store = learningDir(); + settings(dir, { format: 1, learning: "on" }); + const text = "Run the lint step before the build"; + const base = ["note", "--type", "lesson", "--text", text, "--kind", "command", "--about", "package.json", "--source", "said"]; + const first = L(dir, [...base, "--skill", "plan"], store); + const other = L(dir, [...base, "--skill", "document", "--why", "Different skill."], store); + assert.notEqual(other.json.id, first.json.id); + assert.equal(waitingFiles(store).length, 2); +}); + +/* ---------------------------------------------------------------- follow */ + +const followsFile = (dir, store) => path.join(store, core.repositoryKey(dir), "follows.ndjson"); + +test("lessons follow: appends one line per call, on this machine only", () => { + const dir = doubtRepo("follow-lines", SEARCH_AREA("", "A reason.")); + const store = learningDir(); + const a = L(dir, ["follow", "--lesson", LESSON_ID, "--skill", "implement"], store); + assert.equal(a.code, 0, a.stderr); + assert.equal(a.json.noted, true); + const b = L(dir, ["follow", "--lesson", LESSON_ID, "--skill", "quick-task"], store); + assert.equal(b.code, 0, b.stderr); + const lines = fs.readFileSync(followsFile(dir, store), "utf8").split("\n").filter(Boolean).map((x) => JSON.parse(x)); + assert.equal(lines.length, 2); + assert.deepEqual(lines.map((l) => l.skill), ["implement", "quick-task"]); + assert.equal(lines[0].lesson, LESSON_ID); + assert.equal(lines[0].at, nowDate().toISOString()); + assert.equal(fs.existsSync(path.join(dir, "follows.ndjson")), false); + assert.equal(String(gitIn(dir)("status", "--porcelain")).includes("follows"), false, "nothing written into the project"); +}); + +test("lessons follow: an unknown lesson id exits 4 and writes nothing", () => { + const dir = doubtRepo("follow-unknown", SEARCH_AREA("", "A reason.")); + const store = learningDir(); + const r = L(dir, ["follow", "--lesson", "web/no-such-lesson", "--skill", "implement"], store); + assert.equal(r.code, 4); + assert.equal(fs.existsSync(followsFile(dir, store)), false); +}); + +test("lessons follow: with Learning off or paused nothing is written and it exits 0", () => { + const dir = doubtRepo("follow-off", SEARCH_AREA("", "A reason.")); + const store = learningDir(); + settings(dir, { format: 1, learning: "off" }); + const off = L(dir, ["follow", "--lesson", LESSON_ID, "--skill", "implement"], store); + assert.equal(off.code, 0, off.stderr); + assert.equal(off.json.noted, false); + settings(dir, { format: 1, learning: "on" }); + assert.equal(L(dir, ["pause", "on"], store).code, 0); + const paused = L(dir, ["follow", "--lesson", LESSON_ID, "--skill", "implement"], store); + assert.equal(paused.json.noted, false); + assert.equal(fs.existsSync(followsFile(dir, store)), false); +}); + +/* ------------------------------------------------------------------ tidy */ + +const GEN_US = "general/answer-in-us-english"; +const GEN_SUITES = "general/run-the-targeted-suites"; +const WEB_PAGE = "web/draw-the-page-from-state"; +const SRC_SMALL = "source/keep-modules-small"; +const SRC_KEBAB = "source/name-files-in-kebab-case"; + +const tidyNote = (dir, store, change, targets, extra = [], reason = "They say the same thing twice.") => L(dir, ["note", "--type", "tidy", "--change", change, "--targets", targets.join(","), "--reason", reason, "--skill", "dashboard", ...extra], store); +const waitingTidy = (store) => + waitingFiles(store) + .map((f) => JSON.parse(fs.readFileSync(path.join(store, f), "utf8"))) + .filter((w) => w.type === "tidy"); +const lessonFiles = (dir) => Object.fromEntries(fs.readdirSync(path.join(dir, ".plan2code", "lessons")).map((n) => [n, fs.readFileSync(path.join(dir, ".plan2code", "lessons", n), "utf8")])); +const headings = (text) => text.split(/\r?\n/).filter((l) => l.startsWith("### ")).map((l) => l.slice(4)); + +test("lessons tidy-input: every saved lesson with its follow count, last follow and mark, plus how full the areas are", () => { + const dir = readRepo(); + const store = learningDir(); + assert.equal(L(dir, ["follow", "--lesson", GEN_US, "--skill", "implement"], store).code, 0); + assert.equal(L(dir, ["follow", "--lesson", GEN_US, "--skill", "plan"], store).code, 0); + // A commit touching what a lesson is About marks it. + write(dir, "src/web/page.js", "changed\n"); + commitAll(gitIn(dir), "edit page"); + const r = L(dir, ["tidy-input"], store); + assert.equal(r.code, 0, r.stderr); + assert.equal(r.json.lessons.length, 5); + const by = Object.fromEntries(r.json.lessons.map((l) => [l.id, l])); + assert.equal(by[GEN_US].followed, 2); + assert.equal(by[GEN_US].lastFollowed, nowDate().toISOString()); + assert.equal(by[GEN_US].area, "General"); + assert.equal(by[SRC_SMALL].followed, 0); + assert.equal(by[SRC_SMALL].lastFollowed, null); + assert.equal(by[WEB_PAGE].marked, true); + assert.equal(by[SRC_SMALL].marked, false); + assert.equal(by[GEN_SUITES].why, "The full run is slow."); + assert.deepEqual(Object.keys(by[GEN_US]).sort(), ["about", "area", "followed", "gone", "id", "keptOverCheck", "kind", "lastFollowed", "marked", "noted", "search", "text", "why"]); + assert.deepEqual(r.json.general, { count: 2, max: 25 }); + assert.deepEqual(r.json.areas.map((a) => [a.slug, a.count]), [["source", 2], ["web", 1]]); + assert.equal(String(gitIn(dir)("status", "--porcelain")).includes("follows"), false, "reads only"); +}); + +test("lessons note --type tidy: each change kind validates its targets, wording, area and reason", () => { + const dir = readRepo(); + const store = learningDir(); + const bad = (r, field) => { + assert.equal(r.code, 4, r.stdout); + assert.equal(r.json.error, "invalid-tidy"); + assert.ok(r.json.problems.some((p) => p.field === field), `${field} in ${JSON.stringify(r.json.problems)}`); + }; + // merge: two or more targets, a wording that passes the lesson rules (a convention needs its why) + bad(tidyNote(dir, store, "merge", [SRC_SMALL], ["--text", "Keep modules small."]), "targets"); + bad(tidyNote(dir, store, "merge", [SRC_SMALL, SRC_KEBAB], ["--text", "Keep modules small and name files in kebab case."]), "why"); + bad(tidyNote(dir, store, "merge", [SRC_SMALL, SRC_KEBAB], ["--text", "Keep modules small and name files in kebab case.", "--why", "Both keep the tree easy to scan."]), "about"); + bad(tidyNote(dir, store, "merge", [SRC_SMALL, SRC_KEBAB], ["--why", "Both keep the tree easy to scan.", "--about", "src/"]), "text"); + bad(tidyNote(dir, store, "merge", [SRC_SMALL, SRC_SMALL], ["--text", "Keep modules small.", "--why", "It reads better."]), "targets"); + bad(tidyNote(dir, store, "merge", [SRC_SMALL, "source/no-such-lesson"], ["--text", "Keep modules small.", "--why", "It reads better."]), "targets"); + assert.equal(waitingTidy(store).length, 0, "nothing invalid was written"); + const merged = tidyNote(dir, store, "merge", [SRC_SMALL, SRC_KEBAB], ["--text", "Keep modules small and name files in kebab case.", "--why", "Both keep the tree easy to scan.", "--about", "src/"]); + assert.equal(merged.code, 0, merged.stdout); + assert.equal(merged.json.noted, true); + const w = waitingTidy(store)[0]; + assert.deepEqual([w.change, w.targets, w.kind, w.skill], ["merge", [SRC_SMALL, SRC_KEBAB], "convention", "dashboard"]); + assert.deepEqual(w.about, ["src/"]); + assert.equal(w.reason, "They say the same thing twice."); + // reword: one target, a new wording; why and kind default from it + bad(tidyNote(dir, store, "reword", [SRC_SMALL, SRC_KEBAB], ["--text", "Keep modules small."]), "targets"); + bad(tidyNote(dir, store, "reword", [GEN_SUITES], []), "text"); + assert.equal(tidyNote(dir, store, "reword", [GEN_SUITES], ["--text", "Run the targeted suites, not the whole run."]).code, 0); + assert.equal(waitingTidy(store).find((x) => x.change === "reword").why, "The full run is slow."); + // retire needs its reason + bad(L(dir, ["note", "--type", "tidy", "--change", "retire", "--targets", WEB_PAGE, "--skill", "dashboard"], store), "reason"); + assert.equal(tidyNote(dir, store, "retire", [WEB_PAGE], [], "Git marks it and the page no longer draws from state.").code, 0); + // move names an area that exists and is not where the lesson already is + bad(tidyNote(dir, store, "move", [GEN_SUITES], []), "area"); + bad(tidyNote(dir, store, "move", [GEN_SUITES], ["--area", "Nowhere"]), "area"); + bad(tidyNote(dir, store, "move", [GEN_SUITES], ["--area", "General"]), "area"); + assert.equal(tidyNote(dir, store, "move", [GEN_SUITES], ["--area", "Web"]).code, 0); + bad(tidyNote(dir, store, "sideways", [GEN_SUITES], []), "change"); + assert.equal(waitingTidy(store).length, 4); +}); + +test("lessons note --type tidy: a secret in the wording or reason exits 5 and writes nothing, and the same change twice is one proposal", () => { + const dir = readRepo(); + const store = learningDir(); + const key = "AKIA" + "ABCDEFGHIJKLMNOP"; + const inReason = tidyNote(dir, store, "retire", [WEB_PAGE], [], `The key ${key} is in it.`); + assert.equal(inReason.code, 5, inReason.stdout); + assert.equal(inReason.json.error, "secret"); + const inText = tidyNote(dir, store, "reword", [GEN_SUITES], ["--text", `Use ${key} for the suites.`]); + assert.equal(inText.code, 5, inText.stdout); + assert.equal(waitingTidy(store).length, 0); + const first = tidyNote(dir, store, "retire", [WEB_PAGE], [], "Not followed in 90 days."); + const again = tidyNote(dir, store, "retire", [WEB_PAGE], [], "A different sentence about it."); + assert.equal(again.json.already, true); + assert.equal(again.json.id, first.json.id); + assert.equal(waitingTidy(store).length, 1); +}); + +test("lessons check-input --tidy: tidy-ups join the lessons under the cap of 10, and only with the flag", () => { + const dir = readRepo(); + const store = learningDir(); + // Newer than the tidy-ups, which are noted at the pinned clock, so the tidy-ups come first. + for (let i = 0; i < 8; i++) putLesson(dir, store, `w${String(i).padStart(2, "0")}`, new Date(nowDate().getTime() + (i + 1) * 1000)); + assert.equal(tidyNote(dir, store, "merge", [SRC_SMALL, SRC_KEBAB], ["--text", "Keep modules small and name files in kebab case.", "--why", "Both keep the tree easy to scan.", "--about", "src/"]).code, 0); + assert.equal(tidyNote(dir, store, "retire", [WEB_PAGE], [], "Git marks it.").code, 0); + assert.equal(tidyNote(dir, store, "move", [GEN_SUITES], ["--area", "Web"]).code, 0); + const plain = L(dir, ["check-input"], store).json; + assert.equal(plain.lessons.length, 8, "without --tidy only the lessons"); + const r = L(dir, ["check-input", "--tidy"], store); + assert.equal(r.code, 0, r.stderr); + assert.equal(r.json.lessons.length, 10); + assert.equal(r.json.notChecked.length, 1, "the 11th is left for the next run"); + const tidy = r.json.lessons.filter((l) => l.type === "tidy"); + assert.equal(tidy.length, 3, "oldest first: the three tidy-ups, then the lessons"); + const merge = tidy.find((l) => l.change === "merge"); + assert.equal(merge.text, "Keep modules small and name files in kebab case."); + assert.deepEqual(merge.targets.map((t) => t.id), [SRC_SMALL, SRC_KEBAB]); + assert.equal(merge.reason, "They say the same thing twice."); + assert.ok(merge.files.length > 0, "its files are listed with hashes"); + assert.ok(!r.json.context.saved.some((s) => s.id === SRC_SMALL || s.id === SRC_KEBAB), "a merge's own targets are not overlaps of it"); + assert.ok(r.json.context.saved.some((s) => s.id === GEN_US)); +}); + +test("lessons check-record: a tidy-up's verdicts are stored on it and show on its row", () => { + const dir = readRepo(); + const store = learningDir(); + const noted = tidyNote(dir, store, "retire", [WEB_PAGE], [], "Git marks it."); + const input = L(dir, ["check-input", "--tidy"], store).json; + const rec = L(dir, ["check-record", "--file", recordFile({ checkId: input.checkId, how: "same-agent", verdicts: [{ id: noted.json.id, tests: passAll() }] })], store); + assert.equal(rec.code, 0, rec.stdout); + assert.equal(rec.json.recorded, 1); + const row = L(dir, ["list", "--check", input.checkId], store).json.items.find((i) => i.id === noted.json.id); + assert.equal(row.type, "tidy"); + assert.equal(row.check.passed, 4); + assert.equal(L(dir, ["check-input", "--tidy"], store).json.lessons.length, 0, "a fresh check is not run again"); +}); + +test("lessons list: a tidy row says the change in words, offers Reword only where there is a wording, and carries its reason", () => { + const dir = readRepo(); + const store = learningDir(); + tidyNote(dir, store, "merge", [SRC_SMALL, SRC_KEBAB], ["--text", "Keep modules small and name files in kebab case.", "--why", "Both keep the tree easy to scan.", "--about", "src/"]); + tidyNote(dir, store, "retire", [WEB_PAGE], [], "Git marks it."); + tidyNote(dir, store, "move", [GEN_SUITES], ["--area", "Web"]); + tidyNote(dir, store, "reword", [GEN_US], ["--text", "Answer in US English everywhere.", "--why", "US spelling is the project's."]); + const list = L(dir, ["list"], store).json; + const row = (change) => list.items.find((i) => i.type === "tidy" && i.change === change); + assert.equal(row("merge").text, "Merge 2 lessons into: Keep modules small and name files in kebab case."); + assert.deepEqual(row("merge").choices, ["Apply", "Reword", "Leave"]); + assert.equal(row("merge").why, "They say the same thing twice."); + assert.equal(row("merge").wording, "Keep modules small and name files in kebab case."); + assert.equal(row("retire").text, "Retire: Draw the page from state Reason: Git marks it."); + assert.deepEqual(row("retire").choices, ["Apply", "Leave"]); + assert.equal(row("move").text, "Move to Web: Run the targeted suites"); + assert.deepEqual(row("move").choices, ["Apply", "Leave"]); + assert.equal(row("reword").text, "Reword to: Answer in US English everywhere."); + assert.equal(row("reword").area, "General", "a reword stays where it is unless the person picks another area"); + assert.ok(list.rounds.some((r) => r.type === "tidy" && r.items.length === 4)); + const card = list.card.rows.filter((r) => r.type === "tidy"); + assert.equal(card.length, 4); + assert.deepEqual(card.find((r) => r.change === "merge").targets.map((t) => t.id), [SRC_SMALL, SRC_KEBAB]); + // A proposal whose target is gone is not listed. + fs.rmSync(path.join(dir, ".plan2code", "lessons", "web.md")); + assert.ok(!L(dir, ["list"], store).json.items.some((i) => i.change === "retire")); +}); + +test("lessons decide tidy: Apply on a merge writes one block and removes both targets, and stages nothing", () => { + const dir = readRepo(); + const store = learningDir(); + const n = tidyNote(dir, store, "merge", [SRC_SMALL, SRC_KEBAB], ["--text", "Keep modules small and name files in kebab case.", "--why", "Both keep the tree easy to scan.", "--about", "src/"]); + const r = decide(dir, store, [{ id: n.json.id, choice: "Apply" }]); + assert.equal(r.code, 0, r.stdout); + assert.equal(r.json.results[0].outcome, "applied"); + assert.equal(r.json.results[0].change, "merge"); + assert.deepEqual(r.json.written, [".plan2code/lessons/source.md"]); + assert.deepEqual(headings(lessonFiles(dir)["source.md"]), ["Keep modules small and name files in kebab case."]); + assert.match(r.json.closing, /^Tidied 1\. 0 still waiting\.$/); + assert.equal(waitingTidy(store).length, 0); + assert.equal(String(gitIn(dir)("diff", "--cached", "--name-only")).trim(), "", "nothing is staged"); +}); + +test("lessons decide tidy: Reword on a merge writes the person's wording, and Reword on a retire is an invalid choice", () => { + const dir = readRepo(); + const store = learningDir(); + const m = tidyNote(dir, store, "merge", [SRC_SMALL, SRC_KEBAB], ["--text", "Keep modules small and name files in kebab case.", "--why", "Both keep the tree easy to scan.", "--about", "src/"]); + const t = tidyNote(dir, store, "retire", [WEB_PAGE], [], "Git marks it."); + const r = decide(dir, store, [ + { id: m.json.id, choice: "Reword", text: "Keep modules small and kebab-case their files.", why: "The tree stays easy to scan." }, + { id: t.json.id, choice: "Reword", text: "Nope." }, + ]); + assert.equal(r.json.results[0].outcome, "applied"); + assert.equal(r.json.results[1].outcome, "invalid-choice"); + assert.deepEqual(headings(lessonFiles(dir)["source.md"]), ["Keep modules small and kebab-case their files."]); + assert.ok(lessonFiles(dir)["web.md"], "the retire was not applied"); + assert.equal(waitingTidy(store).length, 1, "the invalid choice keeps waiting"); +}); + +test("lessons decide tidy: Apply on a retire removes the block, and the area file with it when it was the last", () => { + const dir = readRepo(); + const store = learningDir(); + const a = tidyNote(dir, store, "retire", [SRC_KEBAB], [], "The folder was renamed."); + const b = tidyNote(dir, store, "retire", [WEB_PAGE], [], "Git marks it."); + const r = decide(dir, store, [{ id: a.json.id, choice: "Apply" }, { id: b.json.id, choice: "Apply" }]); + assert.deepEqual(r.json.results.map((x) => x.outcome), ["applied", "applied"]); + const files = lessonFiles(dir); + assert.deepEqual(headings(files["source.md"]), ["Keep modules small"]); + assert.equal(files["web.md"], undefined, "an emptied area file goes"); + assert.ok(files["general.md"]); + assert.match(r.json.closing, /^Tidied 2\./); +}); + +test("lessons decide tidy: Apply on a move relocates the lesson with its Why and removes it from the old area", () => { + const dir = readRepo(); + const store = learningDir(); + const n = tidyNote(dir, store, "move", [GEN_SUITES], ["--area", "Web"], "It only matters for the page."); + const r = decide(dir, store, [{ id: n.json.id, choice: "Apply" }]); + assert.equal(r.code, 0, r.stdout); + assert.equal(r.json.results[0].outcome, "applied"); + assert.equal(r.json.results[0].change, "move"); + const files = lessonFiles(dir); + assert.ok(!headings(files["general.md"]).includes("Run the targeted suites")); + assert.deepEqual(headings(files["web.md"]), ["Draw the page from state", "Run the targeted suites"]); + assert.match(files["web.md"], /### Run the targeted suites\n- Kind: convention\n- About: scripts\/\n- Why: The full run is slow\.\n- Noted: 2026-11-01, Implement\n/); +}); + +test("lessons decide tidy: Apply on a reword replaces the wording in place", () => { + const dir = readRepo(); + const store = learningDir(); + const n = tidyNote(dir, store, "reword", [GEN_US], ["--text", "Answer in US English everywhere.", "--why", "US spelling is the project's."], "Sharper."); + const r = decide(dir, store, [{ id: n.json.id, choice: "Apply" }]); + assert.equal(r.json.results[0].outcome, "applied"); + assert.deepEqual(headings(lessonFiles(dir)["general.md"]), ["Answer in US English everywhere.", "Run the targeted suites"]); +}); + +test("lessons decide tidy: Leave changes no file and settles the proposal", () => { + const dir = readRepo(); + const store = learningDir(); + const n = tidyNote(dir, store, "merge", [SRC_SMALL, SRC_KEBAB], ["--text", "Keep modules small and name files in kebab case.", "--why", "Both keep the tree easy to scan.", "--about", "src/"]); + const before = lessonFiles(dir); + const r = decide(dir, store, [{ id: n.json.id, choice: "Leave" }]); + assert.equal(r.json.results[0].outcome, "left"); + assert.deepEqual(r.json.written, []); + assert.deepEqual(lessonFiles(dir), before); + assert.equal(waitingTidy(store).length, 0); + assert.match(r.json.closing, /^Left 1 as it was\./); + assert.equal(String(gitIn(dir)("status", "--porcelain")), "", "nothing changed in the project"); +}); + +test("lessons decide tidy: a proposal whose target an earlier decision removed is out of date, and a merge into a full General is undone", () => { + const dir = readRepo(); + const store = learningDir(); + const retire = tidyNote(dir, store, "retire", [SRC_SMALL], [], "Gone from the code."); + const merge = tidyNote(dir, store, "merge", [SRC_SMALL, SRC_KEBAB], ["--text", "Keep modules small and name files in kebab case.", "--why", "Both keep the tree easy to scan.", "--about", "src/"]); + const r = decide(dir, store, [{ id: retire.json.id, choice: "Apply" }, { id: merge.json.id, choice: "Apply" }]); + assert.equal(r.json.results.find((x) => x.id === retire.json.id).outcome, "applied"); + assert.equal(r.json.results.find((x) => x.id === merge.json.id).outcome, "outOfDate"); + assert.deepEqual(headings(lessonFiles(dir)["source.md"]), ["Name files in kebab case"], "the out of date merge changed nothing"); + assert.equal(waitingTidy(store).length, 0, "both are settled"); + + // General is full at 25: a merge into it that does not make room is refused and undone. + const full = readRepo(); + const many = Array.from({ length: 25 }, (_, i) => block(`General lesson number ${String(i).padStart(2, "0")}`, "README.md")).join("\n"); + write(full, ".plan2code/lessons/general.md", "# General\n\n" + many); + const m = tidyNote(full, store, "merge", [SRC_SMALL, SRC_KEBAB], ["--text", "Keep modules small and name files in kebab case.", "--why", "Both keep the tree easy to scan.", "--about", "src/", "--area", "General"]); + assert.equal(m.code, 0, m.stdout); + const before = lessonFiles(full); + const d = decide(full, store, [{ id: m.json.id, choice: "Apply" }]); + assert.equal(d.json.results[0].outcome, "needsRoom"); + assert.deepEqual(lessonFiles(full), before, "a refused merge writes nothing"); + assert.equal(waitingTidy(store).length, 1, "it keeps waiting"); +}); + +test("lessons check-record: a suggested wording is kept on a merge and dropped, with a warning, on a retire or a move", () => { + const dir = readRepo(); + const store = learningDir(); + const merge = tidyNote(dir, store, "merge", [SRC_SMALL, SRC_KEBAB], ["--text", "Keep modules small and name files in kebab case.", "--why", "Both keep the tree easy to scan.", "--about", "src/"]); + const retire = tidyNote(dir, store, "retire", [WEB_PAGE], [], "Git marks it."); + const move = tidyNote(dir, store, "move", [GEN_SUITES], ["--area", "Web"]); + const input = L(dir, ["check-input", "--tidy"], store).json; + const wording = "Keep modules small and kebab-case their files."; + const rec = L(dir, ["check-record", "--file", recordFile({ checkId: input.checkId, how: "same-agent", verdicts: [merge, retire, move].map((n) => ({ id: n.json.id, tests: passAll({ clear: { verdict: "Doubt", reason: "It could be shorter." } }), suggestion: wording })) })], store); + assert.equal(rec.code, 0, rec.stdout); + assert.equal(rec.json.recorded, 3); + assert.deepEqual(rec.json.problems.map((p) => p.id).sort(), [move.json.id, retire.json.id].sort()); + assert.match(rec.json.problems[0].message, /a retire or a move has no wording to change/); + const rows = Object.fromEntries(L(dir, ["list", "--check", input.checkId], store).json.items.filter((i) => i.type === "tidy").map((i) => [i.change, i])); + assert.equal(rows.merge.check.suggestion, wording); + assert.equal(rows.retire.check.suggestion, undefined); + assert.equal(rows.move.check.suggestion, undefined); +}); + +/* ------------------------------------------------- final review fixes */ + +test("lessons record: a search glob over its limits is refused by searchProblems and never parsed from a file", () => { + const busy = "**/".repeat(4) + "*.js"; + assert.equal(record.globTooBusy("src/**/*.js"), null); + assert.equal(record.globTooBusy("**/a/**/b/**/*.js"), null, "three ** is the most"); + assert.match(record.globTooBusy(busy), /has 4 \*\*; at most 3/); + assert.match(record.globTooBusy("a/".repeat(60) + "x.js"), /at most 120/); + assert.ok(record.searchProblems({ glob: busy, match: "never", text: "a" }).some((p) => p.field === "shows-in")); + // A committed line with a hostile glob stays in the file but is never run. + const text = ["# A", "", "### One", "- Kind: command", "- About: a.js", `- Shows in: ${"**/".repeat(22)}z | never matches | x`, "- Noted: 2026-11-01, I", ""].join("\n"); + const area = record.parseAreaFile(text); + assert.equal(area.blocks[0].search, undefined); + assert.equal(area.blocks[0].badLines.length, 1); + assert.equal(record.renderAreaFile(area), text); + // A stored item from before the limits is refused at once, not walked. + const started = Date.now(); + const r = record.runSearch(repo(), { glob: "**/".repeat(22) + "z", match: "never", text: "x" }); + assert.equal(r.refused, true); + assert.ok(Date.now() - started < 2000, "returns at once"); +}); + +test("lessons note: a search glob with more than three ** exits 4", () => { + const dir = repo(); + const store = learningDir(); + settings(dir, { format: 1, learning: "on" }); + const r = L(dir, lesson("Never use localStorage", ["--shows-in", "**/**/**/**/*.js", "--match", "never", "--text-match", "localStorage"]), store); + assert.equal(r.code, 4, r.stdout); + assert.deepEqual(waitingFiles(store), []); +}); + +test("lessons: a said lesson noted with the placeholder Why asks for a Reword on its row, and only a Reword with a reason saves it", () => { + const dir = repo(); + const store = learningDir(); + settings(dir, { format: 1, learning: "on" }); + write(dir, "src/a.js", "x\n"); + const n = L(dir, ["note", "--type", "lesson", "--text", "Keep the header short", "--kind", "convention", "--about", "src/a.js", "--source", "said", "--skill", "Implement", "--why", record.SAID_NO_WHY], store); + assert.equal(n.code, 0, n.stdout); + const row = L(dir, ["list"], store).json.card.rows[0]; + assert.match(row.note, /No reason given yet: use Reword/); + assert.ok(!row.choices.includes("Keep"), "Keep is left off the card, since decide refuses it"); + assert.deepEqual(row.choices, ["Reword", "Drop"]); + const id = row.id; + const kept = decide(dir, store, [{ id, choice: "Keep" }]); + assert.equal(kept.json.results[0].outcome, "invalid"); + assert.equal(kept.json.results[0].problems[0].field, "why"); + assert.equal(waitingFiles(store).length, 1, "still waiting"); + const bare = decide(dir, store, [{ id, choice: "Reword", text: "Keep the header to one line" }]); + assert.equal(bare.json.results[0].outcome, "invalid", "a Reword that keeps the placeholder is refused too"); + const reworded = decide(dir, store, [{ id, choice: "Reword", why: "A long header wraps on phones." }]); + assert.equal(reworded.json.results[0].outcome, "reworded"); + assert.equal(waitingFiles(store).length, 0); +}); + +test("lessons list: a plain list carries no how-checked line, and a --check-failed reason is cut to one line of 200", () => { + const { dir, store, input } = checkedList(); + assert.equal(L(dir, ["list"], store).json.card.checked, undefined, "nothing was checked in this run"); + assert.equal(L(dir, ["list", "--check", input.checkId], store).json.card.checked.count, 3); + const long = "The helper\nstopped " + "x".repeat(300); + const failed = L(dir, ["list", "--check-failed", long], store).json.card.checked.failed; + assert.equal(failed.length, 200); + assert.doesNotMatch(failed, /\n/); +}); + +test("lessons decide tidy: a merge carries the one search its targets hold", () => { + const dir = readRepo(); + const store = learningDir(); + const file = path.join(dir, ".plan2code", "lessons", "source.md"); + fs.writeFileSync(file, fs.readFileSync(file, "utf8").replace("- About: src/core.js\n", "- About: src/core.js\n- Shows in: src/**/*.js | should match | x\n")); + const n = tidyNote(dir, store, "merge", [SRC_SMALL, SRC_KEBAB], ["--text", "Keep modules small and name files in kebab case.", "--why", "Both keep the tree easy to scan.", "--about", "src/"]); + const r = decide(dir, store, [{ id: n.json.id, choice: "Apply" }]); + assert.equal(r.json.results[0].outcome, "applied", r.stdout); + assert.match(lessonFiles(dir)["source.md"], /- Shows in: src\/\*\*\/\*\.js \| should match \| x\n/); +}); + +/* ------------------------------------------------- review of the uncommitted change */ + +test("lessons record: a glob of single wildcards is over its limits too", () => { + assert.equal(record.globTooBusy("src/*/*.js"), null); + assert.equal(record.globTooBusy("src/**/a*b*c?.js"), null, "four wildcards and one ** fit"); + const crafted = "*a".repeat(14) + "*b"; + assert.match(record.globTooBusy(crafted), /has 15 wildcards; at most 6/); + assert.ok(record.searchProblems({ glob: crafted, match: "never", text: "a" }).some((p) => p.field === "shows-in")); + const started = Date.now(); + assert.equal(record.runSearch(repo(), { glob: crafted, match: "never", text: "x" }).refused, true); + assert.ok(Date.now() - started < 2000, "refused at once, never walked"); +}); + +test("lessons record: a search glob holding ' | ' is refused, since the saved line could not be read back", () => { + const problems = record.searchProblems({ glob: "src/a | b/*.js", match: "should", text: "foo" }); + assert.ok(problems.some((p) => p.field === "shows-in" && /cannot contain/.test(p.message)), JSON.stringify(problems)); +}); + +test("lessons check-input: with nothing to grade it keeps no check file", () => { + const { dir, store } = checkRepo(); + const r = L(dir, ["check-input"], store); + assert.equal(r.code, 0, r.stdout); + assert.deepEqual(r.json.lessons, []); + assert.deepEqual(checkFilesIn(dir, store), []); + putLesson(dir, store, "w01", daysBefore(1)); + const one = L(dir, ["check-input"], store).json; + assert.deepEqual(checkFilesIn(dir, store), [`${one.checkId}.json`], "a check with a lesson still keeps its file"); +}); + +test("lessons list: a lesson still on the placeholder Why is never outlined Keep, even when all four tests pass", () => { + const { dir, store } = checkRepo(); + putLesson(dir, store, "w01", daysBefore(1), { kind: "convention", why: record.SAID_NO_WHY }); + const input = L(dir, ["check-input"], store).json; + const rec = L(dir, ["check-record", "--file", recordFile({ checkId: input.checkId, how: "helper", verdicts: [{ id: "w01", tests: passAll() }] })], store); + assert.equal(rec.code, 0, rec.stdout); + const card = L(dir, ["list", "--check", input.checkId], store).json.card; + assert.deepEqual(card.rows[0].choices, ["Reword", "Drop"]); + assert.equal(card.suggested?.w01, undefined); +}); diff --git a/scripts/test-web-console-learning.mjs b/scripts/test-web-console-learning.mjs index f64d7af..87338d7 100644 --- a/scripts/test-web-console-learning.mjs +++ b/scripts/test-web-console-learning.mjs @@ -14,9 +14,9 @@ import os from "node:os"; import path from "node:path"; import { spawnSync } from "node:child_process"; import { ENV, HOME, LEARNING_DIR, ROOT, cli, postPatch, readState, sessionUrl } from "./web-console-test-helpers.mjs"; -import { learningScan, storeDir, writePause, writeWaiting } from "../src/web-console/learning.mjs"; +import { followCounts, learningScan, lessonsNearCap, recordFollow, storeDir, writePause, writeWaiting } from "../src/web-console/learning.mjs"; import { sessionActions } from "../src/web-console/cmd-post-wait.mjs"; -import { indentReply, learningAction, learningBannerText, learningReply, lessonsReply } from "../src/web-console/public/answers.js"; +import { indentReply, learningAction, learningBannerText, learningNearCapText, learningReply, lessonDecisionLine, lessonsReply } from "../src/web-console/public/answers.js"; const LESSONS = path.join(ROOT, "src", "skill-scripts", "lessons.mjs"); @@ -67,7 +67,7 @@ function dashboard(t, dir) { test("scan.learning: not set up, off, on and paused, with the waiting count", (t) => { const none = project(); const s1 = dashboard(t, none); - assert.deepEqual(readState(s1.session).scan.learning, { state: "not-set-up", pausedSince: null, waiting: 0, oldestDays: 0 }); + assert.deepEqual(readState(s1.session).scan.learning, { state: "not-set-up", pausedSince: null, waiting: 0, oldestDays: 0, nearCap: false }); const off = project(SETTINGS("off")); assert.equal(readState(dashboard(t, off).session).scan.learning.state, "off"); @@ -76,7 +76,7 @@ test("scan.learning: not set up, off, on and paused, with the waiting count", (t const noted = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000 - 60000).toISOString(); writeWaiting(on, { id: "20261111-120000-abcdef", type: "lesson", text: "A lesson.", noted }); writeWaiting(on, { id: "20261112-120000-abcdef", type: "lesson", text: "Another.", noted: new Date().toISOString() }); - assert.deepEqual(readState(dashboard(t, on).session).scan.learning, { state: "on", pausedSince: null, waiting: 2, oldestDays: 2 }); + assert.deepEqual(readState(dashboard(t, on).session).scan.learning, { state: "on", pausedSince: null, waiting: 2, oldestDays: 2, nearCap: false }); const paused = project(SETTINGS("on")); const pause = writePause(paused, true, "2026-11-13T09:00:00.000Z"); @@ -92,6 +92,33 @@ test("scan.learning is absent for a settings format this console does not know", assert.equal("learning" in scan, false, "no learning field, so the page draws no row"); }); +// An area file holding `n` lessons. +const lessonFile = (title, n) => + `# ${title}\n\n` + Array.from({ length: n }, (_, i) => `### Lesson number ${i}\n- Kind: how-it-works\n- About: src/a.js\n- Noted: 2026-11-01, Implement\n`).join("\n"); + +test("scan.learning.nearCap: true at 22 general lessons or 30 in an area, false below, and only while Learning is on", (t) => { + const near = (files) => learningScan(project(files)).nearCap; + assert.equal(near({ ...SETTINGS("on") }), false, "no lessons folder"); + assert.equal(near({ ...SETTINGS("on"), ".plan2code/lessons/general.md": lessonFile("General", 21) }), false); + assert.equal(near({ ...SETTINGS("on"), ".plan2code/lessons/general.md": lessonFile("General", 22) }), true); + assert.equal(near({ ...SETTINGS("on"), ".plan2code/lessons/general.md": lessonFile("General", 25) }), true); + assert.equal(near({ ...SETTINGS("on"), ".plan2code/lessons/web.md": lessonFile("Web", 29) }), false); + assert.equal(near({ ...SETTINGS("on"), ".plan2code/lessons/web.md": lessonFile("Web", 30) }), true); + // 22 is the general file's line only: an area at 22 is not crowded. + assert.equal(near({ ...SETTINGS("on"), ".plan2code/lessons/web.md": lessonFile("Web", 22) }), false); + // Either file is enough, and CRLF files count the same. + assert.equal(near({ ...SETTINGS("on"), ".plan2code/lessons/general.md": lessonFile("General", 3), ".plan2code/lessons/web.md": lessonFile("Web", 30).replace(/\n/g, "\r\n") }), true); + // Not on: no nudge, however full. + assert.equal(near({ ...SETTINGS("off"), ".plan2code/lessons/general.md": lessonFile("General", 25) }), false); + assert.equal(lessonsNearCap(project({ ".plan2code/lessons/general.md": lessonFile("General", 25) })), true, "the count itself ignores the state"); + // It reaches the page through the dashboard's scan. + const full = project({ ...SETTINGS("on"), ".plan2code/lessons/general.md": lessonFile("General", 23) }); + assert.equal(readState(dashboard(t, full).session).scan.learning.nearCap, true); + const before = listing(full); + learningScan(full); + assert.deepEqual(listing(full), before, "the scan writes nothing"); +}); + test("a failure in Learning's core never fails the scan", () => { const boom = () => { throw new Error("the core broke"); @@ -109,7 +136,7 @@ test("an unreadable learning store reads as empty: on, not paused, nothing waiti fs.writeFileSync(store, "not a folder"); t.after(() => fs.rmSync(store, { force: true })); const s = dashboard(t, dir); - assert.deepEqual(readState(s.session).scan.learning, { state: "on", pausedSince: null, waiting: 0, oldestDays: 0 }); + assert.deepEqual(readState(s.session).scan.learning, { state: "on", pausedSince: null, waiting: 0, oldestDays: 0, nearCap: false }); }); test("the scan reads without pruning: an old waiting item stays on disk", (t) => { @@ -170,7 +197,7 @@ test("GET /learning/state answers the scan's object, worked out now", async (t) writeWaiting(dir, { id: "20261113-120000-bbbbbb", type: "lesson", text: "New.", noted: new Date().toISOString() }); const res = await s.get("/learning/state"); assert.equal(res.status, 200); - assert.deepEqual(await res.json(), { state: "on", pausedSince: null, waiting: 1, oldestDays: 0 }); + assert.deepEqual(await res.json(), { state: "on", pausedSince: null, waiting: 1, oldestDays: 0, nearCap: false }); const unknown = dashboard(t, project({ ".plan2code/settings.json": "{}" })); assert.deepEqual(await (await unknown.get("/learning/state")).json(), {}); @@ -208,13 +235,37 @@ test("GET /learning/lessons: general first, then the rest by name; no sub-folder if (linked) assert.equal(files.some((f) => f.name === "linked.md"), false, "the link out was not followed"); const empty = dashboard(t, project(SETTINGS("on"))); - assert.deepEqual(await (await empty.get("/learning/lessons")).json(), { files: [] }); + assert.deepEqual(await (await empty.get("/learning/lessons")).json(), { files: [], follows: {} }); +}); + +test("followCounts: sums lines per lesson, keeps the latest time and skips an unreadable line", () => { + const dir = project(SETTINGS("on")); + assert.deepEqual(followCounts(dir), {}, "no file yet"); + recordFollow(dir, { lesson: "web/a", skill: "implement" }, new Date("2026-11-10T09:00:00Z")); + recordFollow(dir, { lesson: "web/a", skill: "quick-task" }, new Date("2026-11-20T09:00:00Z")); + recordFollow(dir, { lesson: "web/b", skill: "implement" }, new Date("2026-11-12T09:00:00Z")); + fs.appendFileSync(path.join(storeDir(dir), "follows.ndjson"), "{ not json\n\n{\"lesson\":3}\n"); + recordFollow(dir, { lesson: "web/a", skill: "implement" }, new Date("2026-11-15T09:00:00Z")); + assert.deepEqual(followCounts(dir), { + "web/a": { count: 3, last: "2026-11-20T09:00:00.000Z" }, + "web/b": { count: 1, last: "2026-11-12T09:00:00.000Z" }, + }); + assert.equal(listing(dir).some((f) => f.includes("follows")), false, "nothing written into the project"); +}); + +test("GET /learning/lessons carries follows from this machine's store", async (t) => { + const dir = project({ ...SETTINGS("on"), ".plan2code/lessons/general.md": "# General\n\n### A lesson\n- Kind: how-it-works\n- About: src/x.js\n- Noted: 2026-11-01, Implement\n" }); + recordFollow(dir, { lesson: "general/a-lesson", skill: "implement" }, new Date("2026-11-10T09:00:00Z")); + recordFollow(dir, { lesson: "general/a-lesson", skill: "implement" }, new Date("2026-11-11T09:00:00Z")); + const s = dashboard(t, dir); + const body = await (await s.get("/learning/lessons")).json(); + assert.deepEqual(body.follows, { "general/a-lesson": { count: 2, last: "2026-11-11T09:00:00.000Z" } }); }); /* ------------------------------------------------- the action and reply */ test("a Learning action reaches the agent whole, and a launch keeps fromBanner", () => { - for (const what of ["review", "switch-on", "switch-off", "move-log", "remove"]) { + for (const what of ["review", "switch-on", "switch-off", "move-log", "remove", "tidy"]) { const action = learningAction(what); assert.deepEqual(action, { i: "__learning", type: "learning", do: what }); assert.deepEqual(sessionActions({ actions: [action] }), [{ i: "__learning", do: what }]); @@ -235,6 +286,25 @@ test("the waiting banner's line shows only while lessons wait and Learning is on assert.equal(learningBannerText(undefined), ""); }); +test("the tidy-up nudge's line shows only while Learning is on and the lessons are near their limit", () => { + assert.equal(learningNearCapText({ state: "on", waiting: 0, nearCap: true }), "Lessons are nearing their limit. Tidy up?"); + assert.equal(learningNearCapText({ state: "on", waiting: 3, nearCap: true }), "Lessons are nearing their limit. Tidy up?", "beside the waiting line"); + assert.equal(learningNearCapText({ state: "on", waiting: 0, nearCap: false }), ""); + assert.equal(learningNearCapText({ state: "on", waiting: 0 }), ""); + assert.equal(learningNearCapText({ state: "paused", nearCap: true }), ""); + assert.equal(learningNearCapText({ state: "off", nearCap: true }), ""); + assert.equal(learningNearCapText({ state: "not-set-up", nearCap: true }), ""); + assert.equal(learningNearCapText(undefined), ""); +}); + +test("a tidy row's decisions read as the change, never as an AGENTS.md file", () => { + const retire = { id: "t1", type: "tidy", change: "retire", text: "Retire: Draw the page from state Reason: Git marks it.", choices: ["Apply", "Leave"] }; + const fix = { id: "f1", type: "agents-fix", file: ".agents-docs/AGENTS-code-style.md", text: "x", choices: ["Apply", "Reword", "Drop"] }; + assert.equal(lessonDecisionLine(retire, { id: "t1", choice: "Apply" }), "Apply: Retire: Draw the page from state Reason: Git marks it."); + assert.equal(lessonDecisionLine(retire, { id: "t1", choice: "Leave" }), "Leave: Retire: Draw the page from state Reason: Git marks it."); + assert.equal(lessonDecisionLine(fix, { id: "f1", choice: "Apply" }), "Apply: .agents-docs/AGENTS-code-style.md", "a fix still shows its file"); +}); + /* ---------------------------------------------- the lessons card, end to end */ test("the lessons card from lessons.mjs list goes up on the dashboard, and a Keep comes back as a Keep line and a decisions file decide takes", async (t) => { diff --git a/scripts/test-web-console-logic.mjs b/scripts/test-web-console-logic.mjs index e63cb9e..6f4e65d 100644 --- a/scripts/test-web-console-logic.mjs +++ b/scripts/test-web-console-logic.mjs @@ -104,6 +104,8 @@ import { loopLessonsLine, } from "../src/web-console/public/answers.js"; import { chatView } from "../src/web-console/public/chat.js"; +import { LEARNING_BUSY_MS, LEARNING_CHECK_MS, learningBusyLimit, learningBusyNow } from "../src/web-console/public/selectors.js"; +import { page } from "../src/web-console/public/state.js"; import { agoWords, whenTitle, whenWords } from "../src/web-console/public/labels.js"; import { ACCENTS, DEFAULT_ACCENT, RETIRED_ACCENTS, accentId } from "../src/web-console/public/palette.js"; import { @@ -1672,7 +1674,7 @@ test("validate: a lessons item takes rows each with a type and its own choices, const one = (extra) => validate({ items: [item(extra)] }); assert.deepEqual(one({ opening: "You are on main: kept lessons will be uncommitted changes here.", rows: [row({ why: "A full run hides it.", origin: "You said this.", note: "", flags: [], refused: null, area: "General", areas: ["General"] })] }), []); assert.deepEqual( - one({ rows: ["lesson", "doubt", "gone", "agents-fix", "log-line", "area"].map((type, i) => row({ id: `w${i}`, type })) }), + one({ rows: ["lesson", "doubt", "gone", "agents-fix", "tidy", "log-line", "area"].map((type, i) => row({ id: `w${i}`, type })) }), [], "every row type the list gives" ); @@ -1705,6 +1707,53 @@ test("validate: a lessons item takes rows each with a type and its own choices, assert.deepEqual(answered, [], "an answered card does not count"); }); +test("validate: a lessons row takes the check's verdicts and a tag, and the card how it was checked", () => { + const check = { fails: [{ test: "Search", reason: "It matches 3 files." }], doubts: [{ test: "Why", reason: "No reason given." }], passed: 2, suggestion: "A shorter wording." }; + const row = (extra = {}) => ({ id: "w1", type: "lesson", text: "A lesson.", choices: ["Keep", "Reword", "Drop"], ...extra }); + const item = (extra) => ({ id: "lessons", kind: "lessons", title: "Lessons to keep", status: "open", rows: [row()], ...extra }); + const one = (extra) => validate({ items: [item(extra)] }); + const refused = (extra, field) => { + const problems = one(extra); + assert.ok(problems.some((p) => p.includes(field)), `${field}: ${problems.join(" | ")}`); + }; + assert.deepEqual(one({ rows: [row({ check, tag: "Checked in an earlier run" })], checked: { how: "helper", count: 6, seconds: 40 } }), [], "a good check, tag and how"); + assert.deepEqual(one({ rows: [row({ check: { fails: [], doubts: [], passed: 4 }, tag: "Not checked yet" })], checked: { how: "same-agent", count: 1, seconds: 0 } }), []); + assert.deepEqual(one({ checked: { failed: "The checker answered with nothing usable." } }), [], "a check that could not run"); + refused({ rows: [row({ check: { ...check, extra: 1 } })] }, 'row "w1" check "extra"'); + refused({ rows: [row({ check: { ...check, passed: 5 } })] }, 'row "w1" check passed'); + refused({ rows: [row({ check: { ...check, fails: [{ test: "Search", reason: 7 }] } })] }, 'row "w1" check fails[0]'); + refused({ rows: [row({ check: { ...check, doubts: Array.from({ length: 5 }, () => ({ test: "a", reason: "b" })) } })] }, 'row "w1" check doubts'); + refused({ rows: [row({ check: { ...check, suggestion: "x".repeat(201) } })] }, 'row "w1" check suggestion'); + refused({ rows: [row({ tag: "Old" })] }, 'row "w1" tag'); + refused({ checked: { how: "robot", count: 1, seconds: 1 } }, "checked"); + refused({ checked: { how: "helper", count: -1, seconds: 1 } }, "checked"); + refused({ checked: { failed: "x".repeat(201) } }, "checked"); +}); + +test("learning busy: a Review or Tidy up the agent is still working on outlasts LEARNING_BUSY_MS, a switch never does", () => { + const saved = { S: page.S, learningBusy: page.learningBusy, pendingResult: page.pendingResult }; + try { + page.pendingResult = null; + const at = (what, agoMs, status) => { + page.S = { agent: { status }, items: [] }; + page.learningBusy = { what, from: "on", at: Date.now() - agoMs, seen: true }; + return learningBusyNow("on"); + }; + page.S = { agent: { status: "working" }, items: [] }; + assert.equal(learningBusyLimit({ what: "review" }), LEARNING_CHECK_MS); + assert.equal(learningBusyLimit({ what: "tidy" }), LEARNING_CHECK_MS); + assert.equal(learningBusyLimit({ what: "switch-on" }), LEARNING_BUSY_MS, "a switch keeps the short limit"); + assert.ok(at("review", LEARNING_BUSY_MS + 10000, "working"), "a Review still being checked stays busy past 30 seconds"); + assert.ok(at("tidy", LEARNING_BUSY_MS + 10000, "working"), "so does a Tidy up"); + assert.equal(at("review", LEARNING_CHECK_MS + 1000, "working"), null, "but not past the check limit"); + assert.equal(at("review", LEARNING_BUSY_MS + 10000, "waiting"), null, "an agent back to waiting ends it at the short limit"); + page.pendingResult = { id: "x" }; + assert.equal(learningBusyLimit({ what: "review" }), LEARNING_CHECK_MS, "a send not yet picked up counts as working"); + } finally { + Object.assign(page, saved); + } +}); + test("validate: a lesson's own words never get the lessons card refused, but the card's own text still can", () => { const marker = "TASK_" + "COMPLETE"; const words = ["Requirements 12 and 13 are checked by check-versions.mjs.", "Risk 3 is the slow blame on Windows.", `Never print ${marker} in a spec file.`, "The grill step reads the map first."]; diff --git a/scripts/test-web-console-page-learning.mjs b/scripts/test-web-console-page-learning.mjs index 18c55ba..6f3fa71 100644 --- a/scripts/test-web-console-page-learning.mjs +++ b/scripts/test-web-console-page-learning.mjs @@ -13,7 +13,7 @@ import test from "node:test"; import assert from "node:assert/strict"; import { pageSuite, openSession, tempProject, textOf, styleOf, stylesOf, itemCard, sendAndCollect, settled, scrollCard } from "./page-test-helpers.mjs"; import { cli, until } from "./web-console-test-helpers.mjs"; -import { writePause, writeWaiting } from "../src/web-console/learning.mjs"; +import { recordFollow, writePause, writeWaiting } from "../src/web-console/learning.mjs"; const suite = pageSuite(test); @@ -126,6 +126,32 @@ test("on: the row is after the last card group, before the tip, with no count of assert.match(await textOf(dlg), /The project's lessons \(\.plan2code\/lessons\/, saved with the repository\)/); }); +test("the lessons reader draws a quiet follow line under each lesson's heading", async (t) => { + const lesson = (title) => `### ${title}\n- Kind: how-it-works\n- About: src/x.js\n- Noted: 2026-11-01, Implement\n\n`; + const { main } = await dashboard( + t, + { ...PROJECT("on"), ".plan2code/lessons/general.md": `# General\n\n${lesson("Followed lesson")}${lesson("Untouched lesson")}${lesson("Once lesson")}` }, + (project) => { + recordFollow(project, { lesson: "general/followed-lesson", skill: "implement" }, new Date("2026-11-10T12:00:00Z")); + recordFollow(project, { lesson: "general/followed-lesson", skill: "quick-task" }, new Date("2026-11-20T12:00:00Z")); + recordFollow(project, { lesson: "general/once-lesson", skill: "implement" }, new Date("2026-11-12T12:00:00Z")); + } + ); + const row = main.locator("section.learn-row"); + await row.waitFor(); + await row.getByRole("button", { name: "Open the lessons" }).click(); + const dlg = main.page().locator("#learn-lessons-modal"); + await dlg.locator(".learn-follow").first().waitFor(); + const lines = await dlg.locator(".learn-follow").allInnerTexts(); + assert.equal(lines.length, 3, "one line per lesson"); + assert.match(lines[0], /^Followed 2 times, last on Nov 2[01]$/); + assert.equal(lines[1], "Not followed yet"); + assert.match(lines[2], /^Followed once, last on Nov 1[123]$/); + // The line sits right under its heading. + const order = await dlg.locator(".learn-lessons-file").evaluate((n) => [...n.children].map((c) => (c.classList.contains("learn-follow") ? "follow" : c.textContent.includes("Followed lesson") ? "heading" : "other"))); + assert.equal(order.indexOf("follow"), order.indexOf("heading") + 1); +}); + test("Pause for me repaints the row with no agent listening, both ways", async (t) => { const { s, main } = await dashboard(t, PROJECT("on")); const bottom = main.locator("section.learn-row.is-bottom"); @@ -153,6 +179,7 @@ test("More opens upward and closes on Escape and on a click outside", async (t) assert.ok(m.y + m.height <= b.y + 1, `the menu opens above its button: ${JSON.stringify({ m, b })}`); assert.deepEqual(await menu.getByRole("menuitem").allInnerTexts(), [ "Switch off for this project", + "Tidy up lessons", "Move the failure log into lessons", "Remove all lessons…", ]); @@ -211,6 +238,50 @@ test("the banner shows only with lessons waiting, directly above the title", asy assert.equal(await paused.main.locator(".learn-banner").count(), 0, "hidden while paused"); }); +test("More has Tidy up lessons, which sends the tidy Learning action and shows working at once", async (t) => { + const { s, main } = await dashboard(t, PROJECT("on")); + const row = main.locator("section.learn-row.is-bottom"); + await row.getByRole("button", { name: /More/ }).click(); + await row.getByRole("menuitem", { name: "Tidy up lessons" }).click(); + const got = s.wait(10); + assert.equal(got.code, 0, "the send reached the agent"); + assert.deepEqual(got.actions, [{ i: "__learning", type: "learning", do: "tidy" }]); + await main.locator(".learn-banner").getByText("Looking over your lessons…").waitFor(); +}); + +// An area file holding `n` lessons. +const lessonFile = (title, n) => + `# ${title}\n\n` + Array.from({ length: n }, (_, i) => `### Lesson number ${i}\n- Kind: how-it-works\n- About: src/a.js\n- Noted: 2026-11-01, Implement\n`).join("\n"); + +test("the banner nudges a tidy-up when lessons are near their limit, and only then", async (t) => { + const full = await dashboard(t, { ...PROJECT("on"), ".plan2code/lessons/general.md": lessonFile("General", 22) }); + const banner = full.main.locator(".learn-banner"); + await banner.waitFor(); + assert.match(await textOf(banner), /Lessons are nearing their limit\. Tidy up\?/); + assert.equal(await banner.getByRole("button", { name: "Review" }).count(), 0, "nothing waits, so no Review"); + await banner.getByRole("button", { name: "Tidy up" }).click(); + const got = full.s.wait(10); + assert.equal(got.code, 0); + assert.deepEqual(got.actions, [{ i: "__learning", type: "learning", do: "tidy" }]); + + // Beside the waiting line when lessons wait too. + const both = await dashboard(t, { ...PROJECT("on"), ".plan2code/lessons/web.md": lessonFile("Web", 30) }, (p) => + writeWaiting(p, { id: "20261113-120000-ffffff", type: "lesson", text: "Waits.", noted: new Date().toISOString() }) + ); + const two = both.main.locator(".learn-banner"); + await two.waitFor(); + const text = await textOf(two); + assert.match(text, /1 lesson is waiting for your review/); + assert.match(text, /Lessons are nearing their limit\. Tidy up\?/); + assert.equal(await two.getByRole("button", { name: "Review" }).count(), 1); + assert.equal(await two.getByRole("button", { name: "Tidy up" }).count(), 1); + + // One short of the line, in general.md and in an area: no nudge. + const below = await dashboard(t, { ...PROJECT("on"), ".plan2code/lessons/general.md": lessonFile("General", 21), ".plan2code/lessons/web.md": lessonFile("Web", 29) }); + await below.main.locator("section.learn-row").waitFor(); + assert.equal(await below.main.locator(".learn-banner").count(), 0, "no banner below the line"); +}); + test("a launch from a dashboard showing lessons waiting carries fromBanner", async (t) => { const { s, main } = await dashboard(t, PROJECT("on"), (p) => writeWaiting(p, { id: "20261113-120000-eeeeee", type: "lesson", text: "Waits.", noted: new Date().toISOString() }) @@ -293,6 +364,29 @@ test("lessons card: each row shows its own choice words, and nothing is chosen", assert.match(await textOf(rowOf(card, "w-area")), /Noted on feature\/x\./); }); +test("lessons card: a tidy row shows the change, the lessons it replaces and its reason, and Reword edits the new wording", async (t) => { + const merge = { id: "w-merge", type: "tidy", change: "merge", text: "Merge 2 lessons into: Keep modules small and kebab-case their files.", why: "They say the same thing twice.", origin: "", note: "", flags: [], refused: null, area: "Source", areas: ["General", "Source"], targets: [{ id: "source/keep-modules-small", text: "Keep modules small", area: "Source" }, { id: "source/name-files-in-kebab-case", text: "Name files in kebab case", area: "Source" }], wording: "Keep modules small and kebab-case their files.", wordingWhy: "Both keep the tree easy to scan.", choices: ["Apply", "Reword", "Leave"] }; + const retire = { id: "w-retire", type: "tidy", change: "retire", text: "Retire: Draw the page from state Reason: Git marks it.", why: "", origin: "", note: "", flags: [], refused: null, area: "", areas: ["General", "Source"], targets: [{ id: "web/draw-the-page-from-state", text: "Draw the page from state", area: "Web" }], choices: ["Apply", "Leave"] }; + const { s, card } = await lessonsCard(t, CARD([merge, retire])); + assert.deepEqual(await choicesOf(rowOf(card, "w-merge")).allInnerTexts(), ["Apply", "Reword", "Leave"]); + assert.deepEqual(await choicesOf(rowOf(card, "w-retire")).allInnerTexts(), ["Apply", "Leave"], "no Reword where there is no wording"); + const text = await textOf(rowOf(card, "w-merge")); + assert.match(text, /Merge 2 lessons into: Keep modules small and kebab-case their files\./); + assert.match(text, /It replaces these lessons:\s+Keep modules small\s+Name files in kebab case/); + assert.match(text, /Why: They say the same thing twice\./); + assert.match(await textOf(rowOf(card, "w-retire")), /Retire: Draw the page from state Reason: Git marks it\./); + // Reword opens on the new wording and its own Why, not on the sentence describing the change. + await rowOf(card, "w-merge").getByRole("button", { name: "Reword" }).click(); + const words = rowOf(card, "w-merge").getByLabel("The lesson"); + assert.equal(await words.inputValue(), "Keep modules small and kebab-case their files."); + assert.equal(await rowOf(card, "w-merge").getByLabel("Why").inputValue(), "Both keep the tree easy to scan."); + await words.fill("Keep modules small and name their files in kebab case."); + await rowOf(card, "w-retire").getByRole("button", { name: "Apply" }).click(); + const got = await sendAndCollect(s); + const decisions = got.actions.find((a) => a.i === "lessons").decisions; + assert.deepEqual(decisions, [{ id: "w-merge", choice: "Reword", text: "Keep modules small and name their files in kebab case.", why: "Both keep the tree easy to scan." }, { id: "w-retire", choice: "Apply" }]); +}); + test("lessons card: Keep on one row sends only that row, and the rest are left waiting", async (t) => { const { s, card } = await lessonsCard(t); await rowOf(card, "w-lesson").getByRole("button", { name: "Keep" }).click(); @@ -409,6 +503,71 @@ test("lessons card: a refused row's Keep still chooses after its words go back a ]); }); +const CHECKED_ROWS = [ + { ...ROWS[0], id: "c-fail", text: "Never run the full suite.", check: { fails: [{ test: "Search", reason: "It matches 3 files." }], doubts: [], passed: 3 } }, + { ...ROWS[0], id: "c-doubt", text: "The handler is small.", tag: "Checked in an earlier run", check: { fails: [], doubts: [{ test: "Why", reason: "The reason repeats the lesson." }], passed: 3 } }, + { ...ROWS[0], id: "c-pass", text: "Use the helper.", check: { fails: [], doubts: [], passed: 4 } }, + { ...ROWS[0], id: "c-none", text: "Not looked at.", tag: "Not checked yet" }, + { ...ROWS[0], id: "c-all", text: "Every test flagged.", check: { fails: [{ test: "Search", reason: "No match." }, { test: "Worth", reason: "Already in AGENTS.md." }], doubts: [{ test: "Why", reason: "Thin." }, { test: "Clear", reason: "Vague." }], passed: 0 } }, +]; + +test("lessons card: a Fail, a Doubt and a pass show their lines, and the outline follows suggested without choosing", async (t) => { + const { card } = await lessonsCard(t, CARD(CHECKED_ROWS, { suggested: { "c-fail": "Drop", "c-pass": "Keep" }, checked: { how: "helper", count: 4, seconds: 40 } })); + const fail = rowOf(card, "c-fail"); + assert.match(await textOf(fail.locator(".lesson-check.fail")), /^Fail Search: It matches 3 files\.$/); + assert.equal(await fail.locator(".lesson-check.doubt").count(), 0); + assert.match(await textOf(fail.locator(".lesson-check-pass")), /^Passed the other 3$/); + const doubt = rowOf(card, "c-doubt"); + assert.match(await textOf(doubt.locator(".lesson-check.doubt")), /^Doubt Why: The reason repeats the lesson\.$/); + assert.equal(await doubt.locator(".lesson-check.fail").count(), 0); + assert.match(await textOf(doubt.locator(".lessons-tag")), /^Checked in an earlier run$/); + const pass = rowOf(card, "c-pass"); + assert.equal(await pass.locator(".lesson-check.fail, .lesson-check.doubt").count(), 0, "a pass lists no verdicts"); + assert.match(await textOf(pass.locator(".lesson-check-pass")), /^Passed the check$/); + const none = rowOf(card, "c-none"); + assert.equal(await none.locator(".lesson-checks").count(), 0, "a row never checked draws nothing"); + assert.match(await textOf(none.locator(".lessons-tag")), /^Not checked yet$/); + const all = rowOf(card, "c-all"); + assert.equal(await all.locator(".lesson-check.fail, .lesson-check.doubt").count(), 4); + assert.equal(await all.locator(".lesson-check-pass").count(), 0, "no pass line when nothing passed"); + const outlined = async (row) => row.locator(".lessons-choices button.is-suggested").allInnerTexts(); + assert.deepEqual(await outlined(fail), ["Drop"]); + assert.deepEqual(await outlined(doubt), [], "a Doubt outlines nothing"); + assert.deepEqual(await outlined(pass), ["Keep"]); + assert.equal(await card.locator('.lessons-choices [aria-pressed="true"]').count(), 0, "nothing is chosen for the person"); + assert.notEqual(await styleOf(fail.locator(".lesson-check.fail"), "color"), await styleOf(pass.locator(".lesson-check-pass"), "color"), "a Fail is not drawn like the quiet pass line"); + const px = async (loc) => parseFloat(await styleOf(loc, "fontSize")); + assert.ok((await px(pass.locator(".lesson-check-pass"))) < (await px(fail.locator(".lesson-check.fail"))), "the pass line is smaller than a verdict line"); + assert.match(await textOf(card.locator(".lessons-checked")), /^Checked 4 lessons in 40 seconds by a fresh helper that could only read$/); +}); + +test("lessons card: the how-checked line names the same agent, or why the check could not run", async (t) => { + const same = await lessonsCard(t, CARD(CHECKED_ROWS.slice(2, 3), { checked: { how: "same-agent", count: 1, seconds: 1 } })); + assert.match(await textOf(same.card.locator(".lessons-checked")), /^Checked 1 lesson in 1 second by the same agent that noted them$/); + const failed = await lessonsCard(t, CARD(CHECKED_ROWS.slice(3, 4), { checked: { failed: "the checker answered with nothing usable." } })); + assert.match(await textOf(failed.card.locator(".lessons-checked")), /^The check could not run: the checker answered with nothing usable\.$/); + const bare = await lessonsCard(t, CARD(CHECKED_ROWS.slice(3, 4))); + assert.equal(await bare.card.locator(".lessons-checked").count(), 0, "no line without a check"); +}); + +test("lessons card: Use this wording opens Reword filled with the suggestion, and what is sent is a normal Reword", async (t) => { + const row = { ...ROWS[0], id: "c-sug", check: { fails: [], doubts: [{ test: "Search", reason: "Two files match." }], passed: 3, suggestion: "Run one page test file alone first." } }; + const { s, card } = await lessonsCard(t, CARD([row])); + const li = rowOf(card, "c-sug"); + assert.match(await textOf(li.locator(".lesson-suggestion")), /^Suggested wording: Run one page test file alone first\./); + await li.getByRole("button", { name: "Use this wording" }).click(); + const edit = li.locator(".lessons-edit"); + await edit.waitFor(); + assert.equal(await li.getByRole("button", { name: "Reword" }).getAttribute("aria-pressed"), "true"); + const text = edit.getByLabel("The lesson"); + assert.equal(await text.inputValue(), "Run one page test file alone first.", "it opens on the suggestion, not the row's own words"); + await text.fill("Run one page test file alone first, then the rest."); + const got = await sendAndCollect(s); + assert.deepEqual(got.actions.find((a) => a.i === "lessons").decisions, [ + { id: "c-sug", choice: "Reword", text: "Run one page test file alone first, then the rest.", why: "A full run hides the race." }, + ]); +}); + test("lessons card: a flagged row says what was flagged", async (t) => { const flagged = { ...ROWS[0], id: "w-flag", flags: [{ pattern: "email", part: "a@b.c" }] }; const { card } = await lessonsCard(t, CARD([flagged])); diff --git a/scripts/test-web-console-skills.mjs b/scripts/test-web-console-skills.mjs index 4e894e4..7063518 100644 --- a/scripts/test-web-console-skills.mjs +++ b/scripts/test-web-console-skills.mjs @@ -399,7 +399,7 @@ test("Implement's card launches Implement + Review when Review is ticked", () => assert.equal(launchVariant(quick, true), quick, "a card with no Review box is unchanged"); }); -test("helper-strength.md ships in the seventeen skills that start helpers, and in no other", () => { +test("helper-strength.md ships in the eighteen skills that start helpers (the dashboard for its lesson check only), and in no other", () => { // npm test has just built skills/; a direct run builds it so the check never reads a stale tree. if (process.env.npm_lifecycle_event !== "test") { execFileSync(process.execPath, [path.join(ROOT, "install.js"), "--build-skills"], { stdio: "ignore" }); @@ -407,6 +407,7 @@ test("helper-strength.md ships in the seventeen skills that start helpers, and i const built = path.join(ROOT, "skills"); const having = fs.readdirSync(built).filter((dir) => fs.existsSync(path.join(built, dir, "references", "helper-strength.md"))); assert.deepEqual(having.sort(), [ + "plan2code", "plan2code-0-pathfinder", "plan2code-1-plan", "plan2code-1b-revise-plan", diff --git a/src/plan2code-0-pathfinder.md b/src/plan2code-0-pathfinder.md index 81a0285..8291c3b 100644 --- a/src/plan2code-0-pathfinder.md +++ b/src/plan2code-0-pathfinder.md @@ -35,7 +35,7 @@ On `local`, the map's bookkeeping is a script; the decisions are yours. `node "< Load `./AGENTS.md` if it exists — its conventions govern; never re-ask what it answers. If missing, fold it into the Step 0 gate batch: *"No `AGENTS.md`. Pathfinder can chart without it. Continue, or run `plan2code-init` first?"* Record the outcome as the first line of `## Ground rules`: ``- `AGENTS.md` exists and governs.`` or, when missing, exactly ``- `AGENTS.md` is absent.`` (the handoff reads it). -**Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "/lessons.mjs"`). +**Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "/lessons.mjs"`); note only what the person asks you to remember (references/lessons.md, While working). ## Rules diff --git a/src/plan2code-1-plan.md b/src/plan2code-1-plan.md index cde0a61..da4ff63 100644 --- a/src/plan2code-1-plan.md +++ b/src/plan2code-1-plan.md @@ -33,7 +33,7 @@ Check if `./AGENTS.md` exists: Do not proceed until user confirms continuing without `AGENTS.md`. -**Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "/lessons.mjs"`); `` is `scripts/` beside this SKILL.md, `~/.agents/skills/plan2code-1-plan/scripts/` globally. +**Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "/lessons.mjs"`); note only what the person asks you to remember (references/lessons.md, While working); `` is `scripts/` beside this SKILL.md, `~/.agents/skills/plan2code-1-plan/scripts/` globally. ## Rules diff --git a/src/plan2code-1b-revise-plan.md b/src/plan2code-1b-revise-plan.md index 7d26614..6bbe8cc 100644 --- a/src/plan2code-1b-revise-plan.md +++ b/src/plan2code-1b-revise-plan.md @@ -13,7 +13,7 @@ The FIRST thing you do, before anything else in this file — before Step 1, bef ## Rules - Follow `./AGENTS.md` if it exists -- **Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "/lessons.mjs"`). +- **Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "/lessons.mjs"`); note only what the person asks you to remember (references/lessons.md, While working). - Never remove completed `[x]` tasks without explicit approval - Warn if changes invalidate completed work - Keep task numbers sequential diff --git a/src/plan2code-2-document.md b/src/plan2code-2-document.md index e06a2ed..21e5b2d 100644 --- a/src/plan2code-2-document.md +++ b/src/plan2code-2-document.md @@ -22,7 +22,7 @@ The FIRST thing you do, before anything else in this file — before Auto-Discov ## Rules - Follow `./AGENTS.md` if it exists -- **Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "/lessons.mjs"`). +- **Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "/lessons.mjs"`); note only what the person asks you to remember (references/lessons.md, While working). - Require planning document before proceeding - Tasks must be specific enough for a developer with NO context - Use checkbox format `- [ ]` for Task items ONLY (not prerequisites, acceptance criteria, or success criteria) diff --git a/src/plan2code-4-finalize.md b/src/plan2code-4-finalize.md index 43e57b3..2bf1d02 100644 --- a/src/plan2code-4-finalize.md +++ b/src/plan2code-4-finalize.md @@ -24,7 +24,7 @@ The FIRST thing you do, before anything else in this file — before the Require ## Rules - Follow `./AGENTS.md` if it exists -- **Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "/lessons.mjs"`). +- **Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "/lessons.mjs"`); note only what the person asks you to remember (references/lessons.md, While working). - Complete steps IN ORDER - STOP and ask user before proceeding when: - Incomplete tasks found (Step 1) diff --git a/src/plan2code-dead-code.md b/src/plan2code-dead-code.md index 8294056..063759e 100644 --- a/src/plan2code-dead-code.md +++ b/src/plan2code-dead-code.md @@ -14,7 +14,7 @@ The FIRST thing you do, before anything else in this file, before running a scri Read `./AGENTS.md` when it exists: its commands, its `## Test map` and anything it says about slow suites or code reached by name. Dead Code still works without one, but the test map is what tells it which tests and build to run after a removal; without it the scripts read the project's config files, and the person confirms the commands. -**Lessons:** follow `references/lessons.md` → Start and While working. +**Lessons:** follow `references/lessons.md` → Start and While working; note only what the person asks you to remember (references/lessons.md, While working). ## Scripts diff --git a/src/plan2code-pr-prep.md b/src/plan2code-pr-prep.md index 54c0285..d88b4dc 100644 --- a/src/plan2code-pr-prep.md +++ b/src/plan2code-pr-prep.md @@ -14,7 +14,7 @@ The FIRST thing you do, before anything else in this file, before reading the br Read `./AGENTS.md` when it exists: its commands, its `## Test map` and anything it says about slow suites. PR Prep still works without one: the scripts find the project's commands from its config files, and nothing here needs Plan2Code's specs. -**Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "/lessons.mjs"`). +**Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "/lessons.mjs"`); note only what the person asks you to remember (references/lessons.md, While working). ## Scripts diff --git a/src/plan2code-ui-prototype.md b/src/plan2code-ui-prototype.md index ffa9086..55e61e6 100644 --- a/src/plan2code-ui-prototype.md +++ b/src/plan2code-ui-prototype.md @@ -24,7 +24,7 @@ When this file is `references/ui-prototype.md` inside Pathfinder, Plan, Revise p Read `./AGENTS.md` when it exists: its stack, its style files and its conventions help Step 1 find the look. Its absence does not block this skill. -**Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "/lessons.mjs"`). +**Lessons:** then read `references/lessons.md` and follow its Start and While working sections (`node "/lessons.mjs"`); note only what the person asks you to remember (references/lessons.md, While working). ## Scripts diff --git a/src/plan2code.md b/src/plan2code.md index 703878f..c6ba974 100644 --- a/src/plan2code.md +++ b/src/plan2code.md @@ -139,7 +139,8 @@ The Learning row and banner send a `__learning` action with `do`. It is no hop: - `switch-off`: `switch off`. - `move-log`: `list --log-all`, then the card below. - `remove`: `remove --confirm` (the page already asked). -- `review`: `list`, then the card below. While the state is `not-set-up`, `list --first-ask` instead: a `firstAsk` goes up as the reference's The first ask card (never `decide --file` before it), then `decide --first-ask yes` or `decide --first-ask no --skill dashboard`; on Yes, the card below from the list it returns. +- `tidy`: while Learning is On, `tidy-input`, then up to 10 proposals, each `note --type tidy --change merge|reword|retire|move --targets --reason "" --skill dashboard` (`--text` for a merge or reword, `--area` for a move; one change each, nothing for lessons that are fine). A retire's reason is what you saw: git marks it and the code no longer does this, or `followed` 0 and none in 90 days (a hint only, never alone for a lesson that is not marked). Then the `review` check step with `check-input --tidy`, `list --check ` and the card below. No proposals: say so in the menu's `note`. In `decide`'s results a tidy-up's `outOfDate` is gone (its lesson changed since), and `applied` and `left` need no follow-up. +- `review`: the check step from `references/lessons.md` End (check-input, the checker, check-record), with an `activity` line ("Checking 4 lessons") posted while it runs, then `list --check ` (`list` when there was nothing to check), then the card below. While the state is `not-set-up`, `list --first-ask` instead: a `firstAsk` goes up as the reference's The first ask card (never `decide --file` before it), then `decide --first-ask yes` or `decide --first-ask no --skill dashboard`; on Yes, the card below from the list it returns. The card: post `list`'s `card` as one `lessons` item with `--wait` (the page shows it over the menu; give it a new `id` when an earlier lessons card is in the session). Write the reply's `Decisions:` JSON to a file in the session folder, adding what End step 6 says a choice still needs, run `decide --file `, and handle its results as End step 7 does. An empty `card` needs no post. The lessons card is the only question the dashboard shows: where End says to ask (a Move's `why` and `about`, or once more for an item), take `about` from the files the line names and post that row again as a new lessons card with the choices `Reword and move` and `Leave` (other rows: their own choices), its `note` saying what is needed. diff --git a/src/shared-references/helper-strength.md b/src/shared-references/helper-strength.md index 491d244..e5c4748 100644 --- a/src/shared-references/helper-strength.md +++ b/src/shared-references/helper-strength.md @@ -1,5 +1,5 @@ # Helper Strength -> Shared by the skills that start helpers (subagents): Init, Init Update, Pathfinder, Plan, Revise Plan, Document, Quick Task, Implement, Implement + Review, Review, Finalize, X-ray, Diagnose, PR Prep, Test, Dead Code and Update Dependencies. Read it when you first start a helper in a session. Never invoked as a skill. +> Shared by the skills that start helpers (subagents): the dashboard (lesson check only), Init, Init Update, Pathfinder, Plan, Revise Plan, Document, Quick Task, Implement, Implement + Review, Review, Finalize, X-ray, Diagnose, PR Prep, Test, Dead Code and Update Dependencies. Read it when you first start a helper in a session. Never invoked as a skill. ## The words @@ -24,6 +24,7 @@ Never write a model or vendor name in a brief, a report or a file, and never inv | Build task needing a design decision the spec leaves open | strongest (or keep it yourself) | high | | Pathfinder research question, sketch | standard | medium | | Plan's PLAN-DRAFT cross-check against the conversation | standard | medium | +| Lesson check (`lesson-check.md`) | standard | medium | | Review analysis, focused scope | standard | high | | Review analysis, branch or full scope, or touching security, auth or data | strongest | high | diff --git a/src/shared-references/lesson-check.md b/src/shared-references/lesson-check.md new file mode 100644 index 0000000..a7d131f --- /dev/null +++ b/src/shared-references/lesson-check.md @@ -0,0 +1,71 @@ +# Lesson check: the checker's brief +> Read by the noting skills (Implement, Implement + Review, Quick Task, Diagnose, X-ray, Review, Test) and the dashboard when they start the checker, and by the checker itself. Never invoked as a skill. + +You are the checker. You grade waiting lessons before a person decides on them. You judge only: the person still decides every lesson. + +## Hard rules + +- Never edit, create or delete any file. +- Never run a command. The search results you need are already in the input. +- Read only the files the input names (each lesson's `files`, plus `AGENTS.md` when `context.agentsMd` is set). Read nothing else. +- Judge only: no fixes, no advice outside a verdict's reason or suggestion. +- Return the JSON below as the whole reply: no prose before or after it, no code fence. + +## The input + +The JSON that `lessons.mjs check-input` printed: + +- `checkId`: copy it into your reply unchanged. +- `lessons`: each with `id`, `text`, `why`, `kind`, `about`, `files` (`path`, `hash`, `read`: `whole` or `sampled`), `budgetHit` (true when files were left unread) and, when the lesson carries a search, `search` and `searchResult` (`matched`, `hits`, `filesSearched`). +- `context`: `agentsMd` (`AGENTS.md` or null), `saved` (the project's saved lessons: `id`, `text`) and `waiting` (the other waiting lessons: `id`, `text`). + +## The four tests + +Give every lesson all four, each a verdict and one sentence of reason. + +- **true**: True against the code. Read the listed files and the search result: does the code still do what the lesson says? A `searchResult` that did not match, or matched where the lesson says it should not, counts against it. +- **worth**: Worth keeping. Not obvious from reading the code, not a one-off, and the `why` earns its place. A teammate's run would act differently because of it. +- **overlap**: Overlap or conflict. Compare with `context.saved`, `context.waiting` and `AGENTS.md`: a near-duplicate, or a statement that contradicts one. Name what it overlaps in the reason. +- **clear**: Clear enough. One sentence a teammate can act on without this conversation: it names the thing and says what to do. + +## Tidy-ups + +With `check-input --tidy`, a lesson may carry `type: "tidy"`, `change` (merge, reword, retire or move), `reason` and `targets` (the saved lessons it touches: `id`, `text`, `why`, `kind`, `about`, `area`). Give it the same four tests and the same reply shape, judging the change: + +- merge, reword: the lesson under test is `text`, the new wording, with the targets' `about`. **true**: it is still true against the files. **worth**: it is worth more than the targets said apart. **overlap**: it overlaps `context.saved` (the targets are left out of it). **clear**: one sentence a teammate can act on. A merge that drops a fact its targets held is a Doubt on **true**. +- retire: grade the proposal, so Pass means the lesson should go. **true**: the reason holds against the files (the lesson no longer matches the code). **worth**: retiring loses nothing a teammate needs. **overlap**: no other saved lesson depends on it. **clear**: the reason is one plain sentence. `reason` is the proposer's view, never proof. +- Suggest a wording only for a merge or reword; a retire or move has none to change, and a suggestion there is dropped. +- move: `area` is where it lands (`targets[0].area` is where it is). **clear**: does the new area's name fit what the lesson is about? The other tests grade the lesson as it stands. + +## The three verdicts + +- **Pass**: it holds. +- **Doubt**: you cannot tell, or it is weak. Give a Doubt when you could not read enough to decide, when `budgetHit` is true and the unread files could change the answer, or when the search does not test what the lesson says. +- **Fail**: it is plainly wrong, a duplicate, a conflict, or unclear. Say what is wrong. + +## A suggested wording + +Optional, on a lesson with a Doubt or Fail where a better sentence would fix it. One sentence, at most 200 characters, in the same voice as the lesson, never a secret, a person's name or a customer detail. Leave `suggestion` out when you have none. A bad one is dropped. + +## The reply + +```json +{ + "checkId": "", + "how": "helper", + "verdicts": [ + { + "id": "", + "tests": { + "true": { "verdict": "Pass", "reason": "One sentence." }, + "worth": { "verdict": "Pass", "reason": "One sentence." }, + "overlap": { "verdict": "Doubt", "reason": "One sentence." }, + "clear": { "verdict": "Pass", "reason": "One sentence." } + }, + "suggestion": "Optional one-sentence wording." + } + ] +} +``` + +One verdict per lesson in `lessons`, none for a lesson not listed. `how` is `helper` when you are a fresh helper, `same-agent` when the noting agent grades in a separate step. Every `reason` is one sentence of at most 200 characters, on one line, with no secret in it. diff --git a/src/shared-references/lessons.md b/src/shared-references/lessons.md index 2b5a505..3ffba69 100644 --- a/src/shared-references/lessons.md +++ b/src/shared-references/lessons.md @@ -27,9 +27,12 @@ Once per run: when a reference sends you here inside a run that already did Star - Before the first edit in a folder outside the areas already read, run `read --paths --run `, keep the new `run`, and print its `line` when not empty, such as "Read 3 more for Web console server." - When a lesson changes what you do, and you would have done otherwise, print at that moment: "Following a lesson: ". + Then run `node "/lessons.mjs" follow --lesson --skill ` (the ids come from `read`) so the reader can show how often lessons are followed. It is recorded on this machine only and does nothing while Learning is off; skip it quietly when it fails. - When your own memory disagrees with a lesson, follow the lesson and say "My own memory says otherwise; following the project's lesson: ". If the person says the memory is right, note a doubt about that lesson. -The rest of this section is for the seven skills that note lessons: Implement, Implement + Review, Quick Task, Diagnose, X-ray, Review and Test. +**Remember this (every skill that reads lessons).** When the person asks for something to be remembered ("remember this", "so this doesn't happen again" or the like), note it in that turn with `--source said` (the note commands below) and print the returned "Noted for the end of the run: " line. The script refuses a correction or convention without a `--why`: when the person gave no reason for one, ask one short question first ("Why does this matter?") and note it once with their answer as the Why; with no answer, note it with `--why "You asked for this to be remembered."`: the card's row then asks for the reason, and only a Reword with one saves it. Noting the same words again with a different `--why` replaces the waiting item. A said lesson in a skill with no End waits, and shows in the dashboard banner's Review. + +Inferred lessons and fixes to `AGENTS.md` (below) are for the seven skills that note lessons only: Implement, Implement + Review, Quick Task, Diagnose, X-ray, Review and Test. The script refuses `--source inferred` from the other eight, which note only what the person said and the doubts Start step 5 and the memory bullet above ask for. **What to offer.** Offer only what a teammate's run should follow: a fact about the code, never secrets, customer or personal details, or remarks about people. Facts about this codebase that a teammate would need are offered as lessons; a person's own preferences stay in whatever memory their agent keeps. Never offer what is already in `AGENTS.md` or in a lesson just read. @@ -44,7 +47,8 @@ The rest of this section is for the seven skills that note lessons: Implement, I **The note commands** (`--skill` is this skill's name, such as `implement`): -- A lesson: `node "/lessons.mjs" note --type lesson --text "" --kind --about --source said|inferred [--seen ] [--why ""] --skill ` +- A lesson: `node "/lessons.mjs" note --type lesson --text "" --kind --about --source said|inferred [--seen ] [--why ""] [--shows-in --match should|never --text-match ""] --skill ` + Give it a search (all three flags or none) when the lesson names text that should always, or never, appear in some files, such as "never `localStorage` in `src/web-console/public/**/*.js`": the check and later reads test it against the code, and a search that stops agreeing raises a doubt. The literal is one line, at most 120 characters. - A doubt about a saved lesson: `note --type doubt --target --found "" --skill ` - A fix to `AGENTS.md`: whatever corrects something `AGENTS.md` states is a fix, not a lesson: `note --type agents-fix --before "" --after "" [--file .agents-docs/.md] --skill `. A test map row is `note --type agents-fix --test-map-row '<{"area","paths":[..],"run","shared"}>' --skill `. Note a lesson only when `AGENTS.md` has no place for it. - A new area: when a lesson fits no existing area and is not general, run `areas --suggest` and note the fitting suggestion, or, when the test map offers none, a name and paths of your own: `note --type area --name "" --paths --skill `. It shows in the same list as Create, Rename or Drop. @@ -53,13 +57,19 @@ Print the returned `line`, such as "Noted for the end of the run: ". ## End -The seven noting skills only (and any skill sent here by Start's Review now), before the commit instructions and before the console's finish. +The seven noting skills (and any skill sent here by Start's Review now) run it before the commit instructions and before the console's finish. The eight read-only skills have no End: their said lessons wait for the next noting run or the dashboard banner's Review. -1. Run `node "/lessons.mjs" list` (`list --first-ask` when the state is `not-set-up`). +**The check** (before step 1, unless the state is `not-set-up`). Skip it when `references/lesson-check.md` is not beside this file (a read-only skill sent here by Review now ships no checker brief): run plain `list`, and the rows show Not checked yet. Otherwise run `node "/lessons.mjs" check-input`. `lessons` empty: skip the check and run step 1 as written. Otherwise: + +- **Start the checker** with `references/lesson-check.md` and the JSON. With helpers on and available, it is a fresh helper given reading tools only, never relying on a permission mode (Claude Code: a custom helper already installed whose tool list holds only reading tools, such as `tools: Read, Grep, Glob`, never the built-in `Explore` or a general-purpose one, since both keep the shell; Devin: `run_subagent` with the read-only explore profile; Codex: a fresh helper told it may only read), `how: "helper"`, at `helper-strength.md`'s lesson check row (standard strength, medium effort). With Subagents off for the skill, no helper support, or (Claude Code) no reading-only helper installed, you grade in a separate step after re-reading the brief, `how: "same-agent"`; the card says so. +- Write its reply to a file in the console session folder, or the OS temp folder in a terminal, never in the project. Run `check-record --file `. Exit 4: give the checker its `problems` once and record again; still failing, step 1 runs `list --check-failed ""` and every lesson still shows. +- Step 1 then runs `list --check `. On the web console, post an `activity` line while it runs ("Checking 4 lessons"). + +1. Run `node "/lessons.mjs" list` (`list --first-ask` when the state is `not-set-up`; `list --check ` after a check, or `list --check-failed ""` when it failed). 2. `items` empty and no `firstAsk`: say nothing and skip this step. 3. `firstAsk` present: see The first ask below, instead of 4 to 7. 4. Show `opening` first when present. -5. **On the web console:** post the returned `card` as one `lessons` item with `--wait` (a new `id` when an earlier lessons card is in the session). Its reply has one line per decision ("Keep: ...", "Reword: ...") and a `Decisions:` line holding them as JSON: that JSON is step 6's file, plus what a choice still needs. A `Suggestions wanted on` line for it: reply in its `thread` and, in the same patch, send `suggested` (row id to one of that row's `choices`, such as `{"w1":"Keep"}`), which outlines those buttons without choosing them. **In a terminal:** ask each group in `rounds` with your question tool, one question per item with exactly its `choices` and nothing pre-selected (`heading`, `text`, `why`, `origin` and `note` are what the person reads; an area shows its `name` and `paths`); with no question tool, a numbered list. A choice that needs more (step 6) asks the person for it. +5. **On the web console:** post the returned `card` as one `lessons` item with `--wait` (a new `id` when an earlier lessons card is in the session). Its reply has one line per decision ("Keep: ...", "Reword: ...") and a `Decisions:` line holding them as JSON: that JSON is step 6's file, plus what a choice still needs. A `Suggestions wanted on` line for it: reply in its `thread` and, in the same patch, send `suggested` (row id to one of that row's `choices`, such as `{"w1":"Keep"}`), which outlines those buttons without choosing them. **In a terminal:** ask each group in `rounds` with your question tool, one question per item with exactly its `choices` and nothing pre-selected (`heading`, `text`, `why`, `origin` and `note` are what the person reads; an area shows its `name` and `paths`); with no question tool, a numbered list. Show the card's `checked` line first ("Checked 6 lessons in 40 seconds by a fresh helper that could only read", "... by the same agent that noted them", or "The check could not run: "). Read each item's `check` and `tag` into its text in this order: every Fail, then every Doubt (each as "Fail : "), then the pass line ("Passed the other N", "Passed the check" with none, and no pass line when all four found something), then its `tag` when present. A `suggestion` is offered as a Reword carrying exactly those words, which the person may adjust. A choice that needs more (step 6) asks the person for it. 6. Write the decisions, one `{ "id", "choice" }` per answered item plus what its choice needs, to a JSON file in the console session folder, or the OS temp folder in a terminal, never in the project. Run `decide --file ` and print its `closing` line, such as "Kept 2 (1 reworded), retired 1. 1 still waiting." What a choice needs: - Reword of a lesson, a doubt or a lesson whose files are gone: the new `text`, plus `why`, `kind`, `about` or `area` when they change. - Rename of an area: the new `name`, plus `paths` when they change. @@ -74,7 +84,7 @@ Never stage or commit: what End writes is part of the run's change. ## Unattended runs -A run with nobody there (an Implementation Loop phase started with `--loop`, or a helper) follows Start without asking the heads-up, follows While working and notes lessons, but never runs End, never approves and never shows the first ask. A helper reports a lesson to the main agent in its result, and the main agent notes it as its own. When `note` exits 5 in an unattended run, the lesson is not written, and the run's report says "1 lesson was not noted: it held secret-shaped text" without the text. +A run with nobody there (an Implementation Loop phase started with `--loop`, or a helper) follows Start without asking the heads-up, follows While working, notes lessons, records each "Following a lesson" moment with `follow` (as above; a helper reports its follows to the main agent, which records them), but never runs End, never approves and never shows the first ask. A helper reports a lesson to the main agent in its result, and the main agent notes it as its own. When `note` exits 5 in an unattended run, the lesson is not written, and the run's report says "1 lesson was not noted: it held secret-shaped text" without the text. A loop phase never runs the check: its lessons are graded at the next lessons card. ## With Learning off diff --git a/src/skill-scripts/lessons.mjs b/src/skill-scripts/lessons.mjs index da417f8..3e7d46b 100644 --- a/src/skill-scripts/lessons.mjs +++ b/src/skill-scripts/lessons.mjs @@ -43,19 +43,32 @@ Every answer carries state (not-set-up, off, on, paused, unknown) and active. The personal pause, on this machine only. Refused unless the project is on. node lessons.mjs read [--paths a,b] [--run ] [--from-banner] - Reads only: the lessons that fit this run, general.md plus the areas - matching the named paths and the branch's changed files, each as + The lessons that fit this run, general.md plus the areas matching the + named paths and the branch's changed files, each as { id, text, why, marked, gone }. run is the handle for the next read, which returns only areas not handed over yet; line is printed as is. The first read adds headsUp (left out with --from-banner) and logLines - (the failure log lines log-lines would offer). + (the failure log lines log-lines would offer). Its only write is on this + machine: a waiting doubt for each marked lesson whose search no longer + agrees with the code, or a marked convention with no Why, listed in + raised ([{ id, target, reason }]) and counted in line. node lessons.mjs note --type lesson --text --kind --about a,b --source said|inferred [--seen a,b] --skill [--why ] [--area ] [--dry-run] + [--shows-in --match should|never --text-match ] Check the lesson, then hold it on this machine until a person decides. - kind: correction (needs --why), convention, how-it-works, command. + kind: correction or convention (both need --why), how-it-works, command. about: one to three files, or one folder. --source inferred needs --seen. + The search is all three of --shows-in, --match and --text-match or none: + the literal (one line, at most 120 characters, no " | ") should match + or never matches in files under the glob. It is saved as the block's + "- Shows in: | should match|never matches | " line, written + before "- Noted:". A "- Noted:" value may end with ", kept over the + check" (after any ", checked "): the person kept it over the check. + The eight read-only skills (pathfinder, plan, revise-plan, document, + finalize, pr-prep, dead-code, ui-prototype) note only --source said: + --source inferred from them exits 5 inferred-from-read-only. Does nothing (noted: false) while Learning is off or paused for you. Exit 4 invalid-lesson with problems; exit 5 secret with pattern and part. @@ -76,24 +89,68 @@ Every answer carries state (not-set-up, off, on, paused, unknown) and active. { area, paths: [..], run, shared }, replacing the row of that area or added. The new text is checked: a secret exits 5, writing nothing. + node lessons.mjs note --type tidy --change merge|reword|retire|move + --targets --reason --skill + [--text ] [--why ] [--kind ] + [--about a,b] [--area ] [--dry-run] + A tidy-up the coach proposes for saved lessons, one change each: merge + (two or more targets into one new wording), reword (one target, new + wording), retire (one target) or move (one target into --area, an + existing area or General). Targets are saved lesson ids from tidy-input. + A new wording is validated as a lesson is (kind, why and about default + from the targets). Every change needs a one-sentence reason. The same + change on the same targets is not written twice (already: true). + Exit 4 invalid-tidy with problems; exit 5 secret with pattern and part. + + node lessons.mjs tidy-input + Reads only: every saved lesson as { id, area, text, why, kind, about, + search, noted, keptOverCheck, marked, gone, followed, lastFollowed }, + plus general { count, max } and areas [{ name, slug, count }]. + node lessons.mjs check --text [--why ] Reads only: the check note and decide run. refused { pattern, part } (a named secret pattern, its text cut to four characters) or null, and flags [{ pattern, part }] (email, handle, person-name). Always exit 0. - node lessons.mjs list [--first-ask] [--log-all] + node lessons.mjs check-input [--tidy] + Reads only (it writes the run's check file on this machine): the waiting + lessons due a check, oldest first, at most 10 (the rest in notChecked; + a lesson whose stored check still holds is left out), each with its + files ({ path, hash, read: whole|sampled }, budgetHit when a folder was + cut at 6 files or 60 KB) and, with a search, searchResult { matched, + hits [{ file, line }], filesSearched }. Also context { agentsMd, saved, + waiting }, checkId and started. With --tidy, waiting tidy-ups join the + lessons under the same cap of 10, each { type: "tidy", change, reason, + targets [{ id, text, why, kind, about, area }] }: its text, why, kind + and about are the new wording and its About (merge, reword) or the + target's own (retire, move), and area is where a move or merge lands. + + node lessons.mjs check-record --file + Store a checker's verdicts, { checkId, how: helper|same-agent, verdicts: + [{ id, tests: { true, worth, overlap, clear: { verdict: Pass|Doubt|Fail, + reason } }, suggestion? }] }, on the waiting lessons with the file hashes + from check-input. Exit 4 invalid-verdicts naming each fault, storing + nothing. A bad suggestion is dropped and named in problems. + + node lessons.mjs list [--first-ask] [--log-all] [--check ] [--check-failed ] Reads only: the approval list of everything waiting: items, opening (the main-branch line), card (the console's lessons item) and rounds (the items grouped by type for a question tool). While on, it adds the new failure log lines (--log-all: every unmarked one). With --first-ask while not set up and a lesson is waiting, firstAsk is the first-ask card: { lesson, sentences, yes, no, later }. + A lesson whose stored check still holds (its files hash as they did) + carries check { fails, doubts, passed, suggestion? }; the card gains + suggested { : Drop|Keep } and checked { how, count, seconds } (or + { failed } with --check-failed). tag is "Not checked yet" without a + fresh check, and "Checked in an earlier run" for one older than --check. node lessons.mjs decide --file [--dry-run] Apply a person's choices, [{ id, choice, text?, why?, area?, name?, paths? }]: Keep, Reword, Drop for a lesson; Create, Rename, Drop for an area; Keep, Reword, Retire for a doubt or a lesson whose files are gone; - Apply, Reword (after, or row), Drop for an AGENTS.md fix; Move (why, + Apply, Reword (text, why, area: merge and reword only), Leave for a + tidy-up; Apply, Reword (after, or row), Drop for an AGENTS.md fix; Move (why, about, area?), Reword and move (lessons: [{ text, why, about, area? }]), Leave in the log for a failure log line. Writes .plan2code/lessons/ and, for fixes and log lines, AGENTS.md or the .agents-docs/ file; @@ -117,6 +174,12 @@ Every answer carries state (not-set-up, off, on, paused, unknown) and active. node lessons.mjs report Reads only: lessons per area, the oldest, marked and gone ones. + node lessons.mjs follow --lesson --skill + Records that a run followed a saved lesson ("Following a lesson: ..."), + one line in follows.ndjson on this machine only; nothing is written into + the project. Does nothing (noted: false) while Learning is off or paused + for you. Exit 4 when the id names no saved lesson (use an id read gave). + node lessons.mjs remove --confirm [--dry-run] Delete .plan2code/lessons/ (removed lists its files). Leaves settings.json, AGENTS.md and this machine's store; stages nothing. @@ -422,8 +485,48 @@ export const GENERAL = "general"; export const GENERAL_MAX = 25; export const KINDS = ["correction", "convention", "how-it-works", "command"]; -const FIELD = /^- (Kind|About|Why|Noted):[ \t]?(.*)$/; -const NOTED = /^(.*?)(?:,\s*checked\s+(\d{4}-\d{2}-\d{2}))?\s*$/; +const FIELD = /^- (Kind|About|Why|Shows in|Noted):[ \t]?(.*)$/; +const NOTED = /^(.*?)(?:,\s*checked\s+(\d{4}-\d{2}-\d{2}))?(,\s*kept over the check)?\s*$/; +const KEPT_OVER_CHECK = "kept over the check"; + +// A search glob's limits: lesson files are shared through the repository, and +// matchGlob turns each **/ into a group that backtracks, so a glob with many of +// them (22 took 47 s for one path) would stall every teammate's read. +export const SEARCH_GLOB_MAX = 120; + +// The Why a said correction or convention is noted with when the person gave +// no reason (lessons.md, Remember this). The card asks for the real one: list +// says so on the row, and decide refuses to save it until a Reword replaces it. +export const SAID_NO_WHY = "You asked for this to be remembered."; +const NEEDS_WHY_NOTE = "No reason given yet: use Reword to say why it matters."; +const isSaidNoWhy = (why) => String(why ?? "").trim() === SAID_NO_WHY; +export const SEARCH_GLOB_STARS_MAX = 3; +// Each single * or ? backtracks too: 15 single stars in 30 characters took 4 s +// for one 30-character name, so every wildcard counts toward one more cap. +export const SEARCH_GLOB_WILDCARDS_MAX = 6; + +/** Why a search glob is over its limits, or null when it is within them. */ +export function globTooBusy(glob) { + const g = String(glob); + if (g.length > SEARCH_GLOB_MAX) return `is ${g.length} characters; at most ${SEARCH_GLOB_MAX}`; + const stars = (g.match(/\*\*/g) || []).length; + if (stars > SEARCH_GLOB_STARS_MAX) return `has ${stars} **; at most ${SEARCH_GLOB_STARS_MAX}`; + const wildcards = (g.match(/\*+|\?/g) || []).length; + if (wildcards > SEARCH_GLOB_WILDCARDS_MAX) return `has ${wildcards} wildcards; at most ${SEARCH_GLOB_WILDCARDS_MAX}`; + return null; +} + +// ` | should match|never matches | ` into { glob, match, text }, +// or null when the value is not exactly those three parts or the glob is over +// its limits (globTooBusy), so a hostile line is never run. +function parseSearch(value) { + const parts = String(value).split(" | "); + if (parts.length !== 3) return null; + const [glob, words, text] = parts.map((p) => p.trim()); + const match = words === "should match" ? "should" : words === "never matches" ? "never" : null; + if (!glob || !match || !text || globTooBusy(glob)) return null; + return { glob, match, text }; +} const splitList = (s) => String(s || "") @@ -458,10 +561,16 @@ function parseBlock(lines, startLine) { if (m[1] === "Kind") block.kind = value; else if (m[1] === "About") block.about = splitList(value); else if (m[1] === "Why") block.why = value; - else { + else if (m[1] === "Shows in") { + // An unparseable line stays in `lines` (never dropped) and is reported here. + const search = parseSearch(value); + if (search) block.search = search; + else (block.badLines ||= []).push(line); + } else { const n = value.match(NOTED); block.noted = n[1].trim(); block.checked = n[2] || null; + if (n[3]) block.keptOverCheck = true; } } return block; @@ -496,7 +605,8 @@ export function parseAreaFile(text) { export function renderBlock(block) { const lines = [`### ${block.heading}`, `- Kind: ${block.kind}`, `- About: ${block.about.join(", ")}`]; if (block.why) lines.push(`- Why: ${block.why}`); - lines.push(`- Noted: ${block.noted}${block.checked ? `, checked ${block.checked}` : ""}`); + if (block.search) lines.push(`- Shows in: ${block.search.glob} | ${block.search.match === "never" ? "never matches" : "should match"} | ${block.search.text}`); + lines.push(`- Noted: ${block.noted}${block.checked ? `, checked ${block.checked}` : ""}${block.keptOverCheck ? `, ${KEPT_OVER_CHECK}` : ""}`); lines.push(""); return lines; } @@ -619,19 +729,42 @@ function pathProblem(p) { return null; } +/** + * The problems with a lesson's search, `[{ field, message }]`: the glob passes + * unsupported() and the same path rules as About, match is should or never, + * and the text is one non-empty line of at most 120 characters without " | ". + */ +export function searchProblems(search) { + const problems = []; + if (!search || typeof search !== "object") return [{ field: "search", message: "The search is missing." }]; + const glob = String(search.glob ?? ""); + const bad = pathProblem(glob) || unsupported(glob) || globTooBusy(glob); + if (bad) problems.push({ field: "shows-in", message: `${glob} ${bad}.` }); + if (glob.includes(" | ")) problems.push({ field: "shows-in", message: "The glob cannot contain ' | '." }); + if (search.match !== "should" && search.match !== "never") problems.push({ field: "match", message: "match must be should or never." }); + const text = String(search.text ?? ""); + if (!text.trim()) problems.push({ field: "text-match", message: "The search text is empty." }); + if (/[\r\n]/.test(text)) problems.push({ field: "text-match", message: "The search text must be one line." }); + if (text.length > 120) problems.push({ field: "text-match", message: `The search text is ${text.length} characters; at most 120.` }); + if (text.includes(" | ")) problems.push({ field: "text-match", message: "The search text cannot contain ' | '." }); + return problems; +} + /** * The problems with a lesson, `[{ field, message }]` (empty when it is fine): * one sentence of at most 200 characters for text and why, a known kind, a - * why for a correction, and one to three files or exactly one folder inside - * the repository. + * why for a correction or a convention, one to three files or exactly one + * folder inside the repository, and a sound search when one is present. */ -export function validateLesson({ text, why, kind, about }, root) { +export function validateLesson({ text, why, kind, about, search }, root) { const problems = []; problems.push(...sentenceProblems("text", text ?? "")); if (why) problems.push(...sentenceProblems("why", why)); // A rejected kind is never echoed: it has not been through the secret check. if (!KINDS.includes(kind)) problems.push({ field: "kind", message: `kind must be one of ${KINDS.join(", ")}.` }); if (kind === "correction" && !String(why || "").trim()) problems.push({ field: "why", message: "A correction needs a why." }); + if (kind === "convention" && !String(why || "").trim()) problems.push({ field: "why", message: "A convention needs a why." }); + if (search) problems.push(...searchProblems(search)); const list = Array.isArray(about) ? about : splitList(about); if (!list.length) problems.push({ field: "about", message: "about names one to three files, or one folder." }); for (const p of list) { @@ -1284,6 +1417,16 @@ async function cmdCheck(L, root, args) { const SOURCES = ["said", "inferred"]; +// Skills that read and plan but never run the code: they note only what the +// person said, never what they inferred. Matched after the `plan2code-` prefix +// and a step number such as `1b-` are dropped, so `plan2code-1-plan` is `plan`. +export const READ_ONLY_SKILLS = new Set(["pathfinder", "plan", "revise-plan", "document", "finalize", "pr-prep", "dead-code", "ui-prototype"]); + +function isReadOnlySkill(skill) { + const name = String(skill).trim().toLowerCase().replace(/[\s_]+/g, "-").replace(/^plan2code-/, "").replace(/^\d+[a-z]?-/, ""); + return READ_ONLY_SKILLS.has(name); +} + /** Fail with exit 4 and the list when a check found problems. */ function refuseProblems(error, problems, what) { if (!problems.length) return; @@ -1332,8 +1475,8 @@ function globProblems(paths) { async function cmdNote(L, root, args) { const type = args.type; - if (type !== "lesson" && type !== "area" && type !== "doubt" && type !== "agents-fix") { - fail(EXIT.USAGE, "missing-value", type ? "That note type is not one of lesson, area, doubt or agents-fix." : "note needs --type lesson, area, doubt or agents-fix.", "Run: lessons.mjs note --type lesson ..., --type area, --type doubt or --type agents-fix."); + if (type !== "lesson" && type !== "area" && type !== "doubt" && type !== "agents-fix" && type !== "tidy") { + fail(EXIT.USAGE, "missing-value", type ? "That note type is not one of lesson, area, doubt, agents-fix or tidy." : "note needs --type lesson, area, doubt, agents-fix or tidy.", "Run: lessons.mjs note --type lesson ..., --type area, --type doubt, --type agents-fix or --type tidy."); } if (typeof args.skill !== "string" || !args.skill.trim()) fail(EXIT.USAGE, "missing-value", "note needs --skill, the skill noting it.", "Add --skill , for example --skill Implement."); const s = stateOf(L, root); @@ -1351,8 +1494,8 @@ async function cmdNote(L, root, args) { }; // Names, paths and the skill are checked before anything is echoed back in // a problem message; the lesson's text and why after validation, as before. - const lists = { about: splitList(args.about), seen: splitList(args.seen), paths: splitGlobs(args.paths) }; - refuseSecret(secretIn(args.skill, args.name, args.area, args.target, args.file, lists.about, lists.seen, lists.paths), type); + const lists = { about: splitList(args.about), seen: splitList(args.seen), paths: splitGlobs(args.paths), targets: splitList(args.targets) }; + refuseSecret(secretIn(args.skill, args.name, args.area, args.target, args.file, args.change, lists.about, lists.seen, lists.paths, lists.targets), type); const skillProblems = /[\r\n]/.test(args.skill) || args.skill.trim().length > 40 ? [{ field: "skill", message: "skill is one line of at most 40 characters, the skill's name." }] : []; let item; if (type === "doubt") { @@ -1374,6 +1517,14 @@ async function cmdNote(L, root, args) { item = { id, type, target, found: args.found.trim(), skill: args.skill.trim(), branch, noted: when.toISOString(), flags }; } else if (type === "agents-fix") { item = agentsFixItem(root, args, { id, skillProblems, refuseSecret, branch, when }); + } else if (type === "tidy") { + item = tidyItem(root, args, lists, { id, skillProblems, refuseSecret, branch, when }); + // The same change on the same targets is one proposal, not two. + const already = L.listWaiting(root, when).find((w) => w.type === "tidy" && w.change === item.change && sameSet(w.targets, item.targets)); + if (already) { + out({ ok: true, state: s.state, active: s.active, noted: false, id: already.id, line: "", already: true }); + return; + } } else if (type === "area") { if (typeof args.name !== "string") fail(EXIT.USAGE, "missing-value", "note --type area needs --name.", "Add --name --paths ."); areaSlug(args.name); @@ -1383,8 +1534,18 @@ async function cmdNote(L, root, args) { } else { const about = lists.about.map((p) => p.replace(/\/{2,}/g, "/")); const seen = lists.seen; - const lesson = { text: args.text ?? "", why: args.why || "", kind: args.kind, about }; + if (args.source === "inferred" && isReadOnlySkill(args.skill)) { + fail(EXIT.REFUSED, "inferred-from-read-only", "This skill notes only what the person said, so the lesson was not noted.", "Note a lesson from this skill only with --source said, after the person told you it.", { state: s.state, active: s.active }); + } + // The search is all three flags or none. + const searchFlags = [["shows-in", args["shows-in"]], ["match", args.match], ["text-match", args["text-match"]]]; + const missingSearch = searchFlags.filter(([, v]) => v === undefined).map(([k]) => `--${k}`); + const searchPartial = missingSearch.length > 0 && missingSearch.length < 3; + refuseSecret(secretIn(args["shows-in"] ?? "", args["text-match"] ?? ""), "lesson"); + const search = missingSearch.length === 0 ? { glob: String(args["shows-in"]).trim().replace(/\/{2,}/g, "/"), match: args.match, text: String(args["text-match"]).trim() } : null; + const lesson = { text: args.text ?? "", why: args.why || "", kind: args.kind, about, search }; const problems = [...skillProblems, ...validateLesson(lesson, root)]; + if (searchPartial) problems.push({ field: "shows-in", message: `A search needs --shows-in, --match and --text-match together; missing ${missingSearch.join(", ")}.` }); if (args.area !== undefined && /[\r\n]/.test(args.area)) problems.push({ field: "area", message: "area is one line, the area's name." }); if (!SOURCES.includes(args.source)) problems.push({ field: "source", message: "source must be said or inferred." }); if (args.source === "inferred" && !seen.length) problems.push({ field: "seen", message: "An inferred lesson names the files it was seen in (--seen)." }); @@ -1396,6 +1557,14 @@ async function cmdNote(L, root, args) { const { refused, flags } = checkAll(lesson.text, lesson.why); refuseSecret(refused, "lesson"); item = { id, type, kind: lesson.kind, text: lesson.text, why: lesson.why, about, source: args.source, seen, skill: args.skill.trim(), branch, noted: when.toISOString(), area: (args.area || "").trim(), flags }; + if (search) item.search = search; + // The same words noted again (a said lesson whose Why the person gave after the first note) replace the waiting item instead of adding a second. + const same = L.listWaiting(root, when, { prune: false }).find((w) => w.type === "lesson" && w.source === "said" && w.skill === item.skill && String(w.text).trim() === lesson.text.trim()); + if (same && !args["dry-run"]) { + item.id = same.id; + item.noted = same.noted || item.noted; + if (!item.search && same.search) item.search = same.search; + } } if (!args["dry-run"]) L.writeWaiting(root, item); out({ @@ -1403,9 +1572,9 @@ async function cmdNote(L, root, args) { state: s.state, active: s.active, noted: true, - id, + id: item.id, flags: item.flags || [], - line: `Noted for the end of the run: ${type === "area" ? `a new area, ${item.name}` : type === "doubt" ? `a doubt about ${item.target}` : type === "agents-fix" ? `a fix to ${item.file}` : item.text}`, + line: `Noted for the end of the run: ${type === "area" ? `a new area, ${item.name}` : type === "doubt" ? `a doubt about ${item.target}` : type === "agents-fix" ? `a fix to ${item.file}` : type === "tidy" ? `a tidy-up (${item.change}): ${item.reason}` : item.text}`, dryRun: !!args["dry-run"], }); } @@ -1455,6 +1624,102 @@ function agentsFixItem(root, args, { id, skillProblems, refuseSecret, branch, wh return { ...base, file, before: args.before, after: args.after, flags }; } +const TIDY_CHANGES = ["merge", "reword", "retire", "move"]; +const sameSet = (a, b) => Array.isArray(a) && Array.isArray(b) && a.length === b.length && [...a].sort().join("\n") === [...b].sort().join("\n"); +const areaNameOf = (entry) => (entry && entry.area.name) || (entry && entry.slug === GENERAL ? "General" : entry ? entry.slug : ""); + +/** + * The waiting item for `note --type tidy`: one change to saved lessons + * (merge, reword, retire or move), its targets as saved lesson ids, and the + * one-sentence reason. A merge or reword carries the new wording, validated as + * a lesson is (kind, why and about default from the targets); a move names an + * existing area; every change needs a reason. New words go through the secret + * screen: a refusal exits 5 and writes nothing. + */ +function tidyItem(root, args, lists, { id, skillProblems, refuseSecret, branch, when }) { + const problems = [...skillProblems]; + const change = args.change; + if (!TIDY_CHANGES.includes(change)) problems.push({ field: "change", message: `change must be one of ${TIDY_CHANGES.join(", ")}.` }); + const loaded = loadAreas(root); + const found = []; + for (const raw of lists.targets) { + const saved = findLesson(loaded, raw.trim()); + if (!saved) { + problems.push({ field: "targets", message: "A target names no saved lesson; use the ids tidy-input returned." }); + continue; + } + const tid = lessonId(saved.entry.slug, saved.block.heading); + if (found.some((f) => f.id === tid)) problems.push({ field: "targets", message: "A target is named twice." }); + else found.push({ id: tid, saved }); + } + if (TIDY_CHANGES.includes(change)) { + if (change === "merge" ? lists.targets.length < 2 : lists.targets.length !== 1) problems.push({ field: "targets", message: change === "merge" ? "A merge needs two or more targets." : `A ${change} takes exactly one target.` }); + } + problems.push(...sentenceProblems("reason", args.reason ?? "")); + let text = ""; + let why = ""; + let kind = ""; + let about = []; + let area = typeof args.area === "string" ? args.area.trim() : ""; + if (/[\r\n]/.test(area)) problems.push({ field: "area", message: "area is one line, the area's name." }); + const first = found[0] && found[0].saved; + if (first) { + const b = first.block; + if (change === "merge" || change === "reword") { + text = typeof args.text === "string" ? args.text : ""; + why = args.why !== undefined ? String(args.why) : found.map((f) => f.saved.block.why).find(Boolean) || ""; + kind = args.kind !== undefined ? args.kind : b.kind; + about = lists.about.length ? lists.about.map((p) => p.replace(/\/{2,}/g, "/")) : [...new Set(found.flatMap((f) => f.saved.block.about))]; + problems.push(...validateLesson({ text, why, kind, about, search: change === "reword" ? b.search : undefined }, root)); + } else { + text = b.heading; + why = b.why || ""; + kind = b.kind; + about = b.about; + } + if (change === "move" || (change === "merge" && area)) { + const slug = slugOf(area); + if (!area) problems.push({ field: "area", message: "A move needs --area, the area to move the lesson to." }); + else if (slug !== GENERAL && !loaded.has(slug)) problems.push({ field: "area", message: "No area by that name; name an existing area or General." }); + else if (change === "move" && slug === first.entry.slug) problems.push({ field: "area", message: "The lesson is already in that area." }); + } + if (change === "reword") area = ""; + } + refuseProblems("invalid-tidy", problems, "tidy-up"); + const { refused, flags } = checkAll(text, why, args.reason); + refuseSecret(refused, "tidy-up"); + return { id, type: "tidy", change, targets: found.map((f) => f.id), text, why, kind, about, area, reason: String(args.reason).trim(), skill: args.skill.trim(), branch, noted: when.toISOString(), flags }; +} + +/** `tidy-input`: every saved lesson with what the coach weighs, and how full the areas are. */ +async function cmdTidyInput(L, root) { + const s = stateOf(L, root); + const loaded = loadAreas(root); + const all = markLessons(root, [...loaded.values()].flatMap(lessonsOf)); + const follows = L.followCounts(root); + const lessons = all.map((l) => { + const f = follows[l.id]; + return { + id: l.id, + area: areaNameOf(loaded.get(l.slug)), + text: l.block.heading, + why: l.block.why || "", + kind: l.block.kind, + about: l.block.about, + search: l.block.search || null, + noted: l.block.noted, + keptOverCheck: !!l.block.keptOverCheck, + marked: !!l.marked, + gone: !!l.gone, + followed: f ? f.count : 0, + lastFollowed: f ? f.last : null, + }; + }); + const general = loaded.get(GENERAL); + const areas = [...loaded.values()].filter((e) => e.slug !== GENERAL).map((e) => ({ name: e.area.name || e.slug, slug: e.slug, count: e.area.blocks.length })); + out({ ok: true, state: s.state, active: s.active, lessons, general: { count: general ? general.area.blocks.length : 0, max: GENERAL_MAX }, areas }); +} + async function cmdAreas(L, root, args) { if (!args.suggest) fail(EXIT.USAGE, "missing-value", "areas needs --suggest.", "Run: lessons.mjs areas --suggest."); const s = stateOf(L, root); @@ -1541,9 +1806,72 @@ function areaTakes(root, globs, p) { const handOver = (l) => ({ id: l.id, text: l.block.heading, why: l.block.why || "", marked: !!l.marked, gone: !!l.gone }); +/** The line a read prints when it raised doubts, such as "Raised 1 doubt: its search no longer matches." */ +export function raisedLine(raised) { + if (!raised.length) return ""; + const reasons = [...new Set(raised.map((r) => r.reason))]; + return `Raised ${plural(raised.length, "doubt", "doubts")}: ${reasons.join(" and ")}.`; +} + +/** + * After a read marks lessons, raise a waiting doubt for each marked lesson whose + * search no longer agrees with the code (a should-match search with no hit, a + * never-matches search with a hit), and for each marked convention with no Why. + * Searches run only for marked lessons that carry one. A lesson with a doubt + * already waiting gets no second one. The waiting store is on this machine only, + * so this writes nothing into the project. Returns `[{ id, target, reason }]`. + */ +function raiseDoubts(L, root, lessons) { + const marked = lessons.filter((l) => l.marked && !l.gone); + if (!marked.length) return []; + const doubted = new Set(L.listWaiting(root, now(), { prune: false }).filter((w) => w.type === "doubt").map((w) => w.target)); + const raised = []; + let listed = null; + for (const l of marked) { + if (doubted.has(l.id)) continue; + let found = null; + let reason = ""; + const search = l.block.search; + if (search) { + listed ||= searchFiles(root); + const r = runSearch(root, search, listed); + const should = search.match !== "never"; + if (should && !r.matched) { + found = "Its search no longer matches: nothing in the searched files holds the text now."; + reason = "its search no longer matches"; + } else if (!should && r.matched) { + const first = r.hits[0]; + const count = `${r.hits.length >= SEARCH_HITS_MAX ? "at least " : ""}${plural(r.hits.length, "line", "lines")}`; + const verb = `${count} now ${r.hits.length === 1 ? "holds" : "hold"} the text`; + // The first hit's file is named when the sentence stays within its 200 characters. + found = `Its search no longer matches: ${verb}, the first in ${first.file} at line ${first.line}.`; + if (found.length > 200) found = `Its search no longer matches: ${verb}, the first at line ${first.line} of a searched file.`; + reason = "its search no longer matches"; + } + } + if (!found && l.block.kind === "convention" && !(l.block.why || "").trim()) { + found = "Needs a Why: a convention is saved with the reason for it, and this one has none."; + reason = "a convention needs its Why"; + } + if (!found || sentenceProblems("found", found).length) continue; + const when = now(); + const { refused, flags } = checkAll(found); + if (refused) continue; + const item = { id: L.newWaitingId(when), type: "doubt", target: l.id, found, skill: "read", branch: safeBranch(root), noted: when.toISOString(), flags }; + try { + L.writeWaiting(root, item); + } catch { + continue; + } + doubted.add(l.id); + raised.push({ id: item.id, target: l.id, reason }); + } + return raised; +} + async function cmdRead(L, root, args) { const handle = args.run !== undefined ? decodeRun(args.run) : null; - // A read never writes, not even the waiting store's 30-day cleanup (NFR-3). + // A read never prunes the waiting store (NFR-3); its only write is a doubt raised for a marked lesson, kept on this machine. const s = L.learningState(root, now(), { prune: false }); if (s.state !== "on") { const answer = { ok: true, state: s.state, active: false, line: s.state === "paused" ? "Learning is paused for you." : "" }; @@ -1562,6 +1890,7 @@ async function cmdRead(L, root, args) { const withGeneral = !given.includes(GENERAL); const returned = [...(withGeneral && generalEntry ? lessonsOf(generalEntry) : []), ...matched.flatMap(lessonsOf)]; markLessons(root, returned); + const raised = raiseDoubts(L, root, returned); const of = (slug) => returned.filter((l) => l.slug === slug).map(handOver); const areas = matched.map((e) => ({ name: e.area.name, slug: e.slug, lessons: of(e.slug) })); const general = withGeneral ? of(GENERAL) : null; @@ -1572,7 +1901,8 @@ async function cmdRead(L, root, args) { state: s.state, active: s.active, run: encodeRun([...given, GENERAL, ...matched.map((e) => e.slug)]), - line: readLine({ first, general: general ? general.length : 0, areas: areas.map((a) => ({ name: a.name, count: a.lessons.length })), empty }), + line: [readLine({ first, general: general ? general.length : 0, areas: areas.map((a) => ({ name: a.name, count: a.lessons.length })), empty }), raisedLine(raised)].filter(Boolean).join(" "), + ...(raised.length ? { raised } : {}), general, areas, }; @@ -1614,15 +1944,373 @@ async function cmdReport(L, root) { }); } +/* ------------------------------------------------- the check (the script's half) */ + +export const CHECK_CAP = 10; +export const FOLDER_FILES = 6; +export const FOLDER_BYTES = 60 * 1024; +export const SEARCH_FILE_MAX = 512 * 1024; +export const SEARCH_HITS_MAX = 20; +const SKIP_DIRS = new Set(["node_modules", ".git"]); +// The four tests, by the key a verdict uses and the name the card shows. +export const CHECK_TESTS = { true: "True against the code", worth: "Worth keeping", overlap: "Overlap or conflict", clear: "Clear enough" }; +const VERDICTS = ["Pass", "Doubt", "Fail"]; +const CHECK_ID = /^[a-z0-9]{1,12}-[0-9a-f]{4}$/; + +const sha256 = (buf) => crypto.createHash("sha256").update(buf).digest("hex"); +const looksBinary = (buf) => buf.subarray(0, 8000).includes(0); + +/** The SHA-256 hex of a project file's bytes, or null when it cannot be read. */ +function hashOf(root, p) { + if (pathProblem(p)) return null; + try { + return sha256(fs.readFileSync(path.join(root, p))); + } catch { + return null; + } +} + +/** Every file under `dir` (a project-relative path, "" for the root) as a posix path, skipping node_modules and .git (and skills/ at the root when asked). */ +function walkFiles(root, dir, { skipSkills = false } = {}) { + const found = []; + const visit = (d) => { + let entries; + try { + entries = fs.readdirSync(path.join(root, d), { withFileTypes: true }); + } catch { + return; + } + for (const e of entries.sort((a, b) => (a.name < b.name ? -1 : 1))) { + const p = d ? `${d}/${e.name}` : e.name; + if (e.isDirectory()) { + if (SKIP_DIRS.has(e.name) || (skipSkills && p === "skills")) continue; + visit(p); + } else if (e.isFile()) found.push(p); + } + }; + visit(dir); + return found; +} + +/** + * The files the checker may read for a lesson, each `{ path, hash, read }`. + * A file About is read whole; a folder About is listed, the files sharing words + * with the lesson first, and sampled until FOLDER_FILES files or FOLDER_BYTES + * (`budgetHit` when files were left unread). A path that is gone is left out. + */ +function filesFor(root, lesson) { + const files = []; + let budgetHit = false; + const words = new Set(`${lesson.text || ""} ${(lesson.about || []).join(" ")}`.toLowerCase().match(/[a-z0-9]{4,}/g) || []); + for (const raw of lesson.about || []) { + if (typeof raw !== "string") continue; + const p = cleanPath(raw); + if (!p || pathProblem(p)) continue; + const abs = path.join(root, p); + if (isDir(abs)) { + const score = (f) => (f.toLowerCase().match(/[a-z0-9]{4,}/g) || []).filter((w) => words.has(w)).length; + const listed = walkFiles(root, p) + .map((f) => ({ f, score: score(f) })) + .sort((a, b) => b.score - a.score || (a.f < b.f ? -1 : 1)) + .map((x) => x.f); + let bytes = 0; + let taken = 0; + for (const f of listed) { + if (taken >= FOLDER_FILES || bytes >= FOLDER_BYTES) { + budgetHit = true; + break; + } + let buf; + try { + buf = fs.readFileSync(path.join(root, f)); + } catch { + continue; + } + if (looksBinary(buf)) continue; + files.push({ path: f, hash: sha256(buf), read: "sampled" }); + bytes += buf.length; + taken++; + } + } else if (fs.existsSync(abs)) { + const hash = hashOf(root, p); + if (hash) files.push({ path: p, hash, read: "whole" }); + } + } + return { files, budgetHit }; +} + +/** + * The files a lesson search may look at, as sorted posix paths: what git tracks + * plus untracked files it does not ignore (so build output such as + * plan2code-app/target/ is never searched), else, outside git, the whole tree. + * Never node_modules, .git or skills/ at the root. A command that runs several + * searches lists once and hands the list to each runSearch(). + */ +export function searchFiles(root) { + const r = gitRun(root, ["ls-files", "--cached", "--others", "--exclude-standard", "-z"]); + if (r.code !== 0) return walkFiles(root, "", { skipSkills: true }); + const skipped = (p) => p === "skills" || p.startsWith("skills/") || p.split("/").some((part) => SKIP_DIRS.has(part)); + return [...new Set(r.out.split("\0").filter((p) => p && !skipped(p)))].sort(); +} + +/** + * Run a lesson's search over the project: the files matching `search.glob` + * among `files` (searchFiles() when not given), each a text file of at most + * 512 KB, and every line holding `search.text` exactly (case and all), at most 20. + */ +export function runSearch(root, search, files = null) { + const hits = []; + let filesSearched = 0; + // A stored item from before the limits: refuse it rather than stall the run. + if (globTooBusy(search.glob)) return { matched: false, hits, filesSearched, refused: true }; + for (const file of files || searchFiles(root)) { + if (!matchGlob(search.glob, file)) continue; + let buf; + try { + if (fs.statSync(path.join(root, file)).size > SEARCH_FILE_MAX) continue; + buf = fs.readFileSync(path.join(root, file)); + } catch { + continue; + } + if (looksBinary(buf)) continue; + filesSearched++; + const lines = buf.toString("utf8").split(/\r?\n/); + for (let n = 0; n < lines.length && hits.length < SEARCH_HITS_MAX; n++) if (lines[n].includes(search.text)) hits.push({ file, line: n + 1 }); + if (hits.length >= SEARCH_HITS_MAX) break; + } + return { matched: hits.length > 0, hits, filesSearched }; +} + +// A stored verdict set of the shape check-record writes: all four tests, each a known verdict and a reason. +const wellFormedTests = (tests) => + !!tests && typeof tests === "object" && Object.keys(CHECK_TESTS).every((k) => tests[k] && typeof tests[k] === "object" && VERDICTS.includes(tests[k].verdict) && typeof tests[k].reason === "string"); + +/** Whether a waiting item's stored check still holds: it is well formed and every file it names hashes as it did. */ +export function checkIsFresh(root, item) { + const check = item && item.check; + if (!check || typeof check !== "object" || !check.files || typeof check.files !== "object" || !wellFormedTests(check.tests)) return false; + return Object.entries(check.files).every(([p, hash]) => hashOf(root, p) === hash); +} + +const checksDir = (L, root) => path.join(L.storeDir(root), "checks"); +export const CHECK_FILE_MAX_AGE_MS = 24 * 60 * 60 * 1000; + +/** + * Delete check files over a day old: a check whose check-record never succeeded + * (an abandoned run, a checker that failed twice, `list --check-failed`) would + * otherwise keep its file forever. The age comes from the id's base-36 start time. + */ +function pruneChecks(L, root) { + let names; + try { + names = fs.readdirSync(checksDir(L, root)); + } catch { + return; + } + for (const name of names) { + const id = name.replace(/\.json$/, ""); + if (id === name || !CHECK_ID.test(id)) continue; + const started = parseInt(id.split("-")[0], 36); + if (Number.isFinite(started) && Date.now() - started > CHECK_FILE_MAX_AGE_MS) fs.rmSync(path.join(checksDir(L, root), name), { force: true }); + } +} + +/** What the checker reads of one waiting tidy-up: the wording under test (the new one for a merge or reword, the target's own for a retire or move), its About, and the targets. */ +function tidyCheckEntry(root, loaded, w, searchList = () => searchFiles(root)) { + const targets = w.targets.map((t) => { + const { entry, block } = findLesson(loaded, t); + return { id: t, text: block.heading, why: block.why || "", kind: block.kind, about: block.about, area: areaNameOf(entry) }; + }); + const own = w.change === "merge" || w.change === "reword"; + const first = findLesson(loaded, w.targets[0]).block; + const text = own ? w.text : targets[0].text; + const about = own ? (Array.isArray(w.about) ? w.about : []) : targets[0].about; + const search = w.change === "reword" || w.change === "retire" ? first.search : null; + const { files, budgetHit } = filesFor(root, { text, about }); + return { + id: w.id, + type: "tidy", + change: w.change, + reason: w.reason, + text, + why: own ? w.why || "" : targets[0].why, + kind: own ? w.kind : targets[0].kind, + about, + area: w.area || (w.change === "move" ? "" : targets[0].area), + targets, + ...(search ? { search, searchResult: runSearch(root, search, searchList()) } : {}), + files, + ...(budgetHit ? { budgetHit: true } : {}), + }; +} + +async function cmdCheckInput(L, root, args = {}) { + const s = stateOf(L, root); + const loaded = args.tidy ? loadAreas(root) : null; + const tidyOk = (w) => w.type === "tidy" && Array.isArray(w.targets) && w.targets.length > 0 && w.targets.every((t) => findLesson(loaded, t)); + const listed = L.listWaiting(root, now(), { prune: false }); + const waiting = listed.filter((w) => w.type === "lesson"); + // Tidy-ups share the cap, oldest first among the lessons. + const eligible = listed.filter((w) => w.type === "lesson" || (args.tidy && tidyOk(w))); + const due = eligible.filter((w) => !checkIsFresh(root, w)); + const picked = due.slice(0, CHECK_CAP); + pruneChecks(L, root); + // One file listing serves every search in this check. + let searchable = null; + const searchList = () => (searchable ||= searchFiles(root)); + const lessons = picked.map((w) => { + if (w.type === "tidy") return tidyCheckEntry(root, loaded, w, searchList); + const about = Array.isArray(w.about) ? w.about : []; + const { files, budgetHit } = filesFor(root, { text: w.text, about }); + return { + id: w.id, + text: w.text, + why: w.why || "", + kind: w.kind, + about, + ...(w.search ? { search: w.search, searchResult: runSearch(root, w.search, searchList()) } : {}), + files, + ...(budgetHit ? { budgetHit: true } : {}), + }; + }); + const inPicked = new Set(picked.map((w) => w.id)); + // A tidy-up's own targets are not overlaps of it. + const inTidy = new Set(picked.filter((w) => w.type === "tidy").flatMap((w) => w.targets)); + const context = { + agentsMd: fs.existsSync(path.join(root, "AGENTS.md")) ? "AGENTS.md" : null, + saved: readLessons(root) + .filter((l) => !inTidy.has(l.id)) + .map((l) => ({ id: l.id, text: l.block.heading })), + waiting: waiting.filter((w) => !inPicked.has(w.id)).map((w) => ({ id: w.id, text: w.text })), + }; + // The id carries the start time (base 36, then a few random hex characters), so list can tell a verdict from this run from an earlier one. + const startedMs = Date.now(); + const checkId = `${startedMs.toString(36)}-${crypto.randomBytes(2).toString("hex")}`; + const result = { ok: true, state: s.state, active: s.active, checkId, started: new Date(startedMs).toISOString(), cap: CHECK_CAP, lessons, context, notChecked: due.slice(CHECK_CAP).map((w) => w.id) }; + // Nothing to grade means no check-record call, so keep no file for one. + if (lessons.length) { + fs.mkdirSync(checksDir(L, root), { recursive: true }); + fs.writeFileSync(path.join(checksDir(L, root), `${checkId}.json`), JSON.stringify(result)); + } + out(result); +} + +const checkProblem = (field, message) => ({ field, message }); + +async function cmdCheckRecord(L, root, args) { + if (typeof args.file !== "string") fail(EXIT.USAGE, "missing-value", "check-record needs --file.", "Run: lessons.mjs check-record --file ."); + const text = readText(path.resolve(args.file)); + if (text === null) fail(EXIT.NOT_FOUND, "no-file", `The verdicts file ${args.file} was not found.`, "Write the checker's verdicts to a JSON file and pass it with --file."); + let data; + try { + data = JSON.parse(text); + } catch { + fail(EXIT.INVALID, "invalid-file", "The verdicts file is not JSON.", "Write { checkId, how, verdicts: [{ id, tests, suggestion? }] }."); + } + const refuse = (problems) => fail(EXIT.INVALID, "invalid-verdicts", `The check was not recorded: ${problems.map((p) => p.message).join(" ")}`, "Fix what problems lists and record it again.", { problems }); + if (!data || typeof data !== "object" || Array.isArray(data)) refuse([checkProblem("file", "The verdicts file must be an object { checkId, how, verdicts }.")]); + const problems = []; + const id = typeof data.checkId === "string" ? data.checkId : ""; + const checkFile = CHECK_ID.test(id) ? path.join(checksDir(L, root), `${id}.json`) : null; + let input = null; + try { + input = checkFile ? JSON.parse(fs.readFileSync(checkFile, "utf8")) : null; + } catch {} + if (!input) { + problems.push(checkProblem("checkId", "The checkId is not one check-input printed (or it was already recorded); run check-input again.")); + refuse(problems); + } + if (data.how !== "helper" && data.how !== "same-agent") problems.push(checkProblem("how", "how must be helper or same-agent.")); + if (!Array.isArray(data.verdicts)) refuse([...problems, checkProblem("verdicts", "verdicts must be a list.")]); + const byId = new Map(input.lessons.map((l) => [l.id, l])); + const seen = new Set(); + const clean = []; + for (const v of data.verdicts) { + const vid = v && typeof v.id === "string" ? v.id : ""; + const lesson = byId.get(vid); + if (!lesson) { + problems.push(checkProblem("id", "A verdict names an id that is not in this check's lessons.")); + continue; + } + if (seen.has(vid)) { + problems.push(checkProblem("id", `${vid} has more than one verdict.`)); + continue; + } + seen.add(vid); + const tests = {}; + for (const key of Object.keys(CHECK_TESTS)) { + const t = v.tests && typeof v.tests === "object" ? v.tests[key] : null; + const field = `${vid}.${key}`; + if (!t || typeof t !== "object") { + problems.push(checkProblem(field, `${field} is missing: every verdict needs all four tests (true, worth, overlap, clear).`)); + continue; + } + if (!VERDICTS.includes(t.verdict)) problems.push(checkProblem(`${field}.verdict`, `${field}.verdict must be Pass, Doubt or Fail.`)); + if (typeof t.reason !== "string") problems.push(checkProblem(`${field}.reason`, `${field}.reason must be one sentence of text.`)); + else if (checkAll(t.reason).refused) problems.push(checkProblem(`${field}.reason`, `${field}.reason holds secret-shaped text; reword it without the secret.`)); + else problems.push(...sentenceProblems(`${field}.reason`, t.reason)); + tests[key] = { verdict: t.verdict, reason: typeof t.reason === "string" ? t.reason.trim() : "" }; + } + let suggestion; + const warnings = []; + const hasSuggestion = v.suggestion !== undefined && v.suggestion !== null && v.suggestion !== ""; + if (hasSuggestion && lesson.type === "tidy" && (lesson.change === "retire" || lesson.change === "move")) { + // A retire or a move has no wording to reword, so the card offers nothing to use it on. + warnings.push({ id: vid, field: "suggestion", message: "The suggested wording was dropped: a retire or a move has no wording to change." }); + } else if (hasSuggestion) { + const wording = typeof v.suggestion === "string" ? v.suggestion : ""; + const bad = validateLesson({ text: wording, why: lesson.why, kind: lesson.kind, about: lesson.about, search: lesson.search }, root); + const secret = checkAll(wording).refused; + if (bad.length || secret || !wording) warnings.push({ id: vid, field: "suggestion", message: secret ? "The suggested wording held secret-shaped text and was dropped." : `The suggested wording was dropped: ${(bad[0] && bad[0].message) || "it is not a sentence."}` }); + else suggestion = wording.trim(); + } + clean.push({ lesson, tests, suggestion, warnings }); + } + if (problems.length) refuse(problems); + const checked = new Date().toISOString(); + const seconds = Math.max(0, Math.round((Date.now() - Date.parse(input.started)) / 1000)); + const warnings = []; + let recorded = 0; + const stored = new Map(L.listWaiting(root, now(), { prune: false }).map((w) => [w.id, w])); + for (const c of clean) { + warnings.push(...c.warnings); + const item = stored.get(c.lesson.id); + if (!item) continue; // decided or aged out while the checker ran + const files = Object.fromEntries(c.lesson.files.map((f) => [f.path, f.hash])); + L.writeWaiting(root, { ...item, check: { tests: c.tests, ...(c.suggestion ? { suggestion: c.suggestion } : {}), how: data.how, files, checked, seconds } }); + recorded++; + } + try { + fs.rmSync(checkFile, { force: true }); + } catch {} + const s = stateOf(L, root); + out({ ok: true, state: s.state, active: s.active, recorded, how: data.how, seconds, problems: warnings }); +} + +// What a row shows of its fresh check, and the card's outline for it. +function checkFields(item, fresh, runMs) { + if (!fresh) return { tag: "Not checked yet" }; + const entries = Object.entries(CHECK_TESTS).map(([key, name]) => ({ test: name, ...item.check.tests[key] })); + const pick = (verdict) => entries.filter((e) => e.verdict === verdict).map((e) => ({ test: e.test, reason: e.reason })); + const earlier = Number.isFinite(runMs) && Date.parse(item.check.checked) < runMs; + return { + check: { fails: pick("Fail"), doubts: pick("Doubt"), passed: entries.filter((e) => e.verdict === "Pass").length, ...(item.check.suggestion ? { suggestion: item.check.suggestion } : {}) }, + ...(earlier ? { tag: "Checked in an earlier run" } : {}), + }; +} + +const outlineOf = (check) => (check.fails.length ? "Drop" : check.passed === Object.keys(CHECK_TESTS).length ? "Keep" : null); + const CHOICES = { lesson: ["Keep", "Reword", "Drop"], area: ["Create", "Rename", "Drop"], doubt: ["Keep", "Reword", "Retire"], gone: ["Keep", "Reword", "Retire"], "agents-fix": ["Apply", "Reword", "Drop"], + tidy: ["Apply", "Reword", "Leave"], "log-line": ["Move", "Reword and move", "Leave in the log"], }; -const ROUND_ORDER = ["area", "lesson", "doubt", "gone", "agents-fix", "log-line"]; +const ROUND_ORDER = ["area", "lesson", "doubt", "gone", "agents-fix", "tidy", "log-line"]; const LOG_ORIGIN = "From the failure log in AGENTS.md."; // The first-ask card's words (FR-30), from "What a person is told". @@ -1648,6 +2336,7 @@ const GONE_PREFIX = "gone:"; function listable(w, loaded) { if (w.type === "lesson" || w.type === "area" || w.type === "agents-fix") return true; if (w.type === "doubt") return !!findLesson(loaded, w.target); + if (w.type === "tidy") return Array.isArray(w.targets) && w.targets.length > 0 && w.targets.every((id) => findLesson(loaded, id)); return false; } @@ -1722,6 +2411,47 @@ function fixItem(root, w, note) { }; } +// A tidy-up's choices: Reword only where there is a new wording to edit. +const tidyChoices = (change) => (change === "merge" || change === "reword" ? CHOICES.tidy : CHOICES.tidy.filter((c) => c !== "Reword")); + +/** + * A tidy-up as the list shows it: the change in words, its reason, the lessons + * it touches (`targets`), and, for a merge or reword, the new wording and its + * Why (`wording`, `wordingWhy`) that the card's Reword edits. + */ +function tidyRow(root, w, loaded, areaNames, note) { + const targets = w.targets.map((id) => { + const { entry, block } = findLesson(loaded, id); + return { id, text: block.heading, area: areaNameOf(entry) }; + }); + const own = w.change === "merge" || w.change === "reword"; + const { refused, flags } = checkAll(w.text, w.why, w.reason); + const words = refused ? masked(w.text) : w.text; + const reason = refused ? masked(w.reason) : w.reason; + let text; + if (w.change === "merge") text = `Merge ${targets.length} lessons into: ${words}`; + else if (w.change === "reword") text = `Reword to: ${words}`; + else if (w.change === "retire") text = `Retire: ${targets[0].text} Reason: ${reason}`; + else text = `Move to ${w.area}: ${targets[0].text}`; + const choices = tidyChoices(w.change); + return { + id: w.id, + type: "tidy", + change: w.change, + text, + why: w.change === "retire" ? "" : reason, + origin: "", + note, + flags, + refused, + area: w.area || (own ? targets[0].area : ""), + targets, + ...(own ? { wording: words, wordingWhy: refused ? masked(w.why || "") : w.why || "" } : {}), + areas: areaNames, + choices: refused ? choices.filter((c) => c !== "Apply") : choices, + }; +} + /** A failure log line as the list shows it, with the lessons it would become. */ function logItem(l) { const { refused, flags } = checkAll(l.text); @@ -1753,6 +2483,12 @@ function buildList(L, root, args) { const proposed = proposedAreas(waiting); const branch = safeBranch(root); const items = []; + // The areas a lesson may be saved in, for the card's Reword: General, every + // area file, and the areas waiting in this same list. + const areaNames = [...new Set(["General", ...areaList.map((a) => a.name), ...proposed.map((p) => p.name)].filter(Boolean))]; + // The run's check, when its id is passed: a verdict from before it is tagged as earlier. + const runMs = typeof args.check === "string" && CHECK_ID.test(args.check) ? parseInt(args.check.split("-")[0], 36) : NaN; + const fresh = new Map(); for (const w of waiting) { if (!listable(w, loaded)) continue; if (w.type === "area") { @@ -1763,6 +2499,12 @@ function buildList(L, root, args) { items.push(fixItem(root, w, branchNote(root, w, branch, null))); continue; } + if (w.type === "tidy") { + const isFresh = checkIsFresh(root, w); + if (isFresh) fresh.set(w.id, w); + items.push({ ...checkFields(w, isFresh, runMs), ...tidyRow(root, w, loaded, areaNames, branchNote(root, w, branch, null)) }); + continue; + } if (w.type === "doubt") { const saved = findLesson(loaded, w.target); const { refused } = checkAll(w.found); @@ -1772,7 +2514,10 @@ function buildList(L, root, args) { const about = Array.isArray(w.about) ? w.about : []; const { refused, flags } = checkAll(w.text, w.why); const seen = Array.isArray(w.seen) && w.seen.length ? w.seen : about; + const isFresh = checkIsFresh(root, w); + if (isFresh) fresh.set(w.id, w); items.push({ + ...checkFields(w, isFresh, runMs), id: w.id, type: "lesson", text: refused ? masked(w.text) : w.text, @@ -1781,10 +2526,11 @@ function buildList(L, root, args) { about, area: areaFor(root, w, areaList, proposed).name, origin: w.source === "inferred" ? `Seen in the code, in ${seen.join(", ")}.` : "You said this.", - note: branchNote(root, w, branch, about), + note: [branchNote(root, w, branch, about), !refused && isSaidNoWhy(w.why) ? NEEDS_WHY_NOTE : ""].filter(Boolean).join(" "), flags, refused, - choices: refused ? CHOICES.lesson.filter((c) => c !== "Keep") : CHOICES.lesson, + // A placeholder Why cannot be kept (decide refuses it), only reworded. + choices: refused || isSaidNoWhy(w.why) ? CHOICES.lesson.filter((c) => c !== "Keep") : CHOICES.lesson, }); } for (const g of goneItems(root, loaded, waiting)) items.push(savedItem(g, findLesson(loaded, g.target), { note: "" })); @@ -1794,16 +2540,14 @@ function buildList(L, root, args) { for (const l of lines) items.push(logItem(l)); } const opening = s.state !== "unknown" && onDefaultBranch(root) ? `You are on ${branch}: kept lessons will be uncommitted changes here.` : null; - // The areas a lesson may be saved in, for the card's Reword: General, every - // area file, and the areas waiting in this same list. - const areaNames = [...new Set(["General", ...areaList.map((a) => a.name), ...proposed.map((p) => p.name)].filter(Boolean))]; // What the card draws beyond the shared fields: the before and after of a fix, // the lessons a log line would become, what a doubt found, and where a lesson may go. const extra = (i) => { if (i.type === "agents-fix") return { file: i.file, before: i.before, after: i.after, ...(i.row ? { row: i.row } : {}) }; if (i.type === "log-line") return { lessons: (i.lessons || []).map((inc) => inc.text).filter(Boolean) }; if (i.type === "doubt" || i.type === "gone") return { heading: i.heading, ...(i.found ? { found: i.found } : {}), areas: areaNames }; - if (i.type === "lesson") return { kind: i.kind, about: i.about, areas: areaNames }; + if (i.type === "lesson") return { kind: i.kind, about: i.about, areas: areaNames, ...(i.check ? { check: i.check } : {}), ...(i.tag ? { tag: i.tag } : {}) }; + if (i.type === "tidy") return { change: i.change, targets: i.targets, areas: i.areas, ...(i.wording !== undefined ? { wording: i.wording, wordingWhy: i.wordingWhy } : {}), ...(i.check ? { check: i.check } : {}), ...(i.tag ? { tag: i.tag } : {}) }; return {}; }; const rows = items.map((i) => @@ -1822,6 +2566,26 @@ function buildList(L, root, args) { } : null; const rounds = ROUND_ORDER.map((type) => ({ type, choices: CHOICES[type], items: items.filter((i) => i.type === type) })).filter((r) => r.items.length); + if (card) { + // The outline: Drop where a test failed, Keep where all four passed, nothing for doubts only. + const suggested = {}; + for (const i of items) { + let pick = i.type === "lesson" && i.check && !i.refused ? outlineOf(i.check) : null; + if (pick && !i.choices.includes(pick)) pick = null; + // A tidy-up: Leave where a test failed, Apply where all four passed. + if (i.type === "tidy" && i.check && !i.refused) pick = { Drop: "Leave", Keep: "Apply" }[outlineOf(i.check)] || null; + if (pick) suggested[i.id] = pick; + } + if (Object.keys(suggested).length) card.suggested = suggested; + // The latest check: the items one record call stamped with the newest time. + const stamps = [...fresh.values()].map((w) => w.check); + const latest = stamps.reduce((a, c) => (!a || Date.parse(c.checked) > Date.parse(a.checked) ? c : a), null); + // The how-checked line speaks only for this run's check: a list without + // --check (nothing new to grade) never repeats an earlier run's numbers. + // A failure reason is one line of at most 200 characters, as the card takes it. + if (typeof args["check-failed"] === "string") card.checked = { failed: args["check-failed"].replace(/\s+/g, " ").trim().slice(0, 200) || "The check did not run." }; + else if (latest && typeof args.check === "string") card.checked = { how: latest.how, count: stamps.filter((c) => c.checked === latest.checked).length, seconds: latest.seconds }; + } const answer = { ok: true, state: s.state, active: s.active, items, opening, card, rounds }; // The first ask (FR-30): only while not set up, led by the newest waiting lesson. if (args["first-ask"] && s.state === "not-set-up") { @@ -1879,6 +2643,8 @@ export function closingLine(c, stillWaiting) { if (c.moved) parts.push(`moved ${c.moved} from the failure log`); if (c.created) parts.push(`created ${plural(c.created, "area", "areas")}`); if (c.dropped) parts.push(`dropped ${c.dropped}`); + if (c.tidied) parts.push(`tidied ${c.tidied}`); + if (c.left) parts.push(`left ${c.left} as ${c.left === 1 ? "it was" : "they were"}`); if (!parts.length) return `Nothing decided. ${stillWaiting} still waiting.`; const first = parts.join(", "); return `${first[0].toUpperCase()}${first.slice(1)}. ${stillWaiting} still waiting.`; @@ -1899,7 +2665,7 @@ function decideSaved(root, loaded, droppedAreas, item, d, today) { block.checked = today; const at = block.lines ? block.lines.findIndex((l) => /^- Noted:/.test(l)) : -1; if (at === -1 || !block.noted) block.lines = null; - else block.lines = block.lines.map((l, n) => (n === at ? `- Noted: ${block.noted}, checked ${today}` : l)); + else block.lines = block.lines.map((l, n) => (n === at ? `- Noted: ${block.noted}, checked ${today}${block.keptOverCheck ? `, ${KEPT_OVER_CHECK}` : ""}` : l)); entry.dirty = true; return { outcome: "kept", lesson: item.target, file: rel(root, entry.file) }; } @@ -1934,7 +2700,7 @@ function decideSaved(root, loaded, droppedAreas, item, d, today) { } else if (loaded.has(slug) && !droppedAreas.has(slug)) target = loaded.get(slug); else return { outcome: "invalid", problems: [{ field: "area", message: "No area by that name; name an existing area or General." }] }; } - const next = { heading: final.text.trim(), kind: final.kind, about: final.about, why: final.why.trim(), noted: block.noted, checked: today }; + const next = { heading: final.text.trim(), kind: final.kind, about: final.about, why: final.why.trim(), noted: block.noted, checked: today, ...(block.search ? { search: block.search } : {}) }; if (target === entry) { const r = replaceBlock(entry.area, item.target, next); if (r.duplicate) return { outcome: "duplicate", area: entry.area.name }; @@ -1949,6 +2715,93 @@ function decideSaved(root, loaded, droppedAreas, item, d, today) { return { outcome: "reworded", area: target.area.name, lesson: lessonId(target.slug, next.heading), file: rel(root, target.file) }; } +/** + * Apply a tidy-up decision to `loaded` (written by the caller). Leave changes + * nothing and settles it; Apply (or Reword, with a new text, why or area) + * merges, rewords, retires or moves the targets. A target that is gone since + * the proposal was noted makes it `outOfDate`. All or nothing: a refused or + * invalid result leaves `loaded` as it was. + */ +function decideTidy(root, loaded, droppedAreas, item, d, today) { + if (d.choice === "Leave") return { outcome: "left" }; + if (d.choice === "Reword" && item.change !== "merge" && item.change !== "reword") return { outcome: "invalid-choice", message: "Only a merge or a reword has a new wording to reword." }; + const targets = item.targets.map((id) => ({ id, saved: findLesson(loaded, id) })); + if (!targets.length || targets.some((t) => !t.saved)) return { outcome: "outOfDate" }; + const reword = d.choice === "Reword"; + if (item.change === "retire") { + const r = decideSaved(root, loaded, droppedAreas, { target: targets[0].id }, { choice: "Retire" }, today); + return r.outcome === "retired" ? { outcome: "applied", change: "retire", lesson: targets[0].id, file: r.file } : r; + } + if (item.change === "reword") { + const next = { choice: "Reword", text: reword && typeof d.text === "string" ? d.text : item.text, why: reword && typeof d.why === "string" ? d.why : item.why, kind: item.kind, about: item.about, ...(reword && typeof d.area === "string" && d.area.trim() ? { area: d.area } : {}) }; + const r = decideSaved(root, loaded, droppedAreas, { target: targets[0].id }, next, today); + return r.outcome === "reworded" ? { ...r, outcome: "applied", change: "reword" } : r; + } + const first = targets[0].saved; + const named = (reword && typeof d.area === "string" && d.area.trim() ? d.area : item.area) || ""; + if (item.change === "move") { + const block = first.block; + const piece = { text: block.heading, why: block.why || "", kind: block.kind, about: block.about, area: named, search: block.search, checked: block.checked, keptOverCheck: block.keptOverCheck }; + const r = placeLessons(root, loaded, droppedAreas, [piece], block.noted); + if (r.outcome !== "moved") return r; + // placeLessons inserted the copy; take out the old block (by position, as the copy may share its heading). + const at = first.entry.area.blocks.indexOf(block); + if (at === -1) return { outcome: "outOfDate" }; + first.entry.area.blocks.splice(at, 1); + first.entry.dirty = true; + if (!first.entry.area.blocks.length && first.entry.slug !== GENERAL) first.entry.remove = true; + return { outcome: "applied", change: "move", area: r.lessons[0].area, lesson: r.lessons[0].lesson, file: r.lessons[0].file }; + } + // A merge writes one block and removes the targets, the targets first so a full General has room; undo both on a problem. + const final = { + text: reword && typeof d.text === "string" ? d.text : item.text, + why: reword && typeof d.why === "string" ? d.why : item.why || "", + kind: item.kind, + about: Array.isArray(item.about) ? item.about : [], + }; + const fieldSecret = secretIn(final.about.filter((p) => typeof p === "string"), named); + if (fieldSecret) return { outcome: "refused", pattern: fieldSecret.pattern, part: fieldSecret.part }; + const problems = validateLesson(final, root); + if (problems.length) return { outcome: "invalid", problems }; + const { refused } = checkAll(final.text, final.why); + if (refused) return { outcome: "refused", pattern: refused.pattern, part: refused.part }; + let slug = first.entry.slug; + if (named) { + const s = slugOf(named); + if (s === GENERAL || (loaded.has(s) && !droppedAreas.has(s))) slug = s; + else return { outcome: "invalid", problems: [{ field: "area", message: "No area by that name; name an existing area or General." }] }; + } + let entry = loaded.get(slug); + if (!entry) { + entry = { slug, file: areaFilePath(root, slug), area: newArea(slug === GENERAL ? "General" : slug, []), existed: false, dirty: false }; + loaded.set(slug, entry); + } + const undo = new Map(); + for (const e of [entry, ...targets.map((t) => t.saved.entry)]) if (!undo.has(e)) undo.set(e, { blocks: [...e.area.blocks], dirty: e.dirty, remove: e.remove }); + for (const t of targets) { + removeBlock(t.saved.entry.area, t.id); + t.saved.entry.dirty = true; + } + const noted = targets.map((t) => t.saved.block.noted).find(Boolean) || `${today}, tidy`; + // The targets' search carries over when they hold exactly one between them (as a + // move and a reword keep theirs); the kept-over-the-check mark does not, since + // the merged wording is a new lesson, as after a Reword. + const searches = [...new Map(targets.filter((t) => t.saved.block.search).map((t) => [JSON.stringify(t.saved.block.search), t.saved.block.search])).values()]; + const block = { heading: final.text.trim(), kind: final.kind, about: final.about, why: final.why.trim(), noted, checked: null, ...(searches.length === 1 ? { search: searches[0] } : {}) }; + const r = insertBlock(entry.area, block, { general: slug === GENERAL }); + if (r.full || r.duplicate) { + for (const [e, was] of undo) { + e.area.blocks = was.blocks; + e.dirty = was.dirty; + e.remove = was.remove; + } + return { outcome: r.full ? "needsRoom" : "duplicate", area: r.full ? "General" : entry.area.name }; + } + entry.dirty = true; + for (const t of targets) if (!t.saved.entry.area.blocks.length && t.saved.entry.slug !== GENERAL) t.saved.entry.remove = true; + return { outcome: "applied", change: "merge", area: entry.area.name, lesson: lessonId(slug, block.heading), file: rel(root, entry.file) }; +} + function readDecisions(file) { const text = readText(file); if (text === null) fail(EXIT.NOT_FOUND, "no-file", `The decisions file ${file} was not found.`, "Write the person's choices to a JSON file and pass it with --file."); @@ -1983,6 +2836,8 @@ function placeLessons(root, loaded, droppedAreas, pieces, noted) { kind: typeof p.kind === "string" ? p.kind : "correction", about: Array.isArray(p.about) ? p.about : splitList(p.about), }; + // A lesson moved whole keeps its search and its marks. + const keep = { ...(p.search ? { search: p.search } : {}), ...(p.checked ? { checked: p.checked } : {}), ...(p.keptOverCheck ? { keptOverCheck: true } : {}) }; const named = typeof p.area === "string" ? p.area : ""; const fieldSecret = secretIn(final.about.filter((x) => typeof x === "string"), named); if (fieldSecret) return { outcome: "refused", pattern: fieldSecret.pattern, part: fieldSecret.part }; @@ -1990,7 +2845,7 @@ function placeLessons(root, loaded, droppedAreas, pieces, noted) { if (problems.length) return { outcome: "invalid", problems }; const { refused } = checkAll(final.text, final.why); if (refused) return { outcome: "refused", pattern: refused.pattern, part: refused.part }; - finals.push({ final, named }); + finals.push({ final, named, keep }); } const saved = new Map(); const created = []; @@ -2002,7 +2857,7 @@ function placeLessons(root, loaded, droppedAreas, pieces, noted) { for (const slug of created) loaded.delete(slug); }; const placed = []; - for (const { final, named } of finals) { + for (const { final, named, keep } of finals) { let slug; if (named && slugOf(named) === GENERAL) slug = GENERAL; else if (named && loaded.has(slugOf(named)) && !droppedAreas.has(slugOf(named))) slug = slugOf(named); @@ -2014,7 +2869,7 @@ function placeLessons(root, loaded, droppedAreas, pieces, noted) { created.push(slug); } if (!saved.has(entry)) saved.set(entry, { blocks: [...entry.area.blocks], dirty: entry.dirty }); - const block = { heading: final.text.trim(), kind: final.kind, about: final.about, why: final.why.trim(), noted, checked: null }; + const block = { heading: final.text.trim(), kind: final.kind, about: final.about, why: final.why.trim(), noted, checked: null, ...keep }; const r = insertBlock(entry.area, block, { general: slug === GENERAL }); if (r.full || r.duplicate) { restore(); @@ -2108,7 +2963,7 @@ async function cmdDecide(L, root, args) { const settledGone = new Set(); const droppedAreas = new Set(); const results = []; - const counts = { kept: 0, reworded: 0, retired: 0, applied: 0, moved: 0, created: 0, dropped: 0 }; + const counts = { kept: 0, reworded: 0, retired: 0, applied: 0, moved: 0, created: 0, dropped: 0, tidied: 0, left: 0 }; const today = isoDate(now()); // Waiting items go only after every file is written (below), so a failure @@ -2173,6 +3028,15 @@ async function cmdDecide(L, root, args) { results.push({ id: d.id, ...r }); continue; } + if (item.type === "tidy") { + const r = decideTidy(root, loaded, droppedAreas, item, d, today); + // Settled whatever cannot be retried: applied, left, or targets gone since it was noted. + if (r.outcome === "applied" || r.outcome === "left" || r.outcome === "outOfDate") drop(d.id); + if (r.outcome === "applied") counts.tidied++; + if (r.outcome === "left") counts.left++; + results.push({ id: d.id, ...r }); + continue; + } if (item.type === "agents-fix" && d.choice !== "Drop") { const reword = d.choice === "Reword"; if (item.row) { @@ -2306,6 +3170,7 @@ async function cmdDecide(L, root, args) { continue; } const problems = validateLesson(final, root); + if (isSaidNoWhy(final.why)) problems.push({ field: "why", message: "The Why is still the placeholder for a lesson noted with no reason; Reword it with why it matters." }); if (problems.length) { results.push({ id: d.id, outcome: "invalid", problems }); continue; @@ -2325,7 +3190,9 @@ async function cmdDecide(L, root, args) { entry = { slug: target.slug, file: areaFilePath(root, target.slug), area: newArea(target.slug === GENERAL ? "General" : target.slug, []), existed: false, dirty: false }; loaded.set(target.slug, entry); } - const block = { heading: final.text.trim(), kind: final.kind, about: final.about, why: final.why.trim(), noted: `${today}, ${skill}`, checked: null }; + // Keep or Reword over a check that found a Fail is recorded on the saved lesson. + const overCheck = checkIsFresh(root, item) && Object.values(item.check.tests).some((t) => t.verdict === "Fail"); + const block = { heading: final.text.trim(), kind: final.kind, about: final.about, why: final.why.trim(), noted: `${today}, ${skill}`, checked: null, ...(item.search ? { search: item.search } : {}), ...(overCheck ? { keptOverCheck: true } : {}) }; const r = insertBlock(entry.area, block, { general: target.slug === GENERAL }); if (r.full) { results.push({ id: d.id, outcome: "needsRoom", area: "General" }); @@ -2366,6 +3233,20 @@ async function cmdDecide(L, root, args) { out({ ok: true, state: s.state, active: s.active, written: written.sort(), stillWaiting, results, closing: closingLine(counts, stillWaiting), dryRun }); } +async function cmdFollow(L, root, args) { + if (typeof args.lesson !== "string" || !args.lesson.trim()) fail(EXIT.USAGE, "missing-value", "follow needs --lesson, the id of the lesson followed.", "Run: lessons.mjs follow --lesson --skill ."); + if (typeof args.skill !== "string" || !args.skill.trim() || /[\r\n]/.test(args.skill) || args.skill.trim().length > 40) fail(EXIT.USAGE, "missing-value", "follow needs --skill, the skill's name (one line, at most 40 characters).", "Add --skill , for example --skill implement."); + const s = stateOf(L, root); + if (!s.active) { + out({ ok: true, state: s.state, active: s.active, noted: false }); + return; + } + const saved = findLesson(loadAreas(root), args.lesson.trim()); + if (!saved) fail(EXIT.INVALID, "unknown-lesson", "No saved lesson has that id.", "Use an id read returned: lessons.mjs read.", { state: s.state, active: s.active }); + L.recordFollow(root, { lesson: lessonId(saved.entry.slug, saved.block.heading), skill: args.skill.trim() }, now()); + out({ ok: true, state: s.state, active: s.active, noted: true }); +} + const COMMANDS = { state: cmdState, switch: cmdSwitch, @@ -2374,17 +3255,21 @@ const COMMANDS = { check: cmdCheck, note: cmdNote, list: cmdList, + "check-input": cmdCheckInput, + "tidy-input": cmdTidyInput, + "check-record": cmdCheckRecord, decide: cmdDecide, "log-lines": cmdLogLines, areas: cmdAreas, report: cmdReport, + follow: cmdFollow, remove: cmdRemove, }; async function main(argv) { const args = parseArgs(argv, { - values: ["root", "type", "text", "why", "kind", "about", "source", "seen", "skill", "area", "name", "paths", "file", "run", "target", "found", "before", "after", "test-map-row"], - booleans: ["dry-run", "suggest", "first-ask", "from-banner", "all", "log-all", "confirm"], + values: ["root", "type", "text", "why", "kind", "about", "source", "seen", "skill", "area", "name", "paths", "file", "run", "lesson", "target", "found", "before", "after", "test-map-row", "shows-in", "match", "text-match", "check", "check-failed", "change", "targets", "reason"], + booleans: ["dry-run", "suggest", "first-ask", "from-banner", "all", "log-all", "confirm", "tidy"], }); const start = path.resolve(args.root || process.cwd()); const cmd = args._[0]; diff --git a/src/web-console/console-launches.md b/src/web-console/console-launches.md index 465b839..741a238 100644 --- a/src/web-console/console-launches.md +++ b/src/web-console/console-launches.md @@ -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 --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 --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 diff --git a/src/web-console/learning.mjs b/src/web-console/learning.mjs index d65e453..33ebcba 100644 --- a/src/web-console/learning.mjs +++ b/src/web-console/learning.mjs @@ -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":"/","at":"","skill":""}`. + * 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"); +} + +/** `{ : { 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), }; } diff --git a/src/web-console/patches.mjs b/src/web-console/patches.mjs index f8d3a2b..922eb8a 100644 --- a/src/web-console/patches.mjs +++ b/src/web-console/patches.mjs @@ -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 .", 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; diff --git a/src/web-console/public/answers.js b/src/web-console/public/answers.js index b0779c5..ba1f47a 100644 --- a/src/web-console/public/answers.js +++ b/src/web-console/public/answers.js @@ -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: ", "Reword: ", "Apply: ". */ 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 diff --git a/src/web-console/public/screens/cards.js b/src/web-console/public/screens/cards.js index af51a7d..ae6416f 100644 --- a/src/web-console/public/screens/cards.js +++ b/src/web-console/public/screens/cards.js @@ -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"; diff --git a/src/web-console/public/screens/dashboard.js b/src/web-console/public/screens/dashboard.js index b1de97b..9ba4d49 100644 --- a/src/web-console/public/screens/dashboard.js +++ b/src/web-console/public/screens/dashboard.js @@ -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", { diff --git a/src/web-console/public/screens/learning-row.js b/src/web-console/public/screens/learning-row.js index dfcf98c..833c075 100644 --- a/src/web-console/public/screens/learning-row.js +++ b/src/web-console/public/screens/learning-row.js @@ -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 `/` 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 { diff --git a/src/web-console/public/selectors.js b/src/web-console/public/selectors.js index 80244d2..c839e91 100644 --- a/src/web-console/public/selectors.js +++ b/src/web-console/public/selectors.js @@ -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; } diff --git a/src/web-console/public/styles/learning.css b/src/web-console/public/styles/learning.css index 5f07411..bc3efd7 100644 --- a/src/web-console/public/styles/learning.css +++ b/src/web-console/public/styles/learning.css @@ -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; diff --git a/src/web-console/routes.mjs b/src/web-console/routes.mjs index 543c244..edd1de1 100644 --- a/src/web-console/routes.mjs +++ b/src/web-console/routes.mjs @@ -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