From 1345aa0a95b24a0d898b3bd177076f44416f640e Mon Sep 17 00:00:00 2001 From: Justin Parker Date: Fri, 27 Nov 2026 23:19:42 -0800 Subject: [PATCH 1/8] 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 From d6a28b5dc86b41737b6aac823c8339cb3f9e68a8 Mon Sep 17 00:00:00 2001 From: Justin Parker Date: Sat, 28 Nov 2026 08:22:31 -0800 Subject: [PATCH 2/8] Release 3.2.0: check every waiting lesson before approval, and tidy up and count saved lessons AI Assisted --- CHANGELOG.md | 20 ++++++++++++++++++++ README.md | 2 +- package.json | 2 +- plan2code-app/Cargo.lock | 4 ++-- plan2code-app/fake-agent/Cargo.toml | 2 +- plan2code-app/package-lock.json | 4 ++-- plan2code-app/package.json | 2 +- plan2code-app/src-tauri/Cargo.toml | 2 +- plan2code-app/src-tauri/tauri.conf.json | 2 +- version.json | 4 ++-- 10 files changed, 32 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index be35199..307d67c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,26 @@ All notable changes to Plan2Code will be documented in this file. +## v3.2.0 (2026-11-28) + +### Highlights + +- Every waiting lesson is graded by a separate check (true, worth keeping, overlap, clear) before the lessons card asks you to approve it. +- Tidy up proposes merging, rewording, retiring or moving saved lessons when a file grows crowded. +- The lessons reader shows how often each lesson was followed, and every skill can now remember what you ask it to. + +### ✨ Added + +- **Learning**: before the lessons card asks for approval, a fresh read-only helper (or the same agent in a separate step) grades every waiting lesson on four tests; each row shows its Fails and Doubts with reasons, the card says who checked and how long it took, and a suggested wording can be taken with Use this wording. +- **Learning**: a Tidy up action (in the banner when lessons near their limit, and in the dashboard's menu) proposes merging, rewording, retiring or moving saved lessons, each graded by the same check before you decide. +- **Learning**: the lessons reader shows under each lesson how often it was followed and when last (recorded on this machine only). +- **Learning**: a lesson can carry a search (text that should always, or never, appear in some files), so the check and later reads test it against the code and raise a doubt when it stops agreeing. + +### 🔧 Changed + +- **Learning**: every skill that reads lessons now notes what you ask it to remember (asking why when you gave no reason); the read-only skills' lessons wait for the next lessons card or the dashboard's Review. +- **For contributors**: new lessons script and page tests cover the check, tidy-ups, follow counts and the near-limit nudge. + ## v3.1.5 (2026-11-23) ### 🐛 Fixed diff --git a/README.md b/README.md index 54c1a3c..6e8c356 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ Plan2Code is a spec-driven workflow for AI coding agents. You work through it on a page in your browser: the dashboard lists every step as a card, and each step's questions, progress and sign-offs arrive on that same page while your agent does the work. An approved plan becomes phase documents, and the agent builds to them one phase at a time. -Version 3.1.5 · Apache 2.0 · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com) +Version 3.2.0 · Apache 2.0 · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com) --- diff --git a/package.json b/package.json index 57c6fed..fd31e60 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "plan2code", - "version": "3.1.5", + "version": "3.2.0", "private": true, "license": "Apache-2.0", "engines": { diff --git a/plan2code-app/Cargo.lock b/plan2code-app/Cargo.lock index 08f5033..273b587 100644 --- a/plan2code-app/Cargo.lock +++ b/plan2code-app/Cargo.lock @@ -957,7 +957,7 @@ dependencies = [ [[package]] name = "fake-agent" -version = "3.1.5" +version = "3.2.0" dependencies = [ "serde_json", "terminal_size", @@ -2647,7 +2647,7 @@ checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" [[package]] name = "plan2code-app" -version = "3.1.5" +version = "3.2.0" dependencies = [ "chrono", "libc", diff --git a/plan2code-app/fake-agent/Cargo.toml b/plan2code-app/fake-agent/Cargo.toml index d60d2b4..611bf62 100644 --- a/plan2code-app/fake-agent/Cargo.toml +++ b/plan2code-app/fake-agent/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "fake-agent" -version = "3.1.5" +version = "3.2.0" description = "A stand-in agent program for the Plan2Code app's tests" edition = "2021" publish = false diff --git a/plan2code-app/package-lock.json b/plan2code-app/package-lock.json index f3bd11e..e30e5bc 100644 --- a/plan2code-app/package-lock.json +++ b/plan2code-app/package-lock.json @@ -1,12 +1,12 @@ { "name": "plan2code-app", - "version": "3.1.5", + "version": "3.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "plan2code-app", - "version": "3.1.5", + "version": "3.2.0", "dependencies": { "@tauri-apps/api": "2.12.4", "@xterm/addon-fit": "0.11.0", diff --git a/plan2code-app/package.json b/plan2code-app/package.json index e3d0667..c840c6c 100644 --- a/plan2code-app/package.json +++ b/plan2code-app/package.json @@ -1,6 +1,6 @@ { "name": "plan2code-app", - "version": "3.1.5", + "version": "3.2.0", "private": true, "description": "Plan2Code desktop app (Tauri). Separate from the repo root so the root and the web console stay dependency-free.", "scripts": { diff --git a/plan2code-app/src-tauri/Cargo.toml b/plan2code-app/src-tauri/Cargo.toml index f5b6e66..bf416de 100644 --- a/plan2code-app/src-tauri/Cargo.toml +++ b/plan2code-app/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "plan2code-app" -version = "3.1.5" +version = "3.2.0" description = "Plan2Code desktop app" edition = "2021" publish = false diff --git a/plan2code-app/src-tauri/tauri.conf.json b/plan2code-app/src-tauri/tauri.conf.json index ac56c51..cef87da 100644 --- a/plan2code-app/src-tauri/tauri.conf.json +++ b/plan2code-app/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Plan2Code", - "version": "3.1.5", + "version": "3.2.0", "identifier": "com.plan2code.desktop", "build": { "frontendDist": "../ui", diff --git a/version.json b/version.json index 826d4a9..bcc99e8 100644 --- a/version.json +++ b/version.json @@ -1,6 +1,6 @@ { "name": "Plan2Code", - "version": "3.1.5", + "version": "3.2.0", "description": "A structured workflow of six steps (Pathfinder, Plan, Document, Implement, Review, Finalize) for AI-assisted software development", "keywords": [ "ai", @@ -17,6 +17,6 @@ "url": "https://github.com/jparkerweb/plan2code" }, "homepage": "https://github.com/jparkerweb/plan2code", - "releaseDate": "2026-11-23", + "releaseDate": "2026-11-28", "mode": "utility" } From 57567d7a0b99494bae494ba7a235d19e783f9e36 Mon Sep 17 00:00:00 2001 From: Justin Parker Date: Sat, 28 Nov 2026 21:09:02 -0800 Subject: [PATCH 3/8] Add the Review Loop: unattended review-and-fix rounds in the desktop app and in loop phases AI Assisted --- .../AGENTS-architecture-console-page.md | 5 +- .agents-docs/AGENTS-architecture-console.md | 1 + .agents-docs/AGENTS-architecture-install.md | 8 +- .agents-docs/AGENTS-development-commands.md | 2 +- .agents-docs/AGENTS-test-map.md | 1 + .readme/web-console.md | 9 + AGENTS.md | 2 +- CHANGELOG.md | 11 +- docs/desktop-app.md | 52 + package.json | 2 +- plan2code-app/fake-agent/src/main.rs | 182 +- plan2code-app/src-tauri/src/agents.rs | 29 +- plan2code-app/src-tauri/src/lib.rs | 6 + plan2code-app/src-tauri/src/loop_driver.rs | 662 ++- plan2code-app/src-tauri/src/loop_report.rs | 49 + .../src-tauri/src/loop_shared/mod.rs | 16 + .../src-tauri/src/loop_shared/report_list.rs | 16 + .../src-tauri/src/loop_shared/retry.rs | 28 + .../src-tauri/src/loop_shared/rounds.rs | 110 + .../src-tauri/src/loop_shared/session.rs | 62 + .../src-tauri/src/loop_shared/watch.rs | 129 + plan2code-app/src-tauri/src/loop_tools.rs | 42 +- plan2code-app/src-tauri/src/main.rs | 215 +- plan2code-app/src-tauri/src/phase_rounds.rs | 631 +++ plan2code-app/src-tauri/src/review_loop.rs | 4868 +++++++++++++++++ plan2code-app/src-tauri/src/review_report.rs | 522 ++ plan2code-app/src-tauri/src/round_boundary.rs | 400 ++ plan2code-app/src-tauri/src/round_logic.rs | 675 +++ plan2code-app/ui/app.js | 104 +- plan2code-app/ui/meter.js | 46 +- scripts/test-agent-lookup.mjs | 7 + scripts/test-app-meter.mjs | 92 +- scripts/test-console-wire-budgets.mjs | 3 +- scripts/test-lanes.json | 2 + scripts/test-web-console-loop.mjs | 336 +- scripts/test-web-console-page-loop.mjs | 34 + scripts/test-web-console-page-review-loop.mjs | 421 ++ scripts/test-web-console-review-loop.mjs | 199 + scripts/test-web-console-server.mjs | 4 +- scripts/test-web-console-shape.mjs | 2 +- scripts/test-web-console-skills.mjs | 45 +- scripts/test-web-console-state.mjs | 4 + src/launcher/agents.json | 8 + src/plan2code-review.md | 2 +- src/shared-references/lessons.md | 2 +- src/web-console/agent-lookup.mjs | 7 +- src/web-console/cmd-open.mjs | 54 +- src/web-console/console.mjs | 2 +- src/web-console/loop-setup.mjs | 4 + src/web-console/notes/review-loop.md | 55 + src/web-console/notes/review.md | 2 + src/web-console/patches.mjs | 168 +- src/web-console/public/answers.js | 9 +- src/web-console/public/app-bridge.js | 28 +- src/web-console/public/app.js | 4 +- src/web-console/public/index.html | 3 + src/web-console/public/loop-parts.js | 262 + src/web-console/public/review-loop-end.js | 201 + src/web-console/public/screens/core.js | 14 +- src/web-console/public/screens/dashboard.js | 32 +- src/web-console/public/screens/ending.js | 2 + src/web-console/public/screens/help-dialog.js | 2 + src/web-console/public/screens/loop-setup.js | 260 +- .../public/screens/review-loop-setup.js | 433 ++ src/web-console/public/skills.js | 31 +- src/web-console/public/state.js | 8 + src/web-console/public/styles/dashboard.css | 9 + src/web-console/review-loop-setup.mjs | 96 + src/web-console/routes.mjs | 38 + src/web-console/sessions.mjs | 1 + src/web-console/static.mjs | 3 + 71 files changed, 11331 insertions(+), 443 deletions(-) create mode 100644 plan2code-app/src-tauri/src/loop_shared/mod.rs create mode 100644 plan2code-app/src-tauri/src/loop_shared/report_list.rs create mode 100644 plan2code-app/src-tauri/src/loop_shared/retry.rs create mode 100644 plan2code-app/src-tauri/src/loop_shared/rounds.rs create mode 100644 plan2code-app/src-tauri/src/loop_shared/session.rs create mode 100644 plan2code-app/src-tauri/src/loop_shared/watch.rs create mode 100644 plan2code-app/src-tauri/src/phase_rounds.rs create mode 100644 plan2code-app/src-tauri/src/review_loop.rs create mode 100644 plan2code-app/src-tauri/src/review_report.rs create mode 100644 plan2code-app/src-tauri/src/round_boundary.rs create mode 100644 plan2code-app/src-tauri/src/round_logic.rs create mode 100644 scripts/test-web-console-page-review-loop.mjs create mode 100644 scripts/test-web-console-review-loop.mjs create mode 100644 src/web-console/notes/review-loop.md create mode 100644 src/web-console/public/loop-parts.js create mode 100644 src/web-console/public/review-loop-end.js create mode 100644 src/web-console/public/screens/review-loop-setup.js create mode 100644 src/web-console/review-loop-setup.mjs diff --git a/.agents-docs/AGENTS-architecture-console-page.md b/.agents-docs/AGENTS-architecture-console-page.md index 1622e9a..e394ec7 100644 --- a/.agents-docs/AGENTS-architecture-console-page.md +++ b/.agents-docs/AGENTS-architecture-console-page.md @@ -13,6 +13,7 @@ One row per file under `src/web-console/public/` (the games and their sound are | `public/diff-parse.js` | the Changes tab's parser: the unified diff `changes.mjs diff` writes, read into files, hunks and numbered lines; never throws | | `public/diff-view.js` | the Changes tab: a `diff` doc block drawn as a file list and one unified diff, with its empty, loading and error states (Check again and Reload send `__changes`) | | `public/hops.js` | no imports: the hop rule, `startsClean(from, to)`, which says whether a hop from one workflow to another starts the new skill on a clean page (to or from the dashboard, into Git, or from one skill into another off a finished screen, but never out of Git or into Review); shared by `cmd-open.mjs`, `server.mjs` (its Ask reset) and `screens/core.js` | +| `public/loop-parts.js` | what the two loop setup screens share so neither imports the other (the shape test forbids it): the field builders (`field`, `toggle`, `radios`, `select`), the strength words, the notification fields with their checks (`notifyFields`, `notifyProblem`, `kindForUrl`) and the silence input. | | `public/looks.js` | how the page looks and sounds: the saved looks, their sync, and the preferences dialog's swatches | | `public/mention-box.js` | the @name suggestions popover under a text box | | `public/net.js` | the page talking to its own server | @@ -32,7 +33,9 @@ One row per file under `src/web-console/public/` (the games and their sound are | `public/screens/core.js` | the core every screen sits inside: connection, the render loop, the page chrome and Send; the only file that imports the screens, and only `app.js` imports it | | `public/screens/dashboard.js` | the dashboard: cards, the spec picker, handoff chips, delete, the first-open wake-up, and Learning's waiting banner (`learningBanner()`: the line from `learningBannerText()` and a **Review** button sending `__learning` `review`, last of the banners), which places Learning's row through `hooks.renderLearningRow` | | `public/screens/learning-row.js` | Learning's row on the dashboard (`renderLearningRow(scan, position)`): four states in two places (under the picker while not set up, off or paused; after the last card group while on), Pause for me posting `/learning/pause` with no agent, More, Open the lessons and the Remove confirm, plus `renderLessonsDialog()`, the Lessons to review dialog that draws an open `lessons` card over the menu; the agent-run controls send `__learning` through `hooks.sendLearning` and gray out under `learningBlocked()` | -| `public/screens/loop-setup.js` | the Implementation Loop's setup screen on the dashboard (app only): the fields, their defaults and read-only facts, the Start checks, and the request to the app. The **Strength per phase** field (`strengthField`) is a grid: four headed columns (Match my session, Thrifty, Balanced, Best; level 0 to 3) and one `radiogroup` row per phase left, one radio per column (`#loop-strength--`, `match` for Match my session; an unmapped word's radio is disabled and its header says "(not mapped)"), the cell's dot (`strengthBars`) over the hidden radio, and the model the pick becomes at the row's end. **Set all to** stays a select (`#loop-strength-all`, blank again after use). **Suggest for me** (`#loop-strength-suggest`, right of it) sends a no-hop `__loopSuggest` (`id`, `spec`, `phases`, the mapped `strengths`) to the dashboard agent and grays the field under `.loop-suggest-overlay` (`.is-suggesting`, `aria-busy`); the agent posts `loopSuggest` (`{ id, spec, picks: [{ n, strength, why }] }`, checked by `loopSuggestProblems` in `patches.mjs`), and the page applies only the answer whose `id` and `spec` match its own request, mapped words only, with each `why` as a `.loop-strength-why` line that a hand change or Set all to clears; `SUGGEST_WAIT_MS` (two minutes) gives the field back with a note when nobody answers. The dashboard skill answers it under "A strength suggestion arrives". `drawStrengthLine(grid)` draws the grid's SVG from the checked nodes' measured positions, never from state: a very light dashed `line.col` per column and a thick square-step `path.step` from each row's node to the next (one path fewer than rows, none under two rows or with the toggle off). It redraws on the window's resize, a `ResizeObserver` on the grid (Preferences' page width), fonts loading and every redraw of the section, and stops once the grid is gone. The colors are the `--lvl-0` to `--lvl-3` tokens (`--lvl-0` is the neutral gray of Match my session); tests wait for the drawn state before reading the line. The page locks while `state.loop.driving` is set (`loopDriving()` in `selectors.js`) until the app posts `loopEnd`; Activities, Notebook, Help and Preferences stay usable. `loopEnd.can` accepts `ask` (`LOOP_CAN` in `patches.mjs`); the app adds it first to every stop that offers `resume`, and the stopped screen's **Ask a question** wakes an ordinary agent on the same session | +| `public/screens/review-loop-setup.js` | the Review Loop's setup screen on the dashboard (app only): scope, round cap, commit and the pre-run commit tick, Suggestions, strength, silence, notify (the lifted `notifyFields` and `silenceField` of `loop-setup.js`), the hands-off and reviewer lines, the Start checks, and the `review-loop-start` request to the app. | +| `public/review-loop-end.js` | how a Review Loop run ends (`renderLoopEnd` hands a `loopEnd` with `kind: "review"` to `renderReviewLoopEnd`): a heading by `reason` (Clean, Stopped at the round cap, Stopped by you, Failed) with `line`, the `report` doc behind Read the full report, after Stop now (`partial`) the partial diff drawn by `diff-view.js` with Keep and Discard (`review-loop-partial`), Continue ("Run one more round" at the cap) only when `canContinue` and no `partial` (`review-loop-continue`), the Suggestions pick (nothing ticked) and the squash switch (only when `canSquash`, off) kept in module state per ending, and Sign off (`review-loop-sign-off` with `picks` and `squash`, always on offer); once `signedOff`, the finished screen: PR Prep and Fix what's left by hand (hidden when `open` is empty) send `review-loop-next` (`pr-prep` or `quick-task`), Back to the dashboard sends `loop-dashboard`. The app's answers land in `page.reviewAction` (`wireLoopMessages`) and show under the card; a pressed button stays disabled until the ending changes or an answer carries an error | +| `public/screens/loop-setup.js` | the Implementation Loop's setup screen on the dashboard (app only): the fields, their defaults and read-only facts, the Start checks, and the request to the app. The **Strength per phase** field (`strengthField`) is a grid: four headed columns (Match my session, Thrifty, Balanced, Best; level 0 to 3) and one `radiogroup` row per phase left, one radio per column (`#loop-strength--`, `match` for Match my session; an unmapped word's radio is disabled and its header says "(not mapped)"), the cell's dot (`strengthBars`) over the hidden radio, and the model the pick becomes at the row's end. **Set all to** stays a select (`#loop-strength-all`, blank again after use). **Suggest for me** (`#loop-strength-suggest`, right of it) sends a no-hop `__loopSuggest` (`id`, `spec`, `phases`, the mapped `strengths`) to the dashboard agent and grays the field under `.loop-suggest-overlay` (`.is-suggesting`, `aria-busy`); the agent posts `loopSuggest` (`{ id, spec, picks: [{ n, strength, why }] }`, checked by `loopSuggestProblems` in `patches.mjs`), and the page applies only the answer whose `id` and `spec` match its own request, mapped words only, with each `why` as a `.loop-strength-why` line that a hand change or Set all to clears; `SUGGEST_WAIT_MS` (two minutes) gives the field back with a note when nobody answers. The dashboard skill answers it under "A strength suggestion arrives". `drawStrengthLine(grid)` draws the grid's SVG from the checked nodes' measured positions, never from state: a very light dashed `line.col` per column and a thick square-step `path.step` from each row's node to the next (one path fewer than rows, none under two rows or with the toggle off). It redraws on the window's resize, a `ResizeObserver` on the grid (Preferences' page width), fonts loading and every redraw of the section, and stops once the grid is gone. The colors are the `--lvl-0` to `--lvl-3` tokens (`--lvl-0` is the neutral gray of Match my session); tests wait for the drawn state before reading the line. The page locks while `state.loop.driving` is set (`loopDriving()` in `selectors.js`) until the app posts `loopEnd`; Activities, Notebook, Help and Preferences stay usable. `loopEnd` takes a third `kind`, `"review"` (the Review Loop's end, `reviewLoopEndProblems` in `patches.mjs`: `reason`, `report`, `canContinue`, `canSquash`, optional `partial`, `suggestions`, `open`, `signedOff`, `note`; `report` and `partial.diff` name docs on the page, no `phases` or `uncommitted` needed); `loopEnd.can` accepts `ask` (`LOOP_CAN` in `patches.mjs`); the app adds it first to every stop that offers `resume`, and the stopped screen's **Ask a question** wakes an ordinary agent on the same session | | `public/screens/docs.js` | documents: tabs, blocks, print and download, and the brief button | | `public/screens/ending.js` | how a session ends: the finished screen, its offers, Stop and the way home; a Diagnose finish whose `doc` is saved shows that file whole as a Bug report box with Copy report (the raw Markdown), above Next step | | `public/screens/git-host.js` | hosts the git board: the tools fold-out (`board.tools`, saved with the board), tabs, panels and what each click sends | diff --git a/.agents-docs/AGENTS-architecture-console.md b/.agents-docs/AGENTS-architecture-console.md index 39c44ae..2e24192 100644 --- a/.agents-docs/AGENTS-architecture-console.md +++ b/.agents-docs/AGENTS-architecture-console.md @@ -16,6 +16,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web | `cmd-open.mjs` | the `open` command: start or resume a session, its server and the browser; refuses a `--workflow` that `isWorkflow()` does not know (exit 2, naming the valid ones), and asks `startsClean()` (`public/hops.js`) whether a resume blanks the page | | `in-app.mjs` | the desktop app's signal to `open`: `inAppSignal()` reads `PLAN2CODE_IN_APP`, `PLAN2CODE_CONSOLE_SID`, `PLAN2CODE_APP_ANNOUNCE` and `PLAN2CODE_APP_TOKEN`; `announcePage()` POSTs the page to that window's loopback endpoint. Under the app `open` never starts a browser, resumes the app's session and announces the page; with the variables unset nothing here runs. Imported by `cmd-open.mjs` | | `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 | +| `review-loop-setup.mjs` | the Review Loop's setup, remembered per project in `~/.plan2code/console/review-loop-setup.json` (one entry per folded project folder, schema 1; a protected file Cleanup never offers): defaults, validation and the read and write the `/review-loop-setup` route uses. Its notify address and kind come from the loop setup, never from here | | `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`, `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`) | diff --git a/.agents-docs/AGENTS-architecture-install.md b/.agents-docs/AGENTS-architecture-install.md index 6a41f50..af67391 100644 --- a/.agents-docs/AGENTS-architecture-install.md +++ b/.agents-docs/AGENTS-architecture-install.md @@ -119,6 +119,12 @@ plan2code/ | `plan2code-app/src-tauri/src/loop_notify.rs` | The loop's notification: `NotifyKind` (query string, JSON body, Discord, Slack, Teams, Google Chat; its comment lists what a new service needs), `valid_url()`, `valid_param()` (mirrored in `loop-setup.mjs` and `screens/loop-setup.js`), `request_for()` (each kind's address and body) and `send()`, with a 10 second limit and errors that never hold the address. The driver writes the message and calls it from `observe()`, `stop_loop()` and `finish()`. | | `plan2code-app/src-tauri/src/loop_report.rs` | The loop's report on everything done for the person: one `LoopReport` per build, entries in order (passed, stopped, retried) with findings fixed, skipped and left open, assumptions read from the phase file, and reported decisions. Saved in the console's `loop-reports.json` after every entry, because a project file would dirty the tree Resume needs clean; `finish()` writes it to `LOOP-SUMMARY-.md` and removes the entry. | | `plan2code-app/src-tauri/src/loop_tools.rs` | What the loop runs on its own, each call with a time limit and its output kept: the spec scripts (`specs.mjs status`, `mark --to done`), `commit-msg.mjs`, git (`add`, `commit`, `status`, the short head), the console's `post` and `open --resume`, and the person's quick check. No shell runs here except the quick check, whose text comes only from `loop-setup.json`, never from a page message | +| `plan2code-app/src-tauri/src/loop_shared/` | What both loop drivers share, moved out of `loop_driver.rs` with its behavior unchanged: `session.rs` (`start_session` with the launch strength, `read_session_state`), `watch.rs` (`watch_loop`, the 2 s tick under `catch_unwind`, and `silence_expired`), `retry.rs` (`should_retry`, `next_strength_word`), `report_list.rs` (`load_reports`, `save_report` over `loop_report`), `rounds.rs` (finding a round's `roundOutcome` on its page, `proofs_for`, report text, the fixer's `reviewer_brief`) and `notify` in `mod.rs` | +| `plan2code-app/src-tauri/src/round_logic.rs` | The Review Loop's pure rules, with their tests: `RoundOutcome` (the console's `roundOutcome`), `judge_round` (clean needs the report doc, targeted tests that ran and passed, and no Critical or Warning; a fixer is judged with at least its reviewer's counts through `hold_reviewer_counts`), `next_step` (round, retry, Suggestions batch, final check or stop), `round_detail` and the round commit subject | +| `plan2code-app/src-tauri/src/round_boundary.rs` | Where a round starts and ends: a full commit id in commit mode, a temp-index `write-tree` snapshot otherwise, the diff between two boundaries into `round-N.diff`, and the `cat-file -e` check that fails a round loudly when a snapshot is gone | +| `plan2code-app/src-tauri/src/review_loop.rs` | The Review Loop's driver: the pre-run commit, one session per round (or a reviewer then a fixer for an agent without `helpers`), retry a strength up, commit or snapshot per round, Stop after this round, Stop now with Keep or Discard, Continue (one round at a time past the cap, never above 6), the Suggestions batch and final check, the `loop-state` banner (`kind: "rounds"`, `afterRounds` after the rounds), the end post, sign-off and squash (never the pre-run commit; refused when anything else landed on top). `open_findings()` carries every round's unfixed findings until a later round fixes them | +| `plan2code-app/src-tauri/src/review_report.rs` | The Review Loop's report markdown: setup, stop reason and evidence, one section per round and batch, Still open (from `open_findings()`), Suggestions and the sign-off; written to the report list and, for a spec scope, `REVIEW-LOOP-.md` | +| `plan2code-app/src-tauri/src/phase_rounds.rs` | Extra review rounds inside an Implementation Loop phase (`reviewRounds` in the loop setup): after a phase agent reports Critical or Warning left, fresh rounds review the phase diff (the first fixer briefed with the phase's unfixed findings) before the phase is judged and committed once. It keeps its own watch and retry (a recorded deviation) | | `plan2code-app/src-tauri/src/agents.rs` | Agents in the app: `CustomAgent`, the `Agent` handle over built-ins and custom entries, `load_custom_agents`, reading the Agents file below; the shipped `agents.json` read at run time with the baked copy as fallback; `find_on_path`, the Rust twin of `agent-lookup.mjs`'s `findAgent` (PATH, PATHEXT, the saved PATH from `node_check::resolved_path()`, npm's global folder, the install folders), held to `scripts/fixtures/agent-lookup-cases.json`. The console side is `src/web-console/agents.mjs` | | Desktop app install (`install.js`) | `installDesktopApp()` downloads `plan2code-app---[.exe]` and `plan2code-app--SHA256SUMS.txt` from the GitHub release (`PLAN2CODE_RELEASE_BASE` replaces the URL; the tests serve a stand-in), checks the SHA-256 and places the file in `~/.plan2code/app/` (the old file is renamed aside first, since Windows cannot overwrite a running exe). `app` is an install piece (`INSTALL_PIECES`, after `launcher`), so `plan2code update` updates it with the rest. `install()` asks for it after the command (default yes; a no is kept as `skipped` in `install.json`); unattended it installs it unless it is already recorded or was declined. A failed app never fails the install. `.github/workflows/release-app.yml` builds one file per system (`tauri build --no-bundle`) and the checksum list on a published release, after `scripts/check-versions.mjs --tag` | @@ -130,7 +136,7 @@ Install and update follow release tags, never `main`. `release-app.yml`'s `publi `~/.plan2code/agents.json` holds the person's custom agent CLIs. The web console is its only writer (User Preferences → Agents & models, through `POST /agents`); the `plan2code` launcher and the desktop app only read it. Each reader carries its own copy of the rules (`src/web-console/agents.mjs` for the console, a copy in `src/launcher/plan2code.js`, `agents.rs` in the app), and `scripts/fixtures/agents-cases.json` is the contract all three readers' tests load: file normalization with its warnings, `buildArgs` command lines and `makeId` ids. Change a rule in the fixture first. -`src/launcher/agents.json` is the shipped list: `kind: "builtin"` entries (Claude Code, Devin, Codex) with `installUrl`, per-OS `install` lines and `installDirs`, and `kind: "template"` entries other CLIs can be saved from. `install.js` copies it to `~/.plan2code/bin/agents.json` beside `agent-lookup.mjs`, which all JS readers share: `loadAgentList()` reads it, `findAgent()` gives a command its `found` / `outside` / `missing` state (PATH, the saved Windows PATH, npm's global bin, the entry's `installDirs`). The app reads the same JSON with `serde_json` at run time (`include_str!` of the repo file baked in as fallback) and `find_on_path` in `agents.rs` is its Rust twin: `scripts/fixtures/agent-lookup-cases.json`, loaded by `scripts/test-agent-lookup.mjs` and by `cargo test` through `include_str!`, is the contract both lookups are held to. +`src/launcher/agents.json` is the shipped list: `kind: "builtin"` entries (Claude Code, Devin, Codex) with `installUrl`, per-OS `install` lines and `installDirs`, and `kind: "template"` entries other CLIs can be saved from. Each entry may carry `helpers` beside `bypassArgs`: the agent can start a subagent from inside a session (`true` for Claude Code, `false` for every other built-in and template); missing means it cannot. `loadAgentList()` and the app's `AgentEntry` both read it as a boolean, so a custom agent without it reads `false`. `install.js` copies it to `~/.plan2code/bin/agents.json` beside `agent-lookup.mjs`, which all JS readers share: `loadAgentList()` reads it, `findAgent()` gives a command its `found` / `outside` / `missing` state (PATH, the saved Windows PATH, npm's global bin, the entry's `installDirs`). The app reads the same JSON with `serde_json` at run time (`include_str!` of the repo file baked in as fallback) and `find_on_path` in `agents.rs` is its Rust twin: `scripts/fixtures/agent-lookup-cases.json`, loaded by `scripts/test-agent-lookup.mjs` and by `cargo test` through `include_str!`, is the contract both lookups are held to. - **File:** `{ "schema": 1, "agents": [...] }`. Any other schema, text that is not JSON, or `agents` that is not a list gives no custom agents and one warning. A missing file is an empty list with no warning. More than 50 entries: the first 50 are used. Unknown keys, in the file and in an entry, are kept when the console saves. - **Entry:** `id`, `name` and `command` are required; `args` (default `[]`), `prompt` (default `"/plan2code"`, blank allowed), `bypassArgs` (`[]`), `modelArgs` (`["--model", "{model}"]`) and `models` (`[]`, each `{ id, label? }`) are optional. The three argument fields are lists of text, one list item per argument. diff --git a/.agents-docs/AGENTS-development-commands.md b/.agents-docs/AGENTS-development-commands.md index 6b14c98..f32d699 100644 --- a/.agents-docs/AGENTS-development-commands.md +++ b/.agents-docs/AGENTS-development-commands.md @@ -92,7 +92,7 @@ The same areas as one-command rows live in the [Test map](./AGENTS-test-map.md), | An Activities game (`public/activities/*`), `public/tones.js` or `public/music.js` | `node --test scripts/test-web-console-tones.mjs scripts/test-web-console-activities.mjs`, plus the game's own `scripts/test-web-console-activities-*.mjs` when it has one; add `test-web-console-page-activities.mjs` when the Activities window or its switches changed | | Page styles (`public/styles/*.css`) or `public/index.html` | `npm run test:page -- scripts/test-web-console-page-layout.mjs`, plus the page file of a screen whose own look changed (`test:page` unsets the app variables, takes `--test-name-pattern`, and is the way to run any page file) | | A music prototype (`prototypes/music//`) | `node prototypes/music/check.cjs ` (nothing in `npm test` reads `prototypes/`) | -| One web console area (server routes, chat, git board, workspace, notepad, Implementation Loop...) | that area's `scripts/test-web-console-.mjs` (the loop's is `test-web-console-loop.mjs`), and its `test-web-console-page-.mjs` when the page changed; `node scripts/parse-check.mjs` after editing any browser module under `public/` | +| One web console area (server routes, chat, git board, workspace, notepad, Implementation Loop...) | that area's `scripts/test-web-console-.mjs` (the loop's is `test-web-console-loop.mjs`, the Review Loop's `test-web-console-review-loop.mjs` with `test-web-console-page-review-loop.mjs`), and its `test-web-console-page-.mjs` when the page changed; `node scripts/parse-check.mjs` after editing any browser module under `public/` | | The launcher (`src/launcher/`) | `node --test scripts/test-launcher.mjs` | | A skill's script | `npm run build:skills`, then `node --test scripts/test-script-.mjs` (and `test-skill-scripts.mjs` for the shared plumbing) | | Dead Code (`src/plan2code-dead-code-scripts/`, `scripts/fixtures/dead-code/`) | `npm run build:skills`, then `node scripts/node-test.mjs scripts/test-script-dead-code.mjs` | diff --git a/.agents-docs/AGENTS-test-map.md b/.agents-docs/AGENTS-test-map.md index fe72691..eaaed8a 100644 --- a/.agents-docs/AGENTS-test-map.md +++ b/.agents-docs/AGENTS-test-map.md @@ -14,6 +14,7 @@ Which checks cover which files, read by PR Prep and Test (`test-map.mjs read` ch | Lessons script | `src/skill-scripts/lessons.mjs`, `src/web-console/learning.mjs` | `npm run build:skills && node scripts/node-test.mjs scripts/test-script-lessons.mjs` | no | | Changes tab and script | `src/skill-scripts/changes.mjs`, `src/web-console/public/diff-parse.js`, `src/web-console/public/diff-view.js`, `src/web-console/public/styles/diff.css` | `npm run build:skills && node scripts/node-test.mjs scripts/test-script-changes.mjs scripts/test-web-console-diff-parse.mjs scripts/test-web-console-page-changes.mjs` | no | | Learning on the console | `src/web-console/learning.mjs`, `src/web-console/public/screens/learning-row.js`, `src/web-console/public/styles/learning.css` | `node scripts/node-test.mjs scripts/test-web-console-learning.mjs scripts/test-web-console-page-learning.mjs` | no | +| Review Loop on the console | `src/web-console/review-loop-setup.mjs`, `src/web-console/notes/review-loop.md`, `src/web-console/public/screens/review-loop-setup.js`, `src/web-console/public/loop-parts.js`, `src/web-console/public/review-loop-end.js` | `node scripts/node-test.mjs scripts/test-web-console-review-loop.mjs scripts/test-web-console-loop.mjs && npm run test:page -- scripts/test-web-console-page-review-loop.mjs` | no | | Workflow prompts | `src/plan2code-*.md` | `node scripts/validate-char-count.js && node scripts/check-skill-table.mjs` | no | | Desktop app | `plan2code-app/**` | `cd plan2code-app && cargo test` | no | | Metrics | `plan2code-metrics/**` | `cd plan2code-metrics && npm test` | no | diff --git a/.readme/web-console.md b/.readme/web-console.md index 1af8874..d00fa03 100644 --- a/.readme/web-console.md +++ b/.readme/web-console.md @@ -479,6 +479,15 @@ stopped, its actions sit beside a **Back to the dashboard** button that opens a fresh dashboard in the frame, no agent needed, and its status line marks it as your move rather than leaving a stale "starting" line behind. +Review rounds per phase (default 2): when a phase's own review leaves Critical or Warning, fresh reviewers run up to this many more rounds before the phase is committed. + +The **Review Loop** card, also app only, sits beside the Implementation Loop's: it reviews and fixes a +finished change in rounds while you are away (round 1 the whole change, each later round only the last +round's fixes, a fresh reviewer every time), stops on a clean round, the round cap, your stop or a failure, +and ends on its own screen with the report, **Continue**, the Suggestions pick, an optional squash, **PR +Prep**, **Fix what's left by hand** and **Back to the dashboard**. The desktop app's guide covers it under +"Review Loop". + A stopped loop also offers **Ask a question**, first in the row. The app ended its agent when the loop stopped, so the Ask tab says no agent is available; the button wakes an ordinary agent on the same page, without starting the loop diff --git a/AGENTS.md b/AGENTS.md index 3b5e7b6..8ed33da 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,7 +36,7 @@ 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 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). +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`), the app-only **Review Loop** (a card beside it, `screens/review-loop-setup.js`, the setup remembered in `~/.plan2code/console/review-loop-setup.json` owned by `review-loop-setup.mjs`; the app's `review_loop.rs` drives review-and-fix rounds, each a Review session opened with `--loop --round N --role` that reports a `roundOutcome` per `notes/review-loop.md`; its end screen is `public/review-loop-end.js`), 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`. diff --git a/CHANGELOG.md b/CHANGELOG.md index 307d67c..4db3c30 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,12 +8,16 @@ All notable changes to Plan2Code will be documented in this file. ### Highlights -- Every waiting lesson is graded by a separate check (true, worth keeping, overlap, clear) before the lessons card asks you to approve it. -- Tidy up proposes merging, rewording, retiring or moving saved lessons when a file grows crowded. +- The desktop app gains a Review Loop: unattended review-and-fix rounds on a finished change, a fresh reviewer every round, until a clean round, the round cap or your stop; Implementation Loop phases can run the same extra rounds. +- Every waiting lesson is graded by a separate check (true, worth keeping, overlap, clear) before the lessons card asks you to approve it, and Tidy up proposes merging, rewording, retiring or moving saved lessons when a file grows crowded. - The lessons reader shows how often each lesson was followed, and every skill can now remember what you ask it to. ### ✨ Added +- **Desktop app**: a Review Loop card (app only) and setup: review the branch, uncommitted changes or a spec's work, with a round cap (3, up to 6), a commit per round (and an optional commit of your own work first), Suggestions on their own, strength, silence and notifications. +- **Desktop app**: round 1 reviews the whole change and each later round only the last round's fixes; the app counts a round clean only with the reviewer's report, tests that ran and passed, and no Critical or Warning, and an agent that cannot start its own reviewer gets a separate reviewer and fixer session. +- **Desktop app**: the Review Loop's banner shows a dot per round with its counts, the Suggestions batch and final check by name, Stop after this round, and Stop now with Keep or Discard for the unfinished round. +- **Desktop app**: the Review Loop ends on one report (also saved as `REVIEW-LOOP-.md` for a spec's work) listing every finding still open, with Continue one round at a time up to 6, the Suggestions pick, an optional squash of the round commits, PR Prep and Fix what's left by hand. - **Learning**: before the lessons card asks for approval, a fresh read-only helper (or the same agent in a separate step) grades every waiting lesson on four tests; each row shows its Fails and Doubts with reasons, the card says who checked and how long it took, and a suggested wording can be taken with Use this wording. - **Learning**: a Tidy up action (in the banner when lessons near their limit, and in the dashboard's menu) proposes merging, rewording, retiring or moving saved lessons, each graded by the same check before you decide. - **Learning**: the lessons reader shows under each lesson how often it was followed and when last (recorded on this machine only). @@ -21,7 +25,10 @@ All notable changes to Plan2Code will be documented in this file. ### 🔧 Changed +- **Implementation Loop**: a new Review rounds per phase setting (default 2): when a phase's own review leaves a Critical or a Warning, fresh reviewers run up to that many more rounds on the phase's diff before it is judged, so existing loops now run these rounds unless it is set to 0. +- **Agents**: the agent list marks which agents can start their own subagents (`helpers`), which picks the Review Loop's round shape. - **Learning**: every skill that reads lessons now notes what you ask it to remember (asking why when you gave no reason); the read-only skills' lessons wait for the next lessons card or the dashboard's Review. +- **For contributors**: the loop machinery both drivers use moved into `loop_shared/`, with new round, boundary and Review Loop driver tests and console and page suites. - **For contributors**: new lessons script and page tests cover the check, tidy-ups, follow counts and the near-limit nudge. ## v3.1.5 (2026-11-23) diff --git a/docs/desktop-app.md b/docs/desktop-app.md index c02ccd8..633ed7d 100644 --- a/docs/desktop-app.md +++ b/docs/desktop-app.md @@ -165,6 +165,7 @@ not), so your own edits never end up inside a phase's commit. **The setup.** The fields and their defaults: - **Review each phase** (on): a fresh agent reviews the phase before it counts. +- **Review rounds per phase** (2, from 0 to 6, only with Review on): when a phase's own review leaves a Critical or a Warning, fresh reviewers run up to this many more rounds on the phase's diff before it is judged. The phase is still committed once. - **Fix findings**: **Smart pick** (the default) has a fresh agent read the findings and fix only the ones worth fixing, recording every skip. A skipped Critical stops the phase. **By level** fixes the Critical, Warning and Suggestion findings you tick (all three start ticked). @@ -268,6 +269,57 @@ the same day). After a stop, **Read why, and the report so far** shows it on the is unfinished it lives in `~/.plan2code/console/loop-reports.json`, not the project, because Continue building needs a clean tree. The in-app **Help** has a matching topic, **Implementation Loop**, which the loop card links to as "How the loop works". +## Review Loop + +The Review Loop reviews and fixes a finished change for you, round after round, while you do something +else. Like the Implementation Loop it is in the app only: the dashboard shows a **Review Loop** card beside +the Implementation Loop's, grayed out while either loop runs (one loop per window). + +**How rounds work.** Round 1 reviews everything you chose. Every later round reviews only what the round +before it changed, so the work shrinks as it goes. Each round's reviewer is a fresh one that never saw the +code being written. An agent that can start its own reviewer runs the round in one session; any other agent +gets two, a reviewer and then a separate fixer. Each round fixes Critical and Warning findings, runs the +tests for what it touched, and is committed (or, with commits off, snapshotted) before the next begins. The +app, not the agent, decides whether a round was clean: it needs the reviewer's report, tests that ran and +passed, and no Critical or Warning left. + +**The setup.** The fields and their defaults: + +- **What to review**: **Branch against main, with uncommitted changes** (everything the branch changed), + **Uncommitted changes only**, or **A spec's work** (the files the chosen spec's phases built). +- **Round cap** (3, from 1 to 6): the run stops after this many rounds. +- **Commit each round to the current branch** (on). With uncommitted changes in the tree, tick **Commit my + current changes first as Work before Review Loop** so your own work stays out of round 1's commit. It + never pushes. +- **Suggestions**: **Apply Suggestions on their own** (off) lists them in the report for you to pick; on, they + are applied in one last pass after the rounds, followed by a final check. +- **Strength for every round**, as in the Implementation Loop. A retried round goes one step up for that + round only. +- **If a round goes quiet** (20 minutes): a stuck round is retried once. +- **Send a notification**: the same address as the Implementation Loop's, plus **Also tell me when each + round finishes** (off). + +The setup is remembered per project in `~/.plan2code/console/review-loop-setup.json`. Please do not edit the +project's files while rounds run: anything changed goes into the round. + +**Watching and stopping.** The banner across the top shows a dot per round, with each finished round's +counts on hover, the current step, the time so far and any retries; the Suggestions batch and the final check +are named as such. **Stop after this round** lets the round finish, be judged and committed; **Stop now** +ends the agent at once and then asks whether to **Keep** or **Discard** what the unfinished round changed. + +**When it ends.** The run stops on a clean round, at the round cap, when you stop it, or on a failure it +cannot repair (a second crash, failing tests, a refused commit). The end screen says which, and **Read the +full report** shows every round: what it found, fixed and left, its tests and its commit, plus any +findings still open, including ones an earlier round could not fix. From there: + +- **Continue** runs one more round from where it stopped, one at a time past the cap, never above 6 in all. +- Pick the Suggestions you want applied, and, when every round was committed and nothing else landed on top, + turn on **Squash the round commits into one** (off; your pre-run commit is never touched). +- **Sign off** finishes the run, with or without picks. For a spec's work the report is also saved as + `specs//REVIEW-LOOP-.md`. +- Then **PR Prep**, or **Fix what's left by hand** (a Quick task with the open findings), or back to the + dashboard. + ## Keep it up to date `plan2code update` brings the skills, the `plan2code` command and the app up together. diff --git a/package.json b/package.json index fd31e60..7eabd37 100644 --- a/package.json +++ b/package.json @@ -18,7 +18,7 @@ "pretest": "node scripts/fix-line-endings.mjs", "test:fast": "node scripts/test-fast.mjs", "test:page": "node scripts/run-page-tests.mjs", - "test": "node scripts/check-test-lanes.mjs && node scripts/validate-char-count.js && node install.js --build-skills && node scripts/check-versions.mjs && node scripts/check-doc-size.mjs && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/check-prompt-wording.mjs && node scripts/check-console-openings.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-test-map.mjs scripts/test-script-lessons.mjs scripts/test-script-test-match.mjs scripts/test-script-test-commands.mjs scripts/test-script-run-check.mjs scripts/test-script-pr-prep.mjs scripts/test-script-dead-code.mjs scripts/test-script-deps.mjs scripts/test-script-ui-prototype.mjs scripts/test-script-coverage.mjs scripts/test-script-changelog.mjs scripts/test-script-changes.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-pointers.mjs scripts/test-web-console-learning.mjs scripts/test-console-wire-budgets.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-diff-parse.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-agents-doc.mjs scripts/test-web-console-prototypes.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities-flock.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-lantern.mjs scripts/test-web-console-activities-ghoul-marrow.mjs scripts/test-web-console-activities-ghoul-mat.mjs scripts/test-web-console-activities-ghoul-eye.mjs scripts/test-web-console-activities-ghoul-bonestair.mjs scripts/test-web-console-activities-ghoul-heart.mjs scripts/test-web-console-activities-ghoul-ending.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-banister.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-tray.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-intro.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-story.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-activities-bounce-arcade.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-card-rows.mjs scripts/test-spec-carry.mjs scripts/test-spec-carry-page.mjs scripts/test-web-console-state.mjs scripts/test-web-console-send-state.mjs scripts/test-web-console-strengths.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-skill-test-runs.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-agent-lookup.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-changes.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-layout.mjs scripts/test-web-console-page-learning.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-activities.mjs scripts/test-web-console-page-setup.mjs scripts/test-ui-prototype-page.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs scripts/test-check-test-lanes.mjs scripts/test-check-doc-size.mjs scripts/test-set-version.mjs scripts/test-console-stub.mjs scripts/test-check-prompt-wording.mjs scripts/test-check-console-openings.mjs" + "test": "node scripts/check-test-lanes.mjs && node scripts/validate-char-count.js && node install.js --build-skills && node scripts/check-versions.mjs && node scripts/check-doc-size.mjs && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/check-prompt-wording.mjs && node scripts/check-console-openings.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-test-map.mjs scripts/test-script-lessons.mjs scripts/test-script-test-match.mjs scripts/test-script-test-commands.mjs scripts/test-script-run-check.mjs scripts/test-script-pr-prep.mjs scripts/test-script-dead-code.mjs scripts/test-script-deps.mjs scripts/test-script-ui-prototype.mjs scripts/test-script-coverage.mjs scripts/test-script-changelog.mjs scripts/test-script-changes.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-pointers.mjs scripts/test-web-console-learning.mjs scripts/test-console-wire-budgets.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-review-loop.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-diff-parse.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-agents-doc.mjs scripts/test-web-console-prototypes.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities-flock.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-lantern.mjs scripts/test-web-console-activities-ghoul-marrow.mjs scripts/test-web-console-activities-ghoul-mat.mjs scripts/test-web-console-activities-ghoul-eye.mjs scripts/test-web-console-activities-ghoul-bonestair.mjs scripts/test-web-console-activities-ghoul-heart.mjs scripts/test-web-console-activities-ghoul-ending.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-banister.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-tray.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-intro.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-story.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-activities-bounce-arcade.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-card-rows.mjs scripts/test-spec-carry.mjs scripts/test-spec-carry-page.mjs scripts/test-web-console-state.mjs scripts/test-web-console-send-state.mjs scripts/test-web-console-strengths.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-skill-test-runs.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-agent-lookup.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-changes.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-layout.mjs scripts/test-web-console-page-learning.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-review-loop.mjs scripts/test-web-console-page-activities.mjs scripts/test-web-console-page-setup.mjs scripts/test-ui-prototype-page.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs scripts/test-check-test-lanes.mjs scripts/test-check-doc-size.mjs scripts/test-set-version.mjs scripts/test-console-stub.mjs scripts/test-check-prompt-wording.mjs scripts/test-check-console-openings.mjs" }, "devDependencies": { "gpt-tokenizer": "2.9.0", diff --git a/plan2code-app/fake-agent/src/main.rs b/plan2code-app/fake-agent/src/main.rs index 46ab410..de35895 100644 --- a/plan2code-app/fake-agent/src/main.rs +++ b/plan2code-app/fake-agent/src/main.rs @@ -10,6 +10,13 @@ //! REPORT write as `loopOutcome` into the session's state.json //! (PLAN2CODE_CONSOLE_HOME and PLAN2CODE_CONSOLE_SID name it), say //! `REPORT written` (`REPORT unavailable` when either is missing) +//! ROUND write as `roundOutcome` the same way; when it names a +//! `report` id, first add that doc (`kind: report`) to `docs`. +//! Says `ROUND written` (`ROUND unavailable` when it cannot) +//! FILE write to under the working directory (`\n` +//! in the text is a line break), for a round's "fixes". Says +//! `FILE written ` (`FILE refused ` for a path that +//! leaves the folder) //! ENV print the variable as `ENV =` //! HANG say `HANGING`, then go silent for good (no more lines read) //! echoed back as `echo: ` @@ -43,6 +50,10 @@ pub enum Command { Env(String), /// `REPORT `: the phase report the loop waits for, as the JSON text. Report(String), + /// `ROUND `: a Review Loop round's report, as the JSON text. + Round(String), + /// `FILE `: a file the agent "fixed", relative to its folder. + File(String, String), /// `HANG`: go silent, to model an agent that stops answering. Hang, Echo(String), @@ -65,6 +76,47 @@ fn write_report_to(home: &std::path::Path, sid: &str, json: &str) -> bool { let Ok(outcome) = serde_json::from_str::(json) else { return false; }; + update_state(home, sid, |state| state["loopOutcome"] = outcome) +} + +/// Write the JSON as the `roundOutcome` of the session named by the environment. +fn write_round(json: &str) -> bool { + let (Ok(home), Ok(sid)) = ( + std::env::var("PLAN2CODE_CONSOLE_HOME"), + std::env::var("PLAN2CODE_CONSOLE_SID"), + ) else { + return false; + }; + write_round_to(std::path::Path::new(&home), &sid, json) +} + +/// `write_round` with the session named. A named `report` is added to `docs` +/// first, as the console would hold it, so the app finds the doc it checks for. +fn write_round_to(home: &std::path::Path, sid: &str, json: &str) -> bool { + let Ok(outcome) = serde_json::from_str::(json) else { + return false; + }; + update_state(home, sid, |state| { + if let Some(report) = outcome.get("report").and_then(|value| value.as_str()) { + let doc = + serde_json::json!({ "id": report, "kind": "report", "title": "Review round" }); + match state.get_mut("docs").and_then(|docs| docs.as_array_mut()) { + Some(docs) => docs.push(doc), + None => state["docs"] = serde_json::json!([doc]), + } + } + state["roundOutcome"] = outcome; + }) +} + +/// Read `/sessions//state.json` (a new object when it is missing or +/// not one), let `change` edit it, and write it back through a temp file and a +/// rename, so a reader never sees half a file. +fn update_state( + home: &std::path::Path, + sid: &str, + change: impl FnOnce(&mut serde_json::Value), +) -> bool { let dir = home.join("sessions").join(sid); let file = dir.join("state.json"); let mut state = std::fs::read_to_string(&file) @@ -73,7 +125,7 @@ fn write_report_to(home: &std::path::Path, sid: &str, json: &str) -> bool { .filter(|value| value.is_object()) // The console's own file always carries its schema number; a new one does too. .unwrap_or_else(|| serde_json::json!({ "schema": 1 })); - state["loopOutcome"] = outcome; + change(&mut state); let _ = std::fs::create_dir_all(&dir); let temp = dir.join("state.json.tmp"); let Ok(text) = serde_json::to_string(&state) else { @@ -109,12 +161,45 @@ pub fn parse(line: &str) -> Command { return Command::Report(json.to_string()); } } + if let Some(rest) = line.strip_prefix("ROUND ") { + let json = rest.trim(); + if serde_json::from_str::(json).is_ok() { + return Command::Round(json.to_string()); + } + } + if let Some(rest) = line.strip_prefix("FILE ") { + let rest = rest.trim_start(); + if let Some((path, text)) = rest.split_once(char::is_whitespace) { + return Command::File(path.to_string(), text.trim_start().to_string()); + } + } if line == "HANG" { return Command::Hang; } Command::Echo(line.to_string()) } +/// Write `text` to `relative` under the working directory. Refuses a path that +/// is absolute or climbs out of it. `\n` in `text` becomes a line break. +fn write_file(relative: &str, text: &str) -> bool { + use std::path::{Component, Path}; + let path = Path::new(relative); + let inside = !relative.is_empty() + && path + .components() + .all(|part| matches!(part, Component::Normal(_) | Component::CurDir)); + if !inside { + return false; + } + if let Some(parent) = path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + { + let _ = std::fs::create_dir_all(parent); + } + std::fs::write(path, text.replace("\\n", "\n")).is_ok() +} + fn main() { say("FAKE-AGENT ready"); // What the app launched it with: the launch prompt is one of these, so a @@ -169,6 +254,20 @@ fn main() { say("REPORT unavailable") } } + Command::Round(json) => { + if write_round(&json) { + say("ROUND written") + } else { + say("ROUND unavailable") + } + } + Command::File(path, text) => { + if write_file(&path, &text) { + say(&format!("FILE written {path}")) + } else { + say(&format!("FILE refused {path}")) + } + } Command::Hang => { say("HANGING"); loop { @@ -230,6 +329,87 @@ mod tests { let _ = std::fs::remove_dir_all(&home); } + #[test] + fn parses_round_and_file() { + assert_eq!( + parse("ROUND {\"round\":1}"), + Command::Round("{\"round\":1}".into()) + ); + assert_eq!(parse("ROUND {nope"), Command::Echo("ROUND {nope".into())); + assert_eq!( + parse("FILE src/a.rs fixed it\\nline two"), + Command::File("src/a.rs".into(), "fixed it\\nline two".into()) + ); + assert_eq!( + parse("FILE onlypath"), + Command::Echo("FILE onlypath".into()) + ); + } + + #[test] + fn a_round_lands_with_its_report_doc_beside_what_was_there() { + let home = std::env::temp_dir().join(format!("fake-agent-round-{}", std::process::id())); + let dir = home.join("sessions").join("s5"); + std::fs::create_dir_all(&dir).unwrap(); + let read = || -> serde_json::Value { + serde_json::from_str(&std::fs::read_to_string(dir.join("state.json")).unwrap()).unwrap() + }; + // A report id adds the doc to a state that had none. + assert!(write_round_to( + &home, + "s5", + "{\"round\":1,\"role\":\"both\",\"report\":\"rep\"}" + )); + let state = read(); + assert_eq!(state["roundOutcome"]["round"], 1); + assert_eq!(state["docs"][0]["id"], "rep"); + assert_eq!(state["docs"][0]["kind"], "report"); + assert_eq!(state["docs"][0]["title"], "Review round"); + assert_eq!(state["schema"], 1); + // Existing docs stay, and the new one is appended. + std::fs::write( + dir.join("state.json"), + "{\"schema\":1,\"docs\":[{\"id\":\"phasefile\"}]}", + ) + .unwrap(); + assert!(write_round_to( + &home, + "s5", + "{\"round\":2,\"report\":\"r2\"}" + )); + let state = read(); + assert_eq!(state["docs"][0]["id"], "phasefile"); + assert_eq!(state["docs"][1]["id"], "r2"); + // No report id, no doc; a fixer's outcome adds none. + std::fs::write(dir.join("state.json"), "{\"schema\":1}").unwrap(); + assert!(write_round_to( + &home, + "s5", + "{\"round\":3,\"role\":\"fixer\"}" + )); + let state = read(); + assert!(state.get("docs").is_none()); + assert_eq!(state["roundOutcome"]["role"], "fixer"); + // The loop's own report key is untouched by a round. + assert!(state.get("loopOutcome").is_none()); + assert!(!write_round_to(&home, "s5", "not json")); + let _ = std::fs::remove_dir_all(&home); + } + + #[test] + fn a_file_command_writes_under_the_working_folder_only() { + let base = format!("fake-agent-file-{}", std::process::id()); + assert!(write_file(&format!("{base}/sub/a.txt"), "one\\ntwo")); + assert_eq!( + std::fs::read_to_string(format!("{base}/sub/a.txt")).unwrap(), + "one\ntwo" + ); + let _ = std::fs::remove_dir_all(&base); + assert!(!write_file("../escape.txt", "x")); + assert!(!write_file("/abs.txt", "x")); + assert!(!write_file("", "x")); + } + #[test] fn a_report_with_bad_json_is_an_echo() { assert_eq!( diff --git a/plan2code-app/src-tauri/src/agents.rs b/plan2code-app/src-tauri/src/agents.rs index 060d3f1..052689b 100644 --- a/plan2code-app/src-tauri/src/agents.rs +++ b/plan2code-app/src-tauri/src/agents.rs @@ -78,6 +78,10 @@ pub struct AgentEntry { pub args: Vec, #[serde(default)] pub bypass_args: Vec, + /// The agent can start a subagent from inside a session. Missing means it + /// cannot, so a custom agent without the key reads `false`. + #[serde(default)] + pub helpers: bool, #[serde(default)] pub model_args: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1678,6 +1682,21 @@ mod tests { .all(|e| !e.command.is_empty() && !e.args.is_empty())); } + #[test] + fn helpers_is_true_for_claude_and_false_for_everything_else() { + // The Review Loop picks its round shape from this flag: one session + // with a reviewer subagent, or a reviewer session then a fixer one. + let list = parse_agent_list(BAKED_AGENTS).expect("the baked list parses"); + for e in list.builtins.iter().chain(list.templates.iter()) { + assert_eq!(e.helpers, e.id == "claude", "helpers for {}", e.id); + } + // An entry without the key reads false. + let text = + r#"{"schema":1,"agents":[{"id":"x","name":"X","kind":"template","command":"x"}]}"#; + let list = parse_agent_list(text).expect("parses"); + assert!(!list.templates[0].helpers); + } + #[test] fn the_list_loader_rejects_a_bad_file_and_reads_the_installed_path() { // Not JSON, not an object, or the wrong schema is an error: the @@ -1809,6 +1828,7 @@ mod tests { prompt: String::new(), args: vec![], bypass_args: vec![], + helpers: false, model_args: vec![], install_url: None, install: PerOs::default(), @@ -1985,10 +2005,11 @@ mod tests { let dir = temp_dir("find"); let file = dir.join("agents.json"); std::fs::write(&file, GOOSE).unwrap(); - assert_eq!( - find_agent_in("claude", Some(&file)), - Some(Agent::Builtin(entry("claude"))) - ); + // A built-in wins over the file. Only its identity is compared: the list the + // lookup reads is the installed one, which a machine may still hold from before + // a field was added, so a whole-entry comparison depended on that machine. + let found = find_agent_in("claude", Some(&file)); + assert!(matches!(&found, Some(Agent::Builtin(e)) if e.id == entry("claude").id)); let goose = find_agent_in("goose", Some(&file)).unwrap(); assert_eq!( ( diff --git a/plan2code-app/src-tauri/src/lib.rs b/plan2code-app/src-tauri/src/lib.rs index fb18fea..adf28ca 100644 --- a/plan2code-app/src-tauri/src/lib.rs +++ b/plan2code-app/src-tauri/src/lib.rs @@ -11,13 +11,19 @@ pub mod loop_commit; pub mod loop_driver; pub mod loop_notify; pub mod loop_report; +pub mod loop_shared; pub mod loop_tools; pub mod models; pub mod node_check; +pub mod phase_rounds; pub mod project; pub mod pty_host; pub mod quit_prompt; pub mod restart_brief; +pub mod review_loop; +pub mod review_report; +pub mod round_boundary; +pub mod round_logic; pub mod session_reader; pub mod settings; #[cfg(windows)] diff --git a/plan2code-app/src-tauri/src/loop_driver.rs b/plan2code-app/src-tauri/src/loop_driver.rs index 3f91184..fcafa7f 100644 --- a/plan2code-app/src-tauri/src/loop_driver.rs +++ b/plan2code-app/src-tauri/src/loop_driver.rs @@ -27,8 +27,18 @@ use crate::console_supervisor::find_console_dir; use crate::loop_commit; use crate::loop_notify::{self, NotifyKind}; use crate::loop_report::{self, EntryResult, LoopReport, ReportEntry}; +use crate::loop_shared::notify as notify_call; +use crate::loop_shared::report_list::{load_reports, save_report}; +use crate::loop_shared::retry::{next_strength_word, should_retry}; +use crate::loop_shared::session::{read_session_state, start_session, Ctx}; +use crate::loop_shared::watch::{ + silence_expired, watch_loop, WatchStep, ACTIVITY_EVERY, WATCH_EVERY, +}; use crate::loop_tools; use crate::models::{self, StrengthRow}; +use crate::phase_rounds; +use crate::round_boundary::{self, Boundary}; +use crate::round_logic::Role; use crate::session_reader::{self, ReadError}; // ---------------------------------------------------------------- the setup @@ -132,6 +142,9 @@ pub struct PhasePick { #[serde(rename_all = "camelCase", default)] pub struct LoopSetup { pub review: bool, + /// Extra fresh review rounds a phase gets while its own review leaves a + /// Critical or Warning (0 turns them off). Read through `extra_rounds()`. + pub review_rounds: u32, // An entry saved before this field existed fixed by level, so it keeps // doing that (FixMode's own default) rather than taking the new setup's. #[serde(default)] @@ -163,6 +176,7 @@ impl Default for LoopSetup { fn default() -> Self { LoopSetup { review: true, + review_rounds: MAX_REVIEW_ROUNDS_DEFAULT, fix_mode: FixMode::Smart, fix: vec![FixLevel::Critical, FixLevel::Warning, FixLevel::Suggestion], commit: true, @@ -181,7 +195,21 @@ impl Default for LoopSetup { } } +/// The Review rounds per phase a setup without the field takes. +const MAX_REVIEW_ROUNDS_DEFAULT: u32 = 2; +/// The most Review rounds per phase the setup allows. +const MAX_REVIEW_ROUNDS: u32 = 6; + impl LoopSetup { + /// The extra review rounds a phase may run: none with Review off, at most 6. + pub fn extra_rounds(&self) -> u32 { + if self.review { + self.review_rounds.min(MAX_REVIEW_ROUNDS) + } else { + 0 + } + } + /// The levels whose leftovers matter: every level in Smart pick. fn chosen_levels(&self) -> Vec { if !self.review { @@ -412,6 +440,28 @@ pub struct RunningRecord { /// not yet locked by the agent's `open --loop`: adopted on a later look /// once its state shows the lock (`note_page`). pub page_candidate: Option, + /// The banner's step while a phase's extra review rounds run ("Review round + /// 1 of 2"); it replaces the step's own label and is cleared by `set_step`. + pub step_text: Option, + /// The extra round session the phase is waiting on, so `note_page` can hand + /// it the page that session announces. + pub round_wait: Option, + /// The working tree as the phase began (a snapshot), kept only when the + /// setup allows extra review rounds: the first round reviews the diff from it. + pub phase_start: Option, + /// The extra review rounds the current phase has run, for its report entry. + pub phase_rounds: Vec, +} + +/// An extra review round session a phase is waiting on. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RoundWait { + pub round: u32, + pub role: Role, + /// The adopted page's session id. + pub sid: Option, + /// A page announced before it showed the agent's lock, adopted once it does. + pub candidate: Option, } /// What one phase runs on, for its start, the strip and the report. @@ -496,6 +546,10 @@ impl RunningRecord { launch_effort: None, phase_baseline: None, page_candidate: None, + step_text: None, + round_wait: None, + phase_start: None, + phase_rounds: Vec::new(), } } @@ -531,7 +585,7 @@ impl RunningRecord { return; }; let Some(word) = phase.strength else { return }; - if let Some(next) = models::next_strength(&self.strength_rows, word.word()) + if let Some(next) = next_strength_word(&self.strength_rows, word.word()) .and_then(|w| Strength::from_word(&w)) { phase.strength = Some(next); @@ -567,6 +621,25 @@ pub struct LoopStateEvent { /// The model and effort the phase runs on, when known. pub model: Option, pub effort: Option, + /// `"phases"` for the Implementation Loop, `"rounds"` for the Review Loop. + pub kind: &'static str, + /// A Review Loop's current round and its cap (0 for the phases kind). + pub round: u32, + pub rounds: u32, + /// Critical and Warning per finished round (empty for the phases kind). + pub round_counts: Vec, + /// Stop after this round is on (a Review Loop). + pub stop_after_round: bool, + /// What a Review Loop runs after its rounds ("Suggestions batch" or + /// "Final check"), empty while a round runs and for the phases kind. + pub after_rounds: &'static str, +} + +/// What one finished Review Loop round found, for the banner's dots. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +pub struct RoundCount { + pub critical: u32, + pub warning: u32, } impl LoopStateEvent { @@ -590,6 +663,12 @@ impl LoopStateEvent { strength: None, model: None, effort: None, + kind: "phases", + round: 0, + rounds: 0, + round_counts: Vec::new(), + stop_after_round: false, + after_rounds: "", } } } @@ -615,7 +694,10 @@ pub fn state_event(rec: &RunningRecord) -> LoopStateEvent { previous_phase: previous.map(|p| p.n), previous_committed: previous.is_some_and(|p| p.commit.is_some()), phase_retried: current.is_some_and(|p| p.retries > 0), - step: rec.step.label().to_string(), + step: rec + .step_text + .clone() + .unwrap_or_else(|| rec.step.label().to_string()), started_at_ms: rec.started_at_ms, retries_used: rec.retries_used, stop_after_phase: rec.stop_after_phase, @@ -627,6 +709,12 @@ pub fn state_event(rec: &RunningRecord) -> LoopStateEvent { .map(|w| w.word().to_string()), model: run.as_ref().and_then(|r| r.model.clone()), effort: run.as_ref().and_then(|r| r.effort.clone()), + kind: "phases", + round: 0, + rounds: 0, + round_counts: Vec::new(), + stop_after_round: false, + after_rounds: "", } } @@ -663,7 +751,7 @@ pub enum Verdict { /// A poisoned mutex is still taken: the watcher catches its own panics (see /// `watch_with`), and a panic inside a lock poisons it, so the stop that /// follows must still be able to clear the slot. -fn lock(m: &Mutex) -> MutexGuard<'_, T> { +pub(crate) fn lock(m: &Mutex) -> MutexGuard<'_, T> { m.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) } @@ -909,28 +997,6 @@ pub fn judge_outcome(outcome: &Outcome, phase_status: &Value, setup: &LoopSetup) Verdict::Approve { warnings } } -/// Whether the agent has been quiet too long. A waiting question never counts -/// (the person may take all night). The limit is the setup's silence minutes -/// or the skill's own `quietMinutes`, whichever is longer, at most 60. -pub fn silence_expired( - now: SystemTime, - last_activity: SystemTime, - setup: &LoopSetup, - quiet_minutes: Option, - waiting: bool, -) -> bool { - if waiting { - return false; - } - let minutes = setup - .silence_minutes - .max(quiet_minutes.unwrap_or(0)) - .min(60); - let limit = Duration::from_secs(u64::from(minutes) * 60); - now.duration_since(last_activity) - .is_ok_and(|quiet| quiet > limit) -} - /// Why a loop ended. #[derive(Clone, Debug, PartialEq, Eq)] pub enum StopCause { @@ -953,17 +1019,6 @@ pub enum StopCause { WatcherFailed(String), } -/// One fresh retry for a crash, silence or an announce notice that never came -/// (a crash), when the setup allows it and the phase has not used it yet. A -/// failed watcher is never retried. -pub fn should_retry(cause: &StopCause, setup: &LoopSetup, retries_used_this_phase: u32) -> bool { - matches!( - cause, - StopCause::Crash | StopCause::Silence | StopCause::NoSession - ) && setup.retry_once - && retries_used_this_phase == 0 -} - /// Whether the session state holds a question for the person: an item still /// open or reopened, required, not handled by the loop and not just a notice. pub fn open_question(state: &Value) -> bool { @@ -1172,7 +1227,7 @@ pub fn prepare( validate_spec(project, spec)?; let setup = read_setup(project)?; let report = session_reader::console_home() - .and_then(|home| loop_report::load(&home, project, spec)) + .and_then(|home| load_reports(&home, project, spec)) .unwrap_or_default(); prepare_with(project, spec, setup, &report, mode, prompt_ok, resuming) } @@ -1266,7 +1321,7 @@ pub fn prepare_with( rec.rebuilt = rebuilt; rec.resumed_files = resumed_files; rec.branch = branch; - rec.start_head = loop_tools::git_head_full(project); + rec.start_head = loop_tools::git_head_full(project).ok(); // On a resumed run this holds the stopped phase's work too, by design: it // is listed as the person's own, the known limit of a baseline. rec.own_dirty = own_dirty; @@ -1289,7 +1344,7 @@ fn phase_pick(setup: &LoopSetup, spec: &str, n: u32, name: &str) -> Option BTreeMap { +pub fn strength_rows_for(agent: &Agent) -> BTreeMap { let models: Vec = match agent { Agent::Builtin(entry) => models::models_for_builtin(&entry.id), Agent::Custom(custom) => custom.models.clone(), @@ -1670,7 +1725,7 @@ fn notify(setup: &LoopSetup, message: &str) -> Option { if setup.notify_url.is_empty() { return None; } - loop_notify::send( + notify_call( setup.notify_kind, &setup.notify_url, &setup.notify_param, @@ -1697,25 +1752,9 @@ pub struct Hooks { pub attention: Box, } -/// What the watch thread needs, shared by every step of one loop. -#[derive(Clone)] -struct Ctx { - slot: LoopSlot, - agent: Arc, - console_dir: PathBuf, - home: PathBuf, - launch: Launch, - run_id: u64, - hooks: Arc, - limits: Limits, -} - /// A notice that waits for the new agent's console: how long before the phase /// counts as crashed. const NOTICE_WAIT: Duration = Duration::from_secs(180); -const WATCH_EVERY: Duration = Duration::from_secs(2); -/// How often silence looks at the session's files and the tree. -const ACTIVITY_EVERY: Duration = Duration::from_secs(30); /// How long a phase's commit may run: a slow pre-commit hook is allowed this /// much, where the quick calls keep their one minute. const COMMIT_LIMIT: Duration = Duration::from_secs(10 * 60); @@ -1775,7 +1814,7 @@ pub fn begin_with_limits( } rec.launch_model.clone_from(&launch.1); rec.launch_effort.clone_from(&launch.2); - if let Some(report) = loop_report::load(&home, &rec.project, &rec.spec) { + if let Some(report) = load_reports(&home, &rec.project, &rec.spec) { rec.report = report; } let ctx = Ctx { @@ -1811,6 +1850,11 @@ pub fn begin_with_limits( /// (`page_is_this_phase`). One without the lock is kept as a candidate the /// watch adopts once the lock shows; one with a report is ignored. pub fn note_page(slot: &LoopSlot, workflow: &str, sid: &str, state: &Value) { + // An extra review round's session, while a phase waits for one. + if workflow == "review" { + note_round_page(slot, sid, state); + return; + } if !matches!(workflow, "implement" | "implement-review") { return; } @@ -1827,6 +1871,27 @@ pub fn note_page(slot: &LoopSlot, workflow: &str, sid: &str, state: &Value) { } } +/// Hand a Review page to the extra round a phase is waiting on: the page the +/// agent locked with `open --loop` for that round and role is its session; one +/// without the lock yet is kept as a candidate the round adopts once it shows. +fn note_round_page(slot: &LoopSlot, sid: &str, state: &Value) { + let mut guard = lock(slot); + let Some(rec) = guard.as_mut() else { return }; + let Some(wait) = rec.round_wait.as_mut() else { + return; + }; + if wait.sid.is_some() { + return; + } + if crate::loop_shared::rounds::page_is_this_round(state, wait.round, wait.role) { + wait.sid = Some(sid.to_string()); + wait.candidate = None; + rec.last_activity = SystemTime::now(); + } else if state.is_object() && state.get("roundOutcome").is_none_or(Value::is_null) { + wait.candidate = Some(sid.to_string()); + } +} + /// Follow `sid` as the phase's session from here. fn adopt_page(rec: &mut RunningRecord, sid: &str) { rec.sid = Some(sid.to_string()); @@ -1839,8 +1904,8 @@ fn adopt_page(rec: &mut RunningRecord, sid: &str) { /// agent's lock; the session to follow, or `None` while there is none yet. fn adopt_candidate(ctx: &Ctx, candidate: Option<&str>) -> Option { let sid = candidate?; - let session = session_reader::load(&ctx.home, sid).ok()?; - if !page_is_this_phase(&session.state) { + let state = read_session_state(ctx, sid)?; + if !page_is_this_phase(&state) { return None; } let mut guard = lock(&ctx.slot); @@ -1938,7 +2003,7 @@ pub fn finalize_prompt(spec: &str) -> String { format!("/plan2code-4-finalize {spec}/overview.md --web") } -fn emit(ctx: &Ctx) { +pub(crate) fn emit(ctx: &Ctx) { let event = { let guard = lock(&ctx.slot); guard @@ -1964,16 +2029,25 @@ fn start_phase(ctx: &Ctx, index: usize) -> Result<(), String> { } else { Vec::new() }; - (rec.project.clone(), carried) + (rec.project.clone(), carried, rec.setup.extra_rounds() > 0) }) } - .map(|(project, carried)| phase_baseline(&project, &carried)); + .map(|(project, carried, rounds)| { + // The tree as the phase begins, for its extra review rounds; a phase + // that allows none never pays for the snapshot. + let start = rounds.then(|| round_boundary::snapshot(&project).ok()); + (phase_baseline(&project, &carried), start) + }); let prompt = { let mut guard = lock(&ctx.slot); let rec = guard.as_mut().ok_or("the loop ended")?; - if let Some(baseline) = baseline { + if let Some((baseline, start)) = baseline { rec.phase_baseline = baseline; + rec.phase_start = start.flatten(); + rec.phase_rounds.clear(); } + rec.round_wait = None; + rec.step_text = None; rec.page_candidate = None; rec.current = index; rec.phases[index].status = PhaseStatus::Running; @@ -1996,11 +2070,8 @@ fn start_phase(ctx: &Ctx, index: usize) -> Result<(), String> { // Said before the agent starts: the banner is up from the moment of Start, // and says what is happening between phases. emit(ctx); - match on { - Some((word, row)) => start_phase_with(&ctx.agent, &ctx.launch, prompt, &row, word)?, - None => start_with(&ctx.agent, &ctx.launch, prompt)?, - } - let generation = ctx.agent.snapshot().generation; + let started = start_session(ctx, &prompt, on.as_ref().map(|(word, row)| (*word, row)))?; + let generation = started.generation; if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) { rec.generation = generation; } @@ -2019,25 +2090,18 @@ fn watch(ctx: Ctx) { /// is cleared, the agent ended and the page told, never a loop left running /// with nothing watching it. fn watch_with(ctx: Ctx, mut step: impl FnMut(&Ctx) -> bool) { - loop { - thread::sleep(ctx.limits.watch_every); - let seen = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| step(&ctx))); - match seen { - Ok(true) => {} - Ok(false) => return, - Err(payload) => { - let text = payload - .downcast_ref::<&str>() - .map(|s| (*s).to_string()) - .or_else(|| payload.downcast_ref::().cloned()) - .unwrap_or_else(|| "an unknown error".to_string()); - let text: String = one_line(&text).chars().take(200).collect(); - let cause = StopCause::WatcherFailed(text); - let line = stop_line(&cause, 0, "", false); - stop_loop(&ctx, cause, line, &["resume", "fix"]); - return; - } + let panicked = watch_loop(ctx.limits.watch_every, || { + if step(&ctx) { + WatchStep::Continue + } else { + WatchStep::Stop } + }); + if let Some(text) = panicked { + let text: String = one_line(&text).chars().take(200).collect(); + let cause = StopCause::WatcherFailed(text); + let line = stop_line(&cause, 0, "", false); + stop_loop(&ctx, cause, line, &["resume", "fix"]); } } @@ -2289,7 +2353,7 @@ fn observe(ctx: &Ctx, stage: Option<&str>, asked: bool) { /// A file time is never later than now: a file dated in the future (a clock /// that was wrong, a copied file) must not hold the last sign of work ahead of /// the clock, or silence would never fire. -fn clamp_to_now(time: SystemTime) -> SystemTime { +pub(crate) fn clamp_to_now(time: SystemTime) -> SystemTime { time.min(SystemTime::now()) } @@ -2303,7 +2367,7 @@ fn modified(path: &Path) -> Option { /// The newest sign of work: the session's own files, or a file `git status` /// lists (ignored folders never appear, so they never count). -fn newest_work(session_dir: &Path, project: &Path) -> Option { +pub(crate) fn newest_work(session_dir: &Path, project: &Path) -> Option { let mut newest = ["state.json", "events.ndjson"] .iter() .filter_map(|name| modified(&session_dir.join(name))) @@ -2409,12 +2473,91 @@ fn stop_before_mark(ctx: &Ctx, snap: &Snapshot, staged: bool) -> bool { false } -fn stop_requested(ctx: &Ctx) -> bool { +pub(crate) fn stop_requested(ctx: &Ctx) -> bool { lock(&ctx.slot) .as_ref() .is_some_and(|r| r.run_id == ctx.run_id && r.stop_now) } +/// The extra review rounds a phase's own review calls for (FR-28): with Review +/// on, `review_rounds` above zero and a Critical or Warning left in a report +/// that otherwise could pass, fresh round sessions review the phase's diff +/// before it is judged. Returns the report to judge (the phase agent's own when +/// no round ran, else with the last round's counts in its place), or `None` +/// when the loop was stopped here and the stop is already recorded. +fn extra_rounds(ctx: &Ctx, snap: &Snapshot, outcome: Outcome) -> Option { + let review = outcome.review.clone().unwrap_or_default(); + let left = leftover(&review, FixLevel::Critical) + leftover(&review, FixLevel::Warning); + // A phase that reports failed only for its findings has no other failure: + // its tests, tasks and conflicts are still checked by the judge afterwards. + let findings_only = outcome.result == "failed" + && outcome.reason.as_deref() == Some("findings") + && outcome.conflicts.is_empty(); + let tests_hold = outcome + .tests + .as_ref() + .is_none_or(|t| !t.ran || t.passed || excused_failures(t)); + if snap.setup.extra_rounds() == 0 + || !review.ran + || left == 0 + || !(outcome.result == "passed" || findings_only) + || !tests_hold + { + return Some(outcome); + } + let n = snap.phase_n; + let stop_with = |cause: StopCause, line: String| { + stop_loop(ctx, cause, line, &["resume", "fix"]); + None + }; + let start = { + let guard = lock(&ctx.slot); + let rec = guard.as_ref().filter(|r| r.run_id == ctx.run_id)?; + rec.phase_start.clone() + }; + let Some(start) = start else { + keep_output( + ctx, + "The extra review rounds were skipped: the tree as the phase began could not be recorded.", + ); + return Some(outcome); + }; + let input = phase_rounds::RoundsInput { + project: snap.project.clone(), + phase: n, + setup: snap.setup.clone(), + cap: snap.setup.extra_rounds(), + helpers: phase_rounds::helpers_for(ctx), + start, + unfixed: review.unfixed.clone(), + dir: ctx + .home + .join("loop-phase-rounds") + .join(format!("{}-phase-{n}", ctx.run_id)), + }; + let end = phase_rounds::run_rounds(ctx, &input); + match end { + phase_rounds::RoundsEnd::Done(done) => { + keep_rounds(ctx, &done.rounds); + Some(phase_rounds::judged_after(outcome, &done)) + } + phase_rounds::RoundsEnd::Person { rounds } => { + keep_rounds(ctx, &rounds); + stop_by_person(ctx, snap); + None + } + phase_rounds::RoundsEnd::Failed { reason, rounds } => { + keep_rounds(ctx, &rounds); + let cause = StopCause::Refused(format!( + "an extra review round failed ({})", + one_line(&reason) + )); + let line = stop_line(&cause, n, "", false); + stop_with(cause, line) + } + } +} + /// Judge a phase's report and, when it holds, record it: quick check, mark, /// approval line, commit, stop the agent, then the next phase, a stop the /// person asked for, or the finish. Returns whether the loop goes on. @@ -2436,6 +2579,11 @@ fn handle_outcome(ctx: &Ctx, snap: &Snapshot, raw: &Value) -> bool { if outcome.phase != n { return refused(format!("the report names Phase {}", outcome.phase)); } + // A phase whose own review left a Critical or a Warning gets fresh review + // rounds before it is judged (the hook; nothing else about the phase changes). + let Some(outcome) = extra_rounds(ctx, snap, outcome) else { + return false; + }; let status = match loop_tools::specs_status(&snap.project, &snap.spec) { Ok(status) => status, Err(e) => return refused(format!("the spec could not be read ({})", one_line(&e))), @@ -2595,6 +2743,11 @@ fn handle_outcome(ctx: &Ctx, snap: &Snapshot, raw: &Value) -> bool { retries: snap.phase_retries, assumed: phase_assumptions(&snap.project, &snap.spec, n, Some(&entry)), warnings, + rounds: lock(&ctx.slot) + .as_ref() + .filter(|r| r.run_id == ctx.run_id) + .map(|r| r.phase_rounds.clone()) + .unwrap_or_default(), ..ReportEntry::default() } .with_outcome(&outcome); @@ -2798,7 +2951,7 @@ fn add_entry(ctx: &Ctx, entry: ReportEntry) { rec.report.entries.push(entry); (rec.project.clone(), rec.report.clone()) }; - let result = loop_report::save(&ctx.home, &saved.0, &saved.1); + let result = save_report(&ctx.home, &saved.0, &saved.1); if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) { rec.report_failure = result.err(); } @@ -2809,8 +2962,9 @@ fn set_step(ctx: &Ctx, step: Step) { let mut guard = lock(&ctx.slot); match guard.as_mut().filter(|r| r.run_id == ctx.run_id) { Some(rec) => { - let changed = rec.step != step; + let changed = rec.step != step || rec.step_text.is_some(); rec.step = step; + rec.step_text = None; changed } None => false, @@ -2827,6 +2981,13 @@ fn keep_output(ctx: &Ctx, output: &str) { } } +/// Keep the extra rounds the phase has run, for its report entry. +pub(crate) fn keep_rounds(ctx: &Ctx, rounds: &[loop_report::RoundEntry]) { + if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) { + rec.phase_rounds = rounds.to_vec(); + } +} + fn keep_report(ctx: &Ctx, outcome: &Outcome, entry: &Value) { if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) { rec.last_outcome = Some(outcome.clone()); @@ -3297,6 +3458,7 @@ fn stop_loop(ctx: &Ctx, cause: StopCause, line: String, can: &[&str]) { if let Some(outcome) = &rec.last_outcome { entry = entry.with_outcome(outcome); } + entry.rounds.clone_from(&rec.phase_rounds); } // What the phase ran on, as `add_entry` does for every other entry. if let Some(run) = rec.phase_run(at) { @@ -3304,7 +3466,7 @@ fn stop_loop(ctx: &Ctx, cause: StopCause, line: String, can: &[&str]) { entry.model = run.model_text(); } rec.report.entries.push(entry); - rec.report_failure = loop_report::save(&ctx.home, &rec.project, &rec.report).err(); + rec.report_failure = save_report(&ctx.home, &rec.project, &rec.report).err(); let mut evidence = evidence_with_report(&evidence_markdown(&cause, &line, &rec), &rec); let sent = stop_message(&cause, &Where::of(&rec, at), &line) .and_then(|message| notify(&rec.setup, &message)); @@ -3681,6 +3843,12 @@ pub fn summary_markdown(rec: &RunningRecord, date: &str, finalize: &FinalizeNote if setup.review { md.push_str(&format!("- Fixes: {}\n", levels_text(setup))); } + if setup.review { + md.push_str(&format!( + "- Review rounds per phase: {}\n", + setup.extra_rounds() + )); + } md.push_str(&format!("- Commit each phase: {}\n", yes(setup.commit))); let on_question = match setup.on_question { OnQuestion::Pause => "pause and wait for you", @@ -3726,7 +3894,7 @@ pub fn summary_markdown(rec: &RunningRecord, date: &str, finalize: &FinalizeNote } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; fn setup() -> LoopSetup { @@ -4837,31 +5005,6 @@ second line" // ----------------------------------------------- failures, stops, the strip - fn at(minutes: u64) -> SystemTime { - UNIX_EPOCH + Duration::from_secs(minutes * 60) - } - - #[test] - fn silence_waits_past_the_limit_and_never_while_a_question_waits() { - let s = setup(); // 20 minutes - assert!(!silence_expired(at(120), at(100), &s, None, false)); - assert!(silence_expired(at(121), at(100), &s, None, false)); - // A waiting question has no time limit. - assert!(!silence_expired(at(1000), at(0), &s, None, true)); - // The skill's own quiet minutes stretch the limit, never shrink it. - assert!(!silence_expired(at(140), at(100), &s, Some(45), false)); - assert!(silence_expired(at(146), at(100), &s, Some(45), false)); - assert!(silence_expired(at(121), at(100), &s, Some(5), false)); - // Capped at 60 minutes whatever either side asks for. - assert!(silence_expired(at(161), at(100), &s, Some(500), false)); - let mut long = setup(); - long.silence_minutes = 60; - assert!(!silence_expired(at(160), at(100), &long, Some(90), false)); - assert!(silence_expired(at(161), at(100), &long, Some(90), false)); - // A clock that went backwards is not silence. - assert!(!silence_expired(at(100), at(200), &s, None, false)); - } - #[test] fn only_a_crash_silence_or_a_missing_console_retries_and_only_once() { let s = setup(); @@ -5268,7 +5411,7 @@ second line" /// Whether `program` runs; a test that needs it says so and skips when not. /// On CI (`CI` is set) a missing program fails the test instead, so a /// runner without git or node cannot turn the tests into silent passes. - fn program_ready(test: &str, program: &str) -> bool { + pub(crate) fn program_ready(test: &str, program: &str) -> bool { let found = std::process::Command::new(program) .arg("--version") .output() @@ -5283,13 +5426,13 @@ second line" found } - fn git_ready(test: &str) -> bool { + pub(crate) fn git_ready(test: &str) -> bool { program_ready(test, "git") } /// Git, node and the skill scripts (`specs.mjs`, `commit-msg.mjs`) the tick /// runs. The scripts are the repository's own (see `loop_tools::skill_script`). - fn harness_ready(test: &str) -> bool { + pub(crate) fn harness_ready(test: &str) -> bool { let scripts = loop_tools::skill_script("specs.mjs").is_some() && loop_tools::skill_script("commit-msg.mjs").is_some(); assert!( @@ -5299,7 +5442,7 @@ second line" git_ready(test) && program_ready(test, "node") } - fn git_in(repo: &Path, args: &[&str]) -> String { + pub(crate) fn git_in(repo: &Path, args: &[&str]) -> String { let out = std::process::Command::new("git") .args(args) .current_dir(repo) @@ -5383,7 +5526,7 @@ second line" } /// Where `cargo build -p fake-agent` leaves the fake agent, built on first use. - fn fake_agent_path() -> PathBuf { + pub(crate) fn fake_agent_path() -> PathBuf { static BUILD: std::sync::Once = std::sync::Once::new(); BUILD.call_once(|| { let status = std::process::Command::new(env!("CARGO")) @@ -5406,7 +5549,7 @@ second line" /// The fake agent as a custom agent. The loop's tests start it this way, not /// through `PLAN2CODE_APP_AGENT_BIN`: that variable is process-wide, and /// other tests in this process read it. - fn fake_agent_launch() -> Launch { + pub(crate) fn fake_agent_launch() -> Launch { let agent = crate::agents::CustomAgent { id: "fake".into(), name: "Fake agent".into(), @@ -5422,7 +5565,7 @@ second line" /// An agent manager for the fake agent, and everything the agents printed. The pump answers the pseudo-terminal's cursor question, /// as a terminal does, or Windows holds the output back. - fn fake_agent_manager(folder: &Path) -> (Arc, Arc>) { + pub(crate) fn fake_agent_manager(folder: &Path) -> (Arc, Arc>) { use crate::agent_manager::AgentEvent; let (tx, rx) = std::sync::mpsc::channel(); let tx = Mutex::new(tx); @@ -5449,7 +5592,7 @@ second line" } /// Poll until `ready`; the wait ends on state, not on a fixed sleep. - fn wait_until(what: &str, mut ready: impl FnMut() -> bool) { + pub(crate) fn wait_until(what: &str, mut ready: impl FnMut() -> bool) { let deadline = Instant::now() + Duration::from_secs(30); while Instant::now() < deadline { if ready() { @@ -7858,4 +8001,271 @@ second line" ); agent.stop(); } + + // ------------------------------------------------ extra review rounds in a phase + + fn quick_limits() -> Limits { + Limits { + watch_every: Duration::from_millis(20), + notice_wait: Duration::from_secs(20), + ..Limits::default() + } + } + + /// A `roundOutcome` the way a round agent posts it; the reviewer lists the + /// Warning it found as unfixed, the fixer says what its round left. + fn round_json(round: u32, role: &str, critical: u32, warning: u32) -> Value { + let mut value = json!({ + "round": round, "role": role, "result": "passed", "reason": null, + "summary": "Round done", + "review": { "critical": critical, "warning": warning, "suggestion": 0, + "fixed": [], "unfixed": [], "suggestions": [] }, + "tests": { "ran": true, "passed": true, "summary": "ok" }, + }); + if role != "fixer" { + value["report"] = json!("report"); + } + if role == "reviewer" { + value.as_object_mut().unwrap().remove("tests"); + if warning > 0 { + value["review"]["unfixed"] = + json!([{ "title": "Close the handle", "file": "work.txt" }]); + } + } + value + } + + /// What the player saw of a round session before it answered. + struct Seen { + scope: String, + banner: String, + } + + /// Answer the phase's extra round sessions in order: wait for each one the + /// driver starts, read its scope file and the banner, hand the driver its + /// page (as the app's notice does) and post its `roundOutcome`. + fn play_rounds( + ctx: &Ctx, + script: Vec<(u32, &'static str, Value)>, + ) -> thread::JoinHandle> { + let ctx = ctx.clone(); + thread::spawn(move || { + let mut seen = Vec::new(); + for (round, role, outcome) in script { + let want = match role { + "reviewer" => Role::Reviewer, + "fixer" => Role::Fixer, + _ => Role::Both, + }; + wait_until("a round session to wait for", || { + lock(&ctx.slot) + .as_ref() + .and_then(|rec| rec.round_wait.as_ref()) + .is_some_and(|w| w.round == round && w.role == want && w.sid.is_none()) + }); + let (phase, banner) = { + let guard = lock(&ctx.slot); + let rec = guard.as_ref().unwrap(); + (rec.phases[rec.current].n, state_event(rec).step) + }; + let dir = ctx + .home + .join("loop-phase-rounds") + .join(format!("{}-phase-{phase}", ctx.run_id)) + .join(format!("round-{round}-{role}-t0")); + let scope = std::fs::read_to_string(dir.join("scope.md")).expect("a scope file"); + let sid = format!("r{round}{role}"); + let folder = ctx.home.join("sessions").join(&sid); + std::fs::create_dir_all(&folder).unwrap(); + let post = |state: &Value| { + let mut state = state.clone(); + state["schema"] = json!(crate::session_reader::SCHEMA); + std::fs::write(folder.join("state.json.tmp"), state.to_string()).unwrap(); + std::fs::rename(folder.join("state.json.tmp"), folder.join("state.json")) + .unwrap(); + state + }; + let locked = + post(&json!({ "loop": { "driving": true, "round": round, "role": role } })); + note_page(&ctx.slot, "review", &sid, &locked); + let mut done = locked.clone(); + done["roundOutcome"] = outcome; + done["docs"] = json!([{ "id": "report", "kind": "report", "title": "Review round", + "blocks": [{ "id": "r", "md": "Found things to fix." }] }]); + post(&done); + seen.push(Seen { scope, banner }); + } + seen + }) + } + + /// A phase report whose own review left one Warning, the way a phase agent + /// that could not fix it reports it. + fn findings_report(phase: u32) -> Value { + let mut report = good_report(phase); + report["result"] = json!("failed"); + report["reason"] = json!("findings"); + report["review"] = json!({ + "ran": true, "recheck": true, + "left": { "critical": 0, "warning": 1, "suggestion": 0 }, + "unfixed": [{ "level": "warning", "title": "Close the handle", "file": "work.txt" }], + }); + report + } + + /// A running loop on a throwaway repo whose Phase 2 is built (tasks ticked, + /// one file written) after the start snapshot the rounds measure from. + fn built_phase(name: &str) -> (Ctx, PathBuf, PathBuf) { + let repo = throwaway_repo(name); + let (ctx, home) = running_loop(&repo, quick_limits()); + lock(&ctx.slot).as_mut().unwrap().phase_start = + Some(round_boundary::snapshot(&repo).unwrap()); + finish_phase_tasks(&repo, 2); + std::fs::write(repo.join("work.txt"), "phase work\n").unwrap(); + (ctx, repo, home) + } + + #[test] + fn a_phase_with_a_warning_left_runs_fresh_rounds_then_commits_once() { + if !harness_ready("extra rounds") { + return; + } + let (ctx, repo, home) = built_phase("extra-rounds"); + let before = git_in(&repo, &["rev-list", "--count", "HEAD"]); + write_session(&home, json!({ "loopOutcome": findings_report(2) })); + let player = play_rounds( + &ctx, + vec![ + (1, "reviewer", round_json(1, "reviewer", 0, 1)), + (1, "fixer", round_json(1, "fixer", 0, 1)), + (2, "reviewer", round_json(2, "reviewer", 0, 0)), + ], + ); + assert!(tick(&ctx), "the clean round 2 lets the phase pass"); + let seen = player.join().unwrap(); + assert_eq!(seen[0].banner, "Review round 1 of 2"); + assert_eq!(seen[2].banner, "Review round 2 of 2"); + assert!( + seen[0].scope.contains("everything the phase changed"), + "{}", + seen[0].scope + ); + let diff = seen[0] + .scope + .lines() + .find_map(|l| l.strip_prefix("- ")) + .unwrap(); + let diff = std::fs::read_to_string(diff).unwrap(); + assert!(diff.contains("work.txt"), "the whole phase diff: {diff}"); + assert!( + seen[1].scope.contains("Close the handle") + && seen[1].scope.contains("reviewer-report.md"), + "the fixer is briefed with the unfixed list: {}", + seen[1].scope + ); + assert!( + !seen[0].scope.contains("Close the handle"), + "the reviewer sees no brief" + ); + assert!( + seen[2].scope.contains("previous round's changes"), + "{}", + seen[2].scope + ); + let after = git_in(&repo, &["rev-list", "--count", "HEAD"]); + assert_eq!( + after.parse::().unwrap(), + before.parse::().unwrap() + 1, + "one commit for the phase" + ); + assert_eq!( + git_in(&repo, &["log", "-1", "--format=%s"]), + "Add the driver" + ); + assert!(git_in(&repo, &["show", "--name-only", "--format=", "HEAD"]).contains("work.txt")); + let entry = last_entry_saved(&home, &repo); + assert_eq!(entry.result, EntryResult::Passed); + assert_eq!(entry.rounds.len(), 2); + assert_eq!((entry.rounds[0].warning, entry.rounds[1].warning), (1, 0)); + let md = loop_report::body_markdown(&lock(&ctx.slot).as_ref().unwrap().report); + assert!( + md.contains("Extra review rounds: 2 (left after: 0 Critical, 0 Warning)"), + "{md}" + ); + end_the_test(&ctx); + } + + #[test] + fn findings_left_after_the_rounds_judge_the_phase_with_those_counts() { + if !harness_ready("extra rounds cap") { + return; + } + let (ctx, repo, home) = built_phase("extra-rounds-cap"); + lock(&ctx.slot).as_mut().unwrap().setup.review_rounds = 1; + // The phase agent leaves two Warnings; the one round leaves one, so only + // the last round's count can make the stop line say "1 Warning". + let mut report = findings_report(2); + report["review"]["left"]["warning"] = json!(2); + report["review"]["unfixed"] + .as_array_mut() + .unwrap() + .push(json!({ "level": "warning", "title": "Name the timer", "file": "work.txt" })); + write_session(&home, json!({ "loopOutcome": report })); + let player = play_rounds( + &ctx, + vec![ + (1, "reviewer", round_json(1, "reviewer", 0, 1)), + (1, "fixer", round_json(1, "fixer", 0, 1)), + ], + ); + assert!( + !tick(&ctx), + "a Warning left after the only round stops the phase" + ); + player.join().unwrap(); + let entry = last_entry_saved(&home, &repo); + assert_eq!(entry.result, EntryResult::Stopped); + assert!( + entry.line.contains("1 Warning left after the re-check"), + "{}", + entry.line + ); + assert_eq!(entry.rounds.len(), 1); + assert_eq!( + git_in(&repo, &["rev-list", "--count", "HEAD"]), + "1", + "nothing was committed" + ); + end_the_test(&ctx); + } + + #[test] + fn no_rounds_run_when_nothing_is_left_when_they_are_zero_or_when_review_is_off() { + if !harness_ready("extra rounds skipped") { + return; + } + // Nothing left: the phase commits as before and no round folder appears. + let (ctx, repo, home) = built_phase("extra-none"); + write_session(&home, json!({ "loopOutcome": good_report(2) })); + assert!(tick(&ctx)); + assert!(last_entry_saved(&home, &repo).rounds.is_empty()); + assert!(!home.join("loop-phase-rounds").exists()); + end_the_test(&ctx); + // Zero rounds: the Warning stops the phase as it always did. + let (ctx, repo, home) = built_phase("extra-zero"); + lock(&ctx.slot).as_mut().unwrap().setup.review_rounds = 0; + write_session(&home, json!({ "loopOutcome": findings_report(2) })); + assert!(!tick(&ctx)); + assert!(last_entry_saved(&home, &repo).rounds.is_empty()); + assert!(!home.join("loop-phase-rounds").exists()); + end_the_test(&ctx); + // Review off: the setting means nothing, and the report judges as before. + let (ctx, repo, home) = built_phase("extra-off"); + lock(&ctx.slot).as_mut().unwrap().setup.review = false; + write_session(&home, json!({ "loopOutcome": findings_report(2) })); + let _ = tick(&ctx); + assert!(last_entry_saved(&home, &repo).rounds.is_empty()); + assert!(!home.join("loop-phase-rounds").exists()); + end_the_test(&ctx); + } } diff --git a/plan2code-app/src-tauri/src/loop_report.rs b/plan2code-app/src-tauri/src/loop_report.rs index 3ff46a3..5cce10d 100644 --- a/plan2code-app/src-tauri/src/loop_report.rs +++ b/plan2code-app/src-tauri/src/loop_report.rs @@ -32,10 +32,42 @@ pub struct Assumption { pub note: String, } +/// Which loop wrote an entry. Entries saved before the Review Loop existed +/// carry no kind and read as `Implementation`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum EntryKind { + #[default] + Implementation, + Review, +} + +/// One round of a Review Loop, as its entry keeps it. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct RoundEntry { + pub n: u32, + pub critical: u32, + pub warning: u32, + pub suggestion: u32, + pub fixed: Vec, + pub left_open: Vec, + pub commit: Option, + pub tests: String, + pub started: String, + pub ended: String, + /// "Balanced" and so on, or empty for an agent run as launched. + pub strength: String, + pub retried: bool, +} + /// One thing that happened to a phase, in the order it happened. #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct ReportEntry { + pub kind: EntryKind, + /// A Review Loop's rounds, in order; empty for an Implementation Loop phase. + pub rounds: Vec, pub at: String, pub phase: u32, pub name: String, @@ -298,6 +330,23 @@ fn entry_markdown(md: &mut String, e: &ReportEntry) { if e.retries > 0 { md.push_str(&format!("- Retries: {}\n", e.retries)); } + if let Some(last) = e.rounds.last() { + md.push_str(&format!( + "- Extra review rounds: {} (left after: {} Critical, {} Warning)\n", + e.rounds.len(), + last.critical, + last.warning + )); + for round in &e.rounds { + md.push_str(&format!( + " - Round {}: {} Critical, {} Warning found, {} fixed\n", + round.n, + round.critical, + round.warning, + round.fixed.len() + )); + } + } if !e.warnings.is_empty() { let notes: Vec = e.warnings.iter().map(|w| cell(w)).collect(); md.push_str(&format!("- Warnings: {}\n", notes.join("; "))); diff --git a/plan2code-app/src-tauri/src/loop_shared/mod.rs b/plan2code-app/src-tauri/src/loop_shared/mod.rs new file mode 100644 index 0000000..6d4af15 --- /dev/null +++ b/plan2code-app/src-tauri/src/loop_shared/mod.rs @@ -0,0 +1,16 @@ +//! Loop machinery both the Implementation Loop (`loop_driver`) and the Review +//! Loop call: starting an agent session, the watcher, the retry rule, the +//! saved report list and the notification. + +pub mod report_list; +pub mod retry; +pub mod rounds; +pub mod session; +pub mod watch; + +use crate::loop_notify::{self, NotifyKind}; + +/// Send a notification of `kind` to `url`; the reason it failed, if it did. +pub fn notify(kind: NotifyKind, url: &str, param: &str, message: &str) -> Result<(), String> { + loop_notify::send(kind, url, param, message) +} diff --git a/plan2code-app/src-tauri/src/loop_shared/report_list.rs b/plan2code-app/src-tauri/src/loop_shared/report_list.rs new file mode 100644 index 0000000..f00c550 --- /dev/null +++ b/plan2code-app/src-tauri/src/loop_shared/report_list.rs @@ -0,0 +1,16 @@ +//! The saved report list (`loop-reports.json`): one entry point for both the +//! Implementation Loop and the Review Loop. + +use std::path::Path; + +use crate::loop_report::{self, LoopReport}; + +/// The saved report for `spec` in `project`, when there is one. +pub fn load_reports(home: &Path, project: &Path, spec: &str) -> Option { + loop_report::load(home, project, spec) +} + +/// Save `report` for `project`. +pub fn save_report(home: &Path, project: &Path, report: &LoopReport) -> Result<(), String> { + loop_report::save(home, project, report) +} diff --git a/plan2code-app/src-tauri/src/loop_shared/retry.rs b/plan2code-app/src-tauri/src/loop_shared/retry.rs new file mode 100644 index 0000000..1489478 --- /dev/null +++ b/plan2code-app/src-tauri/src/loop_shared/retry.rs @@ -0,0 +1,28 @@ +//! The retry rule and the strength step-up, called by both the Implementation +//! Loop and the Review Loop. + +use std::collections::BTreeMap; + +use crate::loop_driver::{LoopSetup, StopCause}; +use crate::models::{self, StrengthRow}; + +/// One fresh retry for a crash, silence or an announce notice that never came +/// (a crash), when the setup allows it and the phase has not used it yet. A +/// failed watcher is never retried. +pub fn should_retry(cause: &StopCause, setup: &LoopSetup, retries_used_this_phase: u32) -> bool { + matches!( + cause, + StopCause::Crash | StopCause::Silence | StopCause::NoSession + ) && setup.retry_once + && retries_used_this_phase == 0 +} + +/// The strength word one step above `current`, or `None` when there is none +/// (Best stays, an unmapped word stays). A thin wrapper over +/// `models::next_strength`, so a caller without a `RunningRecord` can step up. +pub fn next_strength_word( + resolved: &BTreeMap, + current: &str, +) -> Option { + models::next_strength(resolved, current) +} diff --git a/plan2code-app/src-tauri/src/loop_shared/rounds.rs b/plan2code-app/src-tauri/src/loop_shared/rounds.rs new file mode 100644 index 0000000..d4dc25b --- /dev/null +++ b/plan2code-app/src-tauri/src/loop_shared/rounds.rs @@ -0,0 +1,110 @@ +//! The pieces of a review round both loops read the same way: whether an +//! announced page is a round's session, the round's `roundOutcome` in a session +//! state, the report text it names, the proofs the app checks for itself, and +//! the reviewer's findings as the fixer's brief. The Review Loop and the +//! Implementation Loop's extra review rounds (a phase's hook) both call them. + +use serde_json::Value; + +use crate::round_logic::{Finding, Role, RoundOutcome, RoundProofs}; + +/// The word a role goes by in a console state and a prompt. +pub fn role_word(role: Role) -> &'static str { + match role { + Role::Both => "both", + Role::Reviewer => "reviewer", + Role::Fixer => "fixer", + } +} + +/// Whether an announced page is this round's session: the agent locked it with +/// `open --loop` for this round and role, and it holds no report yet. +pub fn page_is_this_round(state: &Value, round: u32, role: Role) -> bool { + state["loop"]["driving"].as_bool().unwrap_or(false) + && state["loop"]["round"].as_u64() == Some(u64::from(round)) + && state["loop"]["role"].as_str() == Some(role_word(role)) + && state.get("roundOutcome").is_none_or(Value::is_null) +} + +/// The round's outcome in `state`, when it is this round's and this role's. +pub fn round_outcome_in( + state: &Value, + round: u32, + role: Role, +) -> Option> { + let raw = state + .get("roundOutcome") + .filter(|value| value.is_object())?; + match serde_json::from_value::(raw.clone()) { + Ok(outcome) => (outcome.round == round && outcome.role == role).then_some(Ok(outcome)), + Err(err) => Some(Err(format!("the round's report could not be read ({err})"))), + } +} + +/// The text of the report doc the outcome names, from the session's `docs`. +pub fn report_text(state: &Value, id: &str) -> Option { + let doc = state["docs"] + .as_array()? + .iter() + .find(|doc| doc["id"].as_str() == Some(id))?; + let mut text = String::new(); + if let Some(blocks) = doc["blocks"].as_array() { + for block in blocks { + if let Some(md) = block["md"].as_str() { + text.push_str(md); + text.push_str("\n\n"); + } + } + } + Some(text) +} + +pub fn proofs_for(state: &Value, outcome: &RoundOutcome, role: Role) -> RoundProofs { + let report_doc_present = match role { + Role::Fixer => true, + _ => outcome + .report + .as_deref() + .is_some_and(|id| report_text(state, id).is_some()), + }; + let (tests_ran, tests_passed) = match role { + // A reviewer changes nothing and is not asked for tests. + Role::Reviewer => (true, true), + _ => outcome + .tests + .as_ref() + .map_or((false, false), |t| (t.ran, t.passed)), + }; + RoundProofs { + report_doc_present, + tests_ran, + tests_passed, + } +} + +pub fn finding_line(finding: &Finding) -> String { + match finding.line { + Some(line) => format!("- {} ({}:{line})", finding.title, finding.file), + None => format!("- {} ({})", finding.title, finding.file), + } +} + +/// The reviewer's findings, as the fixer's brief: the report's text and the +/// Critical and Warning findings the reviewer left unfixed. +pub fn reviewer_brief(text: &str, outcome: &RoundOutcome) -> String { + let mut brief = format!( + "# Reviewer report\n\n{}\n\nFound: {} Critical, {} Warning, {} Suggestion.\n\n", + text.trim(), + outcome.review.critical, + outcome.review.warning, + outcome.review.suggestion + ); + if !outcome.review.unfixed.is_empty() { + brief.push_str("## Fix these\n\n"); + for finding in &outcome.review.unfixed { + brief.push_str(&finding_line(finding)); + brief.push('\n'); + } + } + brief +} diff --git a/plan2code-app/src-tauri/src/loop_shared/session.rs b/plan2code-app/src-tauri/src/loop_shared/session.rs new file mode 100644 index 0000000..614af98 --- /dev/null +++ b/plan2code-app/src-tauri/src/loop_shared/session.rs @@ -0,0 +1,62 @@ +//! What a loop needs to start an agent session and read its console state: the +//! shared context, `start_session` and `read_session_state`. Both the +//! Implementation Loop and the Review Loop call it. + +use std::path::PathBuf; +use std::sync::Arc; + +use crate::agent_manager::AgentManager; +use crate::loop_driver::{self, Hooks, Launch, Limits, LoopSlot, Strength}; +use crate::models::StrengthRow; +use crate::session_reader; + +/// What the watch thread needs, shared by every step of one loop. +#[derive(Clone)] +pub struct Ctx { + pub slot: LoopSlot, + pub agent: Arc, + pub console_dir: PathBuf, + pub home: PathBuf, + pub launch: Launch, + pub run_id: u64, + pub hooks: Arc, + pub limits: Limits, +} + +/// What a started session reports: the agent's generation and the model and +/// effort it started on. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SessionStart { + pub generation: u64, + pub model: Option, + pub effort: Option, +} + +/// Start a fresh agent on `prompt`. With `strength` (the word and its row) the +/// agent starts on that row's model and effort with `PLAN2CODE_LOOP_STRENGTH` +/// set; without it, on the agent's launch choice. +pub fn start_session( + ctx: &Ctx, + prompt: &str, + strength: Option<(Strength, &StrengthRow)>, +) -> Result { + match strength { + Some((word, row)) => { + loop_driver::start_phase_with(&ctx.agent, &ctx.launch, prompt.to_string(), row, word)? + } + None => loop_driver::start_with(&ctx.agent, &ctx.launch, prompt.to_string())?, + } + let snapshot = ctx.agent.snapshot(); + Ok(SessionStart { + generation: snapshot.generation, + model: snapshot.model, + effort: snapshot.effort, + }) +} + +/// The console state of session `sid`, or `None` when it cannot be read now. +pub fn read_session_state(ctx: &Ctx, sid: &str) -> Option { + session_reader::load(&ctx.home, sid) + .ok() + .map(|session| session.state) +} diff --git a/plan2code-app/src-tauri/src/loop_shared/watch.rs b/plan2code-app/src-tauri/src/loop_shared/watch.rs new file mode 100644 index 0000000..580b1d9 --- /dev/null +++ b/plan2code-app/src-tauri/src/loop_shared/watch.rs @@ -0,0 +1,129 @@ +//! The watcher's timing, the silence rule and the generic watch loop, called by +//! both the Implementation Loop and the Review Loop. + +use std::time::{Duration, SystemTime}; + +use crate::loop_driver::LoopSetup; + +/// How often the watcher looks at the running loop. +pub const WATCH_EVERY: Duration = Duration::from_secs(2); +/// How often silence looks at the session's files and the tree. +pub const ACTIVITY_EVERY: Duration = Duration::from_secs(30); + +/// What a step of the watch loop says to do next. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WatchStep { + Continue, + Stop, +} + +/// Look every `every` until `step` says `Stop`. A panic in `step` ends the +/// watch and comes back as its text (`Some`), so the caller can end its loop +/// with the "watcher failed" stop instead of leaving a loop running with +/// nothing watching it; a normal stop returns `None`. +pub fn watch_loop WatchStep>(every: Duration, mut step: F) -> Option { + loop { + std::thread::sleep(every); + let seen = std::panic::catch_unwind(std::panic::AssertUnwindSafe(&mut step)); + match seen { + Ok(WatchStep::Continue) => {} + Ok(WatchStep::Stop) => return None, + Err(payload) => { + return Some( + payload + .downcast_ref::<&str>() + .map(|s| (*s).to_string()) + .or_else(|| payload.downcast_ref::().cloned()) + .unwrap_or_else(|| "an unknown error".to_string()), + ); + } + } + } +} + +/// Whether the agent has been quiet too long. A waiting question never counts +/// (the person may take all night). The limit is the setup's silence minutes +/// or the skill's own `quietMinutes`, whichever is longer, at most 60. +pub fn silence_expired( + now: SystemTime, + last_activity: SystemTime, + setup: &LoopSetup, + quiet_minutes: Option, + waiting: bool, +) -> bool { + if waiting { + return false; + } + let minutes = setup + .silence_minutes + .max(quiet_minutes.unwrap_or(0)) + .min(60); + let limit = Duration::from_secs(u64::from(minutes) * 60); + now.duration_since(last_activity) + .is_ok_and(|quiet| quiet > limit) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::loop_driver::{FixMode, OnQuestion}; + use std::time::UNIX_EPOCH; + + fn setup() -> LoopSetup { + LoopSetup { + fix_mode: FixMode::Levels, + on_question: OnQuestion::Pause, + ..LoopSetup::default() + } + } + + fn at(minutes: u64) -> SystemTime { + UNIX_EPOCH + Duration::from_secs(minutes * 60) + } + + #[test] + fn the_watch_loop_stops_on_stop_and_returns_the_text_of_a_panic() { + let none = Duration::ZERO; + let mut calls = 0; + let stopped = watch_loop(none, || { + calls += 1; + if calls < 3 { + WatchStep::Continue + } else { + WatchStep::Stop + } + }); + assert_eq!((stopped, calls), (None, 3)); + let quiet = std::panic::take_hook(); + std::panic::set_hook(Box::new(|_| {})); + let literal = watch_loop(none, || panic!("literal")); + let text = "formatted".to_string(); + let owned = watch_loop(none, || panic!("{text}")); + let other = watch_loop(none, || std::panic::panic_any(1_u8)); + std::panic::set_hook(quiet); + assert_eq!(literal.as_deref(), Some("literal")); + assert_eq!(owned.as_deref(), Some("formatted")); + assert_eq!(other.as_deref(), Some("an unknown error")); + } + + #[test] + fn silence_waits_past_the_limit_and_never_while_a_question_waits() { + let s = setup(); // 20 minutes + assert!(!silence_expired(at(120), at(100), &s, None, false)); + assert!(silence_expired(at(121), at(100), &s, None, false)); + // A waiting question has no time limit. + assert!(!silence_expired(at(1000), at(0), &s, None, true)); + // The skill's own quiet minutes stretch the limit, never shrink it. + assert!(!silence_expired(at(140), at(100), &s, Some(45), false)); + assert!(silence_expired(at(146), at(100), &s, Some(45), false)); + assert!(silence_expired(at(121), at(100), &s, Some(5), false)); + // Capped at 60 minutes whatever either side asks for. + assert!(silence_expired(at(161), at(100), &s, Some(500), false)); + let mut long = setup(); + long.silence_minutes = 60; + assert!(!silence_expired(at(160), at(100), &long, Some(90), false)); + assert!(silence_expired(at(161), at(100), &long, Some(90), false)); + // A clock that went backwards is not silence. + assert!(!silence_expired(at(100), at(200), &s, None, false)); + } +} diff --git a/plan2code-app/src-tauri/src/loop_tools.rs b/plan2code-app/src-tauri/src/loop_tools.rs index 3938a61..55f5887 100644 --- a/plan2code-app/src-tauri/src/loop_tools.rs +++ b/plan2code-app/src-tauri/src/loop_tools.rs @@ -600,11 +600,17 @@ pub fn git_head_short(project: &Path) -> Option { (run.ok && !hash.is_empty()).then(|| hash.to_string()) } -/// The full hash of `HEAD`, when there is a commit. -pub fn git_head_full(project: &Path) -> Option { +/// The full hash of `HEAD` (40 or 64 hex characters), or why there is none. +pub fn git_head_full(project: &Path) -> Result { let run = run_limited(git(project, &["rev-parse", "HEAD"]), None, QUICK_LIMIT); let hash = run.output.trim(); - (run.ok && !hash.is_empty()).then(|| hash.to_string()) + if !run.ok { + return Err("git could not read the current commit".to_string()); + } + if !matches!(hash.len(), 40 | 64) || !hash.chars().all(|c| c.is_ascii_hexdigit()) { + return Err("git did not return a full commit id".to_string()); + } + Ok(hash.to_string()) } /// The paths `git status --porcelain=v1 -z` lists (renames name the new path). @@ -799,6 +805,36 @@ mod tests { let _ = std::fs::remove_dir_all(&repo); } + #[test] + fn the_full_head_hash_starts_with_the_short_one() { + if Command::new("git").arg("--version").output().is_err() { + assert!(std::env::var_os("CI").is_none(), "git is not on PATH"); + return; + } + let repo = std::env::temp_dir().join(format!("plan2code-head-full-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&repo); + std::fs::create_dir_all(&repo).unwrap(); + let git_in = |args: &[&str]| { + let status = Command::new("git") + .args(["-c", "user.name=t", "-c", "user.email=t@example.com"]) + .args(args) + .current_dir(&repo) + .status() + .unwrap(); + assert!(status.success(), "git {args:?}"); + }; + git_in(&["init", "-q"]); + assert!(git_head_full(&repo).is_err(), "no commit yet"); + std::fs::write(repo.join("a.txt"), "x").unwrap(); + git_in(&["add", "-A"]); + git_in(&["commit", "-q", "--no-gpg-sign", "-m", "first"]); + let full = git_head_full(&repo).unwrap(); + let short = git_head_short(&repo).unwrap(); + assert!(full.starts_with(&short), "{full} / {short}"); + assert!(matches!(full.len(), 40 | 64)); + let _ = std::fs::remove_dir_all(&repo); + } + #[test] fn the_commit_message_is_read_from_the_scripts_output_without_a_shell() { let ok = r#"{"ok":true,"subject":"Add it","message":"Add it\n\nAI Assisted"}"#; diff --git a/plan2code-app/src-tauri/src/main.rs b/plan2code-app/src-tauri/src/main.rs index 8a1dac4..ace96fe 100644 --- a/plan2code-app/src-tauri/src/main.rs +++ b/plan2code-app/src-tauri/src/main.rs @@ -18,6 +18,7 @@ use plan2code_app_lib::node_check; use plan2code_app_lib::project::{self, ProjectDir}; use plan2code_app_lib::quit_prompt::{loop_quit_prompt, quit_prompt, QuitCase}; use plan2code_app_lib::restart_brief; +use plan2code_app_lib::review_loop::{self, ReviewSlot}; use plan2code_app_lib::session_reader; use plan2code_app_lib::settings; #[cfg(windows)] @@ -54,6 +55,9 @@ struct AppState { // The Implementation Loop running now, if any: in memory only, so an app // restart ends it (NFR-5). loop_run: LoopSlot, + // The Review Loop running now, or the one that stopped and waits for + // Continue or its report: in memory only, so an app restart ends it. + review_run: ReviewSlot, // The last loop's project, spec, launch choice and confirmed quick check, // kept after the running record is gone so Resume, Fix together with an agent and // Finalize still work. Memory only. @@ -450,7 +454,7 @@ fn sync_agent_env(app: &tauri::AppHandle) { // commands, and `agent_input` stays open so a trust or login prompt can be // answered. fn refuse_while_looping(state: &AppState, what: &str) -> Result<(), String> { - if loop_driver::is_running(&state.loop_run) { + if loop_driver::is_running(&state.loop_run) || review_loop::is_running(&state.review_run) { return Err(format!( "A loop is running. Stop it before you change the {what}." )); @@ -729,6 +733,7 @@ fn confirm_quit(app: &tauri::AppHandle) { fn agent_is_active(app: &tauri::AppHandle) -> bool { let state = app.state::(); loop_driver::is_running(&state.loop_run) + || review_loop::is_running(&state.review_run) || current_agent(&state).is_some_and(|agent| agent.is_active()) } @@ -739,6 +744,7 @@ fn quit_app(app: &tauri::AppHandle) { let restart = RESTART_ON_QUIT.lock().ok().and_then(|mut plan| plan.take()); let state = app.state::(); loop_driver::abandon(&state.loop_run); + review_loop::abandon(&state.review_run); if let Some(agent) = current_agent(&state) { agent.stop(); } @@ -1410,8 +1416,8 @@ async fn start_loop( spec: String, skip_confirm_if_same: bool, ) -> Result { - if loop_driver::is_running(&state.loop_run) { - return Err("A loop is already running".to_string()); + if loop_driver::is_running(&state.loop_run) || review_loop::is_running(&state.review_run) { + return Err("A loop is already running in this window.".to_string()); } let project = state .project @@ -1601,11 +1607,203 @@ fn loop_stop_now(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<() #[tauri::command] fn loop_state(state: State<'_, AppState>) -> Option { loop_driver::current_event(&state.loop_run) + .or_else(|| review_loop::current_event(&state.review_run)) +} + +// The project folder and the agent a Review Loop would use, or why there is none. +fn review_target( + state: &AppState, +) -> Result<(std::path::PathBuf, Arc, loop_driver::Launch), String> { + let project = state + .project + .lock() + .map_err(|e| e.to_string())? + .as_ref() + .map(|p| p.dir.clone()) + .ok_or("no project folder chosen")?; + let agent = current_agent(state) + .filter(|a| a.folder() == &project) + .ok_or("Start an agent first, with permission checks off.")?; + // A stopped agent has forgotten its launch choice; the run kept its own. + let launch = agent + .launch_choice() + .or_else(|| { + state + .review_run + .lock() + .ok() + .and_then(|run| run.as_ref().map(|r| r.launch.clone())) + }) + .ok_or("Start an agent first, with permission checks off.")?; + Ok((project, agent, launch)) +} + +// What the Review Loop's setup screen shows about the agent a run would use, +// and the notification settings the Implementation Loop's setup holds. +#[tauri::command] +fn review_loop_facts(state: State<'_, AppState>) -> review_loop::ReviewFacts { + let running = + loop_driver::is_running(&state.loop_run) || review_loop::is_running(&state.review_run); + let project = state + .project + .lock() + .ok() + .and_then(|guard| guard.as_ref().map(|p| p.dir.clone())); + let setup = project + .as_deref() + .and_then(|dir| loop_driver::read_setup(dir).ok()) + .unwrap_or_default(); + let agent = current_agent(&state) + .and_then(|a| a.launch_choice()) + .map(|choice| choice.0) + .or_else(|| state.launch.agent.as_deref().and_then(agents::find_agent)); + review_loop::facts(agent.as_ref(), running, &setup) +} + +// Starts a Review Loop. Async and off the main thread: the pre-run commit and +// the start boundary run git. The notification comes from the Implementation +// Loop's setup file, never from the page's message. +#[tauri::command] +async fn review_loop_start( + app: tauri::AppHandle, + state: State<'_, AppState>, + setup: review_loop::ReviewRequest, +) -> Result { + let (project, agent, launch) = review_target(&state)?; + let loop_setup = loop_driver::read_setup(&project).unwrap_or_default(); + let setup = setup.into_setup(&loop_setup); + let (slot, phases) = (state.review_run.clone(), state.loop_run.clone()); + let hooks = loop_hooks(&app); + tauri::async_runtime::spawn_blocking(move || { + review_loop::start_review_loop(&slot, &phases, agent, launch, project, setup, hooks) + }) + .await + .map_err(|e| e.to_string())??; + Ok(true) +} + +// Stop after this round: it finishes, is judged and committed, then the run stops. +#[tauri::command] +fn review_loop_stop_after( + app: tauri::AppHandle, + state: State<'_, AppState>, + on: bool, +) -> Result<(), String> { + let event = review_loop::request_stop_after(&state.review_run, on)?; + let _ = app.emit("loop-state", &event); + Ok(()) +} + +// Stop now: the flag first, then the agent ends at once. Nothing more is +// committed; the stop screen offers Keep or Discard for the partial changes. +#[tauri::command] +fn review_loop_stop_now(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<(), String> { + let agent = current_agent(&state); + review_loop::request_stop_now(&state.review_run, agent.as_deref(), |event| { + let _ = app.emit("loop-state", event); + })?; + Ok(()) +} + +// Keep the partial changes of a Stop now, or put the tree back to the last +// finished round. +#[tauri::command] +async fn review_loop_partial(state: State<'_, AppState>, keep: bool) -> Result<(), String> { + let home = session_reader::console_home().ok_or("no home folder found")?; + let slot = state.review_run.clone(); + // The end screen is posted through node, so this is not main-thread work. + tauri::async_runtime::spawn_blocking(move || review_loop::settle_partial(&slot, keep, &home)) + .await + .map_err(|e| e.to_string())? +} + +// Sign off a finished Review Loop: fix the Suggestions the person ticked (one +// fixer session and its fresh check), squash the round commits when asked, and +// show the finished screen. Async and off the main thread: it runs git. +#[tauri::command] +async fn review_loop_sign_off( + app: tauri::AppHandle, + state: State<'_, AppState>, + picks: Vec, + squash: bool, +) -> Result<(), String> { + let (project, agent, _) = review_target(&state)?; + let same_project = state + .review_run + .lock() + .ok() + .and_then(|run| run.as_ref().map(|r| r.project == project)); + if same_project != Some(true) { + return Err("The project changed since that Review Loop.".to_string()); + } + let home = session_reader::console_home().ok_or("no home folder found")?; + let (slot, phases) = (state.review_run.clone(), state.loop_run.clone()); + let hooks = loop_hooks(&app); + tauri::async_runtime::spawn_blocking(move || { + review_loop::sign_off( + &slot, + &phases, + agent, + hooks, + loop_driver::Limits::default(), + home, + &picks, + squash, + true, + ) + }) + .await + .map_err(|e| e.to_string())? +} + +// The finished screen's PR Prep and Fix what's left by hand: an ordinary +// session on the skill, with no `--loop`, so the person talks to the agent. +#[tauri::command] +fn review_loop_next(state: State<'_, AppState>, next: String) -> Result<(), String> { + let prompt = review_loop::next_prompt(&state.review_run, &next)?; + let (_, agent, launch) = review_target(&state)?; + loop_driver::start_with(&agent, &launch, prompt) +} + +// Continue a stopped Review Loop: the next round from the last boundary; past +// the cap one round at a time, never above six in all. +#[tauri::command] +async fn review_loop_continue( + app: tauri::AppHandle, + state: State<'_, AppState>, +) -> Result<(), String> { + let (project, agent, _) = review_target(&state)?; + // A stopped run stays after a change of project: its git work would run + // in the old folder while the agent works in the new one. + let same_project = state + .review_run + .lock() + .ok() + .and_then(|run| run.as_ref().map(|r| r.project == project)); + if same_project != Some(true) { + return Err("The project changed since that Review Loop.".to_string()); + } + let home = session_reader::console_home().ok_or("no home folder found")?; + let (slot, phases) = (state.review_run.clone(), state.loop_run.clone()); + let hooks = loop_hooks(&app); + tauri::async_runtime::spawn_blocking(move || { + review_loop::continue_run( + &slot, + &phases, + agent, + hooks, + loop_driver::Limits::default(), + home, + true, + ) + }) + .await + .map_err(|e| e.to_string())? } // The last loop, for the stop and finish screens' buttons. fn last_loop(state: &AppState) -> Result { - if loop_driver::is_running(&state.loop_run) { + if loop_driver::is_running(&state.loop_run) || review_loop::is_running(&state.review_run) { return Err("A loop is running".to_string()); } let last = state @@ -1808,6 +2006,14 @@ fn main() { loop_stop_after_phase, loop_stop_now, loop_state, + review_loop_facts, + review_loop_start, + review_loop_stop_after, + review_loop_stop_now, + review_loop_partial, + review_loop_sign_off, + review_loop_next, + review_loop_continue, loop_resume, loop_fix, loop_ask, @@ -1848,6 +2054,7 @@ fn main() { .map(|session| session.state) .unwrap_or(serde_json::Value::Null); loop_driver::note_page(&state.loop_run, ¬ice.workflow, ¬ice.sid, &page); + review_loop::note_page(&state.review_run, ¬ice.workflow, ¬ice.sid, &page); let _ = handle.emit("console-page", ¬ice); } else { eprintln!( diff --git a/plan2code-app/src-tauri/src/phase_rounds.rs b/plan2code-app/src-tauri/src/phase_rounds.rs new file mode 100644 index 0000000..89bc22a --- /dev/null +++ b/plan2code-app/src-tauri/src/phase_rounds.rs @@ -0,0 +1,631 @@ +//! Extra review rounds inside an Implementation Loop phase (FR-28). +//! +//! When a phase's own review leaves a Critical or a Warning, fresh round +//! sessions review (and fix) the phase before it is judged and committed: the +//! first round looks at the whole phase diff and briefs the fixer with the +//! phase agent's unfixed findings, each later round looks only at what the +//! round before it changed. The rounds run here, one at a time, inside the +//! phase's report handling; the rules are `round_logic`'s, the session pieces +//! are `loop_shared`'s and the scope and prompt are the Review Loop's. A phase +//! never commits per round: its own commit at the end carries everything +//! (NFR-1). + +use std::path::{Path, PathBuf}; +use std::time::{Instant, SystemTime}; + +use serde_json::Value; + +use crate::agent_manager::AgentState; +use crate::loop_driver::{ + self, Finding as PhaseFinding, FixLevel, Left, LoopSetup, RoundWait, StopCause, Strength, +}; +use crate::loop_report::RoundEntry; +use crate::loop_shared::retry::should_retry; +use crate::loop_shared::rounds::{ + finding_line, page_is_this_round, proofs_for, report_text, reviewer_brief, role_word, + round_outcome_in, +}; +use crate::loop_shared::session::{read_session_state, start_session, Ctx}; +use crate::loop_shared::watch::silence_expired; +use crate::models::StrengthRow; +use crate::review_loop::round_prompt; +use crate::round_boundary::{self, Boundary}; +use crate::round_logic::{ + self, Finding, Next, Role, RoundOutcome, RoundReview, RunView, StopReason, Verdict, MAX_ROUNDS, +}; +use crate::session_reader; + +/// What the rounds need, copied out of the loop's record. +pub struct RoundsInput { + pub project: PathBuf, + pub phase: u32, + pub setup: LoopSetup, + /// The most rounds to run (the setup's Review rounds per phase). + pub cap: u32, + /// One session per round (the agent starts its own helper) or two. + pub helpers: bool, + /// The working tree as the phase began. + pub start: Boundary, + /// The phase agent's findings it left unfixed: the first fixer's brief. + pub unfixed: Vec, + /// Where each round's scope file and diff are written. + pub dir: PathBuf, +} + +/// How the rounds ended. +#[derive(Debug)] +pub enum RoundsEnd { + /// A clean round, or the cap: the last round's counts judge the phase. + Done(Done), + /// Stop now was pressed. + Person { rounds: Vec }, + /// A round failed after its retry. + Failed { + reason: String, + rounds: Vec, + }, +} + +#[derive(Debug, Default)] +pub struct Done { + pub rounds: Vec, + pub critical: u32, + pub warning: u32, + pub suggestion: u32, + pub unfixed: Vec, +} + +/// How one session of a round ended. +enum SessionEnd { + Outcome(Box, Value), + /// Why it failed, and the cause the retry rule reads (never the words). + Failed(StopCause, String), + Person, +} + +/// What a finished round gives the next step. +struct Played { + outcome: RoundOutcome, + verdict: Verdict, + retried: bool, + started: String, + strength: String, +} + +fn clock() -> String { + chrono::Local::now().format("%Y-%m-%d %H:%M").to_string() +} + +fn one_line(text: &str) -> String { + text.split_whitespace().collect::>().join(" ") +} + +/// Whether the loop's agent can start a helper from inside a session. +pub fn helpers_for(ctx: &Ctx) -> bool { + crate::review_loop::agent_helpers(&ctx.launch.0) +} + +/// The banner's step, "Review round 1 of 2". +fn banner(ctx: &Ctx, round: u32, cap: u32) { + if let Some(rec) = loop_driver::lock(&ctx.slot) + .as_mut() + .filter(|r| r.run_id == ctx.run_id) + { + rec.step_text = Some(format!("Review round {round} of {cap}")); + } + loop_driver::emit(ctx); +} + +fn clear_wait(ctx: &Ctx) { + if let Some(rec) = loop_driver::lock(&ctx.slot) + .as_mut() + .filter(|r| r.run_id == ctx.run_id) + { + rec.round_wait = None; + } +} + +/// The strength the phase runs on now (a retry steps it up first), as +/// `start_phase` reads it. +fn strength_now(ctx: &Ctx) -> Option<(Strength, StrengthRow)> { + let guard = loop_driver::lock(&ctx.slot); + let rec = guard.as_ref().filter(|r| r.run_id == ctx.run_id)?; + let word = rec.phase_run(rec.current)?.strength?; + Some((word, rec.strength_rows.get(word.word())?.clone())) +} + +fn step_strength_up(ctx: &Ctx) { + if let Some(rec) = loop_driver::lock(&ctx.slot) + .as_mut() + .filter(|r| r.run_id == ctx.run_id) + { + let at = rec.current; + rec.step_strength_up(at); + } +} + +/// The text of a round's scope file: the diff to review, the reviewer's report +/// for a fixer and, in the first round, what the phase agent left unfixed. +fn scope_text( + round: u32, + role: Role, + diff: &Path, + report: Option<&Path>, + brief: &[PhaseFinding], +) -> String { + let mut text = format!( + "# Phase review round {round} scope\n\nRole: {}\n", + role_word(role) + ); + if round == 1 { + text.push_str(&format!( + "\nReview exactly this diff, everything the phase changed, and nothing else:\n\n- {}\n", + diff.display() + )); + } else { + text.push_str(&format!( + "\nReview exactly this diff, the previous round's changes, and nothing else:\n\n- {}\n", + diff.display() + )); + } + if !brief.is_empty() && role != Role::Reviewer { + text.push_str("\nThe phase's own review left these findings unfixed (fix them):\n\n"); + for finding in brief { + text.push_str(&finding_line(&Finding { + title: finding.title.clone(), + file: finding.file.clone(), + line: None, + })); + text.push('\n'); + } + } + if let Some(report) = report { + text.push_str(&format!( + "\nThe reviewer's report (fix its Critical and Warning findings):\n\n- {}\n", + report.display() + )); + } + text +} + +fn start_one( + ctx: &Ctx, + input: &RoundsInput, + round: u32, + role: Role, + scope: &str, + attempt: u32, +) -> Result { + let dir = input + .dir + .join(format!("round-{round}-{}-t{attempt}", role_word(role))); + std::fs::create_dir_all(&dir) + .map_err(|err| format!("could not make {}: {err}", dir.display()))?; + let scope_file = dir.join("scope.md"); + std::fs::write(&scope_file, scope) + .map_err(|err| format!("could not write {}: {err}", scope_file.display()))?; + let prompt = round_prompt(round, role, &scope_file); + // A running session (the phase's own, a silent one being retried) ends first. + ctx.agent.stop(); + if let Some(rec) = loop_driver::lock(&ctx.slot) + .as_mut() + .filter(|r| r.run_id == ctx.run_id) + { + rec.round_wait = Some(RoundWait { + round, + role, + sid: None, + candidate: None, + }); + rec.last_activity = SystemTime::now(); + rec.activity_checked = Instant::now(); + } + let on = strength_now(ctx); + let started = start_session(ctx, &prompt, on.as_ref().map(|(word, row)| (*word, row)))?; + Ok(started.generation) +} + +/// The round's session id: the page `note_page` handed over, or a candidate +/// whose state now shows the agent's lock. +fn session_id(ctx: &Ctx, round: u32, role: Role) -> Option { + let candidate = { + let guard = loop_driver::lock(&ctx.slot); + let wait = guard + .as_ref() + .filter(|r| r.run_id == ctx.run_id)? + .round_wait + .as_ref()?; + if let Some(sid) = &wait.sid { + return Some(sid.clone()); + } + wait.candidate.clone()? + }; + let state = read_session_state(ctx, &candidate)?; + if !page_is_this_round(&state, round, role) { + return None; + } + let mut guard = loop_driver::lock(&ctx.slot); + let wait = guard + .as_mut() + .filter(|r| r.run_id == ctx.run_id)? + .round_wait + .as_mut()?; + wait.sid.get_or_insert(candidate); + wait.sid.clone() +} + +fn crashed(ctx: &Ctx, generation: u64) -> Option { + let seen = ctx.agent.snapshot(); + match seen.state { + AgentState::Ended { reason } if seen.generation == generation => Some(reason), + _ => None, + } +} + +/// Watch one round session until it reports, fails or is stopped. The same +/// rules as a phase's watch: a crash, silence or a console that never opens +/// fail it, and so does a question (a round cannot be answered). +fn watch_session( + ctx: &Ctx, + setup: &LoopSetup, + round: u32, + role: Role, + generation: u64, +) -> SessionEnd { + let began = Instant::now(); + let mut last_activity = SystemTime::now(); + let mut checked = Instant::now(); + loop { + std::thread::sleep(ctx.limits.watch_every); + { + let guard = loop_driver::lock(&ctx.slot); + match guard.as_ref().filter(|r| r.run_id == ctx.run_id) { + // The loop ended under us (a stop, a restart): nothing to judge. + None => return SessionEnd::Person, + Some(rec) if rec.stop_now => { + drop(guard); + ctx.agent.stop(); + return SessionEnd::Person; + } + Some(_) => {} + } + } + let Some(sid) = session_id(ctx, round, role) else { + if let Some(reason) = crashed(ctx, generation) { + return SessionEnd::Failed( + StopCause::Crash, + format!("the agent crashed ({reason})"), + ); + } + if began.elapsed() > ctx.limits.notice_wait { + return SessionEnd::Failed( + StopCause::NoSession, + "the round's console never opened".to_string(), + ); + } + continue; + }; + let state = session_reader::load(&ctx.home, &sid) + .ok() + .map(|session| (session.state, session.dir)); + if let Some((state, _)) = &state { + if let Some(found) = round_outcome_in(state, round, role) { + ctx.agent.stop(); + return match found { + Ok(outcome) => SessionEnd::Outcome(Box::new(outcome), state.clone()), + Err(reason) => SessionEnd::Failed(StopCause::Refused(reason.clone()), reason), + }; + } + } + // An agent that writes its report and exits between two looks is + // judged, not called a crash. + if let Some(reason) = crashed(ctx, generation) { + let again = read_session_state(ctx, &sid); + if let Some(Ok(outcome)) = again + .as_ref() + .and_then(|state| round_outcome_in(state, round, role)) + { + return SessionEnd::Outcome(Box::new(outcome), again.unwrap_or(Value::Null)); + } + return SessionEnd::Failed(StopCause::Crash, format!("the agent crashed ({reason})")); + } + let mut quiet = None; + if let Some((state, dir)) = &state { + if let Some(question) = loop_driver::first_open_question(state) { + ctx.agent.stop(); + let reason = format!("the agent asked a question: {}", one_line(&question)); + return SessionEnd::Failed(StopCause::Question, reason); + } + quiet = state["agent"]["quietMinutes"] + .as_u64() + .and_then(|m| u32::try_from(m).ok()); + if checked.elapsed() >= ctx.limits.activity_every { + checked = Instant::now(); + if let Some(time) = loop_driver::newest_work(dir, &input_project(ctx)) { + let time = loop_driver::clamp_to_now(time); + if time > last_activity { + last_activity = time; + } + } + } + } + if silence_expired(SystemTime::now(), last_activity, setup, quiet, false) { + let minutes = setup.silence_minutes.max(quiet.unwrap_or(0)).min(60); + return SessionEnd::Failed( + StopCause::Silence, + format!("the agent went silent for {minutes} minutes"), + ); + } + } +} + +/// The project the loop builds in, for the silence rule's look at the tree. +fn input_project(ctx: &Ctx) -> PathBuf { + loop_driver::lock(&ctx.slot) + .as_ref() + .filter(|r| r.run_id == ctx.run_id) + .map(|r| r.project.clone()) + .unwrap_or_default() +} + +/// One session with its one retry (a step up in strength): `Ok` with the +/// session's outcome, `Err(None)` when stop now ended it, `Err(Some)` with the +/// reason when the retry failed too. `retried` says the retry was used. +fn session_with_retry( + ctx: &Ctx, + input: &RoundsInput, + round: u32, + role: Role, + scope: &str, + retried: &mut bool, +) -> Result<(RoundOutcome, Value), Option> { + let mut attempt = 0; + loop { + let begun = start_one(ctx, input, round, role, scope, attempt).map_err(Some); + let end = match begun { + Ok(generation) => watch_session(ctx, &input.setup, round, role, generation), + Err(Some(reason)) => SessionEnd::Failed( + StopCause::Refused(reason.clone()), + format!("the round could not start ({reason})"), + ), + Err(None) => SessionEnd::Person, + }; + clear_wait(ctx); + match end { + SessionEnd::Person => return Err(None), + SessionEnd::Outcome(outcome, state) => return Ok((*outcome, state)), + SessionEnd::Failed(cause, reason) => { + // A crash, silence or a console that never opened gets one + // fresh try a strength up, as a phase does; `should_retry` + // reads the typed cause, so any other failure (a question, an + // unreadable report) fails the round. + if !*retried && should_retry(&cause, &input.setup, 0) { + *retried = true; + attempt += 1; + step_strength_up(ctx); + continue; + } + return Err(Some(reason)); + } + } + } +} + +/// Play one round: one session, or a reviewer then a fixer that never saw the +/// review. A failed session after its retry comes back as the round's failure. +fn play_round( + ctx: &Ctx, + input: &RoundsInput, + round: u32, + from: &Boundary, + to: &Boundary, +) -> Result> { + let dir = input.dir.join(format!("round-{round}")); + std::fs::create_dir_all(&dir) + .map_err(|err| Some(format!("could not make {}: {err}", dir.display())))?; + let diff = dir.join(format!("round-{round}.diff")); + round_boundary::diff(&input.project, from, to, &diff).map_err(Some)?; + let brief: &[PhaseFinding] = if round == 1 { &input.unfixed } else { &[] }; + let started = clock(); + let strength = strength_now(ctx).map_or_else(String::new, |(word, _)| word.label().to_string()); + let mut retried = false; + let (outcome, state) = if input.helpers { + let scope = scope_text(round, Role::Both, &diff, None, brief); + session_with_retry(ctx, input, round, Role::Both, &scope, &mut retried)? + } else { + let scope = scope_text(round, Role::Reviewer, &diff, None, &[]); + let (reviewed, state) = + session_with_retry(ctx, input, round, Role::Reviewer, &scope, &mut retried)?; + let proofs = proofs_for(&state, &reviewed, Role::Reviewer); + match round_logic::judge_round(&reviewed, &proofs) { + Verdict::Failed(reason) => return Err(Some(reason)), + Verdict::Clean => (reviewed, state), + Verdict::Findings { .. } => { + let text = reviewed + .report + .as_deref() + .and_then(|id| report_text(&state, id)) + .unwrap_or_default(); + let report = dir.join("reviewer-report.md"); + std::fs::write(&report, reviewer_brief(&text, &reviewed)) + .map_err(|err| Some(format!("could not write {}: {err}", report.display())))?; + let scope = scope_text(round, Role::Fixer, &diff, Some(&report), brief); + let (mut fixed, state) = + session_with_retry(ctx, input, round, Role::Fixer, &scope, &mut retried)?; + round_logic::hold_reviewer_counts( + &mut fixed.review, + reviewed.review.critical, + reviewed.review.warning, + ); + (fixed, state) + } + } + }; + let role = outcome.role; + let proofs = proofs_for(&state, &outcome, role); + let verdict = round_logic::judge_round(&outcome, &proofs); + if let Verdict::Failed(reason) = &verdict { + return Err(Some(reason.clone())); + } + Ok(Played { + outcome, + verdict, + retried, + started, + strength, + }) +} + +fn titles(findings: &[Finding]) -> Vec { + findings.iter().map(|f| f.title.clone()).collect() +} + +fn entry_of(round: u32, played: &Played) -> RoundEntry { + let review: &RoundReview = &played.outcome.review; + RoundEntry { + n: round, + critical: review.critical, + warning: review.warning, + suggestion: review.suggestion, + fixed: titles(&review.fixed), + left_open: titles(&review.unfixed), + commit: None, + tests: played + .outcome + .tests + .as_ref() + .map_or_else(String::new, |t| t.summary.clone()), + started: played.started.clone(), + ended: clock(), + strength: played.strength.clone(), + retried: played.retried, + } +} + +fn snapshot(input: &RoundsInput) -> Result { + round_boundary::snapshot(&input.project) +} + +/// Run the phase's extra rounds. Never commits and never marks anything. +pub fn run_rounds(ctx: &Ctx, input: &RoundsInput) -> RoundsEnd { + let cap = input.cap.clamp(1, MAX_ROUNDS); + let mut entries: Vec = Vec::new(); + // Where the phase's own work ended: round 1 reviews start to here. + let mut round_before = match snapshot(input) { + Ok(boundary) => boundary, + Err(reason) => { + return RoundsEnd::Failed { + reason: format!("the phase's work could not be recorded ({reason})"), + rounds: entries, + } + } + }; + let mut from = input.start.clone(); + let mut to = round_before.clone(); + let mut round = 1; + loop { + banner(ctx, round, cap); + let played = match play_round(ctx, input, round, &from, &to) { + Ok(played) => played, + Err(None) => return RoundsEnd::Person { rounds: entries }, + Err(Some(reason)) => { + return RoundsEnd::Failed { + reason, + rounds: entries, + } + } + }; + entries.push(entry_of(round, &played)); + loop_driver::keep_rounds(ctx, &entries); + let stop_now = loop_driver::stop_requested(ctx); + let view = RunView { + round, + cap, + rounds_run: round, + suggestions_on: false, + suggestions_pending: false, + batch_done: false, + // The round's one retry is spent inside `session_with_retry`. + retried_this_round: true, + stop_after_round: false, + stop_now, + }; + match round_logic::next_step(&view, &played.verdict) { + Next::StartRound(next) => { + let after = match snapshot(input) { + Ok(boundary) => boundary, + Err(reason) => { + return RoundsEnd::Failed { + reason: format!("the round's work could not be recorded ({reason})"), + rounds: entries, + } + } + }; + // The next round reviews what this one changed. + from = round_before; + to = after.clone(); + round_before = after; + round = next; + } + Next::Stop(StopReason::Person) => return RoundsEnd::Person { rounds: entries }, + Next::Stop(StopReason::Failed(reason)) => { + return RoundsEnd::Failed { + reason, + rounds: entries, + } + } + // A clean round or the cap; the suggestions batch and the final + // check do not exist inside a phase. + Next::Stop(_) | Next::Retry | Next::SuggestionsBatch | Next::FinalCheck => { + let review = &played.outcome.review; + return RoundsEnd::Done(Done { + rounds: entries, + critical: review.critical, + warning: review.warning, + suggestion: review.suggestion, + unfixed: review.unfixed.clone(), + }); + } + } + } +} + +/// The phase agent's report with the last round's counts in place of its own +/// `review.left`, so `judge_outcome` decides on what is left after the rounds. +/// A phase that reported `failed` only for its findings reads as passed once +/// they are gone; the judge still checks the spec, the tests and the rest. +pub fn judged_after(mut outcome: loop_driver::Outcome, done: &Done) -> loop_driver::Outcome { + let mut review = outcome.review.take().unwrap_or_default(); + review.ran = true; + review.recheck = true; + review.left = Left { + critical: done.critical, + warning: done.warning, + suggestion: done.suggestion, + }; + // The agent's own Critical and Warning entries are replaced by the last + // round's; Suggestions it left stay. The round's list has no levels: its + // first `critical` entries read as Critical, the rest as Warning. + review.unfixed.retain(|f| f.level == FixLevel::Suggestion); + let mut critical_left = done.critical; + for finding in &done.unfixed { + let level = if critical_left > 0 { + critical_left -= 1; + FixLevel::Critical + } else { + FixLevel::Warning + }; + review.unfixed.push(PhaseFinding { + level, + title: finding.title.clone(), + file: finding.file.clone(), + reason: None, + }); + } + outcome.review = Some(review); + if outcome.result == "failed" && outcome.reason.as_deref() == Some("findings") { + outcome.result = "passed".to_string(); + outcome.reason = None; + } + outcome +} diff --git a/plan2code-app/src-tauri/src/review_loop.rs b/plan2code-app/src-tauri/src/review_loop.rs new file mode 100644 index 0000000..ba3f82e --- /dev/null +++ b/plan2code-app/src-tauri/src/review_loop.rs @@ -0,0 +1,4868 @@ +//! The Review Loop's driver: rounds of review and fix, each in a fresh agent +//! session, the app judging what every round reports. The agent reviews and +//! fixes and reports (`roundOutcome`); only this module stages, commits and +//! records boundaries, so the agent never runs git (NFR-3). The run record +//! lives in memory alone: an app restart ends the run (NFR-5). +//! +//! The rules are in `round_logic` (judging, the next step, the commit subject) +//! and the boundaries in `round_boundary`; this module is the part with an +//! agent, git, files and a clock in it. A round runs in one session (`both`, +//! for an agent that can start a helper) or in two (a `reviewer` session, then +//! a `fixer` one that never saw the review: FR-17). A crashed, silent or failed +//! session gets one fresh retry one strength up; the second failure stops the +//! run with the rounds that finished kept (FR-3). + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::thread; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::agent_manager::{AgentManager, AgentState}; +use crate::agents::Agent; +#[cfg(not(test))] +use crate::console_supervisor::find_console_dir; +use crate::loop_commit; +use crate::loop_driver::{ + self, Hooks, Launch, Limits, LoopSlot, LoopStateEvent, RoundCount, StopCause, Strength, +}; +use crate::loop_notify::NotifyKind; +use crate::loop_report::{EntryKind, EntryResult, LoopReport, ReportEntry, RoundEntry}; +use crate::loop_shared::report_list; +use crate::loop_shared::retry::next_strength_word; +use crate::loop_shared::rounds::{ + finding_line, page_is_this_round, proofs_for, report_text, reviewer_brief, + round_outcome_in as outcome_for_round, +}; +use crate::loop_shared::session::{read_session_state, start_session, Ctx}; +use crate::loop_shared::watch::{silence_expired, watch_loop, WatchStep}; +use crate::loop_tools; +use crate::models::StrengthRow; +use crate::review_report::review_report_markdown; +use crate::round_boundary::{self, Boundary}; +use crate::round_logic::{ + self, Finding, Next, Role, RoundOutcome, RoundReview, RoundTests, RunView, StopReason, Verdict, + MAX_ROUNDS, +}; +use crate::session_reader; + +// ---------------------------------------------------------------- the setup + +/// What the person asked a run to review. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ReviewScope { + Branch, + Uncommitted, + Spec, +} + +impl ReviewScope { + pub fn word(self) -> &'static str { + match self { + ReviewScope::Branch => "branch", + ReviewScope::Uncommitted => "uncommitted", + ReviewScope::Spec => "spec", + } + } +} + +/// Whether the run commits each round or only measures it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + Commit, + Snapshot, +} + +/// How a round runs: one session with a helper reviewing, or two sessions. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Shape { + OneSession, + TwoSession, +} + +/// The Start screen's picks, plus the notification the Implementation Loop's +/// setup holds (read by the app, never taken from the page). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ReviewSetup { + pub scope: ReviewScope, + /// The spec folder (`specs/`) for the `spec` scope. + pub spec: Option, + /// Rounds before the run stops at its cap, 1 to 6. + pub cap: u32, + /// Commit each round (off: snapshot mode). + pub commit: bool, + /// The person agreed to commit their uncommitted work first. + pub pre_run_commit_agreed: bool, + /// Fix the collected Suggestions in one batch after the run. + pub suggestions: bool, + /// The strength every round runs on; `None` runs on the launch choice. + pub strength: Option, + pub silence_minutes: u32, + pub notify_rounds: bool, + pub notify_kind: NotifyKind, + pub notify_url: String, + pub notify_param: String, +} + +impl Default for ReviewSetup { + fn default() -> Self { + ReviewSetup { + scope: ReviewScope::Branch, + spec: None, + cap: 3, + commit: true, + pre_run_commit_agreed: false, + suggestions: false, + strength: None, + silence_minutes: 20, + notify_rounds: false, + notify_kind: NotifyKind::default(), + notify_url: String::new(), + notify_param: String::new(), + } + } +} + +// -------------------------------------------------------------- the record + +/// What the banner says a round is doing. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ReviewStep { + Starting, + Reviewing, + Fixing, + Testing, + Committing, +} + +impl ReviewStep { + pub fn label(self) -> &'static str { + match self { + ReviewStep::Starting => "Starting", + ReviewStep::Reviewing => "Reviewing", + ReviewStep::Fixing => "Fixing", + ReviewStep::Testing => "Testing", + ReviewStep::Committing => "Committing", + } + } +} + +/// Which session of the run is going on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Stage { + /// A one-session round. + Both, + /// A two-session round's reviewer. + Reviewer, + /// A two-session round's fixer. + Fixer, + /// The Suggestions batch: a fixer on the collected Suggestions. + Batch, + /// The final check: one fresh reviewer on the batch's diff. + Final, +} + +impl Stage { + pub fn role(self) -> Role { + match self { + Stage::Both => Role::Both, + Stage::Reviewer | Stage::Final => Role::Reviewer, + Stage::Fixer | Stage::Batch => Role::Fixer, + } + } + + fn word(self) -> &'static str { + match self { + Stage::Both => "both", + Stage::Reviewer => "reviewer", + Stage::Fixer => "fixer", + Stage::Batch => "batch", + Stage::Final => "final", + } + } +} + +/// One finished round, for the report and the banner. +#[derive(Clone, Debug, Default)] +pub struct RoundRecord { + pub n: u32, + /// Where the round ended: the next round's diff starts here. + pub boundary: Option, + pub strength: Option, + pub model: Option, + pub effort: Option, + pub started_at: String, + pub ended_at: String, + pub retried: bool, + /// The retry could not go a strength up (already Best, or not mapped). + pub could_not_step_up: bool, + pub verdict: Option, + pub critical: u32, + pub warning: u32, + pub suggestion: u32, + pub fixed: Vec, + pub unfixed: Vec, + pub suggestions: Vec, + pub tests: Option, + pub commit: Option, + pub summary: String, +} + +/// The Suggestions batch and its final check, kept apart from the rounds. +#[derive(Clone, Debug, Default)] +pub struct BatchRecord { + /// How many rounds had finished when the batch began: orders it among them. + pub after_rounds: usize, + /// The Suggestions the fixer was briefed with. + pub briefed: Vec, + /// Where the run stood before the batch: the final check's diff starts here. + pub before: Option, + pub boundary: Option, + pub verdict: Option, + pub commit: Option, + pub summary: String, + pub final_check: Option, + pub final_critical: u32, + pub final_warning: u32, +} + +/// What Stop now left behind: the partial changes of the stopped round. +#[derive(Clone, Debug, Default)] +pub struct Partial { + /// The diff from the last finished boundary to a snapshot taken at the stop. + pub diff: PathBuf, + pub files: u32, + pub added: u32, + pub removed: u32, + /// Files that did not exist at the boundary: what Discard may delete. + pub new_files: Vec, + /// Still to be kept or discarded. + pub pending: bool, +} + +static NEXT_RUN: AtomicU64 = AtomicU64::new(1); + +/// One Review Loop run, with the overview's run-record fields and the live +/// fields the watcher needs. +#[derive(Clone, Debug)] +pub struct ReviewRun { + /// Tells a watch thread whether the record is still its own run's. + pub run_id: u64, + pub id: String, + pub project: PathBuf, + pub setup: ReviewSetup, + pub scope: ReviewScope, + pub cap: u32, + pub mode: Mode, + pub shape: Shape, + pub launch: Launch, + /// Full id of the "Work before Review Loop" commit, when one was made. + pub pre_run_commit: Option, + pub start: Boundary, + pub rounds: Vec, + pub suggestions_batch: Option, + /// Batches from before a Continue, kept for the report. + pub earlier_batches: Vec, + pub stop_reason: Option, + pub stop_evidence: Option, + /// The round the run stopped in; `round` moves on with a sign-off's fix. + pub stop_round: u32, + // ---- live + /// The run's folder under the console home: scope files, diffs, reports. + pub run_dir: PathBuf, + /// False once the run has stopped (it is kept for Continue and the report). + pub running: bool, + pub round: u32, + pub stage: Stage, + pub step: ReviewStep, + pub sid: Option, + pub last_sid: Option, + pub generation: u64, + pub started_at: Instant, + pub started_at_ms: u64, + /// When the current session started, for the "console never opened" wait. + pub session_started_at: Instant, + pub last_activity: SystemTime, + pub activity_checked: Instant, + pub stop_after_round: bool, + pub stop_now: bool, + /// The current round's one retry is used. + pub retried: bool, + pub retries_used: u32, + /// The round in progress. + pub cur: RoundRecord, + pub strength_rows: BTreeMap, + pub cur_strength: Option, + /// Suggestions collected across rounds (FR-19). + pub collected: Vec, + pub reviewer_report: Option, + /// The files the current round's reviewer was shown. + pub reviewed_files: Vec, + /// The files the person's scope named when the run began. + pub scope_files: Vec, + pub scope_base: Option, + /// What the run was going to stop for when the Suggestions batch began. + pub pending_stop: Option, + pub batch_done: bool, + pub partial: Option, + pub notify_failure: Option, + /// A page announced for the session that holds no lock yet. + pub page_candidate: Option, + /// What the person picked at sign-off, and how the squash went. + pub signoff: Option, + /// A sign-off's Suggestions fix is running: its end finishes the sign-off. + pub signing: bool, + pub signed_off: bool, + /// The report written into the spec folder, kept so sign-off rewrites it. + pub report_file: Option, +} + +/// How the sign-off's squash of the round commits went. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Squash { + /// Not asked for. + Off, + /// Done: the one commit that replaced this many commits of the run. + Done { commit: String, commits: usize }, + /// Refused or failed, with the words the person reads. + Refused(String), +} + +/// What the sign-off did, for the report and the finished screen. +#[derive(Clone, Debug)] +pub struct SignOff { + /// The Suggestions the person ticked. + pub picked: Vec, + /// The Suggestions they left. + pub left: Vec, + pub squash_asked: bool, + pub squash: Squash, + /// Why the picked Suggestions were not all fixed, when they were not. + pub problem: Option, +} + +pub type ReviewSlot = Arc>>; + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +fn epoch_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| u64::try_from(d.as_millis()).unwrap_or(0)) + .unwrap_or(0) +} + +fn clock() -> String { + chrono::Local::now().format("%Y-%m-%d %H:%M").to_string() +} + +fn one_line(text: &str) -> String { + text.split_whitespace().collect::>().join(" ") +} + +/// Whether the loop's agent can start a helper from inside a session. +pub(crate) fn agent_helpers(agent: &Agent) -> bool { + matches!(agent, Agent::Builtin(entry) if entry.helpers) +} + +/// A session that never opened its console counts as crashed after this long. +const NOTICE_WAIT: Duration = Duration::from_secs(180); + +impl ReviewRun { + #[allow(clippy::too_many_arguments)] + pub fn new( + project: PathBuf, + setup: ReviewSetup, + launch: Launch, + mode: Mode, + shape: Shape, + start: Boundary, + run_dir: PathBuf, + strength_rows: BTreeMap, + ) -> ReviewRun { + let now = Instant::now(); + let run_id = NEXT_RUN.fetch_add(1, Ordering::SeqCst); + ReviewRun { + run_id, + id: format!("review-{}-{run_id}", epoch_ms()), + project, + scope: setup.scope, + cap: setup.cap.clamp(1, MAX_ROUNDS), + cur_strength: setup.strength, + setup, + mode, + shape, + launch, + pre_run_commit: None, + start, + rounds: Vec::new(), + suggestions_batch: None, + earlier_batches: Vec::new(), + stop_reason: None, + stop_evidence: None, + stop_round: 0, + run_dir, + running: true, + round: 1, + stage: Stage::Both, + step: ReviewStep::Starting, + sid: None, + last_sid: None, + generation: 0, + started_at: now, + started_at_ms: epoch_ms(), + session_started_at: now, + last_activity: SystemTime::now(), + activity_checked: now, + stop_after_round: false, + stop_now: false, + retried: false, + retries_used: 0, + cur: RoundRecord::default(), + strength_rows, + collected: Vec::new(), + reviewer_report: None, + reviewed_files: Vec::new(), + scope_files: Vec::new(), + scope_base: None, + pending_stop: None, + batch_done: false, + partial: None, + notify_failure: None, + page_candidate: None, + signoff: None, + signing: false, + signed_off: false, + report_file: None, + } + } + + /// The boundary before round `n` began: the run's start, or where the + /// round before it ended. + fn boundary_before(&self, n: u32) -> Boundary { + n.checked_sub(2) + .and_then(|at| self.rounds.get(at as usize)) + .and_then(|round| round.boundary.clone()) + .unwrap_or_else(|| self.start.clone()) + } + + /// The Critical and Warning findings still open: every round's unfixed + /// ones that no later round fixed. A later round reviews only the fix + /// diff, so a clean one never clears what an earlier round left. + pub fn open_findings(&self) -> Vec { + let same = |a: &Finding, b: &Finding| a.title == b.title && a.file == b.file; + let mut open: Vec = Vec::new(); + for round in &self.rounds { + open.retain(|left| !round.fixed.iter().any(|fixed| same(left, fixed))); + for finding in &round.unfixed { + if !open.iter().any(|left| same(left, finding)) { + open.push(finding.clone()); + } + } + } + open + } + + /// Where the last finished round ended (or the start). + pub fn last_boundary(&self) -> Boundary { + // The newest committed work: a Suggestions batch counts after the + // rounds that had finished when it ran, and before any later round + // (a Continue starts a round after a finished batch). + let round = self + .rounds + .iter() + .enumerate() + .rev() + .find_map(|(i, round)| round.boundary.clone().map(|b| (i, b))); + let batch = self + .suggestions_batch + .iter() + .chain(self.earlier_batches.iter().rev()) + .find_map(|batch| batch.boundary.clone().map(|b| (batch.after_rounds, b))); + match (round, batch) { + (Some((i, round)), Some((after, batch))) => { + if after > i { + batch + } else { + round + } + } + (Some((_, round)), None) => round, + (None, Some((_, batch))) => batch, + (None, None) => self.start.clone(), + } + } + + fn view(&self, round: u32) -> RunView { + RunView { + round, + cap: self.cap, + rounds_run: u32::try_from(self.rounds.len()).unwrap_or(u32::MAX), + suggestions_on: self.setup.suggestions, + suggestions_pending: !self.collected.is_empty(), + batch_done: self.batch_done, + retried_this_round: self.retried, + stop_after_round: self.stop_after_round, + stop_now: self.stop_now, + } + } +} + +// ----------------------------------------------------------------- events + +/// The banner's state for a Review Loop (`kind: "rounds"`). +pub fn review_state_event(run: &ReviewRun) -> LoopStateEvent { + let (critical, warning) = run + .rounds + .last() + .map_or((0, 0), |round| (round.critical, round.warning)); + let strength = run.cur_strength.map(|word| word.word().to_string()); + let row = run + .cur_strength + .and_then(|word| run.strength_rows.get(word.word())); + // The Suggestions batch and the final check come after the rounds: they + // are named for what they are, and never read as a round past the cap. + let after_rounds = match run.stage { + Stage::Batch => "Suggestions batch", + Stage::Final => "Final check", + _ => "", + }; + let (shown, detail) = if after_rounds.is_empty() { + ( + run.round, + round_logic::round_detail(run.round, run.cap, run.step.label(), critical, warning), + ) + } else { + ( + run.round.min(run.cap), + format!("{after_rounds}: {}", run.step.label()), + ) + }; + LoopStateEvent { + running: run.running, + spec_name: run + .setup + .spec + .as_deref() + .map_or_else(|| run.scope.word().to_string(), |spec| spec.to_string()), + phase: shown, + phases: run.cap, + phase_name: detail, + previous_phase: None, + previous_committed: false, + phase_retried: run.retried, + step: run.step.label().to_string(), + started_at_ms: run.started_at_ms, + retries_used: run.retries_used, + stop_after_phase: run.stop_after_round, + stopping: run.stop_now, + can_stop_after: run.running && run.round < run.cap, + strength, + model: row.map(|r| r.model.clone()), + effort: row.and_then(|r| r.effort.clone()), + kind: "rounds", + round: shown, + rounds: run.cap, + round_counts: run + .rounds + .iter() + .map(|round| RoundCount { + critical: round.critical, + warning: round.warning, + }) + .collect(), + stop_after_round: run.stop_after_round, + after_rounds, + } +} + +/// The running Review Loop's banner state, or `None` when none runs. +pub fn current_event(slot: &ReviewSlot) -> Option { + lock(slot) + .as_ref() + .filter(|run| run.running) + .map(review_state_event) +} + +/// Whether a Review Loop is running (a stopped run waiting for Continue or +/// the report is not). +pub fn is_running(slot: &ReviewSlot) -> bool { + lock(slot).as_ref().is_some_and(|run| run.running) +} + +/// Forget the run without a word to the page: the app is quitting. +pub fn abandon(slot: &ReviewSlot) { + *lock(slot) = None; +} + +// ------------------------------------------------------------- the context + +/// What the watch thread needs: the run's slot and the shared session context. +#[derive(Clone)] +pub struct RoundCtx { + pub slot: ReviewSlot, + pub ctx: Ctx, +} + +fn with_run(rc: &RoundCtx, f: impl FnOnce(&mut ReviewRun) -> R) -> Option { + let mut guard = lock(&rc.slot); + guard + .as_mut() + .filter(|run| run.run_id == rc.ctx.run_id) + .map(f) +} + +fn emit(rc: &RoundCtx) { + let event = with_run(rc, |run| review_state_event(run)); + if let Some(event) = event { + (rc.ctx.hooks.emit)(event); + } +} + +/// The console the end screen is posted to. A test never reaches the real +/// one (it would post to, and resume sessions in, the person's console). +fn console_dir() -> PathBuf { + #[cfg(test)] + { + PathBuf::from(".") + } + #[cfg(not(test))] + { + find_console_dir().unwrap_or_else(|_| PathBuf::from(".")) + } +} + +fn new_ctx( + run: &ReviewRun, + agent: Arc, + home: PathBuf, + hooks: Hooks, + limits: Limits, +) -> Ctx { + Ctx { + // The Review Loop keeps its own slot; this one only fills the field + // the shared session code carries for the Implementation Loop. + slot: Arc::new(Mutex::new(None)), + agent, + console_dir: console_dir(), + home, + launch: run.launch.clone(), + run_id: run.run_id, + hooks: Arc::new(hooks), + limits, + } +} + +// ------------------------------------------------------------ git helpers + +fn git_cmd(project: &Path, args: &[&str]) -> Command { + let mut cmd = Command::new("git"); + cmd.args(args).current_dir(project); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW + } + cmd +} + +/// What `git ` printed, or the first line of why it failed. +fn git_text(project: &Path, args: &[&str]) -> Result { + let out = git_cmd(project, args) + .output() + .map_err(|err| format!("git could not run: {err}"))?; + if !out.status.success() { + let why = String::from_utf8_lossy(&out.stderr) + .lines() + .map(str::trim) + .find(|line| !line.is_empty()) + .unwrap_or("no reason given") + .to_string(); + return Err(format!("git {} failed: {why}", args.first().unwrap_or(&""))); + } + Ok(String::from_utf8_lossy(&out.stdout).to_string()) +} + +fn lines_of(text: &str) -> Vec { + text.lines() + .map(str::trim) + .filter(|line| !line.is_empty()) + .map(str::to_string) + .collect() +} + +/// Names from `git ... -z` output: NUL-separated, never quoted. +fn nul_lines(text: &str) -> Vec { + text.split('\0') + .filter(|name| !name.is_empty()) + .map(str::to_string) + .collect() +} + +/// The branch the work is measured against: the first of `main`, +/// `origin/main`, `master`, `origin/master` that exists. +fn base_branch(project: &Path) -> Option { + ["main", "origin/main", "master", "origin/master"] + .into_iter() + .find(|name| { + git_text( + project, + &["rev-parse", "--verify", "-q", &format!("{name}^{{commit}}")], + ) + .is_ok() + }) + .map(str::to_string) +} + +/// The files a scope names, and the base branch it measured against: for +/// `branch`, the diff against the base plus staged, unstaged and untracked +/// files; for `uncommitted`, those changed files; for `spec`, the spec folder's +/// files plus the branch diff. +pub fn scope_files( + project: &Path, + scope: ReviewScope, + spec: Option<&str>, +) -> Result<(Option, Vec), String> { + let mut files: Vec = Vec::new(); + let mut base = None; + let uncommitted = |files: &mut Vec| -> Result<(), String> { + files.extend(loop_tools::git_status_porcelain(project)?); + Ok(()) + }; + let against_base = |files: &mut Vec, base: &mut Option| -> Result<(), String> { + // Counting only untracked files would hide every commit on the + // branch, so no trunk is an error, as `review-scope.mjs` says. A + // repository with no commits yet has nothing committed to miss. + let has_head = git_text(project, &["rev-parse", "--verify", "-q", "HEAD"]).is_ok(); + match base_branch(project) { + Some(name) => { + let found = git_text(project, &["merge-base", "HEAD", &name]) + .map_err(|e| format!("The branch could not be compared with {name}: {e}"))?; + let point = found.trim().to_string(); + if !point.is_empty() { + files.extend(nul_lines(&git_text( + project, + &["diff", "--name-only", "-z", "--no-renames", &point], + )?)); + *base = Some(name); + } + } + None if has_head => { + return Err( + "There is no main or master branch (local or origin) to compare this branch with." + .to_string(), + ); + } + None => {} + } + files.extend(lines_of(&git_text( + project, + &["ls-files", "--others", "--exclude-standard"], + )?)); + Ok(()) + }; + match scope { + ReviewScope::Uncommitted => uncommitted(&mut files)?, + ReviewScope::Branch => against_base(&mut files, &mut base)?, + ReviewScope::Spec => { + let spec = spec.ok_or("A spec scope needs a spec folder.")?; + let folder = project.join(spec); + if !folder.is_dir() { + return Err(format!("{spec} is not a folder in this project.")); + } + against_base(&mut files, &mut base)?; + if let Ok(entries) = std::fs::read_dir(&folder) { + for entry in entries.flatten() { + if entry.path().is_file() { + files.push(format!( + "{}/{}", + spec.trim_end_matches('/'), + entry.file_name().to_string_lossy() + )); + } + } + } + } + } + files.sort(); + files.dedup(); + Ok((base, files)) +} + +// ------------------------------------------------------- the scope and prompt + +/// Everything a round's scope file says. +struct ScopeInput<'a> { + round: u32, + stage: Stage, + scope: ReviewScope, + spec: Option<&'a str>, + base: Option<&'a str>, + files: &'a [String], + diff: Option<&'a Path>, + report: Option<&'a Path>, + brief: &'a [Finding], +} + +/// The text of a round's scope file. +fn scope_text(input: &ScopeInput) -> String { + let mut text = format!( + "# Review Loop round {} scope\n\nRole: {}\n", + input.round, + input.stage.role_word() + ); + if let Some(diff) = input.diff { + text.push_str(&format!( + "\nReview exactly this diff, the previous round's changes, and nothing else:\n\n- {}\n", + diff.display() + )); + } else if input.stage == Stage::Batch { + text.push_str("\nFix these Suggestions and nothing else:\n\n"); + for finding in input.brief { + text.push_str(&finding_line(finding)); + text.push('\n'); + } + } else { + text.push_str(&format!("\nScope: {}\n", input.scope.word())); + if let Some(spec) = input.spec { + text.push_str(&format!("Spec folder: {spec}\n")); + } + if let Some(base) = input.base { + text.push_str(&format!("Base branch: {base}\n")); + } + text.push_str("\nFiles:\n\n"); + for file in input.files { + text.push_str(&format!("- {file}\n")); + } + } + if let Some(report) = input.report { + text.push_str(&format!( + "\nThe reviewer's report (fix its Critical and Warning findings):\n\n- {}\n", + report.display() + )); + } + text +} + +impl Stage { + fn role_word(self) -> &'static str { + match self.role() { + Role::Both => "both", + Role::Reviewer => "reviewer", + Role::Fixer => "fixer", + } + } +} + +/// A path as the agent's prompt carries it: quoted when it holds a space. +fn quoted(path: &Path) -> String { + let text = path.display().to_string(); + if text.contains(char::is_whitespace) { + format!("\"{text}\"") + } else { + text + } +} + +/// The prompt a round's session starts on. +pub fn round_prompt(round: u32, role: Role, scope_file: &Path) -> String { + let role = match role { + Role::Both => "both", + Role::Reviewer => "reviewer", + Role::Fixer => "fixer", + }; + format!( + "/plan2code-review --web --loop --round {round} --role {role} --scope-file {}", + quoted(scope_file) + ) +} + +/// Suggestions kept across rounds (FR-19): the new round's are added, a repeat +/// (same file and title) is dropped, one whose file and line a round fixed is +/// dropped, and an earlier one about a file the latest reviewer was shown but +/// did not report again is dropped. +pub fn merge_suggestions( + collected: &[Finding], + new: &[Finding], + fixed: &[Finding], + reviewed_files: &[String], +) -> Vec { + let was_fixed = |finding: &Finding| { + fixed + .iter() + .any(|f| f.file == finding.file && f.line.is_some() && f.line == finding.line) + }; + let same = |a: &Finding, b: &Finding| a.file == b.file && a.title == b.title; + let mut kept: Vec = collected + .iter() + .filter(|old| { + !was_fixed(old) + && (new.iter().any(|n| same(n, old)) + || !reviewed_files.iter().any(|file| file == &old.file)) + }) + .cloned() + .collect(); + for finding in new { + if !was_fixed(finding) && !kept.iter().any(|k| same(k, finding)) { + kept.push(finding.clone()); + } + } + kept +} + +/// The files a unified diff touches, from its `+++ b/` lines. +fn diff_files(diff: &Path) -> Vec { + let Ok(text) = std::fs::read_to_string(diff) else { + return Vec::new(); + }; + let mut files: Vec = text + .lines() + .filter_map(|line| line.strip_prefix("+++ b/")) + .map(str::to_string) + .collect(); + files.sort(); + files.dedup(); + files +} + +// ------------------------------------------------------------ starting a run + +fn is_dirty(project: &Path) -> Result { + Ok(!loop_tools::git_status_porcelain(project)?.is_empty()) +} + +/// Stage by name and commit what changed since `before` (everything, with an +/// empty list), through the same checks a phase's commit takes. `Ok(None)` +/// when nothing changed; otherwise the new commit's full id. +fn commit_all( + project: &Path, + subject: &str, + limit: Duration, +) -> Result, (String, String)> { + match loop_commit::stage_and_check(project, Some(&[])) { + Ok(()) => {} + Err(loop_commit::StageError::Add(failure)) => { + return Err((failure.first_line, failure.output)); + } + Err(loop_commit::StageError::Problem(problem)) => { + let files = problem.files.join(", "); + let line = format!("{} {}", files, problem.why); + return Err((line.clone(), line)); + } + } + let staged = loop_tools::git_staged(project).map_err(|e| (e.clone(), e))?; + if staged.is_empty() { + return Ok(None); + } + let message = match loop_tools::commit_message(project, subject) { + Ok(message) => message, + Err(e) => { + // Nothing is committed: the files this run staged come out again. + loop_commit::unstage(project); + return Err((e.clone(), e)); + } + }; + let done = loop_tools::git_commit_with(project, &message, limit); + if !done.ok { + loop_commit::unstage(project); + return Err((loop_commit::first_line(&done.output), done.output)); + } + loop_tools::git_head_full(project) + .map(Some) + .map_err(|e| (e.clone(), e)) +} + +/// Check the setup, make the pre-run commit when agreed, and take the start +/// boundary: everything a run needs before round 1. +pub fn prepare_run( + project: &Path, + launch: &Launch, + setup: ReviewSetup, + home: &Path, +) -> Result { + if !(1..=MAX_ROUNDS).contains(&setup.cap) { + return Err(format!("The round cap is 1 to {MAX_ROUNDS}.")); + } + if setup.scope == ReviewScope::Spec { + let spec = setup + .spec + .as_deref() + .ok_or("A spec scope needs a spec folder.")?; + loop_driver::validate_spec(project, spec)?; + } + let (base, files) = scope_files(project, setup.scope, setup.spec.as_deref())?; + let mode = if setup.commit { + Mode::Commit + } else { + Mode::Snapshot + }; + let shape = if agent_helpers(&launch.0) { + Shape::OneSession + } else { + Shape::TwoSession + }; + let mut pre_run_commit = None; + if mode == Mode::Commit && is_dirty(project)? { + if !setup.pre_run_commit_agreed { + return Err( + "Your project has uncommitted changes. Agree to commit them first, or turn commits off." + .to_string(), + ); + } + match commit_all( + project, + "Work before Review Loop", + Duration::from_secs(10 * 60), + ) { + Ok(id) => pre_run_commit = id, + Err((line, _)) => { + return Err(format!("The work before the run was not committed: {line}")) + } + } + } + let start = match mode { + Mode::Commit => round_boundary::head(project)?, + Mode::Snapshot => round_boundary::snapshot(project)?, + }; + let rows = if setup.strength.is_some() { + loop_driver::strength_rows_for(&launch.0) + } else { + BTreeMap::new() + }; + let mut run = ReviewRun::new( + project.to_path_buf(), + setup, + launch.clone(), + mode, + shape, + start, + PathBuf::new(), + rows, + ); + run.run_dir = home.join("review-loop").join(&run.id); + run.pre_run_commit = pre_run_commit; + run.scope_files = files; + run.scope_base = base; + Ok(run) +} + +/// Start a Review Loop: refuse while any loop runs, prepare the run, store it +/// and start round 1; a watch thread follows it. +pub fn start_review_loop( + slot: &ReviewSlot, + phases: &LoopSlot, + agent: Arc, + launch: Launch, + project: PathBuf, + setup: ReviewSetup, + hooks: Hooks, +) -> Result<(), String> { + let home = session_reader::console_home().ok_or("no home folder found")?; + start_review_loop_with( + slot, + phases, + agent, + launch, + project, + setup, + hooks, + Limits::default(), + home, + true, + ) +} + +/// `start_review_loop` with the console home and the watcher's timing given, +/// and the watch thread optional: a test starts a run and plays the watcher +/// itself. +#[allow(clippy::too_many_arguments)] +pub fn start_review_loop_with( + slot: &ReviewSlot, + phases: &LoopSlot, + agent: Arc, + launch: Launch, + project: PathBuf, + setup: ReviewSetup, + hooks: Hooks, + limits: Limits, + home: PathBuf, + watch: bool, +) -> Result<(), String> { + if loop_driver::is_running(phases) || is_running(slot) { + return Err("A loop is already running in this window.".to_string()); + } + let run = prepare_run(&project, &launch, setup, &home)?; + if run.scope_files.is_empty() { + return Err("There is nothing to review in that scope.".to_string()); + } + let rc = RoundCtx { + slot: Arc::clone(slot), + ctx: new_ctx(&run, agent, home, hooks, limits), + }; + { + let mut guard = lock(slot); + if guard.as_ref().is_some_and(|held| held.running) { + return Err("A loop is already running in this window.".to_string()); + } + *guard = Some(run); + } + let first = with_run(&rc, |run| first_stage(run.shape)).unwrap_or(Stage::Both); + if let Err(e) = start_stage(&rc, first, 1) { + *lock(slot) = None; + (rc.ctx.hooks.emit)(LoopStateEvent::ended()); + return Err(e); + } + if watch { + thread::spawn(move || watcher(rc)); + } + Ok(()) +} + +fn first_stage(shape: Shape) -> Stage { + match shape { + Shape::OneSession => Stage::Both, + Shape::TwoSession => Stage::Reviewer, + } +} + +// ------------------------------------------------------ starting a session + +/// What a session's scope file needs, copied out so git runs outside the lock. +struct Plan { + project: PathBuf, + scope: ReviewScope, + spec: Option, + base: Option, + files: Vec, + diff: Option<(Boundary, Boundary)>, + reviewer_report: Option, + brief: Vec, + dir: PathBuf, + prompt_round: u32, + strength: Option<(Strength, StrengthRow)>, +} + +fn plan_for(run: &ReviewRun, stage: Stage, round: u32) -> Plan { + let diff = match stage { + Stage::Both | Stage::Reviewer | Stage::Fixer if round >= 2 => { + // The round being started ends where the last finished work did, so + // a Suggestions batch committed before a Continue is in its diff. + let to = if usize::try_from(round).ok() == Some(run.rounds.len() + 1) { + run.last_boundary() + } else { + run.boundary_before(round) + }; + Some((run.boundary_before(round - 1), to)) + } + Stage::Final => run + .suggestions_batch + .as_ref() + .and_then(|batch| Some((batch.before.clone()?, batch.boundary.clone()?))), + _ => None, + }; + let brief = if stage == Stage::Batch { + run.collected.clone() + } else { + Vec::new() + }; + let name = format!("round-{round}-{}-t{}", stage.word(), run.retries_used); + Plan { + project: run.project.clone(), + scope: run.scope, + spec: run.setup.spec.clone(), + base: run.scope_base.clone(), + files: run.scope_files.clone(), + diff, + reviewer_report: (stage == Stage::Fixer) + .then(|| run.reviewer_report.clone()) + .flatten(), + brief, + dir: run.run_dir.join(name), + prompt_round: round, + strength: run.cur_strength.and_then(|word| { + run.strength_rows + .get(word.word()) + .map(|row| (word, row.clone())) + }), + } +} + +/// Write the scope file (and the diff and reviewer report it names) and start +/// the stage's session. The prompt names the round, the role and the file. +fn start_stage(rc: &RoundCtx, stage: Stage, round: u32) -> Result<(), String> { + let plan = + with_run(rc, |run| plan_for(run, stage, round)).ok_or("The Review Loop has ended.")?; + std::fs::create_dir_all(&plan.dir) + .map_err(|err| format!("could not make {}: {err}", plan.dir.display()))?; + let mut diff_path = None; + let mut touched = Vec::new(); + if let Some((from, to)) = &plan.diff { + let name = if stage == Stage::Final { + "batch.diff".to_string() + } else { + format!("round-{}.diff", round - 1) + }; + let path = plan.dir.join(name); + round_boundary::diff(&plan.project, from, to, &path)?; + touched = diff_files(&path); + diff_path = Some(path); + } + let report_path = match &plan.reviewer_report { + Some(text) => { + let path = plan.dir.join("reviewer-report.md"); + std::fs::write(&path, text) + .map_err(|err| format!("could not write {}: {err}", path.display()))?; + Some(path) + } + None => None, + }; + let text = scope_text(&ScopeInput { + round, + stage, + scope: plan.scope, + spec: plan.spec.as_deref(), + base: plan.base.as_deref(), + files: &plan.files, + diff: diff_path.as_deref(), + report: report_path.as_deref(), + brief: &plan.brief, + }); + let scope_file = plan.dir.join("scope.md"); + std::fs::write(&scope_file, text) + .map_err(|err| format!("could not write {}: {err}", scope_file.display()))?; + let prompt = round_prompt(plan.prompt_round, stage.role(), &scope_file); + // A running session (a silent one being retried) is ended first. + rc.ctx.agent.stop(); + let started = start_session( + &rc.ctx, + &prompt, + plan.strength.as_ref().map(|(word, row)| (*word, row)), + )?; + let worked = with_run(rc, |run| { + run.round = round; + run.stage = stage; + run.sid = None; + run.page_candidate = None; + run.generation = started.generation; + run.session_started_at = Instant::now(); + run.last_activity = SystemTime::now(); + run.activity_checked = Instant::now(); + run.step = match stage.role() { + Role::Fixer => ReviewStep::Fixing, + _ => ReviewStep::Reviewing, + }; + if !run.retried && matches!(stage, Stage::Both | Stage::Reviewer) { + run.cur = RoundRecord { + n: round, + started_at: clock(), + ..RoundRecord::default() + }; + run.reviewed_files = if touched.is_empty() && round == 1 { + run.scope_files.clone() + } else { + touched.clone() + }; + } + run.cur.strength = run.cur_strength.map(|word| word.word().to_string()); + run.cur.model = started.model.clone(); + run.cur.effort = started.effort.clone(); + run.cur.retried = run.retried; + }); + if worked.is_none() { + rc.ctx.agent.stop(); + return Err("The Review Loop has ended.".to_string()); + } + emit(rc); + Ok(()) +} + +// -------------------------------------------------------------- the watcher + +fn watcher(rc: RoundCtx) { + let panicked = watch_loop(rc.ctx.limits.watch_every, || { + if tick(&rc) { + WatchStep::Continue + } else { + WatchStep::Stop + } + }); + if let Some(text) = panicked { + let text: String = one_line(&text).chars().take(200).collect(); + finish_run( + &rc, + StopReason::Failed(format!("the Review Loop's watcher failed: {text}")), + None, + ); + } +} + +/// What one look needs, copied out so no lock is held while a tool runs. +struct Look { + project: PathBuf, + round: u32, + stage: Stage, + sid: Option, + generation: u64, + stop_now: bool, + running: bool, + last_activity: SystemTime, + activity_due: bool, + waited: Duration, + silence_minutes: u32, + candidate: Option, +} + +fn take_look(rc: &RoundCtx) -> Option { + with_run(rc, |run| Look { + project: run.project.clone(), + round: run.round, + stage: run.stage, + sid: run.sid.clone(), + generation: run.generation, + stop_now: run.stop_now, + running: run.running, + last_activity: run.last_activity, + activity_due: run.activity_checked.elapsed() >= rc.ctx.limits.activity_every, + waited: run.session_started_at.elapsed(), + silence_minutes: run.setup.silence_minutes, + candidate: run.page_candidate.clone(), + }) +} + +/// A page the app took: while a run waits for its round's session, a Review +/// page locked for that round and role is the session. One without the lock +/// yet is kept as a candidate the watch adopts once it shows. +pub fn note_page(slot: &ReviewSlot, workflow: &str, sid: &str, state: &Value) { + if workflow != "review" { + return; + } + if let Some(run) = lock(slot).as_mut().filter(|run| run.running) { + if run.sid.is_some() { + return; + } + if page_is_this_round(state, run.round, run.stage.role()) { + run.sid = Some(sid.to_string()); + run.last_sid = Some(sid.to_string()); + run.last_activity = SystemTime::now(); + run.page_candidate = None; + } else if state.is_object() && state.get("roundOutcome").is_none_or(Value::is_null) { + run.page_candidate = Some(sid.to_string()); + } + } +} + +fn adopt_candidate(rc: &RoundCtx, look: &Look) -> Option { + let candidate = look.candidate.as_deref()?; + let state = read_session_state(&rc.ctx, candidate)?; + if !page_is_this_round(&state, look.round, look.stage.role()) { + return None; + } + with_run(rc, |run| { + if run.sid.is_none() && run.page_candidate.as_deref() == Some(candidate) { + run.sid = Some(candidate.to_string()); + run.last_sid = Some(candidate.to_string()); + run.page_candidate = None; + } + run.sid.clone() + }) + .flatten() +} + +/// The reason the current session's agent ended by itself, if it did. +fn crashed(rc: &RoundCtx, look: &Look) -> Option { + let seen = rc.ctx.agent.snapshot(); + match seen.state { + AgentState::Ended { reason } if seen.generation == look.generation => Some(reason), + _ => None, + } +} + +/// The silence rule's setup: the shared check wants a `LoopSetup`. +fn silence_setup(minutes: u32) -> loop_driver::LoopSetup { + loop_driver::LoopSetup { + silence_minutes: minutes, + ..loop_driver::LoopSetup::default() + } +} + +/// The round's outcome in `state`, when it is this look's round and role. +fn round_outcome_in(state: &Value, look: &Look) -> Option> { + outcome_for_round(state, look.round, look.stage.role()) +} + +/// One look at the running round. Returns false when the run is over. +pub fn tick(rc: &RoundCtx) -> bool { + let Some(look) = take_look(rc) else { + return false; + }; + if !look.running { + return false; + } + if look.stop_now { + stop_now_finish(rc); + return false; + } + let Some(sid) = look.sid.clone().or_else(|| adopt_candidate(rc, &look)) else { + if let Some(reason) = crashed(rc, &look) { + return fail(rc, &look, &StopCause::Crash, &reason); + } + if look.waited > NOTICE_WAIT.max(rc.ctx.limits.notice_wait) { + return fail(rc, &look, &StopCause::NoSession, ""); + } + return true; + }; + let session = match session_reader::load(&rc.ctx.home, &sid) { + Ok(session) => session, + Err(_) => { + if let Some(go) = crash_or_outcome(rc, &look, &sid) { + return go; + } + return silence_check(rc, &look, look.last_activity, None, false); + } + }; + if let Some(found) = round_outcome_in(&session.state, &look) { + return take_outcome(rc, &look, &session.state, found); + } + if let Some(go) = crash_or_outcome(rc, &look, &sid) { + return go; + } + // A round that asks the person a question cannot be answered: it fails. + if let Some(question) = loop_driver::first_open_question(&session.state) { + let reason = format!("the agent asked a question: {}", one_line(&question)); + return settle_failure(rc, &look, reason); + } + observe(rc, session.state["headline"]["stage"].as_str()); + let quiet = session.state["agent"]["quietMinutes"] + .as_u64() + .and_then(|m| u32::try_from(m).ok()); + let mut last = look.last_activity; + if look.activity_due { + last = refresh_activity(rc, &look, &session.dir); + } + silence_check(rc, &look, last, quiet, false) +} + +fn silence_check( + rc: &RoundCtx, + look: &Look, + last: SystemTime, + quiet: Option, + waiting: bool, +) -> bool { + let setup = silence_setup(look.silence_minutes); + if silence_expired(SystemTime::now(), last, &setup, quiet, waiting) { + let minutes = look.silence_minutes.max(quiet.unwrap_or(0)).min(60); + return fail(rc, look, &StopCause::Silence, &minutes.to_string()); + } + true +} + +/// The agent ended by itself: read the session once more before calling it a +/// crash, since an agent that writes its report and exits between two looks +/// must be judged, not retried. +fn crash_or_outcome(rc: &RoundCtx, look: &Look, sid: &str) -> Option { + let reason = crashed(rc, look)?; + if let Ok(session) = session_reader::load(&rc.ctx.home, sid) { + if let Some(found) = round_outcome_in(&session.state, look) { + return Some(take_outcome(rc, look, &session.state, found)); + } + } + Some(fail(rc, look, &StopCause::Crash, &reason)) +} + +fn refresh_activity(rc: &RoundCtx, look: &Look, session_dir: &Path) -> SystemTime { + let newest = loop_driver::newest_work(session_dir, &look.project); + with_run(rc, |run| { + run.activity_checked = Instant::now(); + if let Some(time) = newest.map(loop_driver::clamp_to_now) { + if time > run.last_activity { + run.last_activity = time; + } + } + run.last_activity + }) + .unwrap_or(look.last_activity) +} + +/// Take the banner's step from the page's headline stage. +fn observe(rc: &RoundCtx, stage: Option<&str>) { + let changed = with_run(rc, |run| { + let before = run.step; + if let Some(stage) = stage { + let lower = stage.to_lowercase(); + if lower.contains("test") { + run.step = ReviewStep::Testing; + } else if lower.contains("fix") { + run.step = ReviewStep::Fixing; + } else if lower.contains("review") { + run.step = ReviewStep::Reviewing; + } + } + run.step != before + }); + if changed == Some(true) { + emit(rc); + } +} + +fn cause_text(cause: &StopCause, detail: &str) -> String { + match cause { + StopCause::Crash => format!("the agent crashed ({detail})"), + StopCause::Silence => format!("the agent went silent for {detail} minutes"), + StopCause::NoSession => "the round's console never opened".to_string(), + _ => "the round failed".to_string(), + } +} + +/// A crash, silence or a console that never opened. +fn fail(rc: &RoundCtx, look: &Look, cause: &StopCause, detail: &str) -> bool { + settle_failure(rc, look, cause_text(cause, detail)) +} + +/// A failed round try: one fresh retry a strength up, else the run stops. +fn settle_failure(rc: &RoundCtx, look: &Look, reason: String) -> bool { + // Stop now was pressed since this look began: the ended agent is not a + // crash and nothing is retried. + if with_run(rc, |run| run.stop_now) == Some(true) { + stop_now_finish(rc); + return false; + } + // The final check that fails twice never changes why the run ended: its + // own result is kept apart, and the run stops for the reason it already + // had (FR-19). + if look.stage == Stage::Final { + let original = with_run(rc, |run| { + if !run.retried { + return None; + } + if let Some(batch) = run.suggestions_batch.as_mut() { + batch.final_check = Some(Verdict::Failed(reason.clone())); + } + Some(run.pending_stop.clone().unwrap_or(StopReason::Clean)) + }) + .flatten(); + if let Some(original) = original { + let note = format!("the final check did not finish ({reason})"); + return act( + rc, + Stage::Final, + round_logic::after_final_check(original), + Some(¬e), + ); + } + } + let next = with_run(rc, |run| { + round_logic::next_step(&run.view(look.round), &Verdict::Failed(reason.clone())) + }); + match next { + Some(next) => act(rc, look.stage, next, Some(&reason)), + None => false, + } +} + +// ------------------------------------------------------ handling an outcome + +fn take_outcome( + rc: &RoundCtx, + look: &Look, + state: &Value, + found: Result, +) -> bool { + // Stop now came since this look began: nothing is judged or committed. + if with_run(rc, |run| run.stop_now) == Some(true) { + stop_now_finish(rc); + return false; + } + let mut outcome = match found { + Ok(outcome) => outcome, + Err(reason) => { + rc.ctx.agent.stop(); + return settle_failure(rc, look, reason); + } + }; + if look.stage == Stage::Fixer { + let (critical, warning) = + with_run(rc, |run| (run.cur.critical, run.cur.warning)).unwrap_or((0, 0)); + round_logic::hold_reviewer_counts(&mut outcome.review, critical, warning); + } + let role = look.stage.role(); + let proofs = proofs_for(state, &outcome, role); + let verdict = round_logic::judge_round(&outcome, &proofs); + let report = outcome + .report + .as_deref() + .and_then(|id| report_text(state, id)) + .unwrap_or_default(); + // This session's work is read: its agent ends before anything else starts. + rc.ctx.agent.stop(); + match look.stage { + Stage::Both | Stage::Fixer => finish_round(rc, look, &outcome, verdict), + Stage::Reviewer => match verdict { + Verdict::Failed(reason) => settle_failure(rc, look, reason), + Verdict::Clean => finish_round(rc, look, &outcome, verdict), + Verdict::Findings { .. } => { + let brief = reviewer_brief(&report, &outcome); + with_run(rc, |run| { + run.reviewer_report = Some(brief); + // The round has one retry in all: the fixer gets none when + // the reviewer's session used it. + run.cur.critical = outcome.review.critical; + run.cur.warning = outcome.review.warning; + }); + match start_stage(rc, Stage::Fixer, look.round) { + Ok(()) => true, + Err(e) => { + finish_run( + rc, + StopReason::Failed(format!( + "the fixer could not start ({})", + one_line(&e) + )), + Some(e), + ); + false + } + } + } + }, + Stage::Batch => finish_batch(rc, look, &outcome, verdict), + Stage::Final => finish_final(rc, look, &outcome, verdict), + } +} + +/// Commit what a round changed (commit mode) or take a snapshot (snapshot +/// mode), and say where the round ended. A refused or failed commit stops the +/// run as `Failed` with what git or the staged-file check said. +fn close_round( + rc: &RoundCtx, + project: &Path, + mode: Mode, + subject: &str, +) -> Result<(Option, Boundary), (String, String)> { + with_run(rc, |run| run.step = ReviewStep::Committing); + emit(rc); + match mode { + Mode::Snapshot => round_boundary::snapshot(project) + .map(|boundary| (None, boundary)) + .map_err(|e| (e.clone(), e)), + Mode::Commit => { + let commit = commit_all(project, subject, rc.ctx.limits.commit_limit)?; + let boundary = round_boundary::head(project).map_err(|e| (e.clone(), e))?; + Ok((commit, boundary)) + } + } +} + +/// A title as a commit subject takes it: `commit-msg.mjs` refuses a double +/// quote (straight or curly), a backtick, `$`, `!` and a backslash, since shells +/// read them differently inside double quotes, and review titles carry them +/// often (a backticked name). Quotes become `'`, the rest are dropped. +fn safe_title(title: &str) -> String { + title + .chars() + .filter(|c| !matches!(c, '`' | '$' | '!' | '\\')) + .map(|c| { + if c == '"' || ('\u{201C}'..='\u{201F}').contains(&c) { + '\'' + } else { + c + } + }) + .collect::() + .trim() + .to_string() +} + +fn fix_titles(review: &RoundReview, subject: Option<&str>) -> Vec { + let mut titles: Vec = review.fixed.iter().map(|f| safe_title(&f.title)).collect(); + if titles.is_empty() { + titles.extend(subject.map(safe_title)); + } + titles +} + +/// The Suggestions batch's commit subject, fitted to 72 characters with its +/// own prefix (a longer one than a round's). +fn batch_subject(titles: &[String]) -> String { + let subject = + round_logic::round_commit_message(0, titles).replacen("round 0", "Suggestions batch", 1); + if subject.chars().count() <= 72 { + return subject; + } + let cut: String = subject.chars().take(69).collect(); + format!("{}...", cut.trim_end()) +} + +/// A judged round: record it, commit or snapshot it, then take the next step. +fn finish_round(rc: &RoundCtx, look: &Look, outcome: &RoundOutcome, verdict: Verdict) -> bool { + if let Verdict::Failed(reason) = &verdict { + return settle_failure(rc, look, reason.clone()); + } + if with_run(rc, |run| run.stop_now) == Some(true) { + stop_now_finish(rc); + return false; + } + let (mode, round) = with_run(rc, |run| (run.mode, run.round)).unwrap_or((Mode::Snapshot, 0)); + let subject = round_logic::round_commit_message( + round, + &fix_titles(&outcome.review, outcome.subject.as_deref()), + ); + let (commit, boundary) = match close_round(rc, &look.project, mode, &subject) { + Ok(saved) => saved, + Err((line, evidence)) => { + finish_run( + rc, + StopReason::Failed(format!("the round could not be saved ({line})")), + Some(evidence), + ); + return false; + } + }; + let next = with_run(rc, |run| { + let mut done = std::mem::take(&mut run.cur); + done.n = look.round; + done.boundary = Some(boundary); + done.verdict = Some(verdict.clone()); + done.ended_at = clock(); + done.critical = outcome.review.critical; + done.warning = outcome.review.warning; + done.suggestion = outcome.review.suggestion; + done.fixed = outcome.review.fixed.clone(); + done.unfixed = outcome.review.unfixed.clone(); + done.suggestions = outcome.review.suggestions.clone(); + done.tests = outcome.tests.clone(); + done.commit = commit; + done.retried = run.retried; + done.summary = outcome.summary.clone(); + run.collected = merge_suggestions( + &run.collected, + &outcome.review.suggestions, + &outcome.review.fixed, + &run.reviewed_files, + ); + run.rounds.push(done); + run.step = ReviewStep::Starting; + let next = round_logic::next_step(&run.view(look.round), &verdict); + if next == Next::SuggestionsBatch { + run.pending_stop = Some(if verdict == Verdict::Clean { + StopReason::Clean + } else { + StopReason::Cap + }); + } + next + }); + let Some(next) = next else { return false }; + notify_round(rc, look.round, outcome, &verdict); + emit(rc); + act(rc, look.stage, next, None) +} + +/// Act on the step `next_step` chose. Returns whether the run goes on. +fn act(rc: &RoundCtx, stage: Stage, next: Next, why: Option<&str>) -> bool { + match next { + Next::StartRound(n) => { + with_run(rc, |run| { + run.retried = false; + run.reviewer_report = None; + // A retry's step up applies to that round only. + run.cur_strength = run.setup.strength; + }); + let first = with_run(rc, |run| first_stage(run.shape)).unwrap_or(Stage::Both); + go(rc, start_stage(rc, first, n)) + } + Next::Retry => { + let round = with_run(rc, |run| run.round).unwrap_or(1); + with_run(rc, |run| { + run.retried = true; + run.retries_used += 1; + let stepped = run + .cur_strength + .and_then(|word| next_strength_word(&run.strength_rows, word.word())) + .and_then(|word| Strength::from_word(&word)); + match stepped { + Some(word) => run.cur_strength = Some(word), + None => run.cur.could_not_step_up = true, + } + run.cur.retried = true; + }); + emit(rc); + go(rc, start_stage(rc, stage, round)) + } + Next::SuggestionsBatch => { + let round = with_run(rc, |run| { + let n = u32::try_from(run.rounds.len()).unwrap_or(0) + 1; + run.retried = false; + // A retried round's step up was for that round only. + run.cur_strength = run.setup.strength; + run.suggestions_batch = Some(BatchRecord { + briefed: run.collected.clone(), + before: Some(run.last_boundary()), + after_rounds: run.rounds.len(), + ..BatchRecord::default() + }); + n + }) + .unwrap_or(1); + go(rc, start_stage(rc, Stage::Batch, round)) + } + Next::FinalCheck => { + let round = with_run(rc, |run| { + run.retried = false; + run.cur_strength = run.setup.strength; + u32::try_from(run.rounds.len()).unwrap_or(0) + 2 + }) + .unwrap_or(2); + go(rc, start_stage(rc, Stage::Final, round)) + } + Next::Stop(reason) => { + let evidence = why.map(str::to_string); + finish_run(rc, reason, evidence); + false + } + } +} + +/// A session start that failed stops the run as `Failed`. +fn go(rc: &RoundCtx, started: Result<(), String>) -> bool { + match started { + Ok(()) => true, + Err(e) => { + finish_run( + rc, + StopReason::Failed(format!("a session could not start ({})", one_line(&e))), + Some(e), + ); + false + } + } +} + +/// The Suggestions batch's fixer reported: commit it on its own, then check it. +fn finish_batch(rc: &RoundCtx, look: &Look, outcome: &RoundOutcome, verdict: Verdict) -> bool { + if let Verdict::Failed(reason) = &verdict { + return settle_failure(rc, look, reason.clone()); + } + if with_run(rc, |run| run.stop_now) == Some(true) { + stop_now_finish(rc); + return false; + } + let mode = with_run(rc, |run| run.mode).unwrap_or(Mode::Snapshot); + let subject = batch_subject(&fix_titles(&outcome.review, outcome.subject.as_deref())); + let (commit, boundary) = match close_round(rc, &look.project, mode, &subject) { + Ok(saved) => saved, + Err((line, evidence)) => { + finish_run( + rc, + StopReason::Failed(format!("the Suggestions batch could not be saved ({line})")), + Some(evidence), + ); + return false; + } + }; + let next = with_run(rc, |run| { + if let Some(batch) = run.suggestions_batch.as_mut() { + batch.boundary = Some(boundary); + batch.commit = commit; + batch.verdict = Some(verdict.clone()); + batch.summary = outcome.summary.clone(); + } + // Fixed and committed: a later round never briefs them again. + run.collected.clear(); + run.batch_done = true; + run.step = ReviewStep::Starting; + round_logic::next_step(&run.view(look.round), &verdict) + }); + let Some(next) = next else { return false }; + emit(rc); + act(rc, look.stage, next, None) +} + +/// The final check reported: its verdict is kept apart, and the run ends for +/// the reason it was already ending for (FR-19). +fn finish_final(rc: &RoundCtx, look: &Look, outcome: &RoundOutcome, verdict: Verdict) -> bool { + if let Verdict::Failed(reason) = &verdict { + let retried = with_run(rc, |run| run.retried).unwrap_or(true); + if !retried { + return settle_failure(rc, look, reason.clone()); + } + } + if with_run(rc, |run| run.stop_now) == Some(true) { + stop_now_finish(rc); + return false; + } + let original = with_run(rc, |run| { + if let Some(batch) = run.suggestions_batch.as_mut() { + batch.final_check = Some(verdict.clone()); + batch.final_critical = outcome.review.critical; + batch.final_warning = outcome.review.warning; + } + run.pending_stop.clone().unwrap_or(StopReason::Clean) + }); + let Some(original) = original else { + return false; + }; + let next = round_logic::after_final_check(original); + let note = match &verdict { + Verdict::Failed(reason) => Some(format!("the final check did not finish ({reason})")), + _ => None, + }; + act(rc, look.stage, next, note.as_deref()) +} + +// -------------------------------------------------------- ending a run + +/// End the run: record why, end the agent, tell the banner, then show the end +/// screen. The run is kept for Continue and sign-off. A sign-off's own +/// Suggestions fix ends here too: it keeps the reason the run already ended +/// for and finishes the sign-off. +pub fn finish_run(rc: &RoundCtx, reason: StopReason, evidence: Option) { + rc.ctx.agent.stop(); + let notice = with_run(rc, |run| { + let signing = run.signing; + if signing { + match &reason { + StopReason::Person => { + // Stop now during sign-off: not signed off, the person + // settles the partial changes and signs off again. + run.signing = false; + if let Some(signoff) = run.signoff.as_mut() { + signoff.problem = + Some("Stop now was pressed while the Suggestions were fixed".into()); + } + } + StopReason::Failed(why) => { + if let Some(signoff) = run.signoff.as_mut() { + signoff.problem = Some(one_line(why)); + } + } + _ => {} + } + } else { + run.stop_reason = Some(reason.clone()); + run.stop_evidence = evidence; + run.stop_round = run.round; + } + run.running = false; + run.step = ReviewStep::Starting; + ( + signing, + run.setup.notify_kind, + run.setup.notify_url.clone(), + run.setup.notify_param.clone(), + run.round, + run.open_findings().len(), + ) + }); + (rc.ctx.hooks.emit)(LoopStateEvent::ended()); + let Some((signing, kind, url, param, round, open)) = notice else { + return; + }; + if with_run(rc, |run| run.signing) == Some(true) { + complete_sign_off(rc); + } + show_end(rc); + if !signing { + if let Some(words) = stop_words(&reason, round, open).filter(|_| !url.trim().is_empty()) { + send_notice(rc, kind, url, param, format!("Review Loop {words}")); + } + } +} + +// ----------------------------------------------------- the end screen + +/// The doc ids the end post uses. +const REPORT_DOC: &str = "review-report"; +const PARTIAL_DOC: &str = "review-partial"; + +/// The most Suggestions and open findings the end screen lists. +const LIST_LIMIT: usize = 50; + +fn text_line(text: &str, max: usize) -> String { + one_line(text).chars().take(max).collect() +} + +fn count_words(n: usize, one: &str, many: &str) -> String { + if n == 1 { + format!("1 {one}") + } else { + format!("{n} {many}") + } +} + +fn reason_key(reason: Option<&StopReason>) -> &'static str { + match reason { + Some(StopReason::Clean) => "clean", + Some(StopReason::Cap) => "cap", + Some(StopReason::Person) => "person", + Some(StopReason::Failed(_)) | None => "failed", + } +} + +/// The one line the end screen leads with, never over 200 characters. +pub fn end_line(run: &ReviewRun) -> String { + let rounds = run.rounds.len(); + let ran = count_words(rounds, "round", "rounds"); + let open = run.open_findings().len(); + let line = match &run.stop_reason { + Some(StopReason::Clean) if open > 0 => format!( + "Clean after {ran}, but {} still open.", + count_words( + open, + "finding an earlier round left unfixed is", + "findings earlier rounds left unfixed are" + ) + ), + Some(StopReason::Clean) => { + format!("Clean after {ran}: no Critical or Warning findings are left.") + } + Some(StopReason::Cap) => format!( + "Stopped at the round cap after {ran}: {} still open.", + count_words(open, "finding is", "findings are") + ), + Some(StopReason::Person) if rounds == 0 => { + "Stopped by you before a round finished.".to_string() + } + Some(StopReason::Person) => format!("Stopped by you after {ran} finished."), + Some(StopReason::Failed(why)) => { + let round = if run.stop_round > 0 { + run.stop_round + } else { + run.round + }; + format!("Failed in round {round}: {why}.") + } + None => "The Review Loop has not finished.".to_string(), + }; + text_line(&line, 200) +} + +/// Whether the end screen offers Continue: not after a clean run or a +/// sign-off, not while partial changes wait, and never past six rounds. +pub fn can_continue(run: &ReviewRun) -> bool { + if run.running || run.signing || run.signed_off { + return false; + } + if run.partial.as_ref().is_some_and(|partial| partial.pending) { + return false; + } + let rounds = u32::try_from(run.rounds.len()).unwrap_or(u32::MAX); + match run.stop_reason { + Some(StopReason::Cap) => round_logic::continue_cap(run.cap, rounds).is_some(), + Some(StopReason::Person) | Some(StopReason::Failed(_)) => rounds < MAX_ROUNDS, + Some(StopReason::Clean) | None => false, + } +} + +/// The squash switch shows only in commit mode with two round commits. +pub fn can_squash(run: &ReviewRun) -> bool { + run.mode == Mode::Commit + && !run.signed_off + && run + .rounds + .iter() + .filter(|round| round.commit.is_some()) + .count() + >= 2 +} + +fn finding_json(finding: &Finding) -> Value { + let mut value = serde_json::json!({ + "title": text_line(&finding.title, 200), + "file": finding.file.trim(), + }); + if let Some(line) = finding.line.filter(|line| *line > 0) { + value["line"] = serde_json::json!(line); + } + value +} + +/// What sign-off did, in one line for the finished screen. +fn sign_off_note(run: &ReviewRun) -> Option { + let signoff = run.signoff.as_ref().filter(|_| run.signed_off)?; + let mut parts: Vec = Vec::new(); + match &signoff.squash { + Squash::Done { commits, .. } => parts.push(format!( + "Squashed {} into one.", + count_words(*commits, "commit", "commits") + )), + Squash::Refused(why) => parts.push(why.clone()), + Squash::Off => {} + } + if !signoff.picked.is_empty() && signoff.problem.is_none() { + parts.push(format!( + "Fixed {}.", + count_words(signoff.picked.len(), "Suggestion", "Suggestions") + )); + } + if let Some(problem) = &signoff.problem { + parts.push(format!("The Suggestions were not all fixed: {problem}.")); + } + (!parts.is_empty()).then(|| text_line(&parts.join(" "), 200)) +} + +/// The page's `loopEnd` for the run as it stands. `partial_doc` says the +/// partial diff was put on the page. +pub fn end_patch_for(run: &ReviewRun, partial_doc: bool, report_md: &str) -> Value { + use serde_json::json; + let mut docs = vec![json!({ + "id": REPORT_DOC, + "title": "Review Loop report", + "blocks": [{ "id": "body", "state": "settled", "md": report_md }], + })]; + let mut end = json!({ + "kind": "review", + "line": end_line(run), + "reason": reason_key(run.stop_reason.as_ref()), + "report": REPORT_DOC, + "canContinue": can_continue(run), + "canSquash": can_squash(run), + "can": [], + }); + if let Some(partial) = run.partial.as_ref().filter(|p| p.pending && partial_doc) { + docs.push(json!({ + "id": PARTIAL_DOC, + "title": "Partial changes", + "blocks": [{ "id": "diff", "diff": "partial.diff" }], + })); + end["partial"] = json!({ + "files": partial.files, + "added": partial.added, + "removed": partial.removed, + "diff": PARTIAL_DOC, + }); + } + if !run.signed_off && !run.collected.is_empty() { + let list: Vec = run + .collected + .iter() + .take(LIST_LIMIT) + .enumerate() + .map(|(i, finding)| { + let mut value = finding_json(finding); + value["id"] = json!(format!("s{}", i + 1)); + value + }) + .collect(); + end["suggestions"] = json!(list); + } + let open: Vec = run + .open_findings() + .iter() + .take(LIST_LIMIT) + .map(finding_json) + .collect(); + if !open.is_empty() { + end["open"] = json!(open); + } + if run.signed_off { + end["signedOff"] = json!(true); + if let Some(note) = sign_off_note(run) { + end["note"] = json!(note); + } + } + json!({ "docs": docs, "loopEnd": end }) +} + +/// Put the partial diff in the session's own folder, where a diff block must +/// live. False when the file could not be copied. +fn publish_partial(home: &Path, sid: &str, partial: &Partial) -> bool { + let folder = crate::session_reader::session_dir(home, sid); + std::fs::create_dir_all(&folder).is_ok() + && std::fs::copy(&partial.diff, folder.join("partial.diff")).is_ok() +} + +/// Tell the page how the run ended. A session the console no longer holds is +/// opened again once; a post it refuses is repeated without the partial diff. +fn post_review_end(console_dir: &Path, run: &ReviewRun, patch: &Value) { + let Some(sid) = run.sid.clone().or_else(|| run.last_sid.clone()) else { + return; + }; + // No console to post to (a test, or the console not found): nothing to do. + if !console_dir.join("console.mjs").is_file() { + return; + } + if loop_tools::console_post(console_dir, &sid, patch).ok { + return; + } + if loop_tools::console_resume(console_dir, &sid, "review").ok + && loop_tools::console_post(console_dir, &sid, patch).ok + { + return; + } + let mut plain = patch.clone(); + if let Some(docs) = plain.get_mut("docs").and_then(Value::as_array_mut) { + docs.retain(|doc| doc["id"].as_str() != Some(PARTIAL_DOC)); + } + if let Some(end) = plain.get_mut("loopEnd").and_then(Value::as_object_mut) { + end.remove("partial"); + } + let _ = loop_tools::console_post(console_dir, &sid, &plain); +} + +/// `REVIEW-LOOP-.md`, or `-2`, `-3` and so on when that name is taken. +pub fn unused_report_name(date: &str, taken: impl Fn(&str) -> bool) -> String { + let first = format!("REVIEW-LOOP-{date}.md"); + if !taken(&first) { + return first; + } + (2..) + .map(|n| format!("REVIEW-LOOP-{date}-{n}.md")) + .find(|name| !taken(name)) + .unwrap_or(first) +} + +/// Take the report file out of the spec folder before more work that commits +/// starts (a Suggestions fix, a Continue): the commit would otherwise sweep a +/// stale report into it. The next end writes a fresh one. +fn drop_spec_report(run: &mut ReviewRun) { + if let Some(file) = run.report_file.take() { + let _ = std::fs::remove_file(file); + } +} + +/// Write the report into the spec folder, for a run launched on a spec and +/// only then. A later write (the sign-off's) replaces the first one. +pub fn write_spec_report(run: &ReviewRun, md: &str) -> Option { + if run.scope != ReviewScope::Spec { + return None; + } + let spec = run.setup.spec.as_deref()?; + loop_driver::validate_spec(&run.project, spec).ok()?; + let folder = run.project.join(spec); + let file = match &run.report_file { + Some(file) => file.clone(), + None => { + let date = chrono::Local::now().format("%Y-%m-%d").to_string(); + folder.join(unused_report_name(&date, |name| folder.join(name).exists())) + } + }; + loop_driver::write_atomic(&file, md).ok().map(|()| file) +} + +/// This run's entry for the report list: its rounds and how it ended. +pub fn review_entry(run: &ReviewRun) -> ReportEntry { + let rounds = run + .rounds + .iter() + .map(|round| RoundEntry { + n: round.n, + critical: round.critical, + warning: round.warning, + suggestion: round.suggestion, + fixed: round + .fixed + .iter() + .map(|f| text_line(&f.title, 200)) + .collect(), + left_open: round + .unfixed + .iter() + .map(|f| text_line(&f.title, 200)) + .collect(), + commit: round.commit.clone(), + tests: match &round.tests { + None => "not reported".to_string(), + Some(t) if !t.summary.is_empty() => text_line(&t.summary, 200), + Some(t) if t.passed => "passed".to_string(), + Some(_) => "failed".to_string(), + }, + started: round.started_at.clone(), + ended: round.ended_at.clone(), + strength: round.strength.clone().unwrap_or_default(), + retried: round.retried, + }) + .collect(); + ReportEntry { + kind: EntryKind::Review, + rounds, + at: clock(), + name: run + .setup + .spec + .clone() + .unwrap_or_else(|| run.scope.word().to_string()), + result: if run.stop_reason == Some(StopReason::Clean) { + EntryResult::Passed + } else { + EntryResult::Stopped + }, + line: end_line(run), + summary: end_line(run), + reported: true, + ..ReportEntry::default() + } +} + +/// Save the run's entry in the report list. It has a key of its own, so it +/// never meets an Implementation Loop report for the same spec. +fn save_review_entry(home: &Path, run: &ReviewRun) -> Result<(), String> { + let mut report = LoopReport::new(&format!("review-loop:{}", run.id), &clock()); + report.entries.push(review_entry(run)); + report_list::save_report(home, &run.project, &report) +} + +/// Write the report where it goes (the report list, and the spec folder for a +/// spec launch) and post the end to the page. Returns the spec file written. +fn publish_end(console_dir: &Path, home: &Path, run: &ReviewRun) -> Option { + let md = review_report_markdown(run); + let file = write_spec_report(run, &md); + let _ = save_review_entry(home, run); + let sid = run.sid.clone().or_else(|| run.last_sid.clone()); + let partial_doc = match (&sid, run.partial.as_ref().filter(|p| p.pending)) { + (Some(sid), Some(partial)) => publish_partial(home, sid, partial), + _ => false, + }; + post_review_end(console_dir, run, &end_patch_for(run, partial_doc, &md)); + file +} + +/// Show the end screen for the run as it stands. +fn show_end(rc: &RoundCtx) { + let Some(run) = with_run(rc, |run| run.clone()) else { + return; + }; + if let Some(file) = publish_end(&rc.ctx.console_dir, &rc.ctx.home, &run) { + with_run(rc, |run| run.report_file = Some(file)); + } +} + +// ------------------------------------------------------------- sign-off + +/// The Suggestion a pick id (`s1`, `s2`...) names, as an index. +fn pick_index(id: &str, count: usize) -> Option { + let n: usize = id.strip_prefix('s')?.parse().ok()?; + (1..=count.min(LIST_LIMIT)).contains(&n).then(|| n - 1) +} + +const FOREIGN_COMMIT: &str = + "Something else was committed during the run, so the rounds were not squashed."; + +/// The squash commit's subject: the rounds it covers and what they fixed. +fn squash_subject(first: u32, last: u32, titles: &[String]) -> String { + let subject = round_logic::round_commit_message(0, titles).replacen( + "round 0", + &format!("rounds {first} to {last}"), + 1, + ); + if subject.chars().count() <= 72 { + return subject; + } + let cut: String = subject.chars().take(69).collect(); + format!("{}...", cut.trim_end()) +} + +/// Squash the run's commits (the round commits and the Suggestions commit) +/// into one on top of the start boundary, which holds the pre-run commit and +/// everything before it. Refuses, and changes nothing, when any commit +/// between the start and HEAD was not made by this run or something is +/// staged. +fn squash_rounds(project: &Path, start: &Boundary, mine: &[String], subject: &str) -> Squash { + let Boundary::Commit(start_id) = start else { + return Squash::Refused("There are no round commits to squash.".to_string()); + }; + let Ok(list) = git_text( + project, + &["rev-list", "--reverse", &format!("{start_id}..HEAD")], + ) else { + return Squash::Refused(FOREIGN_COMMIT.to_string()); + }; + let ids = lines_of(&list); + if ids.len() < 2 { + return Squash::Refused("There are not two commits of the run to squash.".to_string()); + } + if ids.len() != mine.len() || ids.iter().any(|id| !mine.contains(id)) { + return Squash::Refused(FOREIGN_COMMIT.to_string()); + } + if git_text(project, &["diff", "--cached", "--quiet"]).is_err() { + return Squash::Refused("Something is staged, so the rounds were not squashed.".into()); + } + let Ok(head) = loop_tools::git_head_full(project) else { + return Squash::Refused("git could not read the current commit.".to_string()); + }; + let message = match loop_tools::commit_message(project, subject) { + Ok(message) => message, + Err(why) => return Squash::Refused(format!("The squash commit was refused: {why}")), + }; + if let Err(why) = git_text(project, &["reset", "--soft", start_id]) { + return Squash::Refused(format!("The rounds were not squashed: {why}")); + } + let done = loop_tools::git_commit(project, &message); + if !done.ok { + // Put every round commit back where it was. + let _ = git_text(project, &["reset", "--soft", &head]); + return Squash::Refused(format!( + "The squash commit failed, so the round commits are as they were ({}).", + loop_commit::first_line(&done.output) + )); + } + match loop_tools::git_head_full(project) { + Ok(commit) => Squash::Done { + commit, + commits: ids.len(), + }, + Err(why) => Squash::Refused(format!("The squash ran, but {why}.")), + } +} + +/// The commits this run made, from its records. +fn run_commits(run: &ReviewRun) -> Vec { + run.rounds + .iter() + .filter_map(|round| round.commit.clone()) + .chain( + run.earlier_batches + .iter() + .chain(run.suggestions_batch.iter()) + .filter_map(|batch| batch.commit.clone()), + ) + .collect() +} + +/// Run the squash the person asked for (if they did) and mark the run signed +/// off. Called once the Suggestions fix, if there was one, has ended. +fn complete_sign_off(rc: &RoundCtx) { + let plan = with_run(rc, |run| { + let asked = run.signoff.as_ref().is_some_and(|s| s.squash_asked); + let first = run.rounds.first().map_or(1, |r| r.n); + let last = run.rounds.last().map_or(1, |r| r.n); + let titles: Vec = run + .rounds + .iter() + .flat_map(|r| r.fixed.iter().map(|f| safe_title(&f.title))) + .collect(); + ( + asked, + run.mode, + run.project.clone(), + run.start.clone(), + run_commits(run), + squash_subject(first, last, &titles), + ) + }); + let Some((asked, mode, project, start, mine, subject)) = plan else { + return; + }; + let squash = match (asked, mode) { + (false, _) => Squash::Off, + (true, Mode::Commit) => squash_rounds(&project, &start, &mine, &subject), + (true, Mode::Snapshot) => Squash::Refused("A squash needs commit mode.".to_string()), + }; + with_run(rc, |run| { + if let Some(signoff) = run.signoff.as_mut() { + signoff.squash = squash; + } + run.signing = false; + run.signed_off = true; + }); +} + +/// Sign off a finished run: fix the Suggestions the person ticked (one fixer +/// session, its fresh check and its own commit, the same path as the auto +/// batch), then squash the round commits when asked, then show the finished +/// screen. With no Suggestions ticked nothing runs but the squash. +#[allow(clippy::too_many_arguments)] +pub fn sign_off( + slot: &ReviewSlot, + phases: &LoopSlot, + agent: Arc, + hooks: Hooks, + limits: Limits, + home: PathBuf, + picks: &[String], + squash: bool, + watch: bool, +) -> Result<(), String> { + if loop_driver::is_running(phases) || is_running(slot) { + return Err("A loop is already running in this window.".to_string()); + } + let (rc, any_picked) = { + let mut guard = lock(slot); + let run = guard + .as_mut() + .ok_or("There is no Review Loop to sign off.")?; + if run.running || run.signing { + return Err("A loop is already running in this window.".to_string()); + } + if run.signed_off { + return Err("This Review Loop was already signed off.".to_string()); + } + if run.stop_reason.is_none() { + return Err("The Review Loop has not finished.".to_string()); + } + if run.partial.as_ref().is_some_and(|partial| partial.pending) { + return Err("Keep or discard the partial changes first.".to_string()); + } + let mut chosen: Vec = Vec::new(); + for id in picks { + let at = + pick_index(id, run.collected.len()).ok_or("That Suggestion is not on the list.")?; + if chosen.contains(&at) { + return Err("A Suggestion was picked twice.".to_string()); + } + chosen.push(at); + } + chosen.sort_unstable(); + let picked: Vec = chosen.iter().map(|at| run.collected[*at].clone()).collect(); + let left: Vec = run + .collected + .iter() + .enumerate() + .filter(|(at, _)| !chosen.contains(at)) + .map(|(_, finding)| finding.clone()) + .collect(); + run.signoff = Some(SignOff { + picked: picked.clone(), + left, + squash_asked: squash, + squash: Squash::Off, + problem: None, + }); + if !picked.is_empty() { + run.signing = true; + run.running = true; + // A neutral sentinel: the check then ends the fix with Clean, so a + // Person or Failed reason can only come from this fix itself. + run.pending_stop = Some(StopReason::Clean); + run.collected = picked; + run.batch_done = false; + run.retried = false; + run.stop_now = false; + run.stop_after_round = false; + run.cur_strength = run.setup.strength; + drop_spec_report(run); + if let Some(batch) = run.suggestions_batch.take() { + run.earlier_batches.push(batch); + } + } + let any = run.signing; + let rc = RoundCtx { + slot: Arc::clone(slot), + ctx: new_ctx(run, agent, home, hooks, limits), + }; + (rc, any) + }; + if !any_picked { + complete_sign_off(&rc); + show_end(&rc); + return Ok(()); + } + emit(&rc); + // A start that fails ends the sign-off through `finish_run`, which says so. + let started = act(&rc, Stage::Batch, Next::SuggestionsBatch, None); + if started && watch { + thread::spawn(move || watcher(rc)); + } + Ok(()) +} + +/// The prompt behind a finished screen's button: PR Prep, or a Quick task on +/// what the run left open. +pub fn next_prompt(slot: &ReviewSlot, which: &str) -> Result { + let guard = lock(slot); + let run = guard.as_ref().ok_or("There is no Review Loop run.")?; + if run.running { + return Err("The Review Loop is still running.".to_string()); + } + match which { + "pr-prep" => Ok("/plan2code-pr-prep --web".to_string()), + "quick-task" => { + let open: Vec = run + .open_findings() + .iter() + .enumerate() + .map(|(i, finding)| { + let at = match (finding.file.is_empty(), finding.line) { + (true, _) => String::new(), + (false, None) => format!(" ({})", finding.file), + (false, Some(line)) => format!(" ({}:{line})", finding.file), + }; + format!("{}. {}{at}", i + 1, text_line(&finding.title, 200)) + }) + .collect(); + if open.is_empty() { + return Err("Nothing is left open.".to_string()); + } + Ok(format!( + "/plan2code-quick-task --web Fix by hand what the Review Loop left open: {}", + open.join("; ") + )) + } + _ => Err("That is not a next step.".to_string()), + } +} + +/// Keep or discard what Stop now left, then show the end screen again +/// without it (Continue is offered once the partial changes are settled). +pub fn settle_partial(slot: &ReviewSlot, keep: bool, home: &Path) -> Result<(), String> { + partial(slot, keep)?; + let run = lock(slot).clone(); + if let Some(run) = run { + if let Some(file) = publish_end(&console_dir(), home, &run) { + if let Some(held) = lock(slot).as_mut().filter(|r| r.run_id == run.run_id) { + held.report_file = Some(file); + } + } + } + Ok(()) +} + +/// What the ending notice says, always naming the round it ended in, or none +/// when the person stopped the run themselves (as the Implementation Loop does). +fn stop_words(reason: &StopReason, round: u32, open: usize) -> Option { + match reason { + StopReason::Clean if open > 0 => Some(format!( + "finished after round {round}, but {} still open.", + count_words( + open, + "finding an earlier round left unfixed is", + "findings earlier rounds left unfixed are" + ) + )), + StopReason::Clean => Some(format!( + "finished after round {round}: no Critical or Warning findings are left." + )), + StopReason::Cap => Some(format!("stopped at the round cap after round {round}.")), + StopReason::Person => None, + StopReason::Failed(why) => Some(format!("failed in round {round}: {why}.")), + } +} + +/// Tell the address on its own thread: a slow one must not delay the watch. +fn send_notice(rc: &RoundCtx, kind: NotifyKind, url: String, param: String, message: String) { + let (slot, run_id) = (Arc::clone(&rc.slot), rc.ctx.run_id); + thread::spawn(move || { + if let Err(reason) = crate::loop_shared::notify(kind, &url, ¶m, &message) { + if let Some(run) = lock(&slot).as_mut().filter(|run| run.run_id == run_id) { + run.notify_failure = Some(reason); + } + } + }); +} + +fn notify_round(rc: &RoundCtx, round: u32, outcome: &RoundOutcome, verdict: &Verdict) { + let target = with_run(rc, |run| { + (run.setup.notify_rounds && !run.setup.notify_url.trim().is_empty()).then(|| { + ( + run.setup.notify_kind, + run.setup.notify_url.clone(), + run.setup.notify_param.clone(), + ) + }) + }) + .flatten(); + if let Some((kind, url, param)) = target { + let how = match verdict { + Verdict::Clean => "clean".to_string(), + Verdict::Findings { critical, warning } => { + format!("{critical} Critical, {warning} Warning") + } + Verdict::Failed(reason) => format!("failed ({reason})"), + }; + let message = format!("Review Loop round {round}: {how}. {}", outcome.summary); + send_notice(rc, kind, url, param, message); + } +} + +// ------------------------------------------------------- the stop buttons + +/// Stop after this round: it finishes, is judged and committed, then the run +/// stops instead of starting the next. Returns the banner's new state. +pub fn request_stop_after(slot: &ReviewSlot, on: bool) -> Result { + let mut guard = lock(slot); + let run = guard + .as_mut() + .filter(|run| run.running) + .ok_or("No Review Loop is running")?; + run.stop_after_round = on; + Ok(review_state_event(run)) +} + +/// Stop now: the flag is set first, so the ended agent is never taken for a +/// crash and nothing more is committed, then the agent ends. The banner's new +/// state goes to `emit` while the slot is held. +pub fn request_stop_now( + slot: &ReviewSlot, + agent: Option<&AgentManager>, + emit: impl FnOnce(&LoopStateEvent), +) -> Result { + let event = { + let mut guard = lock(slot); + let run = guard + .as_mut() + .filter(|run| run.running) + .ok_or("No Review Loop is running")?; + run.stop_now = true; + let event = review_state_event(run); + emit(&event); + event + }; + if let Some(agent) = agent { + agent.stop(); + } + Ok(event) +} + +/// Stop now was pressed: end the run as stopped by the person, commit +/// nothing, and leave the partial changes (a diff from the last finished +/// boundary to a fresh snapshot) for the stop screen. +fn stop_now_finish(rc: &RoundCtx) { + rc.ctx.agent.stop(); + let plan = with_run(rc, |run| { + ( + run.project.clone(), + run.last_boundary(), + run.run_dir.join("partial.diff"), + ) + }); + let Some((project, from, out)) = plan else { + return; + }; + let mut partial = Partial { + diff: out.clone(), + pending: true, + ..Partial::default() + }; + let _ = std::fs::create_dir_all(out.parent().unwrap_or(Path::new("."))); + let mut evidence = None; + match round_boundary::snapshot(&project) { + Ok(now) => match round_boundary::diff(&project, &from, &now, &out) { + Ok(stats) => { + partial.files = stats.files; + partial.added = stats.added; + partial.removed = stats.removed; + partial.new_files = git_text( + &project, + &[ + "diff", + "--name-only", + "-z", + "--no-renames", + "--diff-filter=A", + from.id(), + now.id(), + ], + ) + .map(|text| nul_lines(&text)) + .unwrap_or_default(); + } + Err(e) => evidence = Some(format!("the partial changes could not be listed ({e})")), + }, + Err(e) => evidence = Some(format!("the partial changes could not be listed ({e})")), + } + with_run(rc, |run| run.partial = Some(partial)); + finish_run(rc, StopReason::Person, evidence); +} + +/// Keep or discard what Stop now left. Keep leaves the partial changes +/// uncommitted. Discard puts tracked files back to the last finished +/// boundary and removes only the untracked files that appeared during the +/// stopped round, never others. +pub fn partial(slot: &ReviewSlot, keep: bool) -> Result<(), String> { + let (project, boundary, new_files) = { + let guard = lock(slot); + let run = guard.as_ref().ok_or("No Review Loop to settle")?; + if run.running { + return Err("The Review Loop is still running.".to_string()); + } + let partial = run + .partial + .as_ref() + .filter(|partial| partial.pending) + .ok_or("There are no partial changes waiting.")?; + ( + run.project.clone(), + run.last_boundary(), + partial.new_files.clone(), + ) + }; + if !keep { + // Git names files from the repository's top folder, and the project + // may be a folder inside it: put back and remove from the top. + let top = loop_tools::git_toplevel(&project).unwrap_or_else(|| project.clone()); + match &boundary { + Boundary::Commit(id) => { + git_text(&top, &["checkout", id, "--", "."])?; + } + Boundary::Tree(id) => restore_tree(&top, id)?, + } + for file in &new_files { + let path = top.join(file); + if path.is_file() { + let _ = std::fs::remove_file(&path); + } + } + } + if let Some(run) = lock(slot).as_mut() { + if let Some(partial) = run.partial.as_mut() { + partial.pending = false; + } + } + Ok(()) +} + +/// Put the working tree's files back to a tree id, through a temp index so the +/// real one is never touched. +fn restore_tree(project: &Path, tree: &str) -> Result<(), String> { + let temp = std::env::temp_dir().join(format!( + "plan2code-round-restore-{}-{}", + std::process::id(), + NEXT_RUN.fetch_add(1, Ordering::SeqCst) + )); + let run = |args: &[&str]| -> Result<(), String> { + let out = git_cmd(project, args) + .env("GIT_INDEX_FILE", &temp) + .output() + .map_err(|err| format!("git could not run: {err}"))?; + if out.status.success() { + Ok(()) + } else { + Err(format!( + "git {} failed: {}", + args.first().unwrap_or(&""), + String::from_utf8_lossy(&out.stderr) + .lines() + .next() + .unwrap_or("") + )) + } + }; + let result = run(&["read-tree", tree]).and_then(|()| run(&["checkout-index", "-a", "-f"])); + let _ = std::fs::remove_file(&temp); + result +} + +// ----------------------------------------------------------------- Continue + +/// Continue after a stop by the person, a failure or the cap: start the next +/// round from the run's last boundary. At the cap the cap goes up by one, and +/// never above six rounds in all. +pub fn continue_run( + slot: &ReviewSlot, + phases: &LoopSlot, + agent: Arc, + hooks: Hooks, + limits: Limits, + home: PathBuf, + watch: bool, +) -> Result<(), String> { + if loop_driver::is_running(phases) || is_running(slot) { + return Err("A loop is already running in this window.".to_string()); + } + let (round, rc) = { + let mut guard = lock(slot); + let run = guard + .as_mut() + .ok_or("There is no Review Loop to continue.")?; + if run.running || run.signing { + return Err("A loop is already running in this window.".to_string()); + } + if run.signed_off { + return Err("This Review Loop was signed off.".to_string()); + } + if run.partial.as_ref().is_some_and(|partial| partial.pending) { + return Err("Keep or discard the partial changes first.".to_string()); + } + let rounds_run = u32::try_from(run.rounds.len()).unwrap_or(u32::MAX); + match run.stop_reason { + Some(StopReason::Clean) | None => { + return Err( + "This Review Loop finished clean: there is nothing to continue.".into(), + ); + } + Some(StopReason::Cap) => { + let cap = round_logic::continue_cap(run.cap, rounds_run) + .ok_or("A Review Loop runs at most 6 rounds.")?; + run.cap = cap; + } + Some(StopReason::Person) | Some(StopReason::Failed(_)) => { + if rounds_run >= MAX_ROUNDS { + return Err("A Review Loop runs at most 6 rounds.".to_string()); + } + if rounds_run >= run.cap { + run.cap = rounds_run + 1; + } + } + } + run.running = true; + run.stop_reason = None; + run.stop_evidence = None; + run.stop_now = false; + run.stop_after_round = false; + run.retried = false; + run.reviewer_report = None; + run.cur_strength = run.setup.strength; + run.pending_stop = None; + run.partial = None; + run.batch_done = false; + drop_spec_report(run); + // A finished batch stays in the record; the next one is a new batch. + if let Some(batch) = run.suggestions_batch.take() { + run.earlier_batches.push(batch); + } + let rc = RoundCtx { + slot: Arc::clone(slot), + ctx: new_ctx(run, agent, home, hooks, limits), + }; + (rounds_run + 1, rc) + }; + let first = with_run(&rc, |run| first_stage(run.shape)).unwrap_or(Stage::Both); + if let Err(e) = start_stage(&rc, first, round) { + with_run(&rc, |run| { + run.running = false; + run.stop_round = round; + run.stop_reason = Some(StopReason::Failed(format!( + "a session could not start ({})", + one_line(&e) + ))); + }); + // The report was dropped above: write it again and re-post the end. + show_end(&rc); + (rc.ctx.hooks.emit)(LoopStateEvent::ended()); + return Err(e); + } + if watch { + thread::spawn(move || watcher(rc)); + } + Ok(()) +} + +// ------------------------------------------------------------- the facts + +/// What the setup screen shows about the agent a Review Loop would use. +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ReviewFacts { + pub agent: Option, + pub agent_label: Option, + pub helpers: bool, + pub strengths_mapped: bool, + pub running: bool, + pub prompt_support: bool, + pub notify_kind: NotifyKind, + pub notify_url: String, + pub notify_param: String, +} + +/// The facts for `agent` (or none), a loop running, and the Implementation +/// Loop's notification settings (`loop_setup`). +pub fn facts( + agent: Option<&Agent>, + running: bool, + loop_setup: &loop_driver::LoopSetup, +) -> ReviewFacts { + ReviewFacts { + agent: agent.map(|a| a.id().to_string()), + agent_label: agent.map(|a| a.label().to_string()), + helpers: agent.is_some_and(agent_helpers), + strengths_mapped: agent.is_some_and(|a| !loop_driver::strength_rows_for(a).is_empty()), + running, + prompt_support: agent.is_none_or(loop_driver::prompt_support), + notify_kind: loop_setup.notify_kind, + notify_url: loop_setup.notify_url.clone(), + notify_param: loop_setup.notify_param.clone(), + } +} + +/// The Start screen's request, as the page sends it. The notification comes +/// from the Implementation Loop's setup, never from this message. +#[derive(Clone, Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReviewRequest { + pub scope: ReviewScope, + #[serde(default)] + pub spec: Option, + #[serde(default = "default_cap")] + pub cap: u32, + #[serde(default = "default_true")] + pub commit: bool, + #[serde(default)] + pub pre_run_commit_agreed: bool, + #[serde(default)] + pub suggestions: bool, + #[serde(default)] + pub strength: String, + #[serde(default = "default_silence")] + pub silence_minutes: u32, + #[serde(default)] + pub notify_rounds: bool, +} + +fn default_cap() -> u32 { + 3 +} + +fn default_true() -> bool { + true +} + +fn default_silence() -> u32 { + 20 +} + +impl ReviewRequest { + pub fn into_setup(self, loop_setup: &loop_driver::LoopSetup) -> ReviewSetup { + ReviewSetup { + scope: self.scope, + spec: self.spec.filter(|spec| !spec.trim().is_empty()), + cap: self.cap, + commit: self.commit, + pre_run_commit_agreed: self.pre_run_commit_agreed, + suggestions: self.suggestions, + strength: Strength::from_word(&self.strength), + silence_minutes: self.silence_minutes.clamp(1, 60), + notify_rounds: self.notify_rounds, + notify_kind: loop_setup.notify_kind, + notify_url: loop_setup.notify_url.clone(), + notify_param: loop_setup.notify_param.clone(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::loop_driver::tests::{ + fake_agent_launch, fake_agent_manager, git_in, harness_ready, wait_until, + }; + use serde_json::json; + + #[test] + fn every_ending_notice_names_the_round_and_a_stop_by_the_person_sends_none() { + assert_eq!( + stop_words(&StopReason::Cap, 3, 0).as_deref(), + Some("stopped at the round cap after round 3.") + ); + assert!(stop_words(&StopReason::Clean, 2, 0) + .unwrap() + .contains("after round 2")); + assert!(stop_words(&StopReason::Clean, 2, 1) + .unwrap() + .ends_with("1 finding an earlier round left unfixed is still open.")); + assert!(stop_words(&StopReason::Failed("tests failed".into()), 2, 0) + .unwrap() + .starts_with("failed in round 2: tests failed")); + assert_eq!(stop_words(&StopReason::Person, 1, 0), None); + } + + /// A new repository on `main` in a unique temp folder, with a committed + /// `a.txt` and a `.gitignore` for `ignored.log`, its config scrubbed of + /// anything global. + fn scratch_repo(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!( + "plan2code-review-loop-{name}-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&base); + let repo = base.join("repo"); + std::fs::create_dir_all(&repo).unwrap(); + git_in(&repo, &["init", "-q"]); + git_in(&repo, &["symbolic-ref", "HEAD", "refs/heads/main"]); + for (key, value) in [ + ("user.name", "Review Test"), + ("user.email", "review@example.com"), + ("commit.gpgsign", "false"), + ("core.autocrlf", "false"), + ("core.hooksPath", ".git/hooks"), + ] { + git_in(&repo, &["config", key, value]); + } + std::fs::write(repo.join("a.txt"), "one\ntwo\n").unwrap(); + std::fs::write(repo.join(".gitignore"), "ignored.log\n").unwrap(); + git_in(&repo, &["add", "-A"]); + git_in(&repo, &["commit", "-q", "-m", "first"]); + repo + } + + struct Rig { + rc: RoundCtx, + repo: PathBuf, + home: PathBuf, + phases: LoopSlot, + events: Arc>>, + } + + fn hooks_into(events: &Arc>>) -> Hooks { + let sink = Arc::clone(events); + Hooks { + emit: Box::new(move |event| lock(&sink).push(event)), + attention: Box::new(|| {}), + } + } + + /// A run on a scratch repo with the fake agent, round 1 started, and no + /// watch thread: a test plays the watcher by calling `tick`. + fn rig(name: &str, setup: ReviewSetup, shape: Shape) -> Rig { + rig_on(scratch_repo(name), setup, shape) + } + + fn rig_on(repo: PathBuf, setup: ReviewSetup, shape: Shape) -> Rig { + let home = repo.parent().unwrap().join("console-home"); + std::fs::create_dir_all(home.join("sessions")).unwrap(); + let launch = fake_agent_launch(); + let mut run = prepare_run(&repo, &launch, setup, &home).expect("the run prepares"); + run.shape = shape; + let (agent, _seen) = fake_agent_manager(&repo); + let events = Arc::new(Mutex::new(Vec::new())); + let ctx = new_ctx( + &run, + agent, + home.clone(), + hooks_into(&events), + Limits::default(), + ); + let rc = RoundCtx { + slot: Arc::new(Mutex::new(Some(run))), + ctx, + }; + start_stage(&rc, first_stage(shape), 1).expect("round 1 starts"); + Rig { + rc, + repo, + home, + phases: Arc::new(Mutex::new(None)), + events, + } + } + + fn snap(rig: &Rig) -> ReviewRun { + lock(&rig.rc.slot).clone().expect("a run") + } + + fn done(rig: &Rig) { + rig.rc.ctx.agent.stop(); + let _ = std::fs::remove_dir_all(rig.repo.parent().unwrap()); + } + + fn subjects(repo: &Path) -> Vec { + git_in(repo, &["log", "--format=%s"]) + .lines() + .map(str::to_string) + .collect() + } + + /// A `roundOutcome` the way a round agent posts it. + fn outcome(round: u32, role: &str, critical: u32, warning: u32, fixed: &[&str]) -> Value { + let list: Vec = fixed + .iter() + .map(|title| json!({ "title": title, "file": "a.txt" })) + .collect(); + let mut value = json!({ + "round": round, "role": role, "result": "passed", "reason": null, + "summary": "Round done", + "review": { "critical": critical, "warning": warning, "suggestion": 0, + "fixed": list, "unfixed": [], "suggestions": [] }, + "tests": { "ran": true, "passed": true, "summary": "ok" }, + }); + if role != "fixer" { + value["report"] = json!("report"); + } + if role == "reviewer" { + value.as_object_mut().unwrap().remove("tests"); + value["review"]["unfixed"] = json!(fixed + .iter() + .map(|title| json!({ "title": title, "file": "a.txt" })) + .collect::>()); + value["review"]["fixed"] = json!([]); + } + value + } + + /// Put `outcome` in session `sid` (with the report doc it names, as the + /// console holds it), make `sid` the round's session, and take one look. + fn answer(rig: &Rig, sid: &str, outcome: Value) -> bool { + let mut state = json!({ "schema": session_reader::SCHEMA, "roundOutcome": outcome }); + if let Some(id) = state["roundOutcome"]["report"].as_str() { + state["docs"] = json!([{ "id": id, "kind": "report", "title": "Review round", + "blocks": [{ "id": "r", "md": "Found things to fix." }] }]); + } + let dir = rig.home.join("sessions").join(sid); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("state.json"), state.to_string()).unwrap(); + with_run(&rig.rc, |run| run.sid = Some(sid.to_string())); + tick(&rig.rc) + } + + fn edit(rig: &Rig, file: &str, text: &str) { + std::fs::write(rig.repo.join(file), text).unwrap(); + } + + fn one_session(name: &str, setup: ReviewSetup) -> Option { + harness_ready(name).then(|| rig(name, setup, Shape::OneSession)) + } + + fn go_on(rig: &Rig) -> Result<(), String> { + continue_run( + &rig.rc.slot, + &rig.phases, + Arc::clone(&rig.rc.ctx.agent), + hooks_into(&rig.events), + Limits::default(), + rig.home.clone(), + false, + ) + } + + fn rows() -> BTreeMap { + ["thrifty", "balanced", "best"] + .into_iter() + .map(|word| { + ( + word.to_string(), + StrengthRow { + model: format!("{word}-model"), + effort: None, + }, + ) + }) + .collect() + } + + // ------------------------------------------------------------ pure parts + + fn finding(title: &str, file: &str, line: Option) -> Finding { + Finding { + title: title.into(), + file: file.into(), + line, + } + } + + #[test] + fn suggestions_drop_repeats_fixed_ones_and_ones_the_latest_reviewer_dropped() { + let timer = finding("Name the timer", "x.js", Some(4)); + let handle = finding("Close the handle", "z.js", Some(9)); + let first = merge_suggestions(&[], std::slice::from_ref(&timer), &[], &["x.js".into()]); + assert_eq!(first, vec![timer.clone()]); + let again = merge_suggestions(&first, std::slice::from_ref(&timer), &[], &["x.js".into()]); + assert_eq!(again.len(), 1, "a repeat is kept once"); + let fixed = merge_suggestions(&first, &[], std::slice::from_ref(&timer), &["x.js".into()]); + assert!(fixed.is_empty(), "a later round fixed that file and line"); + let seen = ["x.js".to_string(), "z.js".to_string()]; + let dropped = merge_suggestions(&first, std::slice::from_ref(&handle), &[], &seen); + assert_eq!( + dropped, + vec![handle.clone()], + "the latest reviewer saw x.js and left it out" + ); + let kept = merge_suggestions( + &first, + std::slice::from_ref(&handle), + &[], + &["z.js".to_string()], + ); + assert_eq!( + kept, + vec![timer, handle], + "a file the reviewer never saw stays" + ); + } + + #[test] + fn the_round_prompt_names_the_round_the_role_and_the_scope_file() { + let prompt = round_prompt(2, Role::Fixer, Path::new("C:/runs/scope.md")); + assert_eq!( + prompt, + "/plan2code-review --web --loop --round 2 --role fixer --scope-file C:/runs/scope.md" + ); + let spaced = round_prompt(1, Role::Both, Path::new("C:/Jane Doe/scope.md")); + assert!( + spaced.ends_with("--scope-file \"C:/Jane Doe/scope.md\""), + "{spaced}" + ); + } + + #[test] + fn the_banner_event_is_a_rounds_event_and_the_phases_one_is_unchanged() { + let run = ReviewRun::new( + PathBuf::from("."), + ReviewSetup::default(), + fake_agent_launch(), + Mode::Commit, + Shape::OneSession, + Boundary::Commit("a".repeat(40)), + PathBuf::from("runs"), + BTreeMap::new(), + ); + let event = review_state_event(&run); + assert_eq!((event.kind, event.round, event.rounds), ("rounds", 1, 3)); + assert!(event.running && event.round_counts.is_empty()); + assert_eq!(event.phase_name, "Round 1 of 3: Starting"); + let ended = LoopStateEvent::ended(); + assert_eq!((ended.kind, ended.round, ended.rounds), ("phases", 0, 0)); + assert!(ended.round_counts.is_empty() && !ended.stop_after_round); + } + + #[test] + fn a_request_takes_its_notification_from_the_loop_setup_only() { + let request: ReviewRequest = serde_json::from_value(json!({ + "scope": "spec", "spec": "specs/x", "cap": 4, "suggestions": true, + "strength": "best", "silenceMinutes": 99, "notifyRounds": true, + "notifyUrl": "http://evil.example/", "notifyParam": "x" + })) + .unwrap(); + let loop_setup = loop_driver::LoopSetup { + notify_url: "http://mine.example/".into(), + notify_param: "msg".into(), + ..loop_driver::LoopSetup::default() + }; + let setup = request.into_setup(&loop_setup); + assert_eq!(setup.notify_url, "http://mine.example/"); + assert_eq!(setup.notify_param, "msg"); + assert_eq!(setup.silence_minutes, 60, "clamped to an hour"); + assert_eq!(setup.strength, Some(Strength::Best)); + assert!( + setup.commit, + "commits are on unless the page turns them off" + ); + } + + // ---------------------------------------------------- the four stop reasons + + #[test] + fn a_clean_first_round_stops_clean_with_nothing_to_commit() { + let Some(rig) = one_session("clean", ReviewSetup::default()) else { + return; + }; + let head = git_in(&rig.repo, &["rev-parse", "HEAD"]); + assert!( + !answer(&rig, "s1", outcome(1, "both", 0, 0, &[])), + "the run is over" + ); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Clean)); + assert!(!run.running); + assert_eq!(run.rounds.len(), 1); + assert_eq!(run.rounds[0].verdict, Some(Verdict::Clean)); + assert_eq!(run.rounds[0].commit, None); + assert_eq!(git_in(&rig.repo, &["rev-parse", "HEAD"]), head); + assert!(!is_running(&rig.rc.slot)); + assert!(lock(&rig.events).last().is_some_and(|e| !e.running)); + done(&rig); + } + + #[test] + fn findings_then_clean_commits_each_round_by_number_and_scopes_round_two_to_round_ones_diff() { + let Some(rig) = one_session("two-rounds", ReviewSetup::default()) else { + return; + }; + edit(&rig, "b.txt", "fixed b\n"); + assert!(answer(&rig, "s1", outcome(1, "both", 0, 1, &["Fix b"]))); + let run = snap(&rig); + assert_eq!( + (run.round, run.stage, run.rounds.len()), + (2, Stage::Both, 1) + ); + // The agent never ran git: the app committed the round. + assert_eq!(subjects(&rig.repo)[0], "Review Loop round 1: Fix b"); + // Round 2 reviews exactly round 1's diff. + let dir = run.run_dir.join("round-2-both-t0"); + let diff = std::fs::read_to_string(dir.join("round-1.diff")).unwrap(); + assert!( + diff.contains("+++ b/b.txt") && !diff.contains("a.txt"), + "{diff}" + ); + let scope = std::fs::read_to_string(dir.join("scope.md")).unwrap(); + assert!(scope.contains("round-1.diff"), "{scope}"); + edit(&rig, "c.txt", "tidy c\n"); + assert!(!answer(&rig, "s2", outcome(2, "both", 0, 0, &["Tidy c"]))); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Clean)); + let log = subjects(&rig.repo); + assert_eq!(log[0], "Review Loop round 2: Tidy c"); + assert_eq!(log[1], "Review Loop round 1: Fix b"); + assert_eq!(run.rounds.len(), 2); + assert_eq!(run.rounds[1].commit.as_deref().map(str::len), Some(40)); + done(&rig); + } + + #[test] + fn findings_every_round_stop_at_the_cap_after_three_commits() { + let Some(rig) = one_session("cap", ReviewSetup::default()) else { + return; + }; + for n in 1..=3 { + edit(&rig, &format!("f{n}.txt"), "x\n"); + let more = answer(&rig, &format!("s{n}"), outcome(n, "both", 0, 1, &["Fix"])); + assert_eq!(more, n < 3, "round {n}"); + } + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Cap)); + assert_eq!(run.rounds.len(), 3); + assert_eq!( + subjects(&rig.repo).len(), + 4, + "three rounds and the first commit" + ); + done(&rig); + } + + #[test] + fn stop_after_this_round_commits_the_round_then_stops() { + let Some(rig) = one_session("stop-after", ReviewSetup::default()) else { + return; + }; + let event = request_stop_after(&rig.rc.slot, true).unwrap(); + assert!(event.stop_after_round); + edit(&rig, "b.txt", "x\n"); + assert!(!answer(&rig, "s1", outcome(1, "both", 0, 1, &["Fix b"]))); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Person)); + assert_eq!(subjects(&rig.repo)[0], "Review Loop round 1: Fix b"); + assert_eq!(run.rounds.len(), 1); + done(&rig); + } + + #[test] + fn stop_now_commits_nothing_and_keep_leaves_the_partial_changes() { + let Some(rig) = one_session("stop-now-keep", ReviewSetup::default()) else { + return; + }; + let before = git_in(&rig.repo, &["rev-parse", "HEAD"]); + edit(&rig, "a.txt", "changed\n"); + edit(&rig, "p.txt", "new\n"); + request_stop_now(&rig.rc.slot, Some(&rig.rc.ctx.agent), |_| {}).unwrap(); + assert!(!tick(&rig.rc), "the next look ends the run"); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Person)); + assert_eq!( + git_in(&rig.repo, &["rev-parse", "HEAD"]), + before, + "nothing committed" + ); + let info = run.partial.clone().expect("partial data"); + assert!(info.pending && info.files == 2, "{info:?}"); + let diff = std::fs::read_to_string(&info.diff).unwrap(); + assert!(diff.contains("+++ b/p.txt") && diff.contains("+++ b/a.txt")); + // Continue is held until the partial changes are settled. + assert!(go_on(&rig).unwrap_err().contains("partial changes")); + partial(&rig.rc.slot, true).unwrap(); + assert_eq!( + std::fs::read_to_string(rig.repo.join("a.txt")).unwrap(), + "changed\n" + ); + assert!(rig.repo.join("p.txt").exists()); + assert!(snap(&rig).partial.is_some_and(|p| !p.pending)); + done(&rig); + } + + #[test] + fn stop_now_then_discard_puts_back_tracked_files_and_removes_only_the_rounds_new_ones() { + for (commit, name) in [(true, "discard-commit"), (false, "discard-snapshot")] { + let setup = ReviewSetup { + commit, + ..ReviewSetup::default() + }; + let Some(rig) = one_session(name, setup) else { + return; + }; + // An ignored file that was there before the round: never touched. + std::fs::write(rig.repo.join("ignored.log"), "mine\n").unwrap(); + edit(&rig, "a.txt", "changed\n"); + edit(&rig, "p.txt", "new\n"); + request_stop_now(&rig.rc.slot, Some(&rig.rc.ctx.agent), |_| {}).unwrap(); + assert!(!tick(&rig.rc)); + partial(&rig.rc.slot, false).unwrap(); + assert_eq!( + std::fs::read_to_string(rig.repo.join("a.txt")).unwrap(), + "one\ntwo\n", + "{name}: the tracked file is back" + ); + assert!( + !rig.repo.join("p.txt").exists(), + "{name}: the round's new file is gone" + ); + assert!( + rig.repo.join("ignored.log").exists(), + "{name}: ignored files are never touched" + ); + assert!(snap(&rig).partial.is_some_and(|p| !p.pending)); + // Settled once: a second answer has nothing to act on. + assert!(partial(&rig.rc.slot, false).is_err()); + done(&rig); + } + } + + #[test] + fn continue_past_the_cap_runs_one_round_at_a_time_and_refuses_a_seventh() { + let Some(rig) = one_session("continue", ReviewSetup::default()) else { + return; + }; + for n in 1..=3 { + edit(&rig, &format!("f{n}.txt"), "x\n"); + answer(&rig, &format!("s{n}"), outcome(n, "both", 0, 1, &["Fix"])); + } + assert_eq!(snap(&rig).stop_reason, Some(StopReason::Cap)); + // Each Continue past the cap adds exactly one round. + for n in 4..=6 { + go_on(&rig).unwrap_or_else(|e| panic!("continue for round {n}: {e}")); + let run = snap(&rig); + assert_eq!((run.round, run.cap, run.running), (n, n, true)); + edit(&rig, &format!("f{n}.txt"), "x\n"); + assert!(!answer( + &rig, + &format!("s{n}"), + outcome(n, "both", 0, 1, &["Fix"]) + )); + assert_eq!(snap(&rig).stop_reason, Some(StopReason::Cap)); + } + assert_eq!( + go_on(&rig).unwrap_err(), + "A Review Loop runs at most 6 rounds." + ); + assert_eq!(snap(&rig).rounds.len(), 6); + // A run that finished clean has nothing to continue. + with_run(&rig.rc, |run| run.stop_reason = Some(StopReason::Clean)); + assert!(go_on(&rig).unwrap_err().contains("nothing to continue")); + done(&rig); + } + + // ----------------------------------------- shapes, proofs, retries, modes + + #[test] + fn the_two_session_shape_runs_a_reviewer_then_a_fixer_that_gets_the_reviewers_report() { + if !harness_ready("two-session") { + return; + } + let rig = rig("two-session", ReviewSetup::default(), Shape::TwoSession); + assert_eq!(snap(&rig).stage, Stage::Reviewer); + let reviewer_generation = snap(&rig).generation; + assert!(answer(&rig, "r1", outcome(1, "reviewer", 0, 1, &["Fix x"]))); + let run = snap(&rig); + assert_eq!( + run.stage, + Stage::Fixer, + "the fixer starts in its own session" + ); + assert_ne!( + run.generation, reviewer_generation, + "a fresh agent, not the reviewer's" + ); + let fixer = run.run_dir.join("round-1-fixer-t0"); + let report = std::fs::read_to_string(fixer.join("reviewer-report.md")).unwrap(); + assert!( + report.contains("Found things to fix.") && report.contains("Fix x"), + "{report}" + ); + let scope = std::fs::read_to_string(fixer.join("scope.md")).unwrap(); + assert!(scope.contains("reviewer-report.md"), "{scope}"); + assert_eq!( + subjects(&rig.repo).len(), + 1, + "a report alone commits nothing" + ); + edit(&rig, "x.txt", "fixed\n"); + assert!(answer(&rig, "f1", outcome(1, "fixer", 0, 1, &["Fix x"]))); + assert_eq!(subjects(&rig.repo)[0], "Review Loop round 1: Fix x"); + let run = snap(&rig); + assert_eq!((run.round, run.stage), (2, Stage::Reviewer)); + assert!(!answer(&rig, "r2", outcome(2, "reviewer", 0, 0, &[]))); + assert_eq!(snap(&rig).stop_reason, Some(StopReason::Clean)); + done(&rig); + } + + #[test] + fn a_fixer_that_reports_zero_counts_cannot_end_the_run_clean() { + if !harness_ready("fixer-zero") { + return; + } + let rig = rig("fixer-zero", ReviewSetup::default(), Shape::TwoSession); + assert!(answer(&rig, "r1", outcome(1, "reviewer", 0, 1, &["Fix x"]))); + edit(&rig, "x.txt", "fixed\n"); + assert!( + answer(&rig, "f1", outcome(1, "fixer", 0, 0, &["Fix x"])), + "the run goes on: the reviewer found a Warning" + ); + let run = snap(&rig); + assert_eq!((run.round, run.stage), (2, Stage::Reviewer)); + assert_eq!(run.stop_reason, None); + assert_eq!( + run.rounds[0].warning, 1, + "recorded with the reviewer's count" + ); + assert!(!answer(&rig, "r2", outcome(2, "reviewer", 0, 0, &[]))); + assert_eq!(snap(&rig).stop_reason, Some(StopReason::Clean)); + done(&rig); + } + + #[test] + fn a_finding_a_round_left_unfixed_stays_open_after_a_clean_fix_diff_round() { + if !harness_ready("carry-open") { + return; + } + let rig = rig("carry-open", ReviewSetup::default(), Shape::OneSession); + let mut first = outcome(1, "both", 0, 2, &["Fix a"]); + first["review"]["unfixed"] = json!([{ "title": "Hard one", "file": "b.txt" }]); + edit(&rig, "a.txt", "fixed\n"); + assert!(answer(&rig, "s1", first)); + assert!(!answer(&rig, "s2", outcome(2, "both", 0, 0, &[]))); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Clean)); + let open = run.open_findings(); + assert_eq!(open.len(), 1); + assert_eq!(open[0].title, "Hard one"); + let line = end_line(&run); + assert!( + line.contains("1 finding an earlier round left unfixed is still open"), + "{line}" + ); + done(&rig); + } + + #[test] + fn a_report_that_ran_no_tests_fails_the_round_and_the_retry_runs_one_strength_up() { + if !harness_ready("no-tests") { + return; + } + let setup = ReviewSetup { + strength: Some(Strength::Thrifty), + ..ReviewSetup::default() + }; + let rig = rig("no-tests", setup, Shape::OneSession); + with_run(&rig.rc, |run| run.strength_rows = rows()); + let mut bad = outcome(1, "both", 0, 0, &[]); + bad["tests"] = json!({ "ran": false, "passed": false, "summary": "" }); + assert!( + answer(&rig, "s1", bad.clone()), + "a first failure is retried" + ); + let run = snap(&rig); + assert!(run.retried && run.running); + assert_eq!(run.cur_strength, Some(Strength::Balanced)); + assert!(run.cur.retried && !run.cur.could_not_step_up); + assert!(!answer(&rig, "s2", bad), "the second failure stops the run"); + let run = snap(&rig); + assert_eq!( + run.stop_reason, + Some(StopReason::Failed("targeted tests did not run".into())) + ); + assert!(run.rounds.is_empty()); + done(&rig); + } + + #[test] + fn a_second_failure_keeps_the_rounds_that_finished_and_best_cannot_step_up() { + if !harness_ready("keep-finished") { + return; + } + let setup = ReviewSetup { + strength: Some(Strength::Best), + ..ReviewSetup::default() + }; + let rig = rig("keep-finished", setup, Shape::OneSession); + with_run(&rig.rc, |run| run.strength_rows = rows()); + edit(&rig, "b.txt", "x\n"); + assert!(answer(&rig, "s1", outcome(1, "both", 0, 1, &["Fix b"]))); + let mut failed = outcome(2, "both", 0, 0, &[]); + failed["result"] = json!("failed"); + failed["reason"] = json!("tests"); + assert!(answer(&rig, "s2", failed.clone())); + let run = snap(&rig); + assert_eq!(run.cur_strength, Some(Strength::Best)); + assert!( + run.cur.could_not_step_up, + "Best stays Best, and the report says so" + ); + assert!(!answer(&rig, "s3", failed)); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Failed("tests".into()))); + assert_eq!(run.rounds.len(), 1, "round 1 is kept"); + assert_eq!(subjects(&rig.repo)[0], "Review Loop round 1: Fix b"); + done(&rig); + } + + #[test] + fn a_crashed_agent_gets_one_retry_then_stops_the_run() { + let Some(rig) = one_session("crash", ReviewSetup::default()) else { + return; + }; + let dir = rig.home.join("sessions/s1"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("state.json"), json!({ "schema": 1 }).to_string()).unwrap(); + for attempt in ["first", "second"] { + with_run(&rig.rc, |run| run.sid = Some("s1".into())); + wait_until("the fake agent to be up", || { + rig.rc.ctx.agent.snapshot().state == AgentState::Running + }); + rig.rc.ctx.agent.input(b"EXIT 3\r").unwrap(); + wait_until("the agent to end", || { + matches!(rig.rc.ctx.agent.snapshot().state, AgentState::Ended { .. }) + }); + let goes_on = tick(&rig.rc); + assert_eq!(goes_on, attempt == "first", "{attempt} crash"); + } + let run = snap(&rig); + assert!( + matches!(run.stop_reason, Some(StopReason::Failed(ref why)) if why.contains("crashed")), + "{:?}", + run.stop_reason + ); + done(&rig); + } + + #[test] + fn snapshot_mode_diffs_between_snapshots_and_makes_no_commit() { + let setup = ReviewSetup { + commit: false, + ..ReviewSetup::default() + }; + let Some(rig) = one_session("snapshot", setup) else { + return; + }; + assert!(matches!(snap(&rig).start, Boundary::Tree(_))); + edit(&rig, "b.txt", "fixed b\n"); + assert!(answer(&rig, "s1", outcome(1, "both", 0, 1, &["Fix b"]))); + assert_eq!( + subjects(&rig.repo), + vec!["first"], + "no commit in snapshot mode" + ); + let run = snap(&rig); + assert!(matches!(run.rounds[0].boundary, Some(Boundary::Tree(_)))); + assert_eq!(run.rounds[0].commit, None); + let diff = + std::fs::read_to_string(run.run_dir.join("round-2-both-t0/round-1.diff")).unwrap(); + assert!(diff.contains("+++ b/b.txt"), "{diff}"); + assert_eq!( + git_in(&rig.repo, &["status", "--porcelain"]).trim(), + "?? b.txt", + "the work stays in the tree, uncommitted" + ); + done(&rig); + } + + #[test] + fn the_pre_run_commit_is_made_only_when_agreed() { + if !harness_ready("pre-run") { + return; + } + let repo = scratch_repo("pre-run"); + let home = repo.parent().unwrap().join("console-home"); + std::fs::write(repo.join("d.txt"), "mine\n").unwrap(); + let launch = fake_agent_launch(); + let refused = prepare_run(&repo, &launch, ReviewSetup::default(), &home).unwrap_err(); + assert!(refused.contains("uncommitted changes"), "{refused}"); + assert_eq!(subjects(&repo), vec!["first"], "nothing was committed"); + let setup = ReviewSetup { + pre_run_commit_agreed: true, + ..ReviewSetup::default() + }; + let run = prepare_run(&repo, &launch, setup, &home).expect("agreed"); + assert_eq!(subjects(&repo)[0], "Work before Review Loop"); + let head = git_in(&repo, &["rev-parse", "HEAD"]); + assert_eq!(run.pre_run_commit.as_deref(), Some(head.as_str())); + assert_eq!(run.start, Boundary::Commit(head)); + assert!(git_in(&repo, &["status", "--porcelain"]).trim().is_empty()); + // Commits off needs no agreement: the tree is only measured. + std::fs::write(repo.join("e.txt"), "more\n").unwrap(); + let snapshot_only = ReviewSetup { + commit: false, + ..ReviewSetup::default() + }; + let run = prepare_run(&repo, &launch, snapshot_only, &home).expect("snapshot mode"); + assert!(run.pre_run_commit.is_none() && matches!(run.start, Boundary::Tree(_))); + let _ = std::fs::remove_dir_all(repo.parent().unwrap()); + } + + #[test] + fn a_loop_already_running_refuses_a_second_start_and_a_bad_cap() { + if !harness_ready("refuse") { + return; + } + let rig = rig("refuse", ReviewSetup::default(), Shape::OneSession); + let start = |rig: &Rig| { + let (agent, _) = fake_agent_manager(&rig.repo); + start_review_loop_with( + &rig.rc.slot, + &rig.phases, + agent, + fake_agent_launch(), + rig.repo.clone(), + ReviewSetup::default(), + hooks_into(&rig.events), + Limits::default(), + rig.home.clone(), + false, + ) + }; + assert_eq!( + start(&rig).unwrap_err(), + "A loop is already running in this window." + ); + let high = ReviewSetup { + cap: 7, + ..ReviewSetup::default() + }; + let launch = fake_agent_launch(); + assert!(prepare_run(&rig.repo, &launch, high, &rig.home) + .unwrap_err() + .contains("1 to 6")); + // An Implementation Loop running blocks it too. + abandon(&rig.rc.slot); + *lock(&rig.phases) = Some(loop_driver::RunningRecord::new( + rig.repo.clone(), + "specs/x".into(), + loop_driver::LoopSetup::default(), + vec![], + )); + assert_eq!( + start(&rig).unwrap_err(), + "A loop is already running in this window." + ); + done(&rig); + } + + // ---------------------------------------------- the Suggestions batch + + fn with_suggestions(round: u32, role: &str) -> Value { + let mut value = outcome(round, role, 0, 0, &[]); + value["review"]["suggestion"] = json!(1); + value["review"]["suggestions"] = json!([{ "title": "Name the timer", "file": "a.txt" }]); + value + } + + #[test] + fn with_the_switch_on_a_clean_stop_runs_the_batch_and_the_final_check_outside_the_cap() { + let setup = ReviewSetup { + suggestions: true, + ..ReviewSetup::default() + }; + let Some(rig) = one_session("batch-on", setup) else { + return; + }; + assert!(answer(&rig, "s1", with_suggestions(1, "both"))); + let run = snap(&rig); + assert_eq!((run.stage, run.round), (Stage::Batch, 2)); + assert_eq!(run.pending_stop, Some(StopReason::Clean)); + assert_eq!(run.suggestions_batch.as_ref().unwrap().briefed.len(), 1); + let scope = std::fs::read_to_string(run.run_dir.join("round-2-batch-t0/scope.md")).unwrap(); + assert!(scope.contains("Name the timer"), "{scope}"); + edit(&rig, "t.txt", "named\n"); + assert!(answer( + &rig, + "b1", + outcome(2, "fixer", 0, 0, &["Name the timer"]) + )); + assert_eq!( + subjects(&rig.repo)[0], + "Review Loop Suggestions batch: Name the timer", + "the batch is committed on its own" + ); + let run = snap(&rig); + assert_eq!((run.stage, run.round), (Stage::Final, 3)); + let diff = + std::fs::read_to_string(run.run_dir.join("round-3-final-t0/batch.diff")).unwrap(); + assert!(diff.contains("+++ b/t.txt"), "{diff}"); + assert!(!answer(&rig, "c1", outcome(3, "reviewer", 0, 0, &[]))); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Clean)); + assert_eq!( + run.rounds.len(), + 1, + "the batch and the check are outside the rounds" + ); + let batch = run.suggestions_batch.unwrap(); + assert_eq!(batch.final_check, Some(Verdict::Clean)); + assert!(batch.commit.is_some()); + done(&rig); + } + + #[test] + fn with_the_switch_off_no_batch_runs() { + let Some(rig) = one_session("batch-off", ReviewSetup::default()) else { + return; + }; + assert!(!answer(&rig, "s1", with_suggestions(1, "both"))); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Clean)); + assert!(run.suggestions_batch.is_none()); + assert_eq!( + run.collected.len(), + 1, + "collected for the report, not fixed" + ); + done(&rig); + } + + #[test] + fn after_a_person_stop_or_a_failure_no_batch_runs_even_when_on() { + let setup = ReviewSetup { + suggestions: true, + ..ReviewSetup::default() + }; + let Some(rig) = one_session("batch-person", setup.clone()) else { + return; + }; + request_stop_after(&rig.rc.slot, true).unwrap(); + edit(&rig, "b.txt", "x\n"); + let mut found = with_suggestions(1, "both"); + found["review"]["warning"] = json!(1); + found["review"]["fixed"] = json!([{ "title": "Fix b", "file": "b.txt" }]); + assert!(!answer(&rig, "s1", found)); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Person)); + assert!(run.suggestions_batch.is_none()); + done(&rig); + let Some(rig) = one_session("batch-failed", setup) else { + return; + }; + let mut failed = with_suggestions(1, "both"); + failed["result"] = json!("failed"); + failed["reason"] = json!("other"); + assert!(answer(&rig, "s1", failed.clone())); + assert!(!answer(&rig, "s2", failed)); + let run = snap(&rig); + assert!(matches!(run.stop_reason, Some(StopReason::Failed(_)))); + assert!(run.suggestions_batch.is_none()); + done(&rig); + } + + #[test] + fn a_batch_at_the_cap_keeps_the_cap_as_the_stop_reason() { + let setup = ReviewSetup { + suggestions: true, + cap: 1, + ..ReviewSetup::default() + }; + let Some(rig) = one_session("batch-cap", setup) else { + return; + }; + edit(&rig, "b.txt", "x\n"); + let mut found = with_suggestions(1, "both"); + found["review"]["warning"] = json!(1); + found["review"]["fixed"] = json!([{ "title": "Fix b", "file": "b.txt" }]); + assert!(answer(&rig, "s1", found)); + assert_eq!(snap(&rig).pending_stop, Some(StopReason::Cap)); + edit(&rig, "t.txt", "x\n"); + assert!(answer( + &rig, + "b1", + outcome(2, "fixer", 0, 0, &["Name the timer"]) + )); + assert!(!answer(&rig, "c1", outcome(3, "reviewer", 0, 1, &["Late"]))); + assert_eq!( + snap(&rig).stop_reason, + Some(StopReason::Cap), + "the final check's own verdict never changes why the run ended" + ); + done(&rig); + } + + #[test] + fn a_page_announced_for_this_round_and_role_becomes_its_session() { + let Some(rig) = one_session("note-page", ReviewSetup::default()) else { + return; + }; + let unlocked = json!({ "schema": 1 }); + note_page(&rig.rc.slot, "review", "other", &unlocked); + assert_eq!(snap(&rig).sid, None); + assert_eq!(snap(&rig).page_candidate.as_deref(), Some("other")); + let wrong_round = json!({ "loop": { "driving": true, "round": 2, "role": "both" } }); + note_page(&rig.rc.slot, "review", "later", &wrong_round); + assert_eq!(snap(&rig).sid, None); + let right = json!({ "loop": { "driving": true, "round": 1, "role": "both" } }); + note_page(&rig.rc.slot, "implement", "x", &right); + assert_eq!(snap(&rig).sid, None, "only a Review page counts"); + note_page(&rig.rc.slot, "review", "mine", &right); + assert_eq!(snap(&rig).sid.as_deref(), Some("mine")); + done(&rig); + } + + // ------------------------------------------------- the review's fixes + + #[test] + fn a_title_with_shell_characters_is_cleaned_and_the_round_still_commits() { + assert_eq!( + safe_title("Guard `None` in \u{201C}parse\u{201D} $x! \\n"), + "Guard None in 'parse' x n" + ); + let Some(rig) = one_session("shell-title", ReviewSetup::default()) else { + return; + }; + edit(&rig, "b.txt", "x\n"); + let title = "Guard `None` in \"parse\" $x!"; + assert!(answer(&rig, "s1", outcome(1, "both", 0, 1, &[title]))); + assert_eq!( + subjects(&rig.repo)[0], + "Review Loop round 1: Guard None in 'parse' x" + ); + assert!(git_in(&rig.repo, &["status", "--porcelain"]) + .trim() + .is_empty()); + done(&rig); + } + + #[test] + fn a_refused_subject_takes_the_staged_files_out_again() { + if !harness_ready("refused-subject") { + return; + } + let repo = scratch_repo("refused-subject"); + std::fs::write(repo.join("b.txt"), "x\n").unwrap(); + let long = "x".repeat(150); + let refused = commit_all(&repo, &long, Duration::from_secs(60)); + assert!(refused.is_err(), "a 150 character subject is refused"); + assert!( + git_in(&repo, &["diff", "--cached", "--name-only"]) + .trim() + .is_empty(), + "nothing is left staged" + ); + let _ = std::fs::remove_dir_all(repo.parent().unwrap()); + } + + #[test] + fn the_batch_subject_fits_72_characters_with_its_own_prefix() { + let titles: Vec = [ + "Name the timer correctly everywhere", + "Close the file handle", + ] + .iter() + .map(|t| t.to_string()) + .collect(); + let subject = batch_subject(&titles); + assert!( + subject.starts_with("Review Loop Suggestions batch"), + "{subject}" + ); + assert!(subject.chars().count() <= 72, "{subject}"); + let long = vec!["y".repeat(120)]; + let cut = batch_subject(&long); + assert!(cut.chars().count() <= 72 && cut.ends_with("..."), "{cut}"); + assert_eq!(batch_subject(&[]), "Review Loop Suggestions batch"); + } + + #[test] + fn stop_now_in_the_final_check_then_discard_keeps_the_committed_batch() { + let setup = ReviewSetup { + suggestions: true, + ..ReviewSetup::default() + }; + let Some(rig) = one_session("final-discard", setup) else { + return; + }; + assert!(answer(&rig, "s1", with_suggestions(1, "both"))); + edit(&rig, "t.txt", "named\n"); + assert!(answer( + &rig, + "b1", + outcome(2, "fixer", 0, 0, &["Name the timer"]) + )); + assert_eq!(snap(&rig).stage, Stage::Final); + // The final check is running; the person stops it and a stray file lands. + edit(&rig, "q.txt", "partial\n"); + request_stop_now(&rig.rc.slot, Some(&rig.rc.ctx.agent), |_| {}).unwrap(); + assert!(!tick(&rig.rc)); + let info = snap(&rig).partial.expect("partial data"); + assert_eq!( + info.new_files, + vec!["q.txt".to_string()], + "only the stray file" + ); + partial(&rig.rc.slot, false).unwrap(); + assert!(rig.repo.join("t.txt").exists(), "the committed batch stays"); + assert!(!rig.repo.join("q.txt").exists()); + done(&rig); + } + + #[test] + fn the_branch_scope_needs_a_trunk_and_says_so() { + if !harness_ready("no-trunk") { + return; + } + let repo = scratch_repo("no-trunk"); + git_in(&repo, &["branch", "-m", "main", "feature"]); + let err = scope_files(&repo, ReviewScope::Branch, None).unwrap_err(); + assert!(err.contains("no main or master branch"), "{err}"); + let spec_err = scope_files(&repo, ReviewScope::Spec, Some(".")).unwrap_err(); + assert!(spec_err.contains("no main or master branch"), "{spec_err}"); + assert!(scope_files(&repo, ReviewScope::Uncommitted, None).is_ok()); + let _ = std::fs::remove_dir_all(repo.parent().unwrap()); + } + + #[test] + fn a_final_check_that_fails_twice_keeps_the_reason_the_run_was_ending_for() { + let setup = ReviewSetup { + suggestions: true, + ..ReviewSetup::default() + }; + let Some(rig) = one_session("final-fails", setup) else { + return; + }; + assert!(answer(&rig, "s1", with_suggestions(1, "both"))); + edit(&rig, "t.txt", "named\n"); + assert!(answer( + &rig, + "b1", + outcome(2, "fixer", 0, 0, &["Name the timer"]) + )); + let mut failed = outcome(3, "reviewer", 0, 0, &[]); + failed["result"] = json!("failed"); + failed["reason"] = json!("other"); + assert!( + answer(&rig, "c1", failed.clone()), + "the first failure is retried" + ); + assert!(!answer(&rig, "c2", failed)); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Clean), "not Failed"); + assert!(matches!( + run.suggestions_batch + .as_ref() + .and_then(|b| b.final_check.clone()), + Some(Verdict::Failed(_)) + )); + assert!(run.stop_evidence.is_some_and(|e| e.contains("final check"))); + done(&rig); + } + + #[test] + fn last_boundary_orders_a_kept_batch_among_the_rounds() { + let Some(rig) = one_session("last-boundary", ReviewSetup::default()) else { + return; + }; + let mut run = snap(&rig); + let c = |id: &str| Boundary::Commit(id.to_string()); + let round = |n: u32, id: &str| RoundRecord { + n, + boundary: Some(c(id)), + ..RoundRecord::default() + }; + let batch = |after: usize, id: &str| BatchRecord { + after_rounds: after, + boundary: Some(c(id)), + ..BatchRecord::default() + }; + run.rounds = vec![round(1, "r1"), round(2, "r2")]; + run.earlier_batches = vec![batch(2, "b1")]; + assert_eq!(run.last_boundary(), c("b1"), "the batch came after round 2"); + run.rounds.push(round(3, "r3")); + assert_eq!(run.last_boundary(), c("r3"), "a round after the batch wins"); + run.suggestions_batch = Some(batch(3, "b2")); + assert_eq!(run.last_boundary(), c("b2"), "the current batch is newest"); + done(&rig); + } + + #[test] + fn the_round_after_a_continue_is_scoped_from_the_batch_committed_before_it() { + let Some(rig) = one_session("diff-after-batch", ReviewSetup::default()) else { + return; + }; + let mut run = snap(&rig); + let c = |id: &str| Boundary::Commit(id.to_string()); + let round = |n: u32, id: &str| RoundRecord { + n, + boundary: Some(c(id)), + ..RoundRecord::default() + }; + run.rounds = vec![round(1, "r1"), round(2, "r2")]; + run.earlier_batches = vec![BatchRecord { + after_rounds: 2, + boundary: Some(c("b1")), + ..BatchRecord::default() + }]; + let (from, to) = plan_for(&run, Stage::Both, 3) + .diff + .expect("round 3 has a diff"); + assert_eq!((from, to), (c("r1"), c("b1")), "round 3 sees the batch"); + let (from, to) = plan_for(&run, Stage::Both, 2) + .diff + .expect("round 2 has a diff"); + assert_eq!( + (from, to), + (run.start.clone(), c("r1")), + "an earlier round is unchanged" + ); + done(&rig); + } + + #[test] + fn nul_separated_names_are_never_quoted_or_split_on_spaces() { + assert_eq!( + nul_lines("a b.txt\0caf\u{e9}.txt\0"), + vec!["a b.txt".to_string(), "caf\u{e9}.txt".to_string()] + ); + } + + #[test] + fn continue_after_a_capped_batch_keeps_the_batch_and_never_briefs_it_again() { + let setup = ReviewSetup { + suggestions: true, + cap: 1, + ..ReviewSetup::default() + }; + let Some(rig) = one_session("continue-batch", setup) else { + return; + }; + edit(&rig, "b.txt", "x\n"); + let mut found = with_suggestions(1, "both"); + found["review"]["warning"] = json!(1); + found["review"]["fixed"] = json!([{ "title": "Fix b", "file": "b.txt" }]); + assert!(answer(&rig, "s1", found)); + edit(&rig, "t.txt", "x\n"); + assert!(answer( + &rig, + "b1", + outcome(2, "fixer", 0, 0, &["Name the timer"]) + )); + assert!(!answer(&rig, "c1", outcome(3, "reviewer", 0, 0, &[]))); + assert_eq!(snap(&rig).stop_reason, Some(StopReason::Cap)); + assert!(snap(&rig).collected.is_empty(), "the batch fixed them"); + go_on(&rig).unwrap(); + let run = snap(&rig); + assert_eq!((run.round, run.cap), (2, 2)); + assert_eq!(run.earlier_batches.len(), 1, "the first batch is kept"); + assert!(run.earlier_batches[0].commit.is_some()); + assert!(!answer(&rig, "s2", outcome(2, "both", 0, 0, &[]))); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Clean)); + assert!(run.suggestions_batch.is_none(), "no second batch"); + done(&rig); + } + + #[test] + fn discard_works_from_the_repositorys_top_when_the_project_is_a_folder_inside_it() { + if !harness_ready("subfolder") { + return; + } + let repo = scratch_repo("subfolder"); + std::fs::create_dir_all(repo.join("sub")).unwrap(); + std::fs::write(repo.join("sub/y.txt"), "y\n").unwrap(); + git_in(&repo, &["add", "-A"]); + git_in(&repo, &["commit", "-q", "-m", "add sub"]); + let head = git_in(&repo, &["rev-parse", "HEAD"]); + let mut run = ReviewRun::new( + repo.join("sub"), + ReviewSetup::default(), + fake_agent_launch(), + Mode::Commit, + Shape::OneSession, + Boundary::Commit(head), + repo.parent().unwrap().join("runs"), + BTreeMap::new(), + ); + run.running = false; + run.stop_reason = Some(StopReason::Person); + run.partial = Some(Partial { + pending: true, + new_files: vec!["sub/new.txt".to_string()], + ..Partial::default() + }); + let slot: ReviewSlot = Arc::new(Mutex::new(Some(run))); + std::fs::write(repo.join("sub/y.txt"), "changed\n").unwrap(); + std::fs::write(repo.join("a.txt"), "changed\n").unwrap(); + std::fs::write(repo.join("sub/new.txt"), "new\n").unwrap(); + partial(&slot, false).unwrap(); + assert_eq!( + std::fs::read_to_string(repo.join("sub/y.txt")).unwrap(), + "y\n" + ); + assert_eq!( + std::fs::read_to_string(repo.join("a.txt")).unwrap(), + "one\ntwo\n", + "a tracked file outside the project folder is put back too" + ); + assert!(!repo.join("sub/new.txt").exists()); + let _ = std::fs::remove_dir_all(repo.parent().unwrap()); + } + + // ------------------------------------------------------ Phase 6: the end + + /// A run's finished state with `rounds` committed rounds on a scratch repo, + /// stopped at the cap: the state sign-off starts from. + fn capped(name: &str, setup: ReviewSetup, rounds: u32) -> Option { + let rig = one_session(name, setup)?; + for n in 1..=rounds { + edit(&rig, &format!("f{n}.txt"), "x\n"); + let _ = answer(&rig, &format!("s{n}"), outcome(n, "both", 0, 1, &["Fix"])); + } + Some(rig) + } + + fn sign(rig: &Rig, picks: &[&str], squash: bool) -> Result<(), String> { + let picks: Vec = picks.iter().map(|p| p.to_string()).collect(); + sign_off( + &rig.rc.slot, + &rig.phases, + Arc::clone(&rig.rc.ctx.agent), + hooks_into(&rig.events), + Limits::default(), + rig.home.clone(), + &picks, + squash, + false, + ) + } + + #[test] + fn squashing_three_round_commits_makes_one_commit_and_keeps_the_commit_before_the_run() { + let Some(rig) = capped("squash-three", ReviewSetup::default(), 3) else { + return; + }; + let before = subjects(&rig.repo); + assert_eq!(before.len(), 4, "three rounds and the first commit"); + assert!(can_squash(&snap(&rig))); + sign(&rig, &[], true).expect("sign-off with no picks runs no agent"); + let run = snap(&rig); + assert!(run.signed_off); + match &run.signoff.as_ref().unwrap().squash { + Squash::Done { commits, commit } => { + assert_eq!(*commits, 3); + assert_eq!(commit.as_str(), git_in(&rig.repo, &["rev-parse", "HEAD"])); + } + other => panic!("expected a squash, got {other:?}"), + } + let after = subjects(&rig.repo); + assert_eq!( + after.len(), + 2, + "one squash commit on top of the first: {after:?}" + ); + assert!( + after[0].starts_with("Review Loop rounds 1 to 3"), + "{after:?}" + ); + assert_eq!(after[1], "first", "the commit before the run is untouched"); + for n in 1..=3 { + assert!(rig.repo.join(format!("f{n}.txt")).exists(), "f{n}.txt"); + } + assert_eq!( + git_in(&rig.repo, &["status", "--porcelain"]), + "", + "the tree is clean after the squash" + ); + done(&rig); + } + + #[test] + fn the_squash_never_includes_the_pre_run_commit() { + if !harness_ready("squash-pre") { + return; + } + let repo = scratch_repo("squash-pre"); + std::fs::write(repo.join("mine.txt"), "mine\n").unwrap(); + let setup = ReviewSetup { + pre_run_commit_agreed: true, + cap: 2, + ..ReviewSetup::default() + }; + let rig = rig_on(repo, setup, Shape::OneSession); + for n in 1..=2 { + edit(&rig, &format!("f{n}.txt"), "x\n"); + let _ = answer(&rig, &format!("s{n}"), outcome(n, "both", 0, 1, &["Fix"])); + } + assert_eq!(subjects(&rig.repo)[2], "Work before Review Loop"); + sign(&rig, &[], true).unwrap(); + let after = subjects(&rig.repo); + assert_eq!(after.len(), 3, "{after:?}"); + assert!( + after[0].starts_with("Review Loop rounds 1 to 2"), + "{after:?}" + ); + assert_eq!(after[1], "Work before Review Loop"); + done(&rig); + } + + #[test] + fn the_squash_refuses_when_a_commit_that_is_not_the_runs_sits_on_top() { + let Some(rig) = capped("squash-foreign", ReviewSetup::default(), 3) else { + return; + }; + std::fs::write(rig.repo.join("other.txt"), "other\n").unwrap(); + git_in(&rig.repo, &["add", "-A"]); + git_in(&rig.repo, &["commit", "-q", "-m", "somebody else"]); + let before = subjects(&rig.repo); + sign(&rig, &[], true).unwrap(); + let run = snap(&rig); + assert!(run.signed_off, "the sign-off still finishes"); + assert_eq!( + run.signoff.unwrap().squash, + Squash::Refused(FOREIGN_COMMIT.to_string()) + ); + assert_eq!(subjects(&rig.repo), before, "nothing was rewritten"); + done(&rig); + } + + #[test] + fn the_squash_switch_needs_commit_mode_and_two_round_commits() { + let Some(rig) = capped("squash-switch", ReviewSetup::default(), 1) else { + return; + }; + assert!(!can_squash(&snap(&rig)), "one round commit"); + done(&rig); + let snapshots = ReviewSetup { + commit: false, + ..ReviewSetup::default() + }; + let Some(rig) = capped("squash-snap", snapshots, 2) else { + return; + }; + assert!(!can_squash(&snap(&rig)), "snapshot mode makes no commits"); + done(&rig); + } + + #[test] + fn picked_suggestions_run_as_one_fixer_session_with_its_own_commit_and_a_fresh_check() { + let Some(rig) = one_session("sign-picks", ReviewSetup::default()) else { + return; + }; + assert!(!answer(&rig, "s1", with_suggestions(1, "both"))); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Clean)); + assert_eq!(run.collected.len(), 1); + let patch = end_patch_for(&run, false, "report"); + assert_eq!(patch["loopEnd"]["suggestions"][0]["id"], "s1"); + assert_eq!( + patch["loopEnd"]["suggestions"][0]["title"], + "Name the timer" + ); + assert!( + sign(&rig, &["s9"], false).is_err(), + "an unknown pick is refused" + ); + sign(&rig, &["s1"], false).expect("sign-off starts the fix"); + let run = snap(&rig); + assert!(run.signing && run.running); + assert_eq!((run.stage, run.round), (Stage::Batch, 2)); + assert_eq!(run.suggestions_batch.as_ref().unwrap().briefed.len(), 1); + edit(&rig, "t.txt", "named\n"); + assert!(answer( + &rig, + "b1", + outcome(2, "fixer", 0, 0, &["Name the timer"]) + )); + assert_eq!( + subjects(&rig.repo)[0], + "Review Loop Suggestions batch: Name the timer" + ); + assert!(!answer(&rig, "c1", outcome(3, "reviewer", 0, 0, &[]))); + let run = snap(&rig); + assert!(run.signed_off && !run.signing && !run.running); + assert_eq!( + run.stop_reason, + Some(StopReason::Clean), + "the reason is kept" + ); + let signoff = run.signoff.clone().unwrap(); + assert_eq!(signoff.picked.len(), 1); + assert!(signoff.left.is_empty()); + assert_eq!( + run.suggestions_batch.unwrap().final_check, + Some(Verdict::Clean) + ); + assert!( + sign(&rig, &[], false).is_err(), + "a second sign-off is refused" + ); + done(&rig); + } + + #[test] + fn a_signed_off_run_cannot_continue() { + let Some(rig) = capped("signed-continue", ReviewSetup::default(), 3) else { + return; + }; + sign(&rig, &[], false).unwrap(); + let err = go_on(&rig).unwrap_err(); + assert!(err.contains("signed off"), "{err}"); + done(&rig); + } + + fn spec_run(project: &Path, scope: ReviewScope, spec: Option<&str>) -> ReviewRun { + let setup = ReviewSetup { + scope, + spec: spec.map(str::to_string), + ..ReviewSetup::default() + }; + let mut run = ReviewRun::new( + project.to_path_buf(), + setup, + fake_agent_launch(), + Mode::Commit, + Shape::OneSession, + Boundary::Commit("0".repeat(40)), + PathBuf::new(), + BTreeMap::new(), + ); + run.stop_reason = Some(StopReason::Clean); + run.running = false; + run + } + + #[test] + fn the_report_goes_into_the_spec_folder_only_for_a_spec_launch() { + let base = + std::env::temp_dir().join(format!("plan2code-review-report-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("specs/demo")).unwrap(); + let spec = spec_run(&base, ReviewScope::Spec, Some("specs/demo")); + let first = write_spec_report(&spec, "# one").expect("a spec launch writes it"); + assert!(first.starts_with(base.join("specs/demo"))); + assert!(first + .file_name() + .unwrap() + .to_string_lossy() + .starts_with("REVIEW-LOOP-")); + // A rerun after sign-off replaces the same file. + let mut again = spec.clone(); + again.report_file = Some(first.clone()); + assert_eq!(write_spec_report(&again, "# two"), Some(first.clone())); + assert_eq!(std::fs::read_to_string(&first).unwrap(), "# two"); + // Another run the same day takes a new name. + let second = write_spec_report(&spec, "# three").unwrap(); + assert_ne!(second, first); + assert!(second.to_string_lossy().ends_with("-2.md")); + for scope in [ReviewScope::Branch, ReviewScope::Uncommitted] { + let run = spec_run(&base, scope, Some("specs/demo")); + assert_eq!(write_spec_report(&run, "# no"), None, "{scope:?}"); + } + let escaping = spec_run(&base, ReviewScope::Spec, Some("../elsewhere")); + assert_eq!(write_spec_report(&escaping, "# no"), None); + let _ = std::fs::remove_dir_all(&base); + } + + #[test] + fn the_report_list_gains_a_review_entry_and_old_entries_still_load() { + let base = + std::env::temp_dir().join(format!("plan2code-review-list-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + let project = base.join("project"); + std::fs::create_dir_all(&project).unwrap(); + let mut old = crate::loop_report::LoopReport::new("specs/old", "2026-11-01 09:00"); + old.entries.push(ReportEntry { + phase: 4, + name: "P4".into(), + ..ReportEntry::default() + }); + report_list::save_report(&base, &project, &old).unwrap(); + // A report written before the kind existed reads as an Implementation one. + let file = base.join(crate::loop_report::REPORTS_FILE); + let mut store: Value = + serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap(); + for report in store["reports"].as_object_mut().unwrap().values_mut() { + for entry in report["entries"].as_array_mut().unwrap() { + entry.as_object_mut().unwrap().remove("kind"); + entry.as_object_mut().unwrap().remove("rounds"); + } + } + std::fs::write(&file, store.to_string()).unwrap(); + let mut run = spec_run(&project, ReviewScope::Branch, None); + run.rounds.push(RoundRecord { + n: 1, + critical: 1, + commit: Some("a".repeat(40)), + ..RoundRecord::default() + }); + save_review_entry(&base, &run).unwrap(); + let loaded = report_list::load_reports(&base, &project, "specs/old").unwrap(); + assert_eq!(loaded.entries[0].kind, EntryKind::Implementation); + assert_eq!(loaded.entries[0].name, "P4"); + let mine = report_list::load_reports(&base, &project, &format!("review-loop:{}", run.id)) + .expect("the review run has its own key"); + assert_eq!(mine.entries[0].kind, EntryKind::Review); + assert_eq!(mine.entries[0].rounds.len(), 1); + assert_eq!(mine.entries[0].rounds[0].critical, 1); + let _ = std::fs::remove_dir_all(&base); + } + + #[test] + fn the_end_post_names_the_reason_the_report_continue_and_what_is_open() { + let base = + std::env::temp_dir().join(format!("plan2code-review-end-{}", std::process::id())); + let mut run = spec_run(&base, ReviewScope::Branch, None); + for (n, id) in [(1, "a"), (2, "b")] { + run.rounds.push(RoundRecord { + n, + commit: Some(id.repeat(40)), + unfixed: vec![finding("Missing check", "src/b.rs", Some(40))], + ..RoundRecord::default() + }); + } + run.cap = 2; + for (reason, key, can) in [ + (StopReason::Clean, "clean", false), + (StopReason::Cap, "cap", true), + (StopReason::Person, "person", true), + (StopReason::Failed("tests failed".into()), "failed", true), + ] { + run.stop_reason = Some(reason); + let patch = end_patch_for(&run, false, "# Report"); + let end = &patch["loopEnd"]; + assert_eq!(end["kind"], "review"); + assert_eq!(end["reason"], key); + assert_eq!(end["report"], REPORT_DOC); + assert_eq!(end["canContinue"], can, "{key}"); + assert_eq!(end["canSquash"], true); + assert_eq!(end["open"][0]["file"], "src/b.rs"); + assert_eq!(end["open"][0]["line"], 40); + assert!(end["line"].as_str().unwrap().chars().count() <= 200); + assert!(end.get("signedOff").is_none()); + assert_eq!(patch["docs"][0]["id"], REPORT_DOC); + } + run.rounds.clear(); + run.cap = 6; + run.stop_reason = Some(StopReason::Cap); + for n in 1..=6 { + run.rounds.push(RoundRecord { + n, + ..RoundRecord::default() + }); + } + assert!(!can_continue(&run), "never past six rounds"); + run.signed_off = true; + run.stop_reason = Some(StopReason::Person); + let patch = end_patch_for(&run, false, "# Report"); + assert_eq!(patch["loopEnd"]["signedOff"], true); + assert_eq!(patch["loopEnd"]["canContinue"], false); + } + + #[test] + fn partial_changes_ride_the_end_post_and_hide_continue() { + let mut run = spec_run(&std::env::temp_dir(), ReviewScope::Branch, None); + run.stop_reason = Some(StopReason::Person); + run.partial = Some(Partial { + pending: true, + files: 2, + added: 5, + removed: 1, + ..Partial::default() + }); + let patch = end_patch_for(&run, true, "# Report"); + assert_eq!(patch["loopEnd"]["partial"]["files"], 2); + assert_eq!(patch["loopEnd"]["partial"]["diff"], PARTIAL_DOC); + assert_eq!(patch["docs"][1]["blocks"][0]["diff"], "partial.diff"); + assert_eq!(patch["loopEnd"]["canContinue"], false); + let without = end_patch_for(&run, false, "# Report"); + assert!(without["loopEnd"].get("partial").is_none()); + run.partial.as_mut().unwrap().pending = false; + assert!(end_patch_for(&run, true, "# Report")["loopEnd"] + .get("partial") + .is_none()); + assert!(can_continue(&run), "settled partial changes allow Continue"); + } + + #[test] + fn the_finished_screens_next_steps_build_their_prompts_from_the_open_findings() { + let mut run = spec_run(&std::env::temp_dir(), ReviewScope::Branch, None); + run.rounds.push(RoundRecord { + n: 1, + unfixed: vec![ + finding("Missing check", "src/b.rs", Some(40)), + finding("Wrong default", "src/c.rs", None), + ], + ..RoundRecord::default() + }); + let slot: ReviewSlot = Arc::new(Mutex::new(Some(run))); + assert_eq!( + next_prompt(&slot, "pr-prep").unwrap(), + "/plan2code-pr-prep --web" + ); + let brief = next_prompt(&slot, "quick-task").unwrap(); + assert!(brief.starts_with("/plan2code-quick-task --web "), "{brief}"); + assert!(brief.contains("1. Missing check (src/b.rs:40)"), "{brief}"); + assert!(brief.contains("2. Wrong default (src/c.rs)"), "{brief}"); + assert!(next_prompt(&slot, "other").is_err()); + lock(&slot).as_mut().unwrap().rounds[0].unfixed.clear(); + assert_eq!( + next_prompt(&slot, "quick-task").unwrap_err(), + "Nothing is left open." + ); + } + + #[test] + fn the_spec_report_needs_a_real_specs_folder_never_the_git_folder_or_src() { + let base = + std::env::temp_dir().join(format!("plan2code-review-spec-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + for folder in [".git", "src", "specs/nested/deep"] { + std::fs::create_dir_all(base.join(folder)).unwrap(); + } + for spec in [ + ".git", + "src", + "specs/nested/deep", + "specs/.hidden", + "specs/missing", + ] { + let run = spec_run(&base, ReviewScope::Spec, Some(spec)); + assert_eq!(write_spec_report(&run, "# no"), None, "{spec}"); + } + assert!( + !base.join(".git").join("REVIEW-LOOP.md").exists() + && std::fs::read_dir(base.join("src")) + .unwrap() + .next() + .is_none() + ); + let _ = std::fs::remove_dir_all(&base); + } + + #[test] + fn a_spec_scope_run_refuses_a_folder_that_is_not_a_spec() { + let repo = scratch_repo("not-a-spec"); + let launch = fake_agent_launch(); + let setup = ReviewSetup { + scope: ReviewScope::Spec, + spec: Some("src".to_string()), + ..ReviewSetup::default() + }; + let err = prepare_run(&repo, &launch, setup, &repo.join("home")) + .map(|_| ()) + .unwrap_err(); + assert!(err.contains("not a spec folder"), "{err}"); + let _ = std::fs::remove_dir_all(repo.parent().unwrap()); + } + + /// A finished spec-scope run on a scratch repo whose spec folder is + /// committed, so only the report is new in it. + fn spec_capped(name: &str) -> Option { + if !harness_ready(name) { + return None; + } + let repo = scratch_repo(name); + std::fs::create_dir_all(repo.join("specs/demo")).unwrap(); + std::fs::write(repo.join("specs/demo/overview.md"), "# demo\n").unwrap(); + git_in(&repo, &["add", "-A"]); + git_in(&repo, &["commit", "-q", "-m", "spec"]); + let setup = ReviewSetup { + scope: ReviewScope::Spec, + spec: Some("specs/demo".to_string()), + cap: 2, + ..ReviewSetup::default() + }; + let rig = rig_on(repo, setup, Shape::OneSession); + with_run(&rig.rc, |run| run.last_sid = Some("sx".to_string())); + for n in 1..=2 { + edit(&rig, &format!("f{n}.txt"), "x\n"); + let _ = answer(&rig, &format!("s{n}"), outcome(n, "both", 0, 1, &["Fix"])); + } + Some(rig) + } + + fn spec_reports(rig: &Rig) -> Vec { + std::fs::read_dir(rig.repo.join("specs/demo")) + .unwrap() + .flatten() + .map(|e| e.path()) + .filter(|p| { + p.file_name() + .unwrap() + .to_string_lossy() + .starts_with("REVIEW-LOOP-") + }) + .collect() + } + + #[test] + fn the_end_saves_a_report_entry_and_the_spec_file_and_sign_off_rewrites_both() { + let Some(rig) = spec_capped("end-files") else { + return; + }; + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Cap)); + let kept = + report_list::load_reports(&rig.home, &run.project, &format!("review-loop:{}", run.id)) + .expect("the end saved a review entry"); + assert_eq!(kept.entries[0].kind, EntryKind::Review); + assert_eq!(kept.entries[0].rounds.len(), 2); + let files = spec_reports(&rig); + assert_eq!(files.len(), 1, "{files:?}"); + let first = std::fs::read_to_string(&files[0]).unwrap(); + assert!( + first.starts_with("# Review Loop: Stopped at the round cap"), + "{first}" + ); + assert!(!first.contains("## Sign-off"), "{first}"); + sign(&rig, &[], false).unwrap(); + let files = spec_reports(&rig); + assert_eq!(files.len(), 1, "sign-off rewrites the same file: {files:?}"); + let after = std::fs::read_to_string(&files[0]).unwrap(); + assert!(after.contains("## Sign-off"), "{after}"); + assert!(after.contains("not asked for"), "{after}"); + done(&rig); + } + + #[test] + fn a_picked_fix_never_commits_the_stale_spec_report() { + let Some(rig) = spec_capped("stale-report") else { + return; + }; + with_run(&rig.rc, |run| { + run.collected = vec![finding("Name the timer", "a.txt", None)]; + }); + assert_eq!(spec_reports(&rig).len(), 1); + sign(&rig, &["s1"], false).expect("sign-off starts the fix"); + assert!( + spec_reports(&rig).is_empty(), + "the stale report is out of the way before the fixer commits" + ); + edit(&rig, "t.txt", "named\n"); + assert!(answer( + &rig, + "b1", + outcome(3, "fixer", 0, 0, &["Name the timer"]) + )); + let committed = git_in(&rig.repo, &["show", "--name-only", "--format=", "HEAD"]); + assert!(!committed.contains("REVIEW-LOOP"), "{committed}"); + assert!(!answer(&rig, "c1", outcome(4, "reviewer", 0, 0, &[]))); + let run = snap(&rig); + assert!(run.signed_off); + assert_eq!( + spec_reports(&rig).len(), + 1, + "a fresh report is written after sign-off" + ); + done(&rig); + } + + #[test] + fn sign_off_after_a_stop_by_the_person_still_completes_and_keeps_that_reason() { + let Some(rig) = one_session("sign-person", ReviewSetup::default()) else { + return; + }; + request_stop_after(&rig.rc.slot, true).unwrap(); + let mut found = outcome(1, "both", 0, 1, &["Fix"]); + found["review"]["suggestion"] = json!(1); + found["review"]["suggestions"] = json!([{ "title": "Name the timer", "file": "a.txt" }]); + edit(&rig, "b.txt", "x\n"); + assert!(!answer(&rig, "s1", found)); + let run = snap(&rig); + assert_eq!(run.stop_reason, Some(StopReason::Person)); + assert_eq!(run.collected.len(), 1); + sign(&rig, &["s1"], false).expect("sign-off starts the fix"); + edit(&rig, "t.txt", "named\n"); + assert!(answer( + &rig, + "b1", + outcome(2, "fixer", 0, 0, &["Name the timer"]) + )); + assert!(!answer(&rig, "c1", outcome(3, "reviewer", 0, 0, &[]))); + let run = snap(&rig); + assert!(run.signed_off, "the sign-off finished"); + assert_eq!( + run.stop_reason, + Some(StopReason::Person), + "the reason is kept" + ); + assert_eq!(run.signoff.unwrap().problem, None); + done(&rig); + } + + #[test] + fn a_failed_round_is_named_even_after_a_sign_off_moves_the_round_on() { + let mut run = spec_run(&std::env::temp_dir(), ReviewScope::Branch, None); + run.stop_reason = Some(StopReason::Failed("tests failed".to_string())); + run.stop_round = 2; + run.round = 5; + assert_eq!(end_line(&run), "Failed in round 2: tests failed."); + } +} diff --git a/plan2code-app/src-tauri/src/review_report.rs b/plan2code-app/src-tauri/src/review_report.rs new file mode 100644 index 0000000..b7e38e2 --- /dev/null +++ b/plan2code-app/src-tauri/src/review_report.rs @@ -0,0 +1,522 @@ +//! The Review Loop's end report: one markdown page that says why the run +//! stopped and what every round found, fixed, committed and tested. Pure, like +//! `loop_driver::summary_markdown()`: the driver hands it the run record and +//! writes the text where it goes (the page, the report list and, for a spec +//! launch, the spec folder). + +use crate::review_loop::{BatchRecord, Mode, ReviewRun, ReviewScope, RoundRecord, Shape, Squash}; +use crate::round_logic::{Finding, StopReason, Verdict}; + +/// The stop reason in the words the report and the end screen lead with. +pub fn reason_words(reason: Option<&StopReason>) -> &'static str { + match reason { + Some(StopReason::Clean) => "Clean", + Some(StopReason::Cap) => "Stopped at the round cap", + Some(StopReason::Person) => "Stopped by you", + Some(StopReason::Failed(_)) => "Failed", + None => "Not finished", + } +} + +/// A commit id as people read it: the first seven characters. +pub fn short_id(id: &str) -> &str { + id.get(..7).unwrap_or(id) +} + +/// `title (file:line)`, leaving out what a finding does not name. +pub fn finding_text(finding: &Finding) -> String { + let title = one_line(&finding.title); + match (finding.file.is_empty(), finding.line) { + (true, _) => title, + (false, None) => format!("{title} (`{}`)", finding.file), + (false, Some(line)) => format!("{title} (`{}:{line}`)", finding.file), + } +} + +fn one_line(text: &str) -> String { + text.split_whitespace().collect::>().join(" ") +} + +fn plural(n: usize, one: &str, many: &str) -> String { + if n == 1 { + format!("1 {one}") + } else { + format!("{n} {many}") + } +} + +fn scope_words(run: &ReviewRun) -> String { + match (run.scope, run.setup.spec.as_deref()) { + (ReviewScope::Spec, Some(spec)) => format!("the spec {spec}"), + (ReviewScope::Spec, None) => "a spec".to_string(), + (ReviewScope::Branch, _) => "the branch against its base".to_string(), + (ReviewScope::Uncommitted, _) => "the uncommitted changes".to_string(), + } +} + +fn verdict_words(verdict: Option<&Verdict>, critical: u32, warning: u32) -> String { + match verdict { + Some(Verdict::Clean) => "clean".to_string(), + Some(Verdict::Findings { .. }) => format!("{critical} Critical, {warning} Warning"), + Some(Verdict::Failed(reason)) => format!("did not finish ({})", one_line(reason)), + None => "not checked".to_string(), + } +} + +fn strength_words(round: &RoundRecord) -> String { + let word = match round.strength.as_deref() { + Some(word) if !word.is_empty() => word.to_string(), + _ => "as launched".to_string(), + }; + let model = match (round.model.as_deref(), round.effort.as_deref()) { + (Some(model), Some(effort)) => Some(format!("{model}, {effort}")), + (Some(model), None) => Some(model.to_string()), + _ => None, + }; + match model { + Some(model) => format!("{word} ({model})"), + None => word, + } +} + +fn tests_words(round: &RoundRecord) -> String { + match &round.tests { + None => "not reported".to_string(), + Some(t) => { + let result = if !t.ran { + "did not run" + } else if t.passed { + "passed" + } else { + "failed" + }; + let summary = one_line(&t.summary); + if summary.is_empty() { + result.to_string() + } else { + format!("{summary} ({result})") + } + } + } +} + +fn commit_words(round_commit: Option<&str>, mode: Mode) -> String { + match (round_commit, mode) { + (Some(id), _) => format!("`{}`", short_id(id)), + (None, Mode::Snapshot) => "not committed (snapshot mode)".to_string(), + (None, Mode::Commit) => "not committed (nothing changed)".to_string(), + } +} + +fn round_section(md: &mut String, round: &RoundRecord, mode: Mode) { + md.push_str(&format!("\n## Round {}\n\n", round.n)); + md.push_str(&format!( + "- Found: {} Critical, {} Warning, {} Suggestion ({})\n", + round.critical, + round.warning, + round.suggestion, + verdict_words(round.verdict.as_ref(), round.critical, round.warning) + )); + if round.fixed.is_empty() { + md.push_str("- Fixed: nothing\n"); + } else { + let fixed: Vec = round.fixed.iter().map(finding_text).collect(); + md.push_str(&format!("- Fixed: {}\n", fixed.join("; "))); + } + if !round.unfixed.is_empty() { + let open: Vec = round.unfixed.iter().map(finding_text).collect(); + md.push_str(&format!("- Left open: {}\n", open.join("; "))); + } + md.push_str(&format!( + "- Commit: {}\n", + commit_words(round.commit.as_deref(), mode) + )); + md.push_str(&format!("- Targeted tests: {}\n", tests_words(round))); + let time = match (round.started_at.is_empty(), round.ended_at.is_empty()) { + (false, false) => format!("{} to {}", round.started_at, round.ended_at), + (false, true) => format!("started {}", round.started_at), + _ => "not recorded".to_string(), + }; + md.push_str(&format!("- Time: {time}\n")); + md.push_str(&format!("- Strength: {}\n", strength_words(round))); + if round.retried { + if round.could_not_step_up { + md.push_str( + "- Retry: one fresh session after a failure; it could not step up, so it ran at the same level\n", + ); + } else { + md.push_str("- Retry: one fresh session after a failure, one strength up\n"); + } + } + if !round.summary.trim().is_empty() { + md.push_str(&format!("- Summary: {}\n", one_line(&round.summary))); + } +} + +fn batch_section(md: &mut String, batch: &BatchRecord, mode: Mode, title: &str) { + md.push_str(&format!("\n## {title}\n\n")); + md.push_str(&format!( + "- Briefed with {}\n", + plural(batch.briefed.len(), "Suggestion", "Suggestions") + )); + md.push_str(&format!( + "- Commit: {}\n", + commit_words(batch.commit.as_deref(), mode) + )); + match &batch.final_check { + Some(verdict) => md.push_str(&format!( + "- Final check by a fresh reviewer: {}\n", + verdict_words(Some(verdict), batch.final_critical, batch.final_warning) + )), + None => md.push_str("- Final check by a fresh reviewer: not run\n"), + } + if !batch.summary.trim().is_empty() { + md.push_str(&format!("- Summary: {}\n", one_line(&batch.summary))); + } +} + +/// The whole report for `run`, as it stands: after a stop, and again after +/// sign-off with what was picked and whether the squash ran. +pub fn review_report_markdown(run: &ReviewRun) -> String { + let reason = run.stop_reason.as_ref(); + let mut md = format!("# Review Loop: {}\n\n", reason_words(reason)); + if let Some(StopReason::Failed(why)) = reason { + md.push_str(&format!("Why it failed: {}\n\n", one_line(why))); + } + let rounds_run = run.rounds.len(); + md.push_str(&format!( + "- Rounds run: {} of at most {}\n", + rounds_run, run.cap + )); + md.push_str(&format!("- Reviewed: {}\n", scope_words(run))); + md.push_str(&format!( + "- Mode: {}\n", + match run.mode { + Mode::Commit => "each round committed", + Mode::Snapshot => "snapshots only, nothing committed", + } + )); + md.push_str(&format!( + "- Shape: {}\n", + match run.shape { + Shape::OneSession => "one session per round, with a helper reviewing", + Shape::TwoSession => "two sessions per round, a reviewer and then a fixer", + } + )); + if let Some(id) = &run.pre_run_commit { + md.push_str(&format!( + "- Work before the run was committed first: `{}`\n", + short_id(id) + )); + } + if let Some(evidence) = run + .stop_evidence + .as_deref() + .filter(|e| !e.trim().is_empty()) + { + md.push_str(&format!("- Evidence: {}\n", one_line(evidence))); + } + + for round in &run.rounds { + round_section(&mut md, round, run.mode); + } + for batch in run + .earlier_batches + .iter() + .chain(run.suggestions_batch.iter()) + { + batch_section(&mut md, batch, run.mode, "Suggestions batch"); + } + + md.push_str("\n## Still open\n\n"); + let open = run.open_findings(); + if open.is_empty() { + md.push_str("No Critical or Warning findings are open.\n"); + } else { + md.push_str("Critical or Warning findings no round fixed:\n\n"); + for finding in &open { + md.push_str(&format!("- {}\n", finding_text(finding))); + } + } + + md.push_str("\n## Suggestions\n\n"); + match &run.signoff { + Some(signoff) => { + if signoff.picked.is_empty() { + md.push_str("Nothing was picked at sign-off.\n"); + } else { + md.push_str("Picked at sign-off:\n\n"); + for finding in &signoff.picked { + md.push_str(&format!("- {}\n", finding_text(finding))); + } + } + if let Some(problem) = &signoff.problem { + md.push_str(&format!("\nNot all were fixed: {}\n", one_line(problem))); + } + if !signoff.left.is_empty() { + md.push_str("\nLeft alone:\n\n"); + for finding in &signoff.left { + md.push_str(&format!("- {}\n", finding_text(finding))); + } + } + } + None => { + let applied = run + .earlier_batches + .iter() + .chain(run.suggestions_batch.iter()); + let applied_count: usize = applied.map(|batch| batch.briefed.len()).sum(); + if applied_count > 0 { + md.push_str(&format!( + "{} fixed in the batch above, with its final check.\n", + plural(applied_count, "Suggestion was", "Suggestions were") + )); + } + if run.collected.is_empty() { + if applied_count == 0 { + md.push_str("No Suggestions were collected.\n"); + } + } else { + md.push_str("Waiting for you to pick at sign-off:\n\n"); + for finding in &run.collected { + md.push_str(&format!("- {}\n", finding_text(finding))); + } + } + } + } + + if let Some(signoff) = &run.signoff { + md.push_str("\n## Sign-off\n\n"); + let squash = match (&signoff.squash, signoff.squash_asked) { + (Squash::Done { commit, commits }, _) => format!( + "squashed {} into `{}`", + plural(*commits, "commit", "commits"), + short_id(commit) + ), + (Squash::Refused(why), _) => format!("not squashed: {}", one_line(why)), + (Squash::Off, _) => "not asked for".to_string(), + }; + md.push_str(&format!("- Squash of the round commits: {squash}\n")); + } + + if let Some(partial) = run.partial.as_ref().filter(|p| p.pending) { + md.push_str(&format!( + "\n## Partial changes\n\nStop now left {} changed (+{} -{}) that are not committed, waiting for Keep or Discard.\n", + plural(partial.files as usize, "file", "files"), + partial.added, + partial.removed + )); + } + md +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::loop_driver::tests::fake_agent_launch; + use crate::review_loop::{ReviewSetup, SignOff}; + use crate::round_boundary::Boundary; + use crate::round_logic::RoundTests; + use std::collections::BTreeMap; + use std::path::PathBuf; + + fn run_with(reason: Option) -> ReviewRun { + let mut run = ReviewRun::new( + PathBuf::from("."), + ReviewSetup::default(), + fake_agent_launch(), + Mode::Commit, + Shape::OneSession, + Boundary::Commit("0000000000000000000000000000000000000000".to_string()), + PathBuf::new(), + BTreeMap::new(), + ); + run.stop_reason = reason; + run.running = false; + run + } + + fn finding(title: &str, file: &str, line: Option) -> Finding { + Finding { + title: title.to_string(), + file: file.to_string(), + line, + } + } + + fn round(n: u32, critical: u32, warning: u32) -> RoundRecord { + RoundRecord { + n, + critical, + warning, + suggestion: 1, + verdict: Some(if critical + warning == 0 { + Verdict::Clean + } else { + Verdict::Findings { critical, warning } + }), + commit: Some("1234567890abcdef".to_string()), + started_at: "2026-11-28 10:00".to_string(), + ended_at: "2026-11-28 10:09".to_string(), + tests: Some(RoundTests { + ran: true, + passed: true, + summary: "14 pass".to_string(), + }), + ..RoundRecord::default() + } + } + + #[test] + fn every_stop_reason_leads_the_report_in_words() { + let cases = [ + (Some(StopReason::Clean), "# Review Loop: Clean"), + ( + Some(StopReason::Cap), + "# Review Loop: Stopped at the round cap", + ), + (Some(StopReason::Person), "# Review Loop: Stopped by you"), + ( + Some(StopReason::Failed("tests failed".to_string())), + "# Review Loop: Failed", + ), + ]; + for (reason, heading) in cases { + let md = review_report_markdown(&run_with(reason)); + assert!(md.starts_with(heading), "{md}"); + } + let failed = review_report_markdown(&run_with(Some(StopReason::Failed( + "tests failed".to_string(), + )))); + assert!(failed.contains("Why it failed: tests failed"), "{failed}"); + let clean = review_report_markdown(&run_with(Some(StopReason::Clean))); + assert!(clean.contains("Rounds run: 0 of at most 3"), "{clean}"); + } + + #[test] + fn a_round_says_its_findings_fixes_commit_tests_time_and_strength() { + let mut run = run_with(Some(StopReason::Cap)); + let mut first = round(1, 2, 1); + first.fixed = vec![finding("Close the handle", "src/a.rs", Some(12))]; + first.strength = Some("Balanced".to_string()); + first.model = Some("sonnet".to_string()); + first.effort = Some("low".to_string()); + run.rounds.push(first); + let md = review_report_markdown(&run); + assert!(md.contains("## Round 1"), "{md}"); + assert!( + md.contains("Found: 2 Critical, 1 Warning, 1 Suggestion"), + "{md}" + ); + assert!( + md.contains("Fixed: Close the handle (`src/a.rs:12`)"), + "{md}" + ); + assert!(md.contains("Commit: `1234567`"), "{md}"); + assert!(md.contains("Targeted tests: 14 pass (passed)"), "{md}"); + assert!( + md.contains("Time: 2026-11-28 10:00 to 2026-11-28 10:09"), + "{md}" + ); + assert!(md.contains("Strength: Balanced (sonnet, low)"), "{md}"); + } + + #[test] + fn an_agent_without_strengths_reads_as_launched_and_a_same_level_retry_says_so() { + let mut run = run_with(Some(StopReason::Cap)); + let mut r = round(1, 1, 0); + r.retried = true; + r.could_not_step_up = true; + run.rounds.push(r); + let md = review_report_markdown(&run); + assert!(md.contains("Strength: as launched"), "{md}"); + assert!( + md.contains("it could not step up, so it ran at the same level"), + "{md}" + ); + let mut stepped = run_with(Some(StopReason::Cap)); + let mut r = round(1, 1, 0); + r.retried = true; + r.strength = Some("Best".to_string()); + stepped.rounds.push(r); + let md = review_report_markdown(&stepped); + assert!(md.contains("one strength up"), "{md}"); + assert!(!md.contains("could not step up"), "{md}"); + } + + #[test] + fn open_findings_show_their_file_and_line_and_a_clean_run_has_none() { + let mut run = run_with(Some(StopReason::Cap)); + let mut last = round(2, 1, 1); + last.unfixed = vec![ + finding("Missing check", "src/b.rs", Some(40)), + finding("Wrong default", "src/c.rs", None), + ]; + run.rounds.push(last); + let md = review_report_markdown(&run); + assert!(md.contains("- Missing check (`src/b.rs:40`)"), "{md}"); + assert!(md.contains("- Wrong default (`src/c.rs`)"), "{md}"); + let mut clean = run_with(Some(StopReason::Clean)); + clean.rounds.push(round(1, 0, 0)); + let md = review_report_markdown(&clean); + assert!( + md.contains("No Critical or Warning findings are open."), + "{md}" + ); + } + + #[test] + fn suggestions_are_listed_to_pick_or_reported_as_applied_with_the_final_check() { + let mut waiting = run_with(Some(StopReason::Clean)); + waiting.collected = vec![finding("Name the timer", "src/d.rs", Some(3))]; + let md = review_report_markdown(&waiting); + assert!(md.contains("Waiting for you to pick at sign-off"), "{md}"); + assert!(md.contains("- Name the timer (`src/d.rs:3`)"), "{md}"); + + let mut applied = run_with(Some(StopReason::Clean)); + applied.suggestions_batch = Some(BatchRecord { + briefed: vec![finding("Name the timer", "src/d.rs", None)], + commit: Some("abcdef0123456789".to_string()), + final_check: Some(Verdict::Clean), + ..BatchRecord::default() + }); + let md = review_report_markdown(&applied); + assert!( + md.contains("1 Suggestion was fixed in the batch above"), + "{md}" + ); + assert!( + md.contains("Final check by a fresh reviewer: clean"), + "{md}" + ); + assert!(md.contains("Commit: `abcdef0`"), "{md}"); + } + + #[test] + fn the_sign_off_records_the_picks_and_whether_the_squash_ran_or_was_refused() { + let mut run = run_with(Some(StopReason::Cap)); + run.signoff = Some(SignOff { + picked: vec![finding("Name the timer", "src/d.rs", None)], + left: vec![finding("Tidy import", "src/e.rs", None)], + squash_asked: true, + squash: Squash::Done { + commit: "fedcba9876543210".to_string(), + commits: 3, + }, + problem: None, + }); + let md = review_report_markdown(&run); + assert!(md.contains("Picked at sign-off"), "{md}"); + assert!(md.contains("Left alone"), "{md}"); + assert!(md.contains("squashed 3 commits into `fedcba9`"), "{md}"); + run.signoff.as_mut().unwrap().squash = Squash::Refused( + "Something else was committed during the run, so the rounds were not squashed." + .to_string(), + ); + let md = review_report_markdown(&run); + assert!( + md.contains("not squashed: Something else was committed"), + "{md}" + ); + } +} diff --git a/plan2code-app/src-tauri/src/round_boundary.rs b/plan2code-app/src-tauri/src/round_boundary.rs new file mode 100644 index 0000000..14c24df --- /dev/null +++ b/plan2code-app/src-tauri/src/round_boundary.rs @@ -0,0 +1,400 @@ +//! Where a Review Loop round starts and ends: a full commit id (commit mode) or +//! a tree id from a snapshot of the working tree (snapshot mode), and the diff +//! between any two of them. A snapshot never touches the real index, `HEAD` or +//! the working tree: it adds everything to a copy of the index and writes a tree +//! from that copy, the same technique as `snapshotTree` in `changes.mjs`. + +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use crate::loop_tools; + +/// A point in the project's history a round can be measured from. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Boundary { + /// A full commit id. + Commit(String), + /// A tree id written from a snapshot of the working tree. + Tree(String), +} + +impl Boundary { + /// The object id, whichever kind it is. + pub fn id(&self) -> &str { + match self { + Boundary::Commit(id) | Boundary::Tree(id) => id, + } + } + + fn peel(&self) -> String { + match self { + Boundary::Commit(id) => format!("{id}^{{commit}}"), + Boundary::Tree(id) => format!("{id}^{{tree}}"), + } + } +} + +/// What a diff between two boundaries changed. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct DiffStats { + pub files: u32, + pub added: u32, + pub removed: u32, +} + +fn git(project: &Path, args: &[&str]) -> Command { + let mut cmd = Command::new("git"); + cmd.args(args).current_dir(project); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW + } + cmd +} + +/// The first line git said on stderr, or `fallback`. +fn why(stderr: &[u8], fallback: &str) -> String { + String::from_utf8_lossy(stderr) + .lines() + .map(str::trim) + .find(|line| !line.is_empty()) + .map(str::to_string) + .unwrap_or_else(|| fallback.to_string()) +} + +/// A hex object id (git's full ids are 40 or 64 characters). +fn is_object_id(id: &str) -> bool { + matches!(id.len(), 40 | 64) && id.chars().all(|c| c.is_ascii_hexdigit()) +} + +/// The boundary at `HEAD`, as a full commit id. +pub fn head(project: &Path) -> Result { + loop_tools::git_head_full(project).map(Boundary::Commit) +} + +/// Deletes the copied index on every path out of `snapshot`. +struct TempIndex(PathBuf); + +impl Drop for TempIndex { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + +static SNAPSHOTS: AtomicU64 = AtomicU64::new(0); + +/// Snapshot the working tree (tracked, changed and untracked, ignored files +/// left out) as a tree id, without touching the real index, `HEAD` or any file. +pub fn snapshot(project: &Path) -> Result { + let located = git(project, &["rev-parse", "--git-path", "index"]) + .output() + .map_err(|err| format!("git could not run: {err}"))?; + if !located.status.success() { + return Err(format!( + "git could not find the index: {}", + why(&located.stderr, "not a git repository") + )); + } + let real = String::from_utf8_lossy(&located.stdout).trim().to_string(); + let temp = TempIndex(std::env::temp_dir().join(format!( + "plan2code-round-index-{}-{}", + std::process::id(), + SNAPSHOTS.fetch_add(1, Ordering::Relaxed) + ))); + if !real.is_empty() { + let source = project.join(&real); + if source.is_file() { + std::fs::copy(&source, &temp.0) + .map_err(|err| format!("could not copy the index: {err}"))?; + } + } + let run = |args: &[&str]| { + git(project, args) + .env("GIT_INDEX_FILE", &temp.0) + .output() + .map_err(|err| format!("git could not run: {err}")) + }; + let added = run(&["add", "-A"])?; + if !added.status.success() { + return Err(format!( + "git could not snapshot the working tree: {}", + why(&added.stderr, "git add failed") + )); + } + let written = run(&["write-tree"])?; + let tree = String::from_utf8_lossy(&written.stdout).trim().to_string(); + if !written.status.success() || !is_object_id(&tree) { + return Err(format!( + "git could not write the snapshot: {}", + why(&written.stderr, "git write-tree failed") + )); + } + Ok(Boundary::Tree(tree)) +} + +/// Whether the boundary's object is still in the repository (git may collect +/// an unreferenced snapshot tree). +pub fn exists(project: &Path, b: &Boundary) -> bool { + if !is_object_id(b.id()) { + return false; + } + git(project, &["cat-file", "-e", &b.peel()]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .map(|status| status.success()) + .unwrap_or(false) +} + +/// Write the plain unified diff from `from` to `to` into `out`, and say how big +/// it is. A boundary gone from the repository is refused by name. +pub fn diff( + project: &Path, + from: &Boundary, + to: &Boundary, + out: &Path, +) -> Result { + for side in [from, to] { + if !exists(project, side) { + return Err(format!("round boundary missing: {}", side.id())); + } + } + // Fixed prefixes and no external driver: a user's diff settings must not + // change what the round agent reads. + let base = [ + "--no-color", + "--no-ext-diff", + "--src-prefix=a/", + "--dst-prefix=b/", + ]; + let file = std::fs::File::create(out) + .map_err(|err| format!("could not write {}: {err}", out.display()))?; + let patch = git(project, &["diff"]) + .args(base) + .arg(from.id()) + .arg(to.id()) + .stdout(Stdio::from(file)) + .stderr(Stdio::piped()) + .output() + .map_err(|err| { + let _ = std::fs::remove_file(out); + format!("git could not run: {err}") + })?; + if !patch.status.success() { + let _ = std::fs::remove_file(out); + return Err(format!( + "git diff failed: {}", + why(&patch.stderr, "no reason given") + )); + } + let numstat = git(project, &["diff", "--numstat", "--no-ext-diff"]) + .arg(from.id()) + .arg(to.id()) + .output() + .map_err(|err| { + let _ = std::fs::remove_file(out); + format!("git could not run: {err}") + })?; + if !numstat.status.success() { + let _ = std::fs::remove_file(out); + return Err(format!( + "git diff failed: {}", + why(&numstat.stderr, "no reason given") + )); + } + let mut stats = DiffStats::default(); + for line in String::from_utf8_lossy(&numstat.stdout).lines() { + let mut parts = line.split('\t'); + let (Some(added), Some(removed)) = (parts.next(), parts.next()) else { + continue; + }; + stats.files += 1; + // A binary file shows `-` for both. + stats.added += added.parse::().unwrap_or(0); + stats.removed += removed.parse::().unwrap_or(0); + } + Ok(stats) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn git_in(repo: &Path, args: &[&str]) -> String { + let out = git(repo, args).output().expect("git runs"); + assert!( + out.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).to_string() + } + + /// A new repository in a unique temp folder with one commit, its config + /// scrubbed of anything global (no autocrlf, no hooks, no signing). + fn scratch(name: &str) -> PathBuf { + let repo = std::env::temp_dir() + .join(format!("plan2code-round-{name}-{}", std::process::id())) + .join("repo"); + let _ = std::fs::remove_dir_all(repo.parent().unwrap()); + std::fs::create_dir_all(&repo).unwrap(); + git_in(&repo, &["init", "-q"]); + for (key, value) in [ + ("user.name", "Round Test"), + ("user.email", "round@example.com"), + ("commit.gpgsign", "false"), + ("core.autocrlf", "false"), + ("core.hooksPath", ".git/hooks"), + ] { + git_in(&repo, &["config", key, value]); + } + std::fs::write(repo.join("a.txt"), "one\ntwo\n").unwrap(); + git_in(&repo, &["add", "-A"]); + git_in(&repo, &["commit", "-q", "-m", "first"]); + repo + } + + fn cleanup(repo: &Path) { + let _ = std::fs::remove_dir_all(repo.parent().unwrap()); + } + + #[test] + fn head_is_a_full_commit_id() { + let repo = scratch("head"); + let boundary = head(&repo).unwrap(); + assert!(matches!(&boundary, Boundary::Commit(id) if is_object_id(id))); + assert!(exists(&repo, &boundary)); + cleanup(&repo); + } + + #[test] + fn a_snapshot_leaves_status_and_the_index_unchanged() { + let repo = scratch("untouched"); + std::fs::write(repo.join("a.txt"), "one\ntwo\nthree\n").unwrap(); + std::fs::write(repo.join("new.txt"), "new\n").unwrap(); + // Settle git's own stat refresh before measuring. + git_in(&repo, &["status", "--porcelain"]); + let index = repo.join(".git/index"); + let before = std::fs::read(&index).unwrap(); + let head_before = git_in(&repo, &["rev-parse", "HEAD"]); + let first = snapshot(&repo).unwrap(); + let second = snapshot(&repo).unwrap(); + assert_eq!(first, second, "the same tree twice"); + assert_eq!(std::fs::read(&index).unwrap(), before, "index bytes"); + assert_eq!(git_in(&repo, &["rev-parse", "HEAD"]), head_before); + let status = git_in(&repo, &["status", "--porcelain"]); + assert!(status.contains(" M a.txt"), "{status}"); + assert!(status.contains("?? new.txt"), "still untracked: {status}"); + assert_eq!( + std::fs::read_to_string(repo.join("new.txt")).unwrap(), + "new\n" + ); + cleanup(&repo); + } + + #[test] + fn an_untracked_file_shows_in_the_next_snapshots_diff() { + let repo = scratch("untracked"); + let one = snapshot(&repo).unwrap(); + std::fs::write(repo.join("fresh.txt"), "a\nb\nc\n").unwrap(); + let two = snapshot(&repo).unwrap(); + assert_ne!(one, two); + let out = repo.parent().unwrap().join("round-1.diff"); + let stats = diff(&repo, &one, &two, &out).unwrap(); + let text = std::fs::read_to_string(&out).unwrap(); + assert!(text.contains("+++ b/fresh.txt"), "{text}"); + assert_eq!( + stats, + DiffStats { + files: 1, + added: 3, + removed: 0 + } + ); + cleanup(&repo); + } + + #[test] + fn a_diff_between_two_commits_equals_git_diff() { + let repo = scratch("commits"); + let a = head(&repo).unwrap(); + std::fs::write(repo.join("a.txt"), "one\nTWO\nthree\n").unwrap(); + git_in(&repo, &["add", "-A"]); + git_in(&repo, &["commit", "-q", "-m", "second"]); + let b = head(&repo).unwrap(); + let out = repo.parent().unwrap().join("between.diff"); + let stats = diff(&repo, &a, &b, &out).unwrap(); + let expected = git_in( + &repo, + &[ + "diff", + "--no-color", + "--no-ext-diff", + "--src-prefix=a/", + "--dst-prefix=b/", + a.id(), + b.id(), + ], + ); + assert_eq!(std::fs::read_to_string(&out).unwrap(), expected); + assert_eq!( + stats, + DiffStats { + files: 1, + added: 2, + removed: 1 + } + ); + cleanup(&repo); + } + + #[test] + fn a_commit_and_a_snapshot_can_be_diffed() { + let repo = scratch("mixed"); + let start = head(&repo).unwrap(); + std::fs::write(repo.join("a.txt"), "one\n").unwrap(); + let now = snapshot(&repo).unwrap(); + let out = repo.parent().unwrap().join("mixed.diff"); + let stats = diff(&repo, &start, &now, &out).unwrap(); + assert_eq!(stats.removed, 1); + cleanup(&repo); + } + + #[test] + fn a_made_up_id_does_not_exist_and_the_diff_refuses_it() { + let repo = scratch("missing"); + let real = head(&repo).unwrap(); + let ghost = Boundary::Tree("0123456789abcdef0123456789abcdef01234567".to_string()); + assert!(!exists(&repo, &ghost)); + assert!(!exists(&repo, &Boundary::Commit("--output=x".to_string()))); + let out = repo.parent().unwrap().join("ghost.diff"); + let err = diff(&repo, &real, &ghost, &out).unwrap_err(); + assert_eq!( + err, + "round boundary missing: 0123456789abcdef0123456789abcdef01234567" + ); + // Either side is checked. + assert!(diff(&repo, &ghost, &real, &out).is_err()); + assert!(!out.exists(), "nothing written for a refused diff"); + cleanup(&repo); + } + + #[test] + fn a_snapshot_outside_a_repository_fails_with_a_reason() { + let dir = std::env::temp_dir().join(format!("plan2code-round-none-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + // A `.git` file naming a gitdir that is not there: git stops here + // whatever repository sits above the temp folder. + std::fs::write( + dir.join(".git"), + "gitdir: /plan2code-no-such-gitdir +", + ) + .unwrap(); + let err = snapshot(&dir).unwrap_err(); + assert!(err.starts_with("git could not"), "{err}"); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/plan2code-app/src-tauri/src/round_logic.rs b/plan2code-app/src-tauri/src/round_logic.rs new file mode 100644 index 0000000..8b75bba --- /dev/null +++ b/plan2code-app/src-tauri/src/round_logic.rs @@ -0,0 +1,675 @@ +//! The Review Loop's round rules, with no agent, git, file or clock in them: +//! judging a round, picking the next step, and the wording of a round's commit +//! subject and banner detail. The driver passes everything in. + +use serde::Deserialize; + +/// The most rounds a run may ever reach, Continue included. +pub const MAX_ROUNDS: u32 = 6; + +/// The longest commit subject a round writes, in characters. +const SUBJECT_LIMIT: usize = 72; + +/// Which part of a round a session plays. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Role { + Both, + Reviewer, + Fixer, +} + +/// One finding in a round's report. +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)] +pub struct Finding { + #[serde(default)] + pub title: String, + #[serde(default)] + pub file: String, + #[serde(default)] + pub line: Option, +} + +/// The counts and lists a round reports. +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)] +pub struct RoundReview { + #[serde(default)] + pub critical: u32, + #[serde(default)] + pub warning: u32, + #[serde(default)] + pub suggestion: u32, + #[serde(default)] + pub fixed: Vec, + #[serde(default)] + pub unfixed: Vec, + #[serde(default)] + pub suggestions: Vec, +} + +/// The tests a round ran. +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)] +pub struct RoundTests { + #[serde(default)] + pub ran: bool, + #[serde(default)] + pub passed: bool, + #[serde(default)] + pub summary: String, +} + +/// A round session's `roundOutcome`, as the console validated it. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +pub struct RoundOutcome { + pub round: u32, + pub role: Role, + /// `passed` or `failed`. + pub result: String, + #[serde(default)] + pub reason: Option, + #[serde(default)] + pub summary: String, + /// Id of the report doc in the session. + #[serde(default)] + pub report: Option, + #[serde(default)] + pub review: RoundReview, + #[serde(default)] + pub tests: Option, + #[serde(default)] + pub subject: Option, +} + +/// What the app checked for itself, so a report cannot vouch for its own work. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RoundProofs { + pub report_doc_present: bool, + pub tests_ran: bool, + pub tests_passed: bool, +} + +/// How a round came out. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Verdict { + Clean, + Findings { critical: u32, warning: u32 }, + Failed(String), +} + +/// Judge a round from its report and the app's own proofs. Suggestions never +/// change the verdict. +pub fn judge_round(outcome: &RoundOutcome, proofs: &RoundProofs) -> Verdict { + if outcome.result == "failed" { + let reason = outcome + .reason + .as_deref() + .filter(|reason| !reason.is_empty()) + .unwrap_or("other"); + return Verdict::Failed(reason.to_string()); + } + if !proofs.report_doc_present { + return Verdict::Failed("no reviewer report in the session".to_string()); + } + if !proofs.tests_ran { + return Verdict::Failed("targeted tests did not run".to_string()); + } + if !proofs.tests_passed { + return Verdict::Failed("targeted tests failed".to_string()); + } + let (critical, warning) = (outcome.review.critical, outcome.review.warning); + if critical == 0 && warning == 0 { + Verdict::Clean + } else { + Verdict::Findings { critical, warning } + } +} + +/// A fixer's counts never vouch for its own fix: in the two-session shape the +/// round is judged on what the separate reviewer found, so a fixer that sends +/// lower counts than its reviewer cannot end the run as clean. +pub fn hold_reviewer_counts(review: &mut RoundReview, critical: u32, warning: u32) { + review.critical = review.critical.max(critical); + review.warning = review.warning.max(warning); +} + +/// Why a run stopped. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum StopReason { + Clean, + Cap, + Person, + Failed(String), +} + +/// What the run looks like when a round has just been judged. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RunView { + /// The round just judged. + pub round: u32, + pub cap: u32, + pub rounds_run: u32, + pub suggestions_on: bool, + pub suggestions_pending: bool, + /// The Suggestions batch round has run. + pub batch_done: bool, + pub retried_this_round: bool, + pub stop_after_round: bool, + pub stop_now: bool, +} + +/// What the driver does next. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Next { + StartRound(u32), + Retry, + SuggestionsBatch, + FinalCheck, + Stop(StopReason), +} + +/// Pick the next step after a round with `verdict`. +/// +/// Once the batch has run, its verdict leads to one `FinalCheck` (outside the +/// cap); the driver then ends the run with `after_final_check`, carrying the +/// reason the run was going to stop for. +pub fn next_step(run: &RunView, verdict: &Verdict) -> Next { + if run.stop_now { + return Next::Stop(StopReason::Person); + } + let batch_due = run.suggestions_on && run.suggestions_pending && !run.batch_done; + match verdict { + Verdict::Failed(reason) => { + if run.retried_this_round { + Next::Stop(StopReason::Failed(reason.clone())) + } else { + Next::Retry + } + } + _ if run.batch_done => Next::FinalCheck, + Verdict::Clean => { + // A stop after this round means no more work, the batch included. + if batch_due && !run.stop_after_round { + Next::SuggestionsBatch + } else { + Next::Stop(StopReason::Clean) + } + } + Verdict::Findings { .. } => { + if run.stop_after_round { + Next::Stop(StopReason::Person) + } else if run.round >= run.cap.min(MAX_ROUNDS) { + if batch_due { + Next::SuggestionsBatch + } else { + Next::Stop(StopReason::Cap) + } + } else { + Next::StartRound(run.round + 1) + } + } + } +} + +/// The step after the final check, whatever its verdict: the run ends for the +/// reason it was already ending for (FR-19). +pub fn after_final_check(original: StopReason) -> Next { + Next::Stop(original) +} + +/// The cap Continue may use after a run stopped at its cap: one more round, +/// and never above `MAX_ROUNDS`. +pub fn continue_cap(cap: u32, rounds_run: u32) -> Option { + if rounds_run < cap { + return None; + } + let next = rounds_run + 1; + (next <= MAX_ROUNDS).then_some(next) +} + +/// The subject of a round's commit: the fix titles after the round number, +/// trailing titles dropped for "and N more" to stay within 72 characters. +pub fn round_commit_message(round: u32, titles: &[String]) -> String { + let prefix = format!("Review Loop round {round}"); + let titles: Vec<&str> = titles + .iter() + .map(|title| title.trim()) + .filter(|title| !title.is_empty()) + .collect(); + if titles.is_empty() { + return prefix; + } + let total = titles.len(); + for kept in (1..=total).rev() { + let mut body = titles[..kept].join(", "); + if kept < total { + body.push_str(&format!(" and {} more", total - kept)); + } + let subject = format!("{prefix}: {body}"); + if subject.chars().count() <= SUBJECT_LIMIT { + return subject; + } + } + // Even one title is too long: cut it. + let subject = format!("{prefix}: {}", titles[0]); + let mut cut: String = subject.chars().take(SUBJECT_LIMIT - 3).collect(); + cut = cut.trim_end().to_string(); + cut.push_str("..."); + cut +} + +/// The banner's detail line for a round, such as +/// "Round 2 of 3: Fixing 3 findings (1 Critical, 2 Warning)". +pub fn round_detail(round: u32, cap: u32, step: &str, critical: u32, warning: u32) -> String { + let head = format!("Round {round} of {cap}: {step}"); + let total = critical + warning; + if total == 0 { + return head; + } + let mut parts = Vec::new(); + if critical > 0 { + parts.push(format!("{critical} Critical")); + } + if warning > 0 { + parts.push(format!("{warning} Warning")); + } + let noun = if total == 1 { "finding" } else { "findings" }; + format!("{head} {total} {noun} ({})", parts.join(", ")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_fixer_reporting_zero_is_judged_on_its_reviewers_counts() { + let mut fixer = outcome(0, 0, 0); + fixer.role = Role::Fixer; + hold_reviewer_counts(&mut fixer.review, 1, 2); + let proofs = RoundProofs { + report_doc_present: true, + tests_ran: true, + tests_passed: true, + }; + assert_eq!( + judge_round(&fixer, &proofs), + Verdict::Findings { + critical: 1, + warning: 2 + } + ); + let mut honest = outcome(0, 3, 0); + hold_reviewer_counts(&mut honest.review, 0, 1); + assert_eq!(honest.review.warning, 3, "a higher own count stands"); + } + + fn outcome(critical: u32, warning: u32, suggestion: u32) -> RoundOutcome { + RoundOutcome { + round: 1, + role: Role::Both, + result: "passed".into(), + reason: None, + summary: "done".into(), + report: Some("report".into()), + review: RoundReview { + critical, + warning, + suggestion, + ..RoundReview::default() + }, + tests: Some(RoundTests { + ran: true, + passed: true, + summary: "ok".into(), + }), + subject: None, + } + } + + const ALL: RoundProofs = RoundProofs { + report_doc_present: true, + tests_ran: true, + tests_passed: true, + }; + + #[test] + fn a_round_with_every_proof_and_no_findings_is_clean() { + assert_eq!(judge_round(&outcome(0, 0, 0), &ALL), Verdict::Clean); + } + + #[test] + fn each_missing_proof_fails_with_its_own_message_even_at_zero_counts() { + let no_doc = RoundProofs { + report_doc_present: false, + ..ALL + }; + let no_run = RoundProofs { + tests_ran: false, + tests_passed: false, + ..ALL + }; + let failed = RoundProofs { + tests_passed: false, + ..ALL + }; + let round = outcome(0, 0, 0); + assert_eq!( + judge_round(&round, &no_doc), + Verdict::Failed("no reviewer report in the session".into()) + ); + assert_eq!( + judge_round(&round, &no_run), + Verdict::Failed("targeted tests did not run".into()) + ); + assert_eq!( + judge_round(&round, &failed), + Verdict::Failed("targeted tests failed".into()) + ); + } + + #[test] + fn critical_or_warning_left_is_findings() { + assert_eq!( + judge_round(&outcome(1, 0, 0), &ALL), + Verdict::Findings { + critical: 1, + warning: 0 + } + ); + assert_eq!( + judge_round(&outcome(0, 2, 0), &ALL), + Verdict::Findings { + critical: 0, + warning: 2 + } + ); + } + + #[test] + fn suggestions_alone_are_still_clean() { + assert_eq!(judge_round(&outcome(0, 0, 9), &ALL), Verdict::Clean); + } + + #[test] + fn a_failed_result_passes_its_reason_through() { + let mut round = outcome(0, 0, 0); + round.result = "failed".into(); + round.reason = Some("blocked".into()); + assert_eq!(judge_round(&round, &ALL), Verdict::Failed("blocked".into())); + } + + #[test] + fn an_outcome_reads_from_the_console_json() { + let json = r#"{"round":2,"role":"fixer","result":"passed","reason":null, + "summary":"s","tests":{"ran":true,"passed":true,"summary":"3 pass"}, + "review":{"critical":0,"warning":1,"suggestion":0, + "fixed":[{"title":"t","file":"a.rs","line":4}]}}"#; + let parsed: RoundOutcome = serde_json::from_str(json).unwrap(); + assert_eq!(parsed.role, Role::Fixer); + assert_eq!(parsed.review.fixed[0].line, Some(4)); + assert_eq!(parsed.report, None); + let reviewer: RoundOutcome = + serde_json::from_str(r#"{"round":1,"role":"reviewer","result":"passed"}"#).unwrap(); + assert_eq!(reviewer.role, Role::Reviewer); + } + + fn view() -> RunView { + RunView { + round: 1, + cap: 3, + rounds_run: 1, + suggestions_on: false, + suggestions_pending: false, + batch_done: false, + retried_this_round: false, + stop_after_round: false, + stop_now: false, + } + } + + const FINDINGS: Verdict = Verdict::Findings { + critical: 1, + warning: 0, + }; + + #[test] + fn stop_now_always_stops_for_the_person() { + let run = RunView { + stop_now: true, + suggestions_on: true, + suggestions_pending: true, + ..view() + }; + let done = RunView { + batch_done: true, + ..run + }; + assert_eq!( + next_step(&done, &Verdict::Clean), + Next::Stop(StopReason::Person) + ); + for verdict in [Verdict::Clean, FINDINGS, Verdict::Failed("tests".into())] { + assert_eq!(next_step(&run, &verdict), Next::Stop(StopReason::Person)); + } + } + + #[test] + fn a_failure_retries_once_then_stops_failed() { + let failed = Verdict::Failed("tests".into()); + assert_eq!(next_step(&view(), &failed), Next::Retry); + let retried = RunView { + retried_this_round: true, + ..view() + }; + assert_eq!( + next_step(&retried, &failed), + Next::Stop(StopReason::Failed("tests".into())) + ); + } + + #[test] + fn clean_stops_unless_a_suggestions_batch_is_due() { + assert_eq!( + next_step(&view(), &Verdict::Clean), + Next::Stop(StopReason::Clean) + ); + let on_none_pending = RunView { + suggestions_on: true, + ..view() + }; + assert_eq!( + next_step(&on_none_pending, &Verdict::Clean), + Next::Stop(StopReason::Clean) + ); + let due = RunView { + suggestions_on: true, + suggestions_pending: true, + ..view() + }; + assert_eq!(next_step(&due, &Verdict::Clean), Next::SuggestionsBatch); + let off = RunView { + suggestions_pending: true, + ..view() + }; + assert_eq!( + next_step(&off, &Verdict::Clean), + Next::Stop(StopReason::Clean) + ); + } + + #[test] + fn findings_start_the_next_round_below_the_cap() { + assert_eq!(next_step(&view(), &FINDINGS), Next::StartRound(2)); + let second = RunView { + round: 2, + rounds_run: 2, + ..view() + }; + assert_eq!(next_step(&second, &FINDINGS), Next::StartRound(3)); + } + + #[test] + fn findings_at_the_cap_stop_or_run_the_batch() { + let at_cap = RunView { + round: 3, + rounds_run: 3, + ..view() + }; + assert_eq!(next_step(&at_cap, &FINDINGS), Next::Stop(StopReason::Cap)); + let due = RunView { + suggestions_on: true, + suggestions_pending: true, + ..at_cap + }; + assert_eq!(next_step(&due, &FINDINGS), Next::SuggestionsBatch); + } + + #[test] + fn a_cap_above_the_most_rounds_is_held_to_the_most() { + let run = RunView { + round: MAX_ROUNDS, + rounds_run: MAX_ROUNDS, + cap: 9, + ..view() + }; + assert_eq!(next_step(&run, &FINDINGS), Next::Stop(StopReason::Cap)); + } + + #[test] + fn a_run_with_cap_one_stops_after_round_one() { + let run = RunView { cap: 1, ..view() }; + assert_eq!(next_step(&run, &FINDINGS), Next::Stop(StopReason::Cap)); + assert_eq!( + next_step(&run, &Verdict::Clean), + Next::Stop(StopReason::Clean) + ); + } + + #[test] + fn stop_after_this_round_stops_for_the_person_and_skips_the_batch() { + let run = RunView { + stop_after_round: true, + suggestions_on: true, + suggestions_pending: true, + ..view() + }; + assert_eq!(next_step(&run, &FINDINGS), Next::Stop(StopReason::Person)); + // Clean is clean, but nothing more is started, the batch included. + assert_eq!( + next_step(&run, &Verdict::Clean), + Next::Stop(StopReason::Clean) + ); + } + + #[test] + fn the_batch_never_runs_after_a_failure() { + let run = RunView { + suggestions_on: true, + suggestions_pending: true, + round: 3, + rounds_run: 3, + retried_this_round: true, + ..view() + }; + assert_eq!( + next_step(&run, &Verdict::Failed("tests".into())), + Next::Stop(StopReason::Failed("tests".into())) + ); + } + + #[test] + fn after_the_batch_one_final_check_runs_and_the_original_reason_stands() { + let run = RunView { + suggestions_on: true, + suggestions_pending: true, + batch_done: true, + round: 3, + rounds_run: 4, + ..view() + }; + assert_eq!(next_step(&run, &Verdict::Clean), Next::FinalCheck); + assert_eq!(next_step(&run, &FINDINGS), Next::FinalCheck); + // A batch that fails is retried or stops failed like any round. + assert_eq!( + next_step(&run, &Verdict::Failed("tests".into())), + Next::Retry + ); + // Whatever the final check finds, the run ends as it was ending. + assert_eq!( + after_final_check(StopReason::Cap), + Next::Stop(StopReason::Cap) + ); + assert_eq!( + after_final_check(StopReason::Clean), + Next::Stop(StopReason::Clean) + ); + } + + #[test] + fn continue_adds_one_round_and_never_a_seventh() { + assert_eq!(continue_cap(3, 3), Some(4)); + assert_eq!(continue_cap(1, 1), Some(2)); + assert_eq!(continue_cap(5, 5), Some(6)); + assert_eq!(continue_cap(6, 6), None); + assert_eq!(continue_cap(3, 2), None, "did not stop at the cap"); + } + + fn titles(list: &[&str]) -> Vec { + list.iter().map(|title| title.to_string()).collect() + } + + #[test] + fn the_commit_subject_joins_the_titles() { + assert_eq!( + round_commit_message( + 2, + &titles(&["fix null check in loop_tools", "restore test map row"]) + ), + "Review Loop round 2: fix null check in loop_tools, restore test map row" + ); + assert_eq!( + round_commit_message(1, &titles(&["one fix"])), + "Review Loop round 1: one fix" + ); + assert_eq!(round_commit_message(3, &[]), "Review Loop round 3"); + } + + #[test] + fn a_long_commit_subject_drops_trailing_titles() { + let subject = round_commit_message( + 2, + &titles(&[ + "close the file handle before renaming", + "name the timer", + "restore the test map row", + "tidy the report", + ]), + ); + assert!(subject.chars().count() <= 72, "{subject}"); + assert!(subject.starts_with("Review Loop round 2: close the file handle")); + assert!(subject.contains(" more"), "{subject}"); + // One title that is too long on its own is cut. + let one = round_commit_message(1, &titles(&[&"x".repeat(200)])); + assert_eq!(one.chars().count(), 72); + assert!(one.ends_with("...")); + } + + #[test] + fn the_detail_line_counts_findings() { + assert_eq!( + round_detail(2, 3, "Fixing", 1, 2), + "Round 2 of 3: Fixing 3 findings (1 Critical, 2 Warning)" + ); + assert_eq!( + round_detail(1, 3, "Fixing", 0, 1), + "Round 1 of 3: Fixing 1 finding (1 Warning)" + ); + assert_eq!( + round_detail(1, 3, "Fixing", 1, 0), + "Round 1 of 3: Fixing 1 finding (1 Critical)" + ); + assert_eq!( + round_detail(1, 3, "Reviewing", 0, 0), + "Round 1 of 3: Reviewing" + ); + } +} diff --git a/plan2code-app/ui/app.js b/plan2code-app/ui/app.js index 87f3184..bcb3dcd 100644 --- a/plan2code-app/ui/app.js +++ b/plan2code-app/ui/app.js @@ -1038,6 +1038,85 @@ window.addEventListener('message', (event) => { invoke('loop_facts') .then((facts) => source.postMessage({ plan2code: 'loop-facts', facts }, '*')) .catch(() => {}); + } else if (kind === 'review-loop-facts') { + // The Review Loop's setup screen asks what agent a run would use and + // whether it has helpers. Facts only; the page sends no setup value. + const source = event.source; + invoke('review_loop_facts') + .then((facts) => source.postMessage({ plan2code: 'review-loop-facts', facts }, '*')) + .catch(() => {}); + } else if (kind === 'review-loop-start') { + // Start: the setup screen's picks, only the known fields and kinds. The + // notification address is never taken from the page; the app reads it. + const source = event.source; + const picked = event.data.setup && typeof event.data.setup === 'object' ? event.data.setup : {}; + const text = (value) => (typeof value === 'string' ? value : ''); + const flag = (value) => value === true; + const setup = { + scope: text(picked.scope), + spec: text(picked.spec), + cap: Number.isInteger(picked.cap) ? picked.cap : 3, + commit: picked.commit !== false, + preRunCommitAgreed: flag(picked.preRunCommitAgreed), + suggestions: flag(picked.suggestions), + strength: text(picked.strength), + silenceMinutes: Number.isInteger(picked.silenceMinutes) ? picked.silenceMinutes : 20, + notifyRounds: flag(picked.notifyRounds), + }; + invoke('review_loop_start', { setup }) + .then((started) => source.postMessage({ plan2code: 'review-loop-start-result', ok: true, started, error: null }, '*')) + .catch((error) => + source.postMessage({ plan2code: 'review-loop-start-result', ok: false, started: false, error: String(error) }, '*') + ); + } else if (kind === 'review-loop-continue') { + const source = event.source; + invoke('review_loop_continue') + .then(() => source.postMessage({ plan2code: 'review-loop-continue-result', ok: true, error: null }, '*')) + .catch((error) => + source.postMessage({ plan2code: 'review-loop-continue-result', ok: false, error: String(error) }, '*') + ); + } else if (kind === 'review-loop-partial') { + // Keep or Discard what Stop now left: one boolean, nothing else. + const source = event.source; + if (typeof event.data.keep !== 'boolean') { + // Discard cannot be undone: only an explicit true or false is a choice. + source.postMessage({ plan2code: 'review-loop-partial-result', ok: false, error: 'keep must be true or false' }, '*'); + return; + } + invoke('review_loop_partial', { keep: event.data.keep }) + .then(() => source.postMessage({ plan2code: 'review-loop-partial-result', ok: true, error: null }, '*')) + .catch((error) => + source.postMessage({ plan2code: 'review-loop-partial-result', ok: false, error: String(error) }, '*') + ); + } else if (kind === 'review-loop-sign-off') { + // Sign off: the ticked Suggestions by id and the squash switch, nothing else. + const source = event.source; + const { picks, squash } = event.data; + const refuse = (error) => source.postMessage({ plan2code: 'review-loop-sign-off-result', ok: false, error }, '*'); + if (!Array.isArray(picks) || picks.length > 50 || !picks.every((id) => typeof id === 'string' && /^s[0-9]{1,3}$/.test(id))) { + refuse('picks must be a list of up to 50 suggestion ids'); + return; + } + if (typeof squash !== 'boolean') { + refuse('squash must be true or false'); + return; + } + invoke('review_loop_sign_off', { picks, squash }) + .then(() => source.postMessage({ plan2code: 'review-loop-sign-off-result', ok: true, error: null }, '*')) + .catch((error) => refuse(String(error))); + } else if (kind === 'review-loop-next') { + // The finished screen's launch: one of two words, the app builds the brief. + const source = event.source; + const next = event.data.next; + if (next !== 'pr-prep' && next !== 'quick-task') { + source.postMessage({ plan2code: 'review-loop-next-result', ok: false, error: 'next must be pr-prep or quick-task' }, '*'); + return; + } + invoke('review_loop_next', { next }) + .then(() => source.postMessage({ plan2code: 'review-loop-next-result', ok: true, error: null }, '*')) + .catch((error) => + source.postMessage({ plan2code: 'review-loop-next-result', ok: false, error: String(error) }, '*') + ); } else if (kind === 'loop-resume' || kind === 'loop-ask' || kind === 'loop-fix' || kind === 'loop-finalize') { // Fixed requests, no free text: the page answers with ok or the error. const source = event.source; @@ -1628,6 +1707,19 @@ async function syncLoopState() { } } +// Which loop the strip is showing, so the stop buttons press the right commands. +let loopKind = 'phases'; + +// A pip's hover text: "Phase 2", or for a Review Loop round the counts it found +// ("Round 1: 2 Critical, 1 Warning"), "Round 3" for one not finished yet. +function roundPipTitle(state, i) { + if (state.kind !== 'rounds') return `Phase ${i + 1}`; + const counts = Array.isArray(state.roundCounts) ? state.roundCounts[i] : null; + if (!counts) return `Round ${i + 1}`; + const found = [counts.critical > 0 ? `${counts.critical} Critical` : '', counts.warning > 0 ? `${counts.warning} Warning` : ''].filter(Boolean); + return `Round ${i + 1}: ${found.length ? found.join(', ') : 'nothing found'}`; +} + function applyLoopState(state) { if (!state || !state.running) { const wasRunning = loopRunning; @@ -1664,13 +1756,14 @@ function applyLoopState(state) { ...banner.pips.map((kind, i) => { const pip = document.createElement('span'); pip.className = `loop-pip ${kind}`; - pip.title = `Phase ${i + 1}`; + pip.title = roundPipTitle(state, i); return pip; }) ); setLoopTitle(loopWindowTitle(projectPathEl.textContent, state)); const stopLabels = loopStopLabels(state); - loopStopAfterOn = !!state.stopAfterPhase; + loopStopAfterOn = !!(state.kind === 'rounds' ? state.stopAfterRound : state.stopAfterPhase); + loopKind = state.kind === 'rounds' ? 'rounds' : 'phases'; loopStopAfterBtn.disabled = stopLabels.afterDisabled; loopStopAfterBtn.textContent = stopLabels.afterText; loopStopNowBtn.disabled = stopLabels.nowDisabled; @@ -1730,15 +1823,16 @@ function pressLoop(command, args) { loopRetryBtn.onclick = () => { if (loopRetryAction) loopRetryAction(); }; -loopStopAfterBtn.onclick = () => pressLoop('loop_stop_after_phase', { on: !loopStopAfterOn }); +loopStopAfterBtn.onclick = () => pressLoop(loopKind === 'rounds' ? 'review_loop_stop_after' : 'loop_stop_after_phase', { on: !loopStopAfterOn }); loopStopNowBtn.onclick = async () => { + const rounds = loopKind === 'rounds'; const yes = await confirmModal({ title: 'End the agent now?', - lines: [{ kind: 'text', text: "This phase's changes stay uncommitted." }], + lines: [{ kind: 'text', text: rounds ? "This round's changes stay uncommitted until you choose to keep or discard them." : "This phase's changes stay uncommitted." }], primary: 'Stop now', danger: true, }); - if (yes) pressLoop('loop_stop_now'); + if (yes) pressLoop(rounds ? 'review_loop_stop_now' : 'loop_stop_now'); }; // The right end of the bar: whether the console stopped answering and where diff --git a/plan2code-app/ui/meter.js b/plan2code-app/ui/meter.js index 5564f9c..a287d97 100644 --- a/plan2code-app/ui/meter.js +++ b/plan2code-app/ui/meter.js @@ -210,6 +210,11 @@ export function windowTitleFor(dir) { */ export function loopWindowTitle(dir, state) { const name = lastSegment(dir); + if (state.kind === "rounds") { + const where = state.afterRounds || `Round ${state.round}`; + const round = state.step === "Waiting on you" ? `Review Loop needs you: ${where}` : state.afterRounds ? `Review Loop: ${state.afterRounds}` : `Review Loop: Round ${state.round} of ${state.rounds}`; + return name ? `${round} - ${name}` : round; + } const what = state.step === "Waiting on you" ? `Loop needs you: Phase ${state.phase}` : `Loop: Phase ${state.phase} of ${state.phases}`; return name ? `${what} - ${name}` : what; } @@ -221,6 +226,7 @@ export function loopWindowTitle(dir, state) { * of the spec up to the last this run builds. */ export function loopBanner(state) { + if (state.kind === "rounds") return roundsBanner(state); const { phase, phases, phaseName, step } = state; const named = phaseName ? `Phase ${phase} of ${phases}: ${phaseName}` : `Phase ${phase} of ${phases}`; const pips = Array.from({ length: Math.max(phases, 0) }, (_, i) => (i + 1 < phase ? "done" : i + 1 === phase ? "current" : "todo")); @@ -247,6 +253,40 @@ export function loopBanner(state) { return { ...base, title: "Implementation loop running", detail: ran ? `${where} \u00b7 ${ran}` : where }; } +/** + * The Review Loop's banner (`kind: "rounds"`): the same words as the phase banner + * with "round" for "phase", one pip per round up to the cap, and the detail line + * the app builds from the round, step and counts ("Round 2 of 3: Fixing 3 findings + * (1 Critical, 2 Warning)", carried in `phaseName`). After the rounds, + * `afterRounds` names the Suggestions batch or the final check, and every pip + * shows done. + */ +function roundsBanner(state) { + const { round, rounds, step } = state; + const after = state.afterRounds || ""; + const named = after || `Round ${round} of ${rounds}`; + const detailLine = state.phaseName || (step ? `${named}: ${step}` : named); + const pips = Array.from({ length: Math.max(rounds, 0) }, (_, i) => (after || i + 1 < round ? "done" : i + 1 === round ? "current" : "todo")); + const base = { tone: "running", pips, hint: "Working on its own. You can walk away." }; + if (state.stopping) { + return { ...base, title: "Stopping", detail: "The agent is ending. You will be asked what to do with the round's changes.", hint: "The stop screen follows in a moment." }; + } + if (step === "Waiting on you") { + return { ...base, tone: "waiting", title: "The Review Loop needs your answer", detail: `${named} is waiting on the question below.`, hint: "Nothing is lost while it waits." }; + } + if (state.stopAfterRound) { + return { ...base, title: "Stopping after this round", detail: `${named} finishes, is judged and committed, then the Review Loop stops.`, hint: "Stop now ends the agent at once." }; + } + if (step === "Starting") { + if (state.phaseRetried) return { ...base, title: after ? `Retrying the ${after.toLowerCase()}` : `Retrying round ${round}`, detail: `The agent crashed or went quiet, so a fresh one is picking up ${after ? `the ${after.toLowerCase()}` : named}.` }; + if (after) return { ...base, title: "Rounds done", detail: `Opening a fresh agent for the ${after.toLowerCase()}.` }; + if (round > 1) return { ...base, title: `Round ${round - 1} done`, detail: `Opening a fresh agent for ${named}.` }; + return { ...base, title: "Starting the Review Loop", detail: `Opening a fresh agent for ${named}.` }; + } + const ran = loopRunText(state); + return { ...base, title: "Review Loop running", detail: ran ? `${detailLine} · ${ran}` : detailLine }; +} + /** * What the running phase runs on, from the app's `loop-state`: "Thrifty (sonnet, * low)" for a phase on a strength, "(opus, high)" for a Match my session phase @@ -267,9 +307,11 @@ export function loopRunText(state) { */ export function loopStopLabels(state) { const stopping = Boolean(state.stopping); - const on = Boolean(state.stopAfterPhase); + const rounds = state.kind === "rounds"; + const on = Boolean(rounds ? state.stopAfterRound : state.stopAfterPhase); + const unit = rounds ? "round" : "phase"; return { - afterText: on ? "Cancel stop after this phase" : "Stop after this phase", + afterText: on ? `Cancel stop after this ${unit}` : `Stop after this ${unit}`, afterDisabled: stopping || (!on && state.canStopAfter === false), nowDisabled: stopping, }; diff --git a/scripts/test-agent-lookup.mjs b/scripts/test-agent-lookup.mjs index a7ecb2c..6e9ae8b 100644 --- a/scripts/test-agent-lookup.mjs +++ b/scripts/test-agent-lookup.mjs @@ -118,6 +118,13 @@ test("loadAgentList: the shipped agents.json loads with 3 built-ins and 5 templa assert.deepEqual(templates.map((a) => a.id), ["copilot", "opencode", "gemini", "pi", "cursor"]); }); +test("loadAgentList: helpers is true for claude, false for every other shipped entry and for one without the key", (t) => { + const { builtins, templates } = loadAgentList({ dir: path.join(ROOT, "src", "launcher") }); + for (const a of [...builtins, ...templates]) assert.equal(a.helpers, a.id === "claude", a.id); + const dir = listDir(t, JSON.stringify({ schema: 1, agents: [{ kind: "template", id: "x", name: "X", command: "x" }, { kind: "template", id: "y", name: "Y", command: "y", helpers: "yes" }] })); + assert.deepEqual(loadAgentList({ dir }).templates.map((a) => a.helpers), [false, false]); +}); + test("every shipped template passes normalizeAgents() with no warnings", () => { const { templates } = loadAgentList({ dir: path.join(ROOT, "src", "launcher") }); const { agents, warnings } = normalizeAgents(JSON.stringify({ schema: 1, agents: templates })); diff --git a/scripts/test-app-meter.mjs b/scripts/test-app-meter.mjs index 4b5dba3..a13c7f6 100644 --- a/scripts/test-app-meter.mjs +++ b/scripts/test-app-meter.mjs @@ -471,8 +471,9 @@ test("the stop buttons: Stop after is a toggle, off on the last phase, and both test("app.js sends the toggle's wish and shows a failed press with a Retry", () => { const app = fs.readFileSync(path.join(HERE, "..", "plan2code-app", "ui", "app.js"), "utf8"); assert.match(app, /invoke\(command, args\)\.then\(hideLoopError/, "a good press clears the error"); - assert.match(app, /pressLoop\('loop_stop_after_phase', \{ on: !loopStopAfterOn \}\)/); - assert.match(app, /pressLoop\('loop_stop_now'\)/); + // The press goes to the phase commands for an Implementation Loop and to the Review Loop's own for rounds. + assert.match(app, /'loop_stop_after_phase', \{ on: !loopStopAfterOn \}\)/); + assert.match(app, /: 'loop_stop_now'\)/); assert.match(app, /loopRetryBtn\.hidden = false/, "a failed press offers Retry"); const html = fs.readFileSync(path.join(HERE, "..", "plan2code-app", "ui", "index.html"), "utf8"); assert.match(html, /id="loop-error"[^>]*hidden/); @@ -570,6 +571,93 @@ test("the banner and stop buttons agree for a state carrying stopping, stopAfter assert.equal(loopStopLabels(last).afterDisabled, true); }); +// The Review Loop's banner: the same states in round words, one pip per round, and the detail the app builds. +const ROUNDS = { running: true, kind: "rounds", round: 2, rounds: 3, phase: 2, phases: 3, phaseName: "Round 2 of 3: Reviewing", step: "Reviewing", stopAfterRound: false, stopAfterPhase: false, stopping: false, canStopAfter: true, phaseRetried: false, roundCounts: [{ critical: 2, warning: 1 }] }; + +test("a rounds state says Review Loop, with one pip per round and the app's detail line", () => { + const banner = loopBanner(ROUNDS); + assert.equal(banner.title, "Review Loop running"); + assert.equal(banner.detail, "Round 2 of 3: Reviewing"); + assert.equal(banner.tone, "running"); + assert.deepEqual(banner.pips, ["done", "current", "todo"]); + assert.deepEqual(loopBanner({ ...ROUNDS, round: 1 }).pips, ["current", "todo", "todo"]); + assert.deepEqual(loopBanner({ ...ROUNDS, round: 3 }).pips, ["done", "done", "current"]); + assert.deepEqual(loopBanner({ ...ROUNDS, rounds: 6, round: 4 }).pips, ["done", "done", "done", "current", "todo", "todo"]); +}); + +test("a rounds state in each step: fixing with counts, starting, retrying, waiting, stopping, stop after this round", () => { + const fixing = loopBanner({ ...ROUNDS, step: "Fixing", phaseName: "Round 2 of 3: Fixing 3 findings (1 Critical, 2 Warning)" }); + assert.equal(fixing.title, "Review Loop running"); + assert.equal(fixing.detail, "Round 2 of 3: Fixing 3 findings (1 Critical, 2 Warning)"); + // Without the app's detail line the banner builds the plain one from the round and step. + assert.equal(loopBanner({ ...ROUNDS, step: "Testing", phaseName: "" }).detail, "Round 2 of 3: Testing"); + assert.equal(loopBanner({ ...ROUNDS, step: "Testing", phaseName: "Round 2 of 3: Testing", model: "sonnet", effort: "low", strength: "thrifty" }).detail, "Round 2 of 3: Testing \u00b7 Thrifty (sonnet, low)"); + + const first = loopBanner({ ...ROUNDS, round: 1, step: "Starting" }); + assert.equal(first.title, "Starting the Review Loop"); + assert.equal(first.detail, "Opening a fresh agent for Round 1 of 3."); + const next = loopBanner({ ...ROUNDS, step: "Starting" }); + assert.equal(next.title, "Round 1 done"); + assert.equal(next.detail, "Opening a fresh agent for Round 2 of 3."); + const retry = loopBanner({ ...ROUNDS, step: "Starting", phaseRetried: true }); + assert.equal(retry.title, "Retrying round 2"); + assert.match(retry.detail, /crashed or went quiet, so a fresh one is picking up Round 2 of 3/); + + const waiting = loopBanner({ ...ROUNDS, step: "Waiting on you" }); + assert.equal(waiting.title, "The Review Loop needs your answer"); + assert.equal(waiting.tone, "waiting"); + assert.equal(waiting.detail, "Round 2 of 3 is waiting on the question below."); + + const stopping = loopBanner({ ...ROUNDS, stopping: true }); + assert.equal(stopping.title, "Stopping"); + assert.deepEqual(stopping.pips, ["done", "current", "todo"]); + + const after = loopBanner({ ...ROUNDS, stopAfterRound: true, stopAfterPhase: true }); + assert.equal(after.title, "Stopping after this round"); + assert.match(after.detail, /Round 2 of 3 finishes, is judged and committed, then the Review Loop stops/); +}); + +test("a rounds state's stop buttons and window title use round words", () => { + assert.deepEqual(loopStopLabels(ROUNDS), { afterText: "Stop after this round", afterDisabled: false, nowDisabled: false }); + assert.deepEqual(loopStopLabels({ ...ROUNDS, stopAfterRound: true }), { afterText: "Cancel stop after this round", afterDisabled: false, nowDisabled: false }); + assert.equal(loopStopLabels({ ...ROUNDS, canStopAfter: false }).afterDisabled, true, "the cap round has nothing to stop after"); + assert.deepEqual(loopStopLabels({ ...ROUNDS, stopping: true }), { afterText: "Stop after this round", afterDisabled: true, nowDisabled: true }); + assert.equal(loopWindowTitle("C:/git/lunch", ROUNDS), "Review Loop: Round 2 of 3 - lunch"); + assert.equal(loopWindowTitle("C:/git/lunch", { ...ROUNDS, step: "Waiting on you" }), "Review Loop needs you: Round 2 - lunch"); +}); + +test("the Suggestions batch and final check are named for what they are, never as a round past the cap", () => { + const batch = { ...ROUNDS, round: 3, phase: 3, afterRounds: "Suggestions batch", phaseName: "Suggestions batch: Fixing", step: "Fixing" }; + const shown = loopBanner(batch); + assert.equal(shown.detail, "Suggestions batch: Fixing"); + assert.deepEqual(shown.pips, ["done", "done", "done"]); + assert.equal(loopBanner({ ...batch, step: "Starting" }).detail, "Opening a fresh agent for the suggestions batch."); + assert.equal(loopWindowTitle("C:/git/lunch", { ...batch, afterRounds: "Final check" }), "Review Loop: Final check - lunch"); + assert.doesNotMatch(JSON.stringify(shown), /Round 4|of 3: Fixing/); +}); + +test("a phases state renders exactly as before, whatever kind it names", () => { + const phases = { running: true, phase: 2, phases: 4, phaseName: "API", step: "Build", stopAfterPhase: false, stopping: false, canStopAfter: true }; + const plain = loopBanner(phases); + assert.equal(plain.title, "Implementation loop running"); + assert.equal(plain.detail, "Phase 2 of 4: API \u00b7 Build"); + assert.deepEqual(plain.pips, ["done", "current", "todo", "todo"]); + assert.deepEqual(loopBanner({ ...phases, kind: "phases", round: 0, rounds: 0, roundCounts: [], stopAfterRound: false }), plain); + assert.deepEqual(loopStopLabels({ ...phases, kind: "phases" }), loopStopLabels(phases)); + assert.equal(loopWindowTitle("C:/git/lunch", { ...phases, kind: "phases" }), "Loop: Phase 2 of 4 - lunch"); +}); + +test("app.js hangs round counts on the pips and sends the Review Loop's stop buttons to its own commands", () => { + assert.match(APP_JS, /function roundPipTitle\(state, i\)/); + assert.match(APP_JS, /pip\.title = roundPipTitle\(state, i\)/); + const title = APP_JS.slice(APP_JS.indexOf("function roundPipTitle"), APP_JS.indexOf("function applyLoopState")); + assert.match(title, /if \(state\.kind !== 'rounds'\) return `Phase \$\{i \+ 1\}`/, "a phases pip keeps its title"); + assert.match(title, /Round \$\{i \+ 1\}: \$\{found\.length \? found\.join\(', '\) : 'nothing found'\}/); + assert.match(APP_JS, /pressLoop\(loopKind === 'rounds' \? 'review_loop_stop_after' : 'loop_stop_after_phase'/); + assert.match(APP_JS, /pressLoop\(rounds \? 'review_loop_stop_now' : 'loop_stop_now'\)/); + assert.match(APP_JS, /loopStopAfterOn = !!\(state\.kind === 'rounds' \? state\.stopAfterRound : state\.stopAfterPhase\)/); +}); + test("app.js asks loop_state after attach and again once it listens, without calling a reload a loop's end", () => { assert.match(APP_JS, /async function syncLoopState\(\)[\s\S]*?invoke\('loop_state'\)/); assert.match(APP_JS, /\.listen\('loop-state'[\s\S]*?\.then\(syncLoopState/, "asked again once the listener is up"); diff --git a/scripts/test-console-wire-budgets.mjs b/scripts/test-console-wire-budgets.mjs index d706eb3..4a97eb2 100644 --- a/scripts/test-console-wire-budgets.mjs +++ b/scripts/test-console-wire-budgets.mjs @@ -43,7 +43,8 @@ export const BUDGETS = { "plan.md": 1023, // raised by the UI prototype line's bytes only "pr-prep.md": 4500, "quick-task.md": 5194, // raised by the UI prototype line's, the prototype recap line's, the prototype archive wording's, the lessons card line's and the Changes tab lines' bytes only - "review.md": 1140, // raised by the lessons card line's bytes only + "review-loop.md": 4000, // its written size (3,564 bytes) plus 10 percent, rounded up to the next 100 + "review.md": 1190, // raised by the lessons card line's bytes, then the Review Loop pointer line's bytes only "revise-plan.md": 1422, // raised by the UI prototype line's bytes only "test.md": 5540, // raised by the lessons card line's bytes only "ui-prototype.md": 4600, diff --git a/scripts/test-lanes.json b/scripts/test-lanes.json index de6742e..dbe4b71 100644 --- a/scripts/test-lanes.json +++ b/scripts/test-lanes.json @@ -120,6 +120,7 @@ "test-web-console-page-help.mjs", "test-web-console-page-learning.mjs", "test-web-console-page-loop.mjs", + "test-web-console-page-review-loop.mjs", "test-web-console-page-notepad.mjs", "test-web-console-page-prefs.mjs", "test-web-console-page-send.mjs", @@ -128,6 +129,7 @@ "test-web-console-page-workspace.mjs", "test-web-console-pointers.mjs", "test-web-console-qa.mjs", + "test-web-console-review-loop.mjs", "test-web-console-server.mjs", "test-web-console-session.mjs", "test-web-console-source.mjs", diff --git a/scripts/test-web-console-loop.mjs b/scripts/test-web-console-loop.mjs index cedf659..94d3e92 100644 --- a/scripts/test-web-console-loop.mjs +++ b/scripts/test-web-console-loop.mjs @@ -17,7 +17,7 @@ import fs from "node:fs"; import path from "node:path"; import { spawnSync } from "node:child_process"; import { pathToFileURL } from "node:url"; -import { applyPatch, blankState, validate, switchWorkflow } from "../src/web-console/patches.mjs"; +import { applyPatch, blankState, validate, switchWorkflow, ROUND_ROLES } from "../src/web-console/patches.mjs"; import { ROOT, CONSOLE_CLI, ENV, HOME, MODELS_DIR, cli, readState, sessionUrl, payload } from "./web-console-test-helpers.mjs"; const APP_VARS = ["PLAN2CODE_IN_APP", "PLAN2CODE_EMBED_ORIGIN", "PLAN2CODE_APP_ANNOUNCE", "PLAN2CODE_APP_TOKEN", "PLAN2CODE_CONSOLE_SID"]; @@ -82,13 +82,13 @@ test("open --loop under the app locks the session: loop { driving: true } in sta } }); -test("open --loop goes only with Implement or Implement + Review: any other workflow, or none, exits 2", () => { +test("open --loop goes only with Implement, Implement + Review or Review: any other workflow, or none, exits 2", () => { const cwd = tempProject("gate-wf"); const before = sessionCount(); for (const args of [["--workflow", "plan"], ["--workflow", "dashboard"], []]) { const res = run(["open", ...args, "--loop", "--no-open"], { cwd, extra: IN_APP }); assert.equal(res.status, 2, `exit 2 for ${args.join(" ") || "no workflow"}`); - assert.match(res.stderr, /--loop goes only with --workflow implement or --workflow implement-review/); + assert.match(res.stderr, /--loop goes only with --workflow implement or --workflow implement-review or --workflow review/); } assert.equal(sessionCount(), before, "no session folder was made"); }); @@ -546,6 +546,75 @@ test("loopEnd: an unknown evidence id, a push in can, and the other bad fields a } }); +const REPORT_DOC = { id: "report", title: "Review Loop report", blocks: [{ id: "b1", md: "# Clean\n\nNo findings." }] }; +const PARTIAL_DOC = { id: "partial-diff", title: "partial.diff", blocks: [{ id: "d1", diff: "partial.diff", text: "diff --git a/x b/x\n" }] }; +const reviewEnd = (extra = {}) => ({ + kind: "review", + line: "Clean after 2 rounds", + reason: "clean", + report: "report", + canContinue: false, + canSquash: false, + can: [], + ...extra, +}); + +test("loopEnd: a review end with each reason is stored, with no phases or uncommitted", () => { + for (const reason of ["clean", "cap", "person", "failed"]) { + const { problems, next } = tryPatch(loopState(), { docs: [REPORT_DOC], loopEnd: reviewEnd({ reason }) }); + assert.deepEqual(problems, [], reason); + assert.equal(next.loopEnd.reason, reason); + assert.equal(next.loopEnd.kind, "review"); + } + const full = reviewEnd({ + reason: "person", + canContinue: true, + canSquash: true, + partial: { files: 1, added: 2, removed: 0, diff: "partial-diff" }, + suggestions: [{ id: "s1", title: "Rename it", file: "src/a.js", line: 4 }, { id: "s2", title: "Tidy", file: "" }], + open: [{ title: "Unchecked input", file: "src/b.js", line: 9 }, { level: "warning", title: "Slow loop", file: "src/c.js" }], + signedOff: true, + note: "Squashed 3 round commits into one.", + can: ["dashboard"], + }); + const stored = tryPatch(loopState(), { docs: [REPORT_DOC, PARTIAL_DOC], loopEnd: full }); + assert.deepEqual(stored.problems, []); + assert.equal(stored.next.loopEnd.signedOff, true); +}); + +test("loopEnd: bad review fields are refused, each named", () => { + const cases = [ + ["a bad reason", reviewEnd({ reason: "done" }), /loopEnd\.reason must be one of clean, cap, person, failed/], + ["a missing report", reviewEnd({ report: undefined }), /loopEnd\.report must be the id of a doc on the page/], + ["an unknown report", reviewEnd({ report: "nope" }), /loopEnd\.report must be the id of a doc on the page/], + ["a non-boolean canContinue", reviewEnd({ canContinue: "yes" }), /loopEnd\.canContinue must be true or false/], + ["a non-boolean canSquash", reviewEnd({ canSquash: 1 }), /loopEnd\.canSquash must be true or false/], + ["a non-boolean signedOff", reviewEnd({ signedOff: "yes" }), /loopEnd\.signedOff must be true or false/], + ["can that is not an array", reviewEnd({ can: undefined }), /loopEnd\.can must be an array/], + ["a two-line note", reviewEnd({ note: "a\nb" }), /loopEnd\.note must be one line/], + ["a two-line line", reviewEnd({ line: "a\nb" }), /loopEnd\.line must be one line/], + ["a partial with an unknown diff", reviewEnd({ partial: { files: 1, added: 1, removed: 1, diff: "nope" } }), /loopEnd\.partial\.diff must be the id of a doc on the page/], + ["a negative partial count", reviewEnd({ partial: { files: -1, added: 1, removed: 1, diff: "report" } }), /loopEnd\.partial\.files must be a non-negative integer/], + ["a suggestion with a bad id", reviewEnd({ suggestions: [{ id: "x", title: "T", file: "" }] }), /loopEnd\.suggestions\[0\]\.id must look like s1/], + ["duplicate suggestion ids", reviewEnd({ suggestions: [{ id: "s1", title: "A", file: "" }, { id: "s1", title: "B", file: "" }] }), /loopEnd\.suggestions\[1\]\.id must be unique/], + ["a suggestion file that climbs out", reviewEnd({ suggestions: [{ id: "s1", title: "A", file: "../x" }] }), /loopEnd\.suggestions\[0\]\.file must be a relative path/], + ["a suggestion line of zero", reviewEnd({ suggestions: [{ id: "s1", title: "A", file: "a.js", line: 0 }] }), /loopEnd\.suggestions\[0\]\.line must be a positive integer/], + ["an open item with no file", reviewEnd({ open: [{ title: "A" }] }), /loopEnd\.open\[0\]\.file must be a relative path/], + ["an open item with a bad level", reviewEnd({ open: [{ level: "info", title: "A", file: "a.js" }] }), /loopEnd\.open\[0\]\.level must be/], + ["a forbidden marker in line", reviewEnd({ line: "TASK_COMPLETE" }), /loopEnd\.line: contains a loop completion marker/], + ]; + for (const [what, end, expected] of cases) { + const { problems } = tryPatch(loopState(), { docs: [REPORT_DOC], loopEnd: end }); + assert.ok(problems.some((p) => expected.test(p)), `${what}: expected ${expected}, got ${JSON.stringify(problems)}`); + } +}); + +test("loopEnd: an Implementation Loop end still needs its phases and uncommitted, and review ones never need evidence", () => { + assert.deepEqual(tryPatch(loopState(), { loopEnd: goodEnd() }).problems, []); + const { phases, ...noPhases } = goodEnd(); + assert.ok(tryPatch(loopState(), { loopEnd: noPhases }).problems.some((p) => /loopEnd\.phases must be an array/.test(p))); +}); + test("handledBy: \"loop\" is accepted in a loop session and refused outside one or with any other value", () => { const card = (extra = {}) => ({ id: "fixes", @@ -604,6 +673,7 @@ test("loop-setup: a new project reads as the defaults with remembered false, and assert.equal(got.setup.onQuestion, "guess"); assert.deepEqual(got.setup.fix, ["critical", "warning", "suggestion"]); assert.equal(got.setup.silenceMinutes, 20); + assert.equal(got.setup.reviewRounds, 2, "a phase gets two extra review rounds by default"); assert.equal(got.setup.notifyUrl, "", "no web address is called by default"); assert.equal(got.setup.notifyKind, "query"); assert.equal(got.setup.notifyParam, "message"); @@ -658,6 +728,38 @@ test("loop-setup: a save reads back per project, keeps another project's entry, const WORKSPACE_URL = pathToFileURL(path.join(ROOT, "src", "web-console", "workspace.mjs")).href; +test("loop-setup: an entry saved before reviewRounds existed reads the default 2", () => { + fs.rmSync(LOOP_SETUP_PATH, { force: true }); + const got = inStore( + async (m, { project, workspace }) => { + const fs = await import("node:fs"); + const { foldKey } = await import(workspace); + const { reviewRounds, ...legacy } = { ...m.LOOP_DEFAULTS, fix: ["warning"], saved: "2026-01-01T00:00:00.000Z" }; + fs.writeFileSync(m.LOOP_SETUP_FILE, JSON.stringify({ schema: 1, projects: { [foldKey(project)]: legacy } })); + const stored = JSON.parse(fs.readFileSync(m.LOOP_SETUP_FILE, "utf8")).projects[foldKey(project)]; + const kept = m.saveLoopSetup(project, { ...m.LOOP_DEFAULTS, fix: ["warning"], reviewRounds: 0 }); + return { read: m.readLoopSetup(project), onDisk: "reviewRounds" in stored, kept: kept.reviewRounds }; + }, + { project: projectA, workspace: WORKSPACE_URL } + ); + assert.equal(got.onDisk, false, "the stored entry has no reviewRounds"); + assert.equal(got.kept, 0, "0 turns the rounds off and is remembered"); + assert.equal(got.read.reviewRounds, 0); + fs.rmSync(LOOP_SETUP_PATH, { force: true }); + const old = inStore( + async (m, { project, workspace }) => { + const fs = await import("node:fs"); + const { foldKey } = await import(workspace); + const { reviewRounds, ...legacy } = { ...m.LOOP_DEFAULTS, fix: ["warning"], saved: "2026-01-01T00:00:00.000Z" }; + fs.writeFileSync(m.LOOP_SETUP_FILE, JSON.stringify({ schema: 1, projects: { [foldKey(project)]: legacy } })); + return m.readLoopSetup(project); + }, + { project: projectA, workspace: WORKSPACE_URL } + ); + assert.equal(old.reviewRounds, 2, "an older entry reads the default"); + assert.equal(old.remembered, true); +}); + test("loop-setup: an entry saved before fixMode existed reads as levels", () => { fs.rmSync(LOOP_SETUP_PATH, { force: true }); const got = inStore( @@ -724,6 +826,7 @@ test("loop-setup: a bad field throws with the problem named and leaves the file const cases = [ ["silenceMinutes: 0", { silenceMinutes: 0 }, /"silenceMinutes" must be a whole number from 1 to 60/], ["silenceMinutes: 61", { silenceMinutes: 61 }, /"silenceMinutes"/], + ...[-1, 7, 1.5, "2", null].map((reviewRounds) => [`reviewRounds: ${reviewRounds}`, { reviewRounds }, /"reviewRounds" must be a whole number from 0 to 6/]), ...["example.com", "ftp://example.com", "javascript:alert(1)", "https:/example.com", "https://", "https://me:secret@example.com/", "https://exa mple.com", "https://example.com/é", "https://example.com/\nx", `https://e.com/${"x".repeat(2000)}`].map((notifyUrl) => [`notifyUrl: ${notifyUrl.slice(0, 30)}`, { notifyUrl }, /"notifyUrl" must be an http or https web address/]), ["notifyUrl as a number", { notifyUrl: 5 }, /"notifyUrl"/], ["notifyKind: carrier-pigeon", { notifyKind: "carrier-pigeon" }, /"notifyKind" must be one of query, discord, slack, teams, google-chat, json/], @@ -854,7 +957,7 @@ test("loop-setup: GET /loop-setup lists the phases left for a spec and refuses a } // Saving through the route, then reading it back in a new request. - const save = await send({ review: true, fixMode: "smart", fix: ["critical"], commit: true, onQuestion: "stop", afterLast: "offer-finalize", quickCheck: "", notifyKind: "query", notifyUrl: "https://example.com/hook", notifyParam: "msg", notifyPhases: true, retryOnce: true, silenceMinutes: 30, phaseStrength: false, strengths: {} }); + const save = await send({ review: true, reviewRounds: 3, fixMode: "smart", fix: ["critical"], commit: true, onQuestion: "stop", afterLast: "offer-finalize", quickCheck: "", notifyKind: "query", notifyUrl: "https://example.com/hook", notifyParam: "msg", notifyPhases: true, retryOnce: true, silenceMinutes: 30, phaseStrength: false, strengths: {} }); assert.equal(save.status, 200, await save.clone().text()); const after = await get("?spec=specs/demo"); assert.equal(after.body.remembered, true); @@ -1024,7 +1127,7 @@ test("GET /loop-setup?agent= answers the loop agent's resolved strengths and thi // A save with picks reads back for its own spec; a pick for a phase that is not there is pruned. const entry = { review: true, fixMode: "smart", fix: ["critical"], commit: true, onQuestion: "guess", afterLast: "offer-finalize", quickCheck: "", - notifyKind: "query", notifyUrl: "", notifyParam: "message", notifyPhases: false, retryOnce: true, silenceMinutes: 20, phaseStrength: true, + notifyKind: "query", notifyUrl: "", notifyParam: "message", notifyPhases: false, retryOnce: true, silenceMinutes: 20, reviewRounds: 2, phaseStrength: true, strengths: { "specs/demo": [{ n: 2, name: "Two", strength: "best" }, { n: 9, name: "Gone", strength: "best" }] }, }; const save = await fetch(`${base}/loop-setup`, { method: "POST", headers: { "content-type": "application/json", cookie, origin: base, connection: "close" }, body: JSON.stringify(entry) }); @@ -1078,3 +1181,226 @@ test("loopSuggest: each bad field is refused with a message naming it", () => { assert.ok(got.problems.some((p) => pattern.test(p)), `${label}: ${got.problems.join(" | ") || "accepted"}`); } }); + +/* -------------------------------------- Review Loop rounds: open and report */ + +const ROUND_FLAGS = (scope) => ["--round", "2", "--role", "both", "--scope-file", scope]; + +function openRound(name = "round", flags = {}) { + const cwd = tempProject(name); + const scope = path.join(cwd, "scope.md"); + fs.writeFileSync(scope, "Scope: the branch diff\n"); + const args = ["open", "--workflow", "review", "--loop", "--no-open", "--round", String(flags.round ?? 2), "--role", flags.role ?? "both", "--scope-file", scope]; + const res = run(args, { cwd, extra: IN_APP }); + assert.equal(res.status, 0, res.stderr); + const stop = () => cli(["stop", "--session", res.json.sid, "--force"], { cwd, expectFail: true }); + return { cwd, sid: res.json.sid, session: res.json.session, scope, json: res.json, stop }; +} + +test("a Review Loop round opens only with --round, --role and --scope-file, each checked, exit 2 naming the flag", () => { + const cwd = tempProject("round-gate"); + const scope = path.join(cwd, "scope.md"); + fs.writeFileSync(scope, "x"); + const before = sessionCount(); + const base = ["open", "--workflow", "review", "--loop", "--no-open"]; + const cases = [ + [["--role", "both", "--scope-file", scope], /--round/], + [["--round", "2", "--scope-file", scope], /--role/], + [["--round", "2", "--role", "both"], /--scope-file/], + [["--round", "0", "--role", "both", "--scope-file", scope], /--round/], + [["--round", "x", "--role", "both", "--scope-file", scope], /--round/], + [["--round", "2", "--role", "boss", "--scope-file", scope], /--role/], + [["--round", "2", "--role", "both", "--scope-file", path.join(cwd, "nope.md")], /--scope-file/], + ]; + for (const [flags, pattern] of cases) { + const res = run([...base, ...flags], { cwd, extra: IN_APP }); + assert.equal(res.status, 2, flags.join(" ")); + assert.match(res.stderr, pattern); + } + assert.equal(sessionCount(), before, "no session folder was made"); +}); + +test("the round flags are refused on an Implement loop open and without --loop, and outside the app a round open exits 3", () => { + const cwd = tempProject("round-other"); + const scope = path.join(cwd, "scope.md"); + fs.writeFileSync(scope, "x"); + const withRound = ROUND_FLAGS(scope); + assert.equal(run(["open", "--workflow", "implement", "--loop", "--no-open", ...withRound], { cwd, extra: IN_APP }).status, 2); + assert.equal(run(["open", "--workflow", "review", "--no-open", ...withRound], { cwd, extra: IN_APP }).status, 2); + const outside = run(["open", "--workflow", "review", "--loop", "--no-open", ...withRound], { cwd }); + assert.equal(outside.status, 3); + assert.match(outside.stderr, /desktop app/); +}); + +test("a round session is stamped with its round, role and scope file, and its open names the round notes", () => { + const s = openRound("round-stamp", { round: 3, role: "reviewer" }); + try { + assert.deepEqual(readState(s.session).loop, { driving: true, round: 3, role: "reviewer", scopeFile: s.scope }); + assert.deepEqual(s.json.read, [path.join(path.dirname(CONSOLE_CLI), "notes", "review-loop.md")]); + const again = run(["open", "--resume", s.sid, "--workflow", "review", "--loop", "--no-open", "--round", "3", "--role", "reviewer", "--scope-file", s.scope], { cwd: s.cwd, extra: IN_APP }); + assert.equal(again.status, 0, again.stderr); + assert.equal(readState(s.session).loop.round, 3); + } finally { + s.stop(); + } + // An Implement loop keeps its stamp exactly as it was. + const impl = openLoop("implement", "round-impl"); + try { + assert.deepEqual(readState(impl.session).loop, { driving: true }); + } finally { + impl.stop(); + } +}); + +// A round session's state as post would see it: the stamp, and the report doc. +const roundState = (role = "both", extra = {}) => ({ + ...blankState({ sid: "s", workflow: "review", project: "p" }), + loop: { driving: true, round: 2, role, scopeFile: "scope.md" }, + docs: [{ id: "report", title: "Report", version: 1, stale: false, blocks: [{ id: "b", md: "Findings" }] }], + ...extra, +}); +const goodRound = (role = "both") => ({ + round: 2, + role, + result: "passed", + reason: null, + summary: "Fixed 2 warnings; 1 suggestion left", + report: "report", + review: { + critical: 0, + warning: 2, + suggestion: 1, + fixed: [{ title: "Close the file handle", file: "src/z.js", line: 12 }], + unfixed: [], + suggestions: [{ title: "Name the timer", file: "src/x.js" }], + }, + tests: { ran: true, passed: true, summary: "14 pass" }, + subject: "Close the file handle in z.js", +}); + +test("a roundOutcome is stored with its report doc in the session, once, for each role", () => { + assert.deepEqual(ROUND_ROLES, ["both", "reviewer", "fixer"]); + for (const role of ROUND_ROLES) { + const o = goodRound(role); + if (role === "reviewer") delete o.tests; + if (role === "fixer") delete o.report; + const got = tryPatch(roundState(role, role === "fixer" ? { docs: [] } : {}), { roundOutcome: o }); + assert.deepEqual(got.problems, [], role); + assert.deepEqual(got.next.roundOutcome, o); + } + const first = tryPatch(roundState(), { roundOutcome: goodRound() }); + const second = tryPatch(first.next, { roundOutcome: goodRound() }); + assert.match(second.problems.join(" "), /roundOutcome: was already posted/); +}); + +test("a roundOutcome with no report doc is refused naming roundOutcome.report", () => { + for (const role of ["both", "reviewer"]) { + const missing = tryPatch(roundState(role, { docs: [] }), { roundOutcome: goodRound(role) }); + assert.match(missing.problems.join(" "), /roundOutcome\.report must name a report doc already posted in this session/, role); + } + const wrong = tryPatch(roundState(), { roundOutcome: { ...goodRound(), report: "other" } }); + assert.match(wrong.problems.join(" "), /roundOutcome\.report/); +}); + +test("each bad roundOutcome field is refused with a message naming it", () => { + const mut = (fn, role = "both") => { + const o = goodRound(role); + fn(o); + return tryPatch(roundState(role), { roundOutcome: o }).problems.join(" | "); + }; + const cases = [ + ["round", (o) => (o.round = 3), /roundOutcome\.round/], + ["round type", (o) => (o.round = "2"), /roundOutcome\.round/], + ["role", (o) => (o.role = "fixer"), /roundOutcome\.role/], + ["result", (o) => (o.result = "maybe"), /roundOutcome\.result/], + ["reason when passed", (o) => (o.reason = "tests"), /roundOutcome\.reason/], + ["reason when failed", (o) => ((o.result = "failed"), (o.reason = "nope")), /roundOutcome\.reason/], + ["summary empty", (o) => (o.summary = ""), /roundOutcome\.summary/], + ["summary long", (o) => (o.summary = "x".repeat(201)), /roundOutcome\.summary/], + ["summary lines", (o) => (o.summary = "a\nb"), /roundOutcome\.summary/], + ["subject long", (o) => (o.subject = "x".repeat(101)), /roundOutcome\.subject/], + ["review missing", (o) => delete o.review, /roundOutcome\.review /], + ["review count", (o) => (o.review.warning = -1), /roundOutcome\.review\.warning/], + ["review list", (o) => (o.review.fixed = "none"), /roundOutcome\.review\.fixed/], + ["review list size", (o) => (o.review.unfixed = Array.from({ length: 51 }, () => ({ title: "t", file: "a.js" }))), /roundOutcome\.review\.unfixed/], + ["finding file", (o) => (o.review.fixed[0].file = "../x"), /roundOutcome\.review\.fixed\[0\]\.file/], + ["finding line", (o) => (o.review.fixed[0].line = 0), /roundOutcome\.review\.fixed\[0\]\.line/], + ["tests missing", (o) => delete o.tests, /roundOutcome\.tests /], + ["tests passed", (o) => (o.tests.passed = "yes"), /roundOutcome\.tests\.passed/], + ["completion marker", (o) => (o.summary = "TASK_COMPLETE"), /roundOutcome\.summary/], + ]; + for (const [label, fn, pattern] of cases) assert.match(mut(fn), pattern, label); +}); + +test("a roundOutcome outside a round session is refused, and a loopOutcome in a round session is refused", () => { + const plain = tryPatch({ ...blankState({ sid: "s", workflow: "review", project: "p" }) }, { roundOutcome: goodRound() }); + assert.match(plain.problems.join(" "), /roundOutcome: is only accepted in a Review Loop round session/); + const impl = tryPatch(loopState(), { roundOutcome: goodRound() }); + assert.match(impl.problems.join(" "), /roundOutcome: is only accepted in a Review Loop round session/); + const viaLoop = tryPatch(roundState(), { loopOutcome: goodOutcome() }); + assert.match(viaLoop.problems.join(" "), /a round reports roundOutcome, not loopOutcome/); +}); + +test("blankState holds no roundOutcome and a hop drops it", () => { + assert.equal("roundOutcome" in blankState({ sid: "s", workflow: "review", project: "p" }), false); + const hopped = switchWorkflow(roundState("both", { roundOutcome: goodRound() }), { workflow: "plan", title: "t", specDir: "" }); + assert.equal("roundOutcome" in hopped, false); + assert.equal("loop" in hopped, false); +}); + +test("a resume drops a stored roundOutcome and report doc when the round or role changes or the lock goes, and keeps them otherwise", () => { + const s = openRound("round-resume", { round: 2, role: "reviewer" }); + const resume = (flags) => run(["open", "--resume", s.sid, "--no-open", ...flags], { cwd: s.cwd, extra: IN_APP }); + const loopFlags = (round, role) => ["--workflow", "review", "--loop", "--round", String(round), "--role", role, "--scope-file", s.scope]; + const seed = () => { + const o = goodRound("reviewer"); + delete o.tests; + const res = post(s, { docs: [{ id: "report", title: "Report", blocks: [{ id: "b1", md: "Findings" }] }], roundOutcome: o }); + assert.equal(res.status, 0, res.stderr); + assert.ok(readState(s.session).roundOutcome, "seeded"); + }; + try { + seed(); + assert.equal(resume(loopFlags(2, "reviewer")).status, 0); + assert.ok(readState(s.session).roundOutcome, "the same round and role keeps its report"); + assert.ok(readState(s.session).docs.some((d) => d.id === "report")); + assert.equal(resume(loopFlags(2, "fixer")).status, 0); + let state = readState(s.session); + assert.equal("roundOutcome" in state, false, "a new role starts without the old report"); + assert.equal(state.docs.some((d) => d.id === "report"), false, "and without the old report doc"); + assert.equal(state.loop.role, "fixer"); + // The fixer's own report is now accepted. + const o = goodRound("fixer"); + delete o.report; + assert.equal(post(s, { roundOutcome: o }).status, 0); + assert.equal(resume(loopFlags(3, "fixer")).status, 0); + assert.equal("roundOutcome" in readState(s.session), false, "a new round starts without the old report"); + seedFixer(s); + assert.equal(resume(["--workflow", "review"]).status, 0); + state = readState(s.session); + assert.equal("roundOutcome" in state, false, "a resume without --loop drops the report"); + assert.equal("loop" in state, false); + } finally { + s.stop(); + } + function seedFixer(sess) { + const o = goodRound("fixer"); + o.round = 3; + delete o.report; + const res = run(["open", "--resume", sess.sid, "--no-open", ...loopFlags(3, "fixer")], { cwd: sess.cwd, extra: IN_APP }); + assert.equal(res.status, 0); + assert.equal(post(sess, { roundOutcome: o }).status, 0); + } +}); + +test("a round session's scope file is stored as an absolute path", () => { + const cwd = tempProject("round-scope"); + fs.writeFileSync(path.join(cwd, "scope.md"), "x"); + const res = run(["open", "--workflow", "review", "--loop", "--no-open", "--round", "1", "--role", "both", "--scope-file", "scope.md"], { cwd, extra: IN_APP }); + try { + assert.equal(res.status, 0, res.stderr); + assert.equal(readState(res.json.session).loop.scopeFile, path.join(cwd, "scope.md")); + } finally { + cli(["stop", "--session", res.json.sid, "--force"], { cwd, expectFail: true }); + } +}); diff --git a/scripts/test-web-console-page-loop.mjs b/scripts/test-web-console-page-loop.mjs index eaaa661..3e8925d 100644 --- a/scripts/test-web-console-page-loop.mjs +++ b/scripts/test-web-console-page-loop.mjs @@ -956,3 +956,37 @@ test("a pick for an unmapped word, or a phase left out, keeps that row as it was assert.deepEqual((await strengthRows(s)).map((r) => r.pick), ["", "thrifty"]); assert.equal(await s.page.locator(".loop-strength-why").count(), 0, "no reason shows for a pick that was not applied"); }); + +test("Review rounds per phase shows under Review, is off with Review off, and goes out with the setup", async (t) => { + const s = await openSetup(t); + const rounds = s.page.locator("#loop-review-rounds"); + const field = s.page.locator(".loop-field", { hasText: "Review each phase with a fresh agent" }); + assert.equal(await field.locator("#loop-review-rounds").count(), 1, "the number sits in the Review field"); + assert.equal(await rounds.inputValue(), "2", "two rounds by default"); + assert.deepEqual(await rounds.evaluate((el) => [el.min, el.max, el.disabled]), ["0", "6", false]); + assert.equal(await field.getByText("Applies only with Review on").count(), 0, "no hint while Review is on"); + + await rounds.fill("4"); + await s.page.locator("#loop-review").uncheck(); + assert.equal(await rounds.isDisabled(), true, "Review off disables the field"); + assert.equal(await field.getByText("Applies only with Review on").count(), 1); + assert.equal(await rounds.inputValue(), "4", "the number is kept while it is off"); + + await s.page.locator("#loop-review").check(); + assert.equal(await rounds.isDisabled(), false); + const body = await s.page.evaluate(async () => { + const { page } = await import(new URL("state.js", document.baseURI).href); + const { setupBody } = await import(new URL("screens/loop-setup.js", document.baseURI).href); + return setupBody(page.loopSetup.form, page.loopSetup); + }); + assert.equal(body.reviewRounds, 4, "the number is in the posted body"); + const saved = await s.page.evaluate(async () => { + const { page } = await import(new URL("state.js", document.baseURI).href); + const { setupBody } = await import(new URL("screens/loop-setup.js", document.baseURI).href); + const res = await fetch("/loop-setup", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(setupBody(page.loopSetup.form, page.loopSetup)) }); + return { status: res.status, body: await res.json() }; + }); + assert.equal(saved.status, 200, JSON.stringify(saved.body)); + const reread = await s.page.evaluate(async () => (await fetch("/loop-setup")).json()); + assert.equal(reread.reviewRounds, 4, "remembered with the rest of the setup"); +}); diff --git a/scripts/test-web-console-page-review-loop.mjs b/scripts/test-web-console-page-review-loop.mjs new file mode 100644 index 0000000..9bbf4cc --- /dev/null +++ b/scripts/test-web-console-page-review-loop.mjs @@ -0,0 +1,421 @@ +// Page tests for the Review Loop's setup screen. The dashboard card that opens +// it only shows inside the desktop app, so these open the screen through its +// own module, then drive the real page, the way test-web-console-page-loop.mjs +// does for the Implementation Loop's. Run with: +// node --test scripts/test-web-console-page-review-loop.mjs + +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { pageSuite, openSession, tempProject, textOf } from "./page-test-helpers.mjs"; +import { MODELS_DIR } from "./web-console-test-helpers.mjs"; + +const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url))); + +const suite = pageSuite(test); + +const PROJECT = { + "AGENTS.md": "# AGENTS.md\n\nA small demo project.\n", + "specs/ready/overview.md": "# Overview\n\n## Phase Checklist\n\n- [ ] Phase 1: One\n", + "specs/ready/phase-1.md": "# Phase 1\n\n- [ ] **Task 1.1:** One\n", +}; + +const MENU = { menu: { note: "Ready when you are." }, agent: { status: "waiting" } }; + +const FACTS = { agent: "claude", agentLabel: "Claude Code", helpers: true, strengthsMapped: true, running: false, promptSupport: true, notifyKind: "query", notifyUrl: "", notifyParam: "message" }; + +// Stands a real window in for the app that frames the page, listening to what +// the page tells it; the returned function replies the way the app does. +async function frameInFakeApp(s) { + await s.page.evaluate(() => { + const frame = document.createElement("iframe"); + frame.hidden = true; + document.body.appendChild(frame); + const app = frame.contentWindow; + window.__told = []; + app.postMessage = (message) => window.__told.push(message); + Object.defineProperty(window, "parent", { value: app, configurable: true }); + }); + return (data) => + s.page.evaluate((message) => { + window.dispatchEvent(new MessageEvent("message", { source: window.parent, data: message })); + }, data); +} + +// The installed copy of the shipped model menu, with its strengths, as install.js drops it. +function installShippedModels() { + const shipped = path.join(MODELS_DIR, "bin", "models.json"); + fs.mkdirSync(path.dirname(shipped), { recursive: true }); + fs.copyFileSync(path.join(ROOT, "src", "launcher", "models.json"), shipped); +} + +async function openReview(t, { spec = null } = {}) { + installShippedModels(); + const browser = await suite.browser(); + const s = await openSession(browser, { t, workflow: "dashboard", payload: MENU, project: tempProject(PROJECT) }); + const skip = s.page.getByRole("button", { name: "Skip the intro" }); + await skip.click(); + await skip.waitFor({ state: "hidden" }); + await s.page.locator("#main").getByRole("heading", { name: "What are we doing today?" }).waitFor(); + const welcomeDone = s.page.getByRole("button", { name: "Start building" }); + if (await welcomeDone.isVisible()) { + await welcomeDone.click(); + await welcomeDone.waitFor({ state: "hidden" }); + } + const answer = await frameInFakeApp(s); + await s.page.evaluate(async (pick) => { + const m = await import(new URL("screens/review-loop-setup.js", document.baseURI).href); + await m.openReviewLoopSetup(pick); + }, spec); + await s.page.locator("#review-loop-start").waitFor(); + return { ...s, answer }; +} + +const radios = (s, name) => s.page.locator(`input[name="${name}"]`).evaluateAll((all) => all.map((r) => [r.id, r.checked])); + +test("the screen asks the app for its facts and lists its fields in order, with their defaults", async (t) => { + const s = await openReview(t); + assert.ok(await s.page.evaluate(() => window.__told.some((m) => m.plan2code === "review-loop-facts")), "the facts were asked for"); + + const labels = await s.page.locator(".loop-label").allInnerTexts(); + assert.deepEqual(labels, ["What to review", "Round cap", "Commit", "Suggestions", "Strength", "Reviewers", "If a round goes quiet", "Send a notification"]); + assert.deepEqual(await radios(s, "reviewscope"), [["loop-reviewscope-branch", true], ["loop-reviewscope-uncommitted", false], ["loop-reviewscope-spec", false]]); + assert.equal(await s.page.locator("#review-loop-spec").count(), 0, "no spec picker until the spec scope is chosen"); + assert.equal(await s.page.locator("#review-loop-cap").inputValue(), "3"); + assert.equal(await s.page.locator("#review-loop-commit").isChecked(), true, "commit each round is on"); + assert.equal(await s.page.locator("#review-loop-suggestions").isChecked(), false, "Suggestions on their own are off"); + assert.equal(await s.page.locator("#loop-silence").inputValue(), "20"); + assert.equal(await s.page.locator("#loop-notify-url").inputValue(), ""); + assert.equal(await s.page.locator("#review-loop-notify-rounds").isVisible(), false, "no address, no round messages to choose"); + + await s.page.locator("#loop-notify-url").fill("https://example.com/hook"); + const rounds = s.page.locator("#review-loop-notify-rounds"); + assert.equal(await rounds.isVisible(), true); + assert.equal(await rounds.isChecked(), false, "a message per round is opt-in"); + assert.match(await textOf(s.page.locator("label", { has: rounds })), /Also tell me when each round finishes/); +}); + +test("a spec picked on the dashboard fills the picker and the spec scope", async (t) => { + const s = await openReview(t, { spec: { dir: "specs/ready" } }); + assert.deepEqual(await radios(s, "reviewscope"), [["loop-reviewscope-branch", false], ["loop-reviewscope-uncommitted", false], ["loop-reviewscope-spec", true]]); + assert.equal(await s.page.locator("#review-loop-spec").inputValue(), "specs/ready"); + // The pre-fill is not a save. + const saved = await s.page.evaluate(async () => (await fetch("/review-loop-setup")).json()); + assert.equal(saved.remembered, false); + assert.equal(saved.scope, "branch"); + + await s.page.locator("#review-loop-spec").selectOption(""); + await s.answer({ plan2code: "review-loop-facts", facts: FACTS }); + await s.page.getByText("Pick the spec whose work to review.").waitFor(); + assert.equal(await s.page.locator("#review-loop-start").isDisabled(), true, "the spec scope needs a spec"); +}); + +test("uncommitted changes need a tick before Start, and the tick is what the app is told", async (t) => { + const s = await openReview(t); + await s.answer({ plan2code: "review-loop-facts", facts: FACTS }); + const start = s.page.locator("#review-loop-start"); + await s.page.waitForFunction(() => !document.getElementById("review-loop-start").disabled); + assert.equal(await s.page.locator("#review-loop-agree").count(), 0, "a clean tree has nothing to agree to"); + + // The tree is dirty: two files changed (what the console's scan counts). + await s.page.evaluate(async () => { + const { page, redraw } = await import(new URL("state.js", document.baseURI).href); + page.reviewLoopSetup.facts.pending = 2; + redraw(); + }); + const tick = s.page.locator("#review-loop-agree"); + await tick.waitFor(); + assert.match(await textOf(s.page.locator("label", { has: tick })), /Commit my current changes first as Work before Review Loop/); + assert.equal(await tick.isChecked(), false); + assert.equal(await start.isDisabled(), true, "Start waits on the tick"); + assert.match(await textOf(s.page.locator(".loop-why")), /2 uncommitted changes need your say-so/); + + await tick.check(); + assert.equal(await start.isDisabled(), false); + await start.click(); + await s.page.waitForFunction(() => window.__told.some((m) => m.plan2code === "review-loop-start")); + const sent = await s.page.evaluate(() => window.__told.find((m) => m.plan2code === "review-loop-start")); + assert.deepEqual(sent.setup, { scope: "branch", spec: "", cap: 3, commit: true, suggestions: false, strength: "", silenceMinutes: 20, notifyRounds: false, preRunCommitAgreed: true }); + const saved = await s.page.evaluate(async () => (await fetch("/review-loop-setup")).json()); + assert.equal(saved.remembered, true, "the picks were saved first"); + assert.equal("preRunCommitAgreed" in saved, false, "the agreement is never remembered"); + + await s.page.getByText("Waiting for the app's confirm...").waitFor(); + await s.answer({ plan2code: "review-loop-start-result", ok: false, started: false, error: "A loop is already running." }); + await s.page.getByText("A loop is already running.").waitFor(); + assert.equal(await start.isDisabled(), false, "a refusal shows inline and gives the button back"); +}); + +test("turning commits off drops the tick, and the app is told the work needs no agreement", async (t) => { + const s = await openReview(t); + await s.answer({ plan2code: "review-loop-facts", facts: FACTS }); + await s.page.evaluate(async () => { + const { page, redraw } = await import(new URL("state.js", document.baseURI).href); + page.reviewLoopSetup.facts.pending = 1; + redraw(); + }); + await s.page.locator("#review-loop-agree").waitFor(); + await s.page.locator("#review-loop-commit").uncheck(); + assert.equal(await s.page.locator("#review-loop-agree").count(), 0); + await s.page.locator("#review-loop-start").click(); + await s.page.waitForFunction(() => window.__told.some((m) => m.plan2code === "review-loop-start")); + const sent = await s.page.evaluate(() => window.__told.find((m) => m.plan2code === "review-loop-start")); + assert.equal(sent.setup.commit, false); + assert.equal(sent.setup.preRunCommitAgreed, false); +}); + +test("the hands-off line and the reviewer note are on the screen", async (t) => { + const s = await openReview(t); + const main = await textOf(s.page.locator(".review-loop-setup")); + assert.ok(main.includes("Please do not edit this project's files while rounds run: anything changed goes into the round.")); + assert.ok(main.includes("Each round's reviewer runs fresh, whatever the Subagents switch says; the switch still governs other helpers.")); +}); + +test("an agent with no strengths mapped grays the strength choice and links to Agents & models", async (t) => { + const s = await openReview(t); + await s.answer({ plan2code: "review-loop-facts", facts: { ...FACTS, agent: "nonesuch", strengthsMapped: false } }); + const note = s.page.locator(".loop-strength-none"); + await note.waitFor(); + assert.match(await textOf(note), /This agent has no strengths mapped yet\./); + assert.equal(await s.page.locator("#review-loop-strength").count(), 0, "no picker to choose from"); + await note.getByRole("button", { name: "Map them in Agents & models" }).click(); + await s.page.locator("#prefs-modal[open], dialog[open]").first().waitFor(); +}); + +test("an agent with strengths shows the choice, and a running loop holds Start", async (t) => { + const s = await openReview(t); + await s.answer({ plan2code: "review-loop-facts", facts: FACTS }); + await s.page.locator("#review-loop-strength").waitFor(); + const options = await s.page.locator("#review-loop-strength option").allInnerTexts(); + assert.equal(options[0], "Match my session"); + assert.equal(await s.page.locator("#review-loop-strength").inputValue(), ""); + + await s.answer({ plan2code: "review-loop-facts", facts: { ...FACTS, running: true } }); + await s.page.getByText(/A loop is already running in this window/).waitFor(); + assert.equal(await s.page.locator("#review-loop-start").isDisabled(), true); +}); + +/* ---------------------------------------------------------------- the end */ + +const DIFF = [ + "diff --git a/src/app.js b/src/app.js", + "index 1111111..2222222 100644", + "--- a/src/app.js", + "+++ b/src/app.js", + "@@ -1,2 +1,3 @@", + " one", + "-two", + "+TWO", + "+three", + "", +].join("\n"); + +const REPORT_DOC = { id: "report", title: "Review Loop report", blocks: [{ id: "r1", md: "# Report\n\nTwo rounds ran." }] }; +const PARTIAL_DOC = { id: "partial", title: "Partial changes", blocks: [{ id: "p1", diff: "partial.diff" }] }; + +const END = { + kind: "review", + line: "No Critical or Warning findings are left.", + reason: "clean", + report: "report", + canContinue: false, + canSquash: false, + can: [], +}; + +const SUGGESTIONS = [ + { id: "s1", title: "Rename the helper", file: "src/a.js", line: 12 }, + { id: "s2", title: "Drop the unused import", file: "" }, +]; + +// A review session as the app's window shows it, the app faked, with `end` +// posted along with the report and partial diff docs. +async function openEnd(t, end) { + const s = await openSession(await suite.browser(), { + t, + workflow: "implement", + open: ["--loop"], + env: { PLAN2CODE_IN_APP: "1" }, + payload: { title: "demo", agent: { status: "working" } }, + project: tempProject(PROJECT), + }); + const answer = await frameInFakeApp(s); + fs.writeFileSync(path.join(s.session, "partial.diff"), DIFF); + s.post({ docs: [REPORT_DOC, PARTIAL_DOC], loopEnd: end, agent: { status: "waiting" } }); + await s.page.locator(".review-end").waitFor(); + return { ...s, answer }; +} + +const told = (s, kind) => s.page.evaluate((k) => window.__told.filter((m) => m.plan2code === k), kind); +const buttons = (s) => s.page.locator(".review-end button").evaluateAll((all) => all.map((b) => b.id).filter(Boolean)); + +test("the end screen heads each reason in words, with the line under it and the report behind a button", async (t) => { + const s = await openEnd(t, END); + const headings = { clean: "Clean", cap: "Stopped at the round cap", person: "Stopped by you", failed: "Failed" }; + for (const [reason, words] of Object.entries(headings)) { + s.post({ loopEnd: { ...END, reason, line: `Line for ${reason}` } }); + await s.page.getByText(`Line for ${reason}`).waitFor(); + assert.equal(await textOf(s.page.locator(".review-end-heading")), words); + } + await s.page.getByRole("button", { name: "Read the full report" }).click(); + await s.page.getByText("Two rounds ran.").waitFor(); +}); + +test("Continue shows only when allowed, says Run one more round at the cap, and is held while the app answers", async (t) => { + const s = await openEnd(t, END); + assert.equal(await s.page.locator("#review-end-continue").count(), 0, "nothing to continue after a clean run"); + + s.post({ loopEnd: { ...END, reason: "person", line: "You stopped it", canContinue: true } }); + const go = s.page.locator("#review-end-continue"); + await go.waitFor(); + assert.equal(await textOf(go), "Continue"); + + s.post({ loopEnd: { ...END, reason: "cap", line: "The cap was reached", canContinue: true } }); + await s.page.getByRole("button", { name: "Run one more round" }).waitFor(); + + await s.page.locator("#review-end-continue").click(); + await s.page.waitForFunction(() => window.__told.some((m) => m.plan2code === "review-loop-continue")); + assert.equal(await s.page.locator("#review-end-continue").isDisabled(), true, "held while the app answers"); + await s.answer({ plan2code: "review-loop-continue-result", ok: false, error: "A loop is already running." }); + await s.page.getByText("A loop is already running.").waitFor(); + assert.equal(await s.page.locator("#review-end-continue").isDisabled(), false, "an error gives the button back"); +}); + +test("after Stop now the partial diff, its stats, Keep and Discard show and Continue is hidden", async (t) => { + const s = await openEnd(t, { + ...END, + reason: "person", + line: "You stopped it", + canContinue: true, + partial: { files: 1, added: 2, removed: 1, diff: "partial" }, + }); + await s.page.locator(".review-end-diff .diff-view").waitFor(); + assert.match(await textOf(s.page.locator(".review-end-stats")), /1 file changed, \+2 -1/); + assert.match(await textOf(s.page.locator(".review-end-diff")), /app\.js/); + assert.equal(await s.page.locator("#review-end-continue").count(), 0, "Continue waits for Keep or Discard"); + assert.equal(await s.page.locator("#review-end-signoff").isDisabled(), true, "Sign off waits for Keep or Discard too"); + assert.match(await textOf(s.page.locator(".review-end")), /Keep or discard the partial changes first/); + + await s.page.locator("#review-end-keep").click(); + await s.page.waitForFunction(() => window.__told.some((m) => m.plan2code === "review-loop-partial")); + assert.deepEqual(await told(s, "review-loop-partial"), [{ plan2code: "review-loop-partial", keep: true }]); + await s.answer({ plan2code: "review-loop-partial-result", ok: false, error: "Nothing to keep." }); + await s.page.getByText("Nothing to keep.").waitFor(); + await s.page.locator("#review-end-discard").click(); + await s.page.waitForFunction(() => window.__told.filter((m) => m.plan2code === "review-loop-partial").length === 2); + assert.equal((await told(s, "review-loop-partial"))[1].keep, false); + + // The app answers with a new end without the partial: Continue comes back. + s.post({ loopEnd: { ...END, reason: "person", line: "You stopped it", canContinue: true } }); + await s.page.locator("#review-end-continue").waitFor(); + assert.equal(await s.page.locator("#review-end-keep").count(), 0); +}); + +test("a second ending with the same words after Continue starts with live buttons", async (t) => { + const again = { ...END, reason: "cap", line: "Stopped at the cap", canContinue: true }; + const s = await openEnd(t, again); + await s.page.locator("#review-end-continue").click(); + await s.page.waitForFunction(() => window.__told.some((m) => m.plan2code === "review-loop-continue")); + assert.equal(await s.page.locator("#review-end-continue").isDisabled(), true, "the press waits on the app"); + // The app starts another round (a blank session, no end card), then it ends the same way again. + await s.page.evaluate(async () => { + const { page, redraw } = await import(new URL("state.js", document.baseURI).href); + window.__keptEnd = page.S.loopEnd; + delete page.S.loopEnd; + redraw(); + }); + await s.page.locator("#review-end-continue").waitFor({ state: "detached" }); + await s.page.evaluate(async () => { + const { page, redraw } = await import(new URL("state.js", document.baseURI).href); + page.S.loopEnd = window.__keptEnd; + redraw(); + }); + await s.page.locator("#review-end-continue").waitFor(); + assert.equal(await s.page.locator("#review-end-continue").isEnabled(), true, "Continue is live again"); + assert.equal(await s.page.locator("#review-end-signoff").isEnabled(), true, "Sign off is live again"); +}); + +test("the Suggestions pick starts unticked, shows only with suggestions, and what is ticked is what Sign off sends", async (t) => { + const s = await openEnd(t, END); + assert.equal(await s.page.locator(".review-end-suggestions").count(), 0, "no pick without suggestions"); + assert.equal(await s.page.locator("#review-end-signoff").isEnabled(), true, "Sign off is always there"); + + s.post({ loopEnd: { ...END, line: "With suggestions", suggestions: SUGGESTIONS } }); + await s.page.locator(".review-end-suggestions").waitFor(); + assert.deepEqual( + await s.page.locator(".review-end-pick input").evaluateAll((all) => all.map((i) => [i.id, i.checked])), + [["review-end-pick-s1", false], ["review-end-pick-s2", false]] + ); + assert.match(await textOf(s.page.locator(".review-end-pick").first()), /Rename the helper\s*src\/a\.js:12/); + await s.page.locator("#review-end-pick-s2").check(); + // A redraw keeps the tick. + await s.page.evaluate(async () => (await import(new URL("state.js", document.baseURI).href)).redraw()); + assert.equal(await s.page.locator("#review-end-pick-s2").isChecked(), true); + + await s.page.locator("#review-end-signoff").click(); + await s.page.waitForFunction(() => window.__told.some((m) => m.plan2code === "review-loop-sign-off")); + assert.deepEqual(await told(s, "review-loop-sign-off"), [{ plan2code: "review-loop-sign-off", picks: ["s2"], squash: false }]); + assert.equal(await s.page.locator("#review-end-signoff").isDisabled(), true); + await s.answer({ plan2code: "review-loop-sign-off-result", ok: false, error: "Something went wrong." }); + await s.page.getByText("Something went wrong.").waitFor(); +}); + +test("what was ticked survives Keep or Discard reposting the end without the partial changes", async (t) => { + const withPartial = { ...END, reason: "person", line: "You stopped it", canSquash: true, suggestions: SUGGESTIONS, partial: { files: 1, added: 2, removed: 1, diff: "partial" } }; + const s = await openEnd(t, withPartial); + await s.page.locator("#review-end-pick-s2").check(); + await s.page.locator("#review-end-squash").check(); + const { partial, ...settled } = withPartial; + s.post({ loopEnd: { ...settled, canContinue: true } }); + await s.page.locator("#review-end-continue").waitFor(); + assert.equal(await s.page.locator("#review-end-pick-s2").isChecked(), true, "the pick is kept"); + assert.equal(await s.page.locator("#review-end-squash").isChecked(), true, "the squash switch is kept"); + assert.equal(await s.page.locator("#review-end-signoff").isEnabled(), true, "Sign off is back"); +}); + +test("the squash switch shows only when canSquash, starts off, and is sent with Sign off", async (t) => { + const s = await openEnd(t, END); + assert.equal(await s.page.locator("#review-end-squash").count(), 0); + + s.post({ loopEnd: { ...END, line: "Can squash", canSquash: true } }); + const sw = s.page.locator("#review-end-squash"); + await sw.waitFor(); + assert.equal(await sw.isChecked(), false); + assert.match(await textOf(s.page.locator("label", { has: sw })), /Squash the round commits into one/); + await sw.check(); + await s.page.locator("#review-end-signoff").click(); + await s.page.waitForFunction(() => window.__told.some((m) => m.plan2code === "review-loop-sign-off")); + assert.deepEqual(await told(s, "review-loop-sign-off"), [{ plan2code: "review-loop-sign-off", picks: [], squash: true }]); +}); + +test("the finished screen offers PR Prep, Fix what's left by hand when something is open, and the dashboard", async (t) => { + const done = { ...END, line: "Signed off", signedOff: true, note: "Squashed 3 round commits into one." }; + const s = await openEnd(t, { ...done, open: [{ title: "Unchecked input", file: "src/b.js", line: 9 }] }); + assert.deepEqual(await buttons(s), ["review-end-pr-prep", "review-end-quick-task", "review-end-dashboard"]); + assert.equal(await textOf(s.page.locator(".review-end-heading")), "Signed off"); + assert.match(await textOf(s.page.locator(".review-end-note")), /Squashed 3 round commits into one\./); + assert.equal(await s.page.locator("#review-end-signoff").count(), 0, "no sign-off after sign-off"); + + await s.page.locator("#review-end-quick-task").click(); + await s.page.waitForFunction(() => window.__told.some((m) => m.plan2code === "review-loop-next")); + assert.deepEqual(await told(s, "review-loop-next"), [{ plan2code: "review-loop-next", next: "quick-task" }]); + assert.equal(await s.page.locator("#review-end-pr-prep").isDisabled(), true, "all held while the app answers"); + await s.answer({ plan2code: "review-loop-next-result", ok: false, error: "Could not start it." }); + await s.page.getByText("Could not start it.").waitFor(); + await s.page.locator("#review-end-pr-prep").click(); + await s.page.waitForFunction(() => window.__told.filter((m) => m.plan2code === "review-loop-next").length === 2); + assert.equal((await told(s, "review-loop-next"))[1].next, "pr-prep"); + await s.answer({ plan2code: "review-loop-next-result", ok: false, error: "Nope." }); + await s.page.locator("#review-end-dashboard").click(); + await s.page.waitForFunction(() => window.__told.some((m) => m.plan2code === "loop-dashboard")); +}); + +test("Fix what's left by hand is hidden when nothing is open", async (t) => { + const s = await openEnd(t, { ...END, signedOff: true, line: "Signed off" }); + assert.deepEqual(await buttons(s), ["review-end-pr-prep", "review-end-dashboard"]); + s.post({ loopEnd: { ...END, signedOff: true, line: "Signed off", open: [] } }); + await s.page.locator("#review-end-pr-prep").waitFor(); + assert.equal(await s.page.locator("#review-end-quick-task").count(), 0); +}); diff --git a/scripts/test-web-console-review-loop.mjs b/scripts/test-web-console-review-loop.mjs new file mode 100644 index 0000000..4184e1e --- /dev/null +++ b/scripts/test-web-console-review-loop.mjs @@ -0,0 +1,199 @@ +// Web console tests: the Review Loop's setup store and its route. Run with: +// node --test scripts/test-web-console-review-loop.mjs +// +// The store (review-loop-setup.mjs) keeps one entry per project in +// review-loop-setup.json; GET and POST /review-loop-setup serve it. The +// store fixes its file at import time from PLAN2CODE_CONSOLE_HOME, so it runs +// in a child process here, as test-web-console-loop.mjs does for loop-setup.mjs. + +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import { pathToFileURL } from "node:url"; +import { ROOT, ENV, HOME, cli, sessionUrl } from "./web-console-test-helpers.mjs"; + +const APP_VARS = ["PLAN2CODE_IN_APP", "PLAN2CODE_EMBED_ORIGIN", "PLAN2CODE_APP_ANNOUNCE", "PLAN2CODE_APP_TOKEN", "PLAN2CODE_CONSOLE_SID", "PLAN2CODE_LOOP_STRENGTH"]; +const SETUP_PATH = path.join(HOME, "review-loop-setup.json"); +const LOOP_SETUP_PATH = path.join(HOME, "loop-setup.json"); +const STORE_URL = pathToFileURL(path.join(ROOT, "src", "web-console", "review-loop-setup.mjs")).href; + +function cleanEnv() { + const env = { ...ENV }; + for (const key of APP_VARS) delete env[key]; + return env; +} + +// Runs `fn(m, args)` in a child process where m is review-loop-setup.mjs. `fn` +// must be self-contained: it is sent as source text. Returns its JSON result. +function inStore(fn, args = {}) { + const code = + `const m = await import(${JSON.stringify(STORE_URL)});` + + `const out = await (${fn.toString()})(m, ${JSON.stringify(args)});` + + "console.log(JSON.stringify(out));"; + const res = spawnSync(process.execPath, ["--input-type=module", "-e", code], { env: cleanEnv(), encoding: "utf8", cwd: ROOT }); + assert.equal(res.status, 0, res.stderr); + return JSON.parse(String(res.stdout).trim().split("\n").pop()); +} + +const projectA = path.join(HOME, "review-store-a"); +const projectB = path.join(HOME, "review-store-b"); + +test("review-loop-setup: a new project reads as the defaults with remembered false, and nothing is written", () => { + fs.rmSync(SETUP_PATH, { force: true }); + const got = inStore((m, { project }) => ({ setup: m.readReviewLoopSetup(project), defaults: m.REVIEW_LOOP_DEFAULTS }), { project: projectA }); + assert.deepEqual(got.setup, { ...got.defaults, remembered: false }); + assert.deepEqual(got.defaults, { scope: "branch", spec: "", cap: 3, commit: true, suggestions: false, strength: "", silenceMinutes: 20, notifyRounds: false }); + assert.equal(fs.existsSync(SETUP_PATH), false, "reading never creates the file"); +}); + +test("review-loop-setup: a save reads back per project and keeps another project's entry", () => { + fs.rmSync(SETUP_PATH, { force: true }); + inStore( + (m, { a, b }) => { + m.saveReviewLoopSetup(a, { ...m.REVIEW_LOOP_DEFAULTS, cap: 5, suggestions: true, scope: "spec", spec: "specs/demo", strength: "best" }); + m.saveReviewLoopSetup(b, { ...m.REVIEW_LOOP_DEFAULTS, cap: 2, notifyRounds: true }); + return null; + }, + { a: projectA, b: projectB } + ); + const got = inStore((m, { a, b }) => ({ a: m.readReviewLoopSetup(a), b: m.readReviewLoopSetup(b) }), { a: projectA, b: projectB }); + assert.equal(got.a.cap, 5); + assert.equal(got.a.suggestions, true); + assert.equal(got.a.scope, "spec"); + assert.equal(got.a.spec, "specs/demo"); + assert.equal(got.a.strength, "best"); + assert.equal(got.a.remembered, true); + assert.equal(got.b.cap, 2); + assert.equal(got.b.notifyRounds, true); + const file = JSON.parse(fs.readFileSync(SETUP_PATH, "utf8")); + assert.equal(file.schema, 1); + assert.equal(Object.keys(file.projects).length, 2); + for (const entry of Object.values(file.projects)) assert.match(entry.saved, /^\d{4}-\d\d-\d\dT/); +}); + +test("review-loop-setup: unknown keys and out-of-range values are refused with the problem named", () => { + fs.rmSync(SETUP_PATH, { force: true }); + const problems = (patch) => inStore((m, { patch }) => m.reviewLoopSetupProblems({ ...m.REVIEW_LOOP_DEFAULTS, ...patch }), { patch }); + assert.deepEqual(problems({}), []); + assert.match(problems({ notifyUrl: "https://x.example/" }).join(), /"notifyUrl" is not a setup field/, "the notify address is the loop setup's, never kept here"); + assert.match(problems({ cap: 0 }).join(), /"cap" must be a whole number from 1 to 6/); + assert.match(problems({ cap: 7 }).join(), /"cap"/); + assert.match(problems({ cap: 2.5 }).join(), /"cap"/); + assert.deepEqual(problems({ cap: 1 }), []); + assert.deepEqual(problems({ cap: 6 }), []); + assert.match(problems({ silenceMinutes: 0 }).join(), /"silenceMinutes" must be a whole number from 1 to 60/); + assert.match(problems({ silenceMinutes: 61 }).join(), /"silenceMinutes"/); + assert.match(problems({ scope: "everything" }).join(), /"scope" must be one of branch, uncommitted, spec/); + for (const spec of ["demo", "specs/", "specs/a/b", "specs/.hidden", "../x", 3]) { + assert.match(problems({ spec }).join(), /"spec" must be empty or a folder directly under specs\//, `spec ${spec}`); + } + assert.deepEqual(problems({ spec: "specs/demo" }), []); + assert.match(problems({ commit: "yes" }).join(), /"commit" must be true or false/); + assert.match(problems({ strength: "mighty" }).join(), /"strength"/); + assert.match(inStore((m) => m.reviewLoopSetupProblems(null), {}).join(), /must be an object/); + + const before = inStore((m, { a }) => (m.saveReviewLoopSetup(a, { ...m.REVIEW_LOOP_DEFAULTS }), null), { a: projectA }); + assert.equal(before, null); + const text = fs.readFileSync(SETUP_PATH, "utf8"); + const threw = inStore( + (m, { a }) => { + try { + m.saveReviewLoopSetup(a, { ...m.REVIEW_LOOP_DEFAULTS, cap: 99 }); + return "saved"; + } catch (e) { + return { message: e.message, problems: e.problems }; + } + }, + { a: projectA } + ); + assert.match(threw.message, /the review loop setup is not valid/); + assert.equal(threw.problems.length, 1); + assert.equal(fs.readFileSync(SETUP_PATH, "utf8"), text, "a refused save leaves the file as it was"); +}); + +test("review-loop-setup: the picks live only in review-loop-setup.json, never in the project or the loop's setup", () => { + fs.rmSync(SETUP_PATH, { force: true }); + fs.rmSync(LOOP_SETUP_PATH, { force: true }); + const project = fs.mkdtempSync(path.join(HOME, "review-nowrite-")); + inStore((m, { project }) => (m.saveReviewLoopSetup(project, { ...m.REVIEW_LOOP_DEFAULTS, cap: 4 }), null), { project }); + assert.ok(fs.existsSync(SETUP_PATH)); + assert.equal(fs.existsSync(LOOP_SETUP_PATH), false, "the Implementation Loop's file is untouched"); + assert.deepEqual(fs.readdirSync(project), [], "nothing appears in the project"); +}); + +test("review-loop-setup: Cleanup never offers the file", () => { + const code = `const m = await import(${JSON.stringify(pathToFileURL(path.join(ROOT, "src", "web-console", "sessions.mjs")).href)}); console.log(JSON.stringify([...m.PROTECTED_CONSOLE_FILES]));`; + const res = spawnSync(process.execPath, ["--input-type=module", "-e", code], { env: cleanEnv(), encoding: "utf8", cwd: ROOT }); + assert.equal(res.status, 0, res.stderr); + assert.ok(JSON.parse(String(res.stdout).trim().split("\n").pop()).includes("review-loop-setup.json")); +}); + +test("review-loop-setup: GET and POST /review-loop-setup, with ?spec= filling the answer without saving", async () => { + fs.rmSync(SETUP_PATH, { force: true }); + const cwd = fs.mkdtempSync(path.join(HOME, "review-route-")); + const opened = cli(["open", "--workflow", "review", "--no-open"], { cwd }); + const parsed = JSON.parse(String(opened.stdout).trim().split("\n").filter((l) => l.startsWith("{")).pop()); + const { base, cookie } = sessionUrl(parsed.url); + const get = async (query = "") => { + const res = await fetch(`${base}/review-loop-setup${query}`, { headers: { cookie, connection: "close" } }); + return { status: res.status, body: await res.json() }; + }; + const send = (body, { origin = base } = {}) => + fetch(`${base}/review-loop-setup`, { + method: "POST", + headers: { "content-type": "application/json", cookie, ...(origin ? { origin } : {}), connection: "close" }, + body: typeof body === "string" ? body : JSON.stringify(body), + }); + try { + const bare = await get(); + assert.equal(bare.status, 200); + assert.equal(bare.body.remembered, false); + assert.equal(bare.body.scope, "branch"); + assert.equal(bare.body.cap, 3); + + const filled = await get("?spec=specs/demo"); + assert.equal(filled.body.spec, "specs/demo"); + assert.equal(filled.body.scope, "spec"); + assert.equal(filled.body.remembered, false); + assert.equal(fs.existsSync(SETUP_PATH), false, "a pre-fill is never saved"); + assert.equal((await get()).body.scope, "branch", "and the next plain read is the defaults again"); + + for (const spec of ["../x", "specs/../x", "specs/a/b", "specs/.hidden", "specs", "specs/"]) { + const refused = await get(`?spec=${spec}`); + assert.equal(refused.status, 400, `spec=${spec} is refused`); + assert.match(refused.body.error, /spec must be a folder directly under specs\//); + } + + const facts = await get("?facts=1"); + assert.equal(typeof facts.body.branch, "string"); + assert.ok("pending" in facts.body); + + const good = { scope: "uncommitted", spec: "", cap: 4, commit: false, suggestions: true, strength: "balanced", silenceMinutes: 15, notifyRounds: true }; + const saved = await send(good); + assert.equal(saved.status, 200, await saved.clone().text()); + const back = await get(); + assert.equal(back.body.remembered, true); + for (const [key, value] of Object.entries(good)) assert.equal(back.body[key], value, key); + + const bad = await send({ ...good, cap: 9, extra: 1 }); + assert.equal(bad.status, 400); + const badBody = await bad.json(); + assert.equal(badBody.ok, false); + assert.ok(badBody.problems.some((p) => /"cap"/.test(p))); + assert.ok(badBody.problems.some((p) => /"extra" is not a setup field/.test(p))); + assert.equal((await get()).body.cap, 4, "a refused save changes nothing"); + assert.equal((await send("[1]")).status, 400); + + // The POST is origin-checked: another page's origin is refused, and nothing is saved by it. + const before = JSON.stringify((await get()).body); + const foreign = await send({ ...good, cap: 2 }, { origin: "http://evil.example" }); + assert.equal(foreign.status, 403, "a foreign origin is refused"); + assert.equal(JSON.stringify((await get()).body), before); + } finally { + cli(["stop", "--session", parsed.sid, "--force"], { cwd, expectFail: true }); + } + assert.deepEqual(fs.readdirSync(cwd), [], "the route never wrote into the project"); + assert.equal(fs.existsSync(LOOP_SETUP_PATH), false, "and never touched the Implementation Loop's file"); +}); diff --git a/scripts/test-web-console-server.mjs b/scripts/test-web-console-server.mjs index f2ab885..1706f6a 100644 --- a/scripts/test-web-console-server.mjs +++ b/scripts/test-web-console-server.mjs @@ -365,6 +365,7 @@ test("the scratch sweep removes old patches and helpers, never looks, the pointe file("looks.json"), file("workspaces.json"), file("loop-setup.json"), + file("review-loop-setup.json"), file("spec-carry.json"), file("loop-reports.json"), file("subagents.json"), @@ -382,7 +383,7 @@ test("the scratch sweep removes old patches and helpers, never looks, the pointe const stale = staleScratch(dir, Date.now(), SESSION_MAX_AGE_MS).sort(); assert.deepEqual(stale, ["helper.mjs", "p2.json"]); assert.deepEqual( - (await removeScratch(dir, [...stale, "looks.json", "workspaces.json", "loop-setup.json", "loop-reports.json", "subagents.json", "spec-carry.json", "pr-hosts.json", "../p.json", "console-dir", "update-check.json"])).sort(), + (await removeScratch(dir, [...stale, "looks.json", "workspaces.json", "loop-setup.json", "review-loop-setup.json", "loop-reports.json", "subagents.json", "spec-carry.json", "pr-hosts.json", "../p.json", "console-dir", "update-check.json"])).sort(), ["helper.mjs", "p2.json"] ); for (const p of removable) assert.equal(fs.existsSync(p), false, p); @@ -393,6 +394,7 @@ test("the scratch sweep removes old patches and helpers, never looks, the pointe "loop-reports.json", "loop-setup.json", "pr-hosts.json", + "review-loop-setup.json", "spec-carry.json", "subagents.json", "update-check.json", diff --git a/scripts/test-web-console-shape.mjs b/scripts/test-web-console-shape.mjs index 4bc3b7a..fb7d7cd 100644 --- a/scripts/test-web-console-shape.mjs +++ b/scripts/test-web-console-shape.mjs @@ -193,7 +193,7 @@ const ROUTE_ORDER = [ "/notepad", "/notepad/text", "/notepad/image", "/notepad/thumb", "/notepad/image/delete", "/notepad/tab", "/notepad/tab/rename", "/notepad/tab/delete", "/notepad/tab/order", "/notepad/tab/last", "/notepad/tab/sent", "/notepad/images/", "/attachments/", "/shots/", "/uploads/", "/submit", "/open-link", "/open-prototype", "/chat", "/chat/decision", "/workspace", - "WORKSPACE_EDITS", "/workspace/scope", "/workspace/browse", "/loop-setup", "/loop-setup", "/spec-carry", "/cancel", "/ping", "/bye", + "WORKSPACE_EDITS", "/workspace/scope", "/workspace/browse", "/loop-setup", "/loop-setup", "/review-loop-setup", "/review-loop-setup", "/spec-carry", "/cancel", "/ping", "/bye", ]; test("shape: routes.mjs lists every URL the server answers, in order", () => { diff --git a/scripts/test-web-console-skills.mjs b/scripts/test-web-console-skills.mjs index 7063518..c11b04d 100644 --- a/scripts/test-web-console-skills.mjs +++ b/scripts/test-web-console-skills.mjs @@ -19,7 +19,7 @@ import { isWorkflow, isAgentless, } from "../src/web-console/public/skills.js"; -import { CONSOLE_WORKFLOWS, SKILL_CATALOG, catalogEntry, launchVariant, START_POSES, WORKFLOW_LABEL, dashNoteKind, onInitialPick, startPose, startingHint } from "../src/web-console/public/answers.js"; +import { APP_ONLY_ENTRIES, REVIEW_LOOP_ENTRY, cardAvailability, CONSOLE_WORKFLOWS, SKILL_CATALOG, catalogEntry, launchVariant, START_POSES, WORKFLOW_LABEL, dashNoteKind, onInitialPick, startPose, startingHint } from "../src/web-console/public/answers.js"; import { LAUNCH_COUNTED, PROGRESS_WORKFLOWS } from "../src/web-console/public/meter.js"; import { BUILD_WORKFLOWS } from "../src/web-console/public/labels.js"; import { helpTabFor } from "../src/web-console/public/help.js"; @@ -428,19 +428,34 @@ test("helper-strength.md ships in the eighteen skills that start helpers (the da ]); }); -// The Implementation Loop is a card the desktop app offers, not a skill: it -// has no workflow, so no list built from the workflows may hold it. -test("the app-only Implementation Loop entry stays out of every workflow list", () => { - const loop = EVERY_ENTRY.find((s) => s.appOnly); - assert.ok(loop, "skills.js has an appOnly entry"); - assert.equal(loop.skill, "plan2code-loop"); - assert.equal(loop.workflow, null); - assert.deepEqual(EVERY_ENTRY.filter((s) => s.appOnly).length, 1); - assert.ok(!SKILLS.includes(loop), "FLOW_SKILLS leaves it out"); - assert.ok(!WORKFLOWS.includes(null) && !isWorkflow("plan2code-loop") && !isWorkflow(null)); - assert.equal(skillByName("plan2code-loop"), null); - assert.ok(!CONSOLE_WORKFLOWS.includes(loop.command), "no console page is offered for it"); - assert.ok(!SKILL_CATALOG.some((e) => e.skill === loop.skill), "the dashboard does not draw it yet"); +// The Implementation Loop and the Review Loop are cards the desktop app offers, +// not skills: neither has a workflow, so no list built from the workflows may hold them. +test("the app-only Implementation Loop and Review Loop entries stay out of every workflow list", () => { + const apps = EVERY_ENTRY.filter((s) => s.appOnly); + assert.deepEqual(apps.map((s) => s.skill), ["plan2code-loop", "plan2code-review-loop"], "both, the Implementation Loop first"); + for (const entry of apps) { + assert.equal(entry.workflow, null); + assert.ok(!SKILLS.includes(entry), "FLOW_SKILLS leaves it out"); + assert.ok(!isWorkflow(entry.skill)); + assert.equal(skillByName(entry.skill), null); + assert.ok(!CONSOLE_WORKFLOWS.includes(entry.command), "no console page is offered for it"); + assert.ok(!SKILL_CATALOG.some((e) => e.skill === entry.skill), "the dashboard draws it apart from the catalog"); + assert.equal(entry.subagents, null); + assert.equal(entry.card.group, "pipeline", "beside the Implementation Loop"); + } + assert.ok(!WORKFLOWS.includes(null) && !isWorkflow(null)); assert.ok(!("null" in WORKFLOW_LABEL)); - assert.deepEqual([...loop.states], ["documented", "building"]); + assert.deepEqual([...apps[0].states], ["documented", "building"]); + assert.equal(apps[1].states, "any", "a Review Loop needs no spec"); + assert.equal(apps[1].card.title, "Review Loop"); + assert.equal(apps[1].card.blurb, "Review and fix in rounds on its own, each round checked by a fresh reviewer."); +}); + +test("the Review card carries the app-only pointer line, and the app-only cards are the dashboard's extras", () => { + const review = SKILL_CATALOG.find((e) => e.skill === "plan2code-review"); + assert.equal(review.appNote, "In the app, the Review Loop runs review and fix rounds on its own."); + assert.deepEqual(SKILL_CATALOG.filter((e) => e.appNote).map((e) => e.skill), ["plan2code-review"], "no other card has one"); + assert.deepEqual(APP_ONLY_ENTRIES.map((e) => e.skill), ["plan2code-loop", "plan2code-review-loop"]); + assert.equal(REVIEW_LOOP_ENTRY.command, "Desktop app only"); + assert.equal(cardAvailability(REVIEW_LOOP_ENTRY, { hasAgents: true }, null).on, true, "lit for any project state"); }); diff --git a/scripts/test-web-console-state.mjs b/scripts/test-web-console-state.mjs index 9ffc76d..16e9e22 100644 --- a/scripts/test-web-console-state.mjs +++ b/scripts/test-web-console-state.mjs @@ -52,6 +52,10 @@ test("state: the rest of the shared state starts as app.js always started it", ( terminalCollapsed: false, loop: null, loopSetup: null, + reviewLoopSetup: null, + reviewFacts: null, + reviewStart: null, + reviewAction: null, loopFacts: null, loopNotifyTest: null, loopStart: null, diff --git a/src/launcher/agents.json b/src/launcher/agents.json index 760947d..8aa5c0e 100644 --- a/src/launcher/agents.json +++ b/src/launcher/agents.json @@ -6,6 +6,7 @@ "name": "Claude Code", "kind": "builtin", "command": "claude", + "helpers": true, "prompt": "/plan2code", "args": ["{prompt}", "{bypass}", "{model}"], "bypassArgs": ["--permission-mode", "bypassPermissions"], @@ -37,6 +38,7 @@ "name": "Devin", "kind": "builtin", "command": "devin", + "helpers": false, "prompt": "/plan2code", "args": ["{bypass}", "{model}", "--", "{prompt}"], "bypassArgs": ["--permission-mode", "bypass"], @@ -64,6 +66,7 @@ "name": "Codex", "kind": "builtin", "command": "codex", + "helpers": false, "prompt": "$plan2code", "args": ["{bypass}", "{model}", "{prompt}"], "bypassArgs": ["--dangerously-bypass-approvals-and-sandbox"], @@ -94,6 +97,7 @@ "name": "GitHub Copilot CLI", "kind": "template", "command": "copilot", + "helpers": false, "prompt": "Use the /plan2code skill", "args": ["-i", "{prompt}"], "bypassArgs": ["--allow-all-tools"], @@ -104,6 +108,7 @@ "name": "OpenCode", "kind": "template", "command": "opencode", + "helpers": false, "prompt": "@plan2code", "args": ["{model}", "--prompt", "{prompt}"], "bypassArgs": ["--auto"], @@ -114,6 +119,7 @@ "name": "Gemini CLI", "kind": "template", "command": "gemini", + "helpers": false, "prompt": "Use the plan2code skill", "args": ["{model}", "{prompt}"], "bypassArgs": ["--approval-mode=yolo"], @@ -125,6 +131,7 @@ "name": "Pi", "kind": "template", "command": "pi", + "helpers": false, "prompt": "/skill:plan2code", "args": ["{model}", "{prompt}"], "modelArgs": ["--model", "{model}"] @@ -134,6 +141,7 @@ "name": "Cursor CLI", "kind": "template", "command": "agent", + "helpers": false, "prompt": "/plan2code", "args": ["{model}", "{prompt}"], "bypassArgs": ["--force"], diff --git a/src/plan2code-review.md b/src/plan2code-review.md index 11b8032..f597458 100644 --- a/src/plan2code-review.md +++ b/src/plan2code-review.md @@ -8,7 +8,7 @@ Critical review specialist -- experienced senior engineer providing independent ## Interface -The FIRST thing you do, before anything else in this file — before the scope detection: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "/console.mjs" open --workflow review` before reading (: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-review/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read /console.md and /notes/review.md. Scope questions, the findings report and the pick-what-gets-fixed menu all go through it; the report lands on the page as a doc. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then Process. Read inside a build session for its review button? Skip this section — building-review.md's overrides govern, the session is already running. +The FIRST thing you do, before anything else in this file — before the scope detection: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "/console.mjs" open --workflow review` before reading (: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-review/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read /console.md and /notes/review.md. Scope questions, the findings report and the pick-what-gets-fixed menu all go through it; the report lands on the page as a doc. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. `--loop` (only inside the desktop app, a Review Loop round): open with `open --loop --workflow review --round --role --scope-file ` from the arguments, read `/notes/review-loop.md` after `console.md`, and follow it; it replaces the scope question, the fix menu, the sign-off, Lessons End and every git step below. Launched by the dashboard? Its session is already open — resume it (console-launches.md), then Process. Read inside a build session for its review button? Skip this section — building-review.md's overrides govern, the session is already running. ## Scripts diff --git a/src/shared-references/lessons.md b/src/shared-references/lessons.md index 3ffba69..b88e987 100644 --- a/src/shared-references/lessons.md +++ b/src/shared-references/lessons.md @@ -61,7 +61,7 @@ The seven noting skills (and any skill sent here by Start's Review now) run it b **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. +- **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 one whose `tools:` line lists only the read, search and list-files tools, 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"). diff --git a/src/web-console/agent-lookup.mjs b/src/web-console/agent-lookup.mjs index 4afd3fc..143fab0 100644 --- a/src/web-console/agent-lookup.mjs +++ b/src/web-console/agent-lookup.mjs @@ -58,8 +58,11 @@ export function loadAgentList({ dir = MODULE_DIR, optional = false } = {}) { warnings.push(`agents[${index}] skipped: not an object`); return; } - if (entry.kind === "builtin") builtins.push(entry); - else if (entry.kind === "template") templates.push(entry); + // helpers: the agent can start a subagent from inside a session; a missing + // key reads false. + const carried = { ...entry, helpers: entry.helpers === true }; + if (entry.kind === "builtin") builtins.push(carried); + else if (entry.kind === "template") templates.push(carried); else warnings.push(`agents[${index}] skipped: unknown kind ${JSON.stringify(entry.kind)}`); }); return { builtins, templates, warnings }; diff --git a/src/web-console/cmd-open.mjs b/src/web-console/cmd-open.mjs index 8fbdf3b..f0ed227 100644 --- a/src/web-console/cmd-open.mjs +++ b/src/web-console/cmd-open.mjs @@ -42,6 +42,7 @@ import { resolveDocFiles, resolveDocImages, validate, + ROUND_ROLES, } from "./patches.mjs"; import { initialWorkspace, @@ -111,14 +112,40 @@ function leavePointer() { const EMBED_API = 1; // The only workflows a loop drives (open --loop). -const LOOP_WORKFLOWS = ["implement", "implement-review"]; +const LOOP_WORKFLOWS = ["implement", "implement-review", "review"]; // What the loop locks a session with: `driving`, and, when the app started this // phase on a strength, its word (PLAN2CODE_LOOP_STRENGTH), which the server's // Subagents sync reads so the phase's helpers follow it. -function loopLock() { +function loopLock(round) { const strength = process.env.PLAN2CODE_LOOP_STRENGTH; - return STRENGTH_ORDER.includes(strength) ? { driving: true, strength } : { driving: true }; + const lock = STRENGTH_ORDER.includes(strength) ? { driving: true, strength } : { driving: true }; + return round ? { ...lock, ...round } : lock; +} + +// A Review Loop round (open --loop --workflow review) carries its round, role +// and scope file; every other open refuses them. Returns the stamp, or null. +function roundFlags(loopMode) { + const given = ["round", "role", "scope-file"].filter((f) => args[f] !== undefined); + const isRound = loopMode && args.workflow === "review"; + if (!isRound) { + if (given.length) die(`--${given[0]} goes only with --loop --workflow review`, 2); + return null; + } + const n = Number(args.round); + if (args.round === undefined || args.round === true || !Number.isInteger(n) || n < 1 || !/^\d+$/.test(String(args.round))) { + die("--round must be a positive integer for a Review Loop round", 2); + } + if (typeof args.role !== "string" || !ROUND_ROLES.includes(args.role)) { + die(`--role must be one of ${ROUND_ROLES.join(", ")} for a Review Loop round`, 2); + } + const scopeFile = args["scope-file"]; + let isFile = false; + try { + isFile = typeof scopeFile === "string" && scopeFile !== "" && fs.statSync(scopeFile).isFile(); + } catch {} + if (!isFile) die("--scope-file must name an existing file for a Review Loop round", 2); + return { round: n, role: args.role, scopeFile: path.resolve(scopeFile) }; } export async function cmdOpen() { @@ -140,6 +167,7 @@ export async function cmdOpen() { die(`--loop goes only with --workflow ${LOOP_WORKFLOWS.join(" or --workflow ")}`, 2); } } + const round = roundFlags(loopMode); leavePointer(); // Under the desktop app the page belongs in the app's window: never the // browser, and (unless a session was named) the app's own session, so one @@ -252,9 +280,10 @@ export async function cmdOpen() { } else if (switching) { s.workflow = args.workflow; // An inline switch (into Review) is not a loop phase. - if (!LOOP_WORKFLOWS.includes(args.workflow)) { + if (!LOOP_WORKFLOWS.includes(args.workflow) || args.workflow === "review") { delete s.loopOutcome; delete s.loopEnd; + delete s.roundOutcome; } } if (args.title) s.title = args.title; @@ -270,9 +299,17 @@ export async function cmdOpen() { // without it (Fix together with an agent, from a stop screen) is an ordinary, // unlocked session. `loopExpect` goes with the lock: the app restamps it // on its next look, so a stale setup never judges a new run. - if (loopMode) s.loop = loopLock(); - else { + if (loopMode) { + // A different round or role never inherits the last one's report: its + // outcome and its `report` doc go, so the report proof is that run's own. + if (round && (s.loop?.round !== round.round || s.loop?.role !== round.role)) { + delete s.roundOutcome; + s.docs = (s.docs || []).filter((d) => d && d.id !== "report"); + } + s.loop = loopLock(round); + } else { delete s.loop; + delete s.roundOutcome; delete s.loopExpect; // The loop's cards mean nothing without it, and validate() refuses // handledBy outside a loop session, which would wedge every post. @@ -302,7 +339,7 @@ export async function cmdOpen() { // Only a freshly opened dashboard plays Planny's wake-up. if (args.workflow === "dashboard") state.wake = true; // Locked from the first frame, before the state is first written. - if (loopMode) state.loop = loopLock(); + if (loopMode) state.loop = loopLock(round); // The setup session's hand-over data (forCli + the token /handover // checks), created with the state so the first write already has it. if (args.workflow === "setup") { @@ -583,6 +620,9 @@ export async function cmdOpen() { ...owed, ...(remote.remote ? { remote: remote.remote } : {}), ...(notes.length ? { note: notes.join(" ") } : {}), + // A Review Loop round reads its own notes once, the way a phase agent is + // pointed at notes/loop.md by its skill: the console names the file. + ...(round ? { read: [path.join(HERE, "notes", "review-loop.md")] } : {}), }); advanceSubagents(dir, subCursor); // After the print, never before it: the page and the link wait for nothing. diff --git a/src/web-console/console.mjs b/src/web-console/console.mjs index b523b45..b96b722 100644 --- a/src/web-console/console.mjs +++ b/src/web-console/console.mjs @@ -115,7 +115,7 @@ if (!cmd || !Object.hasOwn(COMMANDS, cmd)) { // A flag given with no value parses as `true`, and a boolean handed on as a // path or a name crashes somewhere deep (path.basename(true) throws). Every // flag that takes a value is checked once, here, and refused as bad usage. -const VALUE_FLAGS = ["session", "sid", "resume", "file", "spec", "title", "workflow", "skill", "handoff", "upload", "name", "from", "seconds", "limit", "idle-ms", "for-cli"]; +const VALUE_FLAGS = ["session", "sid", "resume", "file", "spec", "title", "workflow", "skill", "handoff", "upload", "name", "from", "seconds", "limit", "idle-ms", "for-cli", "round", "role", "scope-file"]; for (const flag of VALUE_FLAGS) { if (flag in args && typeof args[flag] !== "string") die(`--${flag} needs a value`, 2); } diff --git a/src/web-console/loop-setup.mjs b/src/web-console/loop-setup.mjs index 14f03e1..d0d75cc 100644 --- a/src/web-console/loop-setup.mjs +++ b/src/web-console/loop-setup.mjs @@ -29,6 +29,7 @@ const SPEC_KEY = /^specs\/[^/\\.][^/\\]*$/; export const LOOP_DEFAULTS = Object.freeze({ review: true, + reviewRounds: 2, fixMode: "smart", fix: Object.freeze([...LEVELS]), commit: true, @@ -68,6 +69,9 @@ export function loopSetupProblems(entry) { if (!Array.isArray(entry.fix) || !entry.fix.every((l) => LEVELS.includes(l)) || new Set(entry.fix).size !== entry.fix.length) { problems.push(`"fix" must list distinct levels from ${LEVELS.join(", ")}`); } + if (!Number.isInteger(entry.reviewRounds) || entry.reviewRounds < 0 || entry.reviewRounds > 6) { + problems.push('"reviewRounds" must be a whole number from 0 to 6'); + } if (!FIX_MODES.includes(entry.fixMode)) problems.push(`"fixMode" must be one of ${FIX_MODES.join(", ")}`); if (!ON_QUESTION.includes(entry.onQuestion)) problems.push(`"onQuestion" must be one of ${ON_QUESTION.join(", ")}`); if (!AFTER_LAST.includes(entry.afterLast)) problems.push(`"afterLast" must be one of ${AFTER_LAST.join(", ")}`); diff --git a/src/web-console/notes/review-loop.md b/src/web-console/notes/review-loop.md new file mode 100644 index 0000000..f5cade8 --- /dev/null +++ b/src/web-console/notes/review-loop.md @@ -0,0 +1,55 @@ +# Review Loop Round + +Read after `console.md`. Run by the desktop app's Review Loop (`--loop` on `review`), part of the `console.md` contract. This note replaces the scope card, the fix menu, the sign-off, Lessons End and every git step. + +## Who you are + +One round of a Review Loop. The app started you with `--round `, `--role ` and `--scope-file `, and opened the session with `open --loop --workflow review --round --role --scope-file `: run that open again if the server went away, with the same flags. Nobody is watching. Never run git in any form, never ask the person, never commit. A real question is a stop: report `failed`, reason `other`. + +## Scope + +Read the scope file first. For round 1 it names the scope the person picked. For a later round it is the previous round's diff. Review nothing outside it. A file the scope names but that is gone is a finding only if the change deleted it. + +## Role both + +1. Start one fresh read-only reviewer subagent with `reviewer-brief.md` filled in for the scope, whatever the Subagents switch says. It never sees this conversation. +2. Verify every finding it returns (`verification-protocol.md`), and drop what does not hold. +3. Post the verified findings as one doc with id `report`, grouped Critical, Warning, Suggestion. +4. Fix Critical and Warning only. List Suggestions without fixing them. +5. Run the targeted tests for the files you changed (`references/test-runs.md`), never the full suite. Changed nothing? Run the targeted tests for the files in scope: a passed round never sends `ran:false`. + +## Role reviewer + +Do the review only: steps 1 to 3 of Role both. Change no file. Post the `report` doc and report; leave `tests` out, and send `fixed` as an empty list. + +## Role fixer + +The scope file names the reviewer's report by file path. Read it, fix Critical and Warning, run the targeted tests for what you changed, and start no new review. Leave `report` out. Still send `review`: its counts and lists come from the reviewer's report, with `fixed` and `unfixed` showing what this round fixed and left. + +## Reporting + +Post in this order, each as its own patch with no `--wait`: + +1. The `report` doc (roles both and reviewer), before the outcome. +2. One top-level `roundOutcome`: + +```json +{ "roundOutcome": { + "round": 2, "role": "both", "result": "passed", "reason": null, + "summary": "Fixed 1 warning; 1 suggestion left", + "report": "report", + "review": { "critical": 0, "warning": 1, "suggestion": 1, + "fixed": [ { "title": "Close the file handle", "file": "src/z.js", "line": 12 } ], + "unfixed": [], + "suggestions": [ { "title": "Name the timer", "file": "src/x.js" } ] }, + "tests": { "ran": true, "passed": true, "summary": "14 pass" }, + "subject": "Close the file handle in z.js" } } +``` + +3. `{"agent":{"status":"waiting"}}`, then keep waiting in bounded `wait` slices until the app ends the session. Never end the turn on text. + +Every field is required except `report` for a fixer and `tests` for a reviewer. `round` and `role` must equal the flags. `critical`, `warning` and `suggestion` count what the review found before fixing; `fixed` and `unfixed` list the Critical and Warning findings by that outcome (at most 50 each, `file` relative to the project). `result` is `passed` when the round ran its steps and its tests; `failed` carries one reason: `tests`, `findings`, `blocked`, `conflict` or `other`. `summary` is one line under 200 characters, `subject` one line under 100. + +## Refusals + +An exit 3 on `roundOutcome` names the field: fix it and post again inside the same round. A `loopOutcome` is refused here: a round reports `roundOutcome` only. diff --git a/src/web-console/notes/review.md b/src/web-console/notes/review.md index d716c2b..1648208 100644 --- a/src/web-console/notes/review.md +++ b/src/web-console/notes/review.md @@ -9,3 +9,5 @@ Closing gate: `review` "Check the fixes", `"doc":"report"`, `"nothingYet":false` Lessons first: with lessons to offer (`references/lessons.md`, End), post its `card` as one `lessons` item with `--wait` before the finish. Completion finish: `command` is the suggested commit when fixes landed (AGENTS.md format, `"where":"When you are happy with it, commit it from your terminal:"`, `"commit":true`), else none; `"dashboard":true`. A stop's `command` is the bare `/plan2code-review`, no dashboard. + +Under `--loop` (a Review Loop round, desktop app only): read `notes/review-loop.md` after `console.md`; it replaces the scope card, the fix menu and the sign-off. diff --git a/src/web-console/patches.mjs b/src/web-console/patches.mjs index 922eb8a..4308c50 100644 --- a/src/web-console/patches.mjs +++ b/src/web-console/patches.mjs @@ -598,7 +598,7 @@ export function applyPatch(state, patch) { if (v === null) { // The loop's report fields are set, never deleted: a null here would // strip the app's criteria or an already-posted report. - if (["loopExpect", "loopOutcome", "loopEnd"].includes(k)) throw new Error(rule("", k, "cannot be deleted by a patch")); + if (["loopExpect", "loopOutcome", "loopEnd", "roundOutcome"].includes(k)) throw new Error(rule("", k, "cannot be deleted by a patch")); delete next[k]; continue; } @@ -664,9 +664,19 @@ export function applyPatch(state, patch) { next.chat = chat; break; } + case "roundOutcome": + // A Review Loop round's one report. validate() checks its shape and + // the report doc; here only who may send it, and how often. + if (state.loop?.driving !== true || !state.loop.round) { + throw new Error(rule("", "roundOutcome", "is only accepted in a Review Loop round session")); + } + if (state.roundOutcome !== undefined) throw new Error(rule("", "roundOutcome", "was already posted for this session")); + next.roundOutcome = v; + break; case "loopOutcome": // The skill's one report of a phase built under the loop. The shape is // checked by validate(); here only who may send it, and how often. + if (state.loop?.round) throw new Error(rule("", "loopOutcome", "is not accepted in a round session: a round reports roundOutcome, not loopOutcome")); if (!state.loop?.driving) { throw new Error(rule("", "loopOutcome", "is only accepted in a loop session; a resume without --loop unlocked it, so run open --resume --workflow --loop, then post this again")); } @@ -1248,6 +1258,7 @@ export function validate(state) { if (state.loopExpect !== undefined) problems.push(...loopExpectProblems(state.loopExpect)); if (state.loopOutcome !== undefined) problems.push(...loopOutcomeProblems(state.loopOutcome, state.loopExpect)); if (state.loopEnd !== undefined) problems.push(...loopEndProblems(state.loopEnd, state)); + if (state.roundOutcome !== undefined) problems.push(...roundOutcomeProblems(state.roundOutcome, state)); // The dashboard agent's answer to Suggest for me on the loop setup screen. if (state.loopSuggest !== undefined) problems.push(...loopSuggestProblems(state.loopSuggest)); @@ -1489,6 +1500,7 @@ export function isOpen(item) { /* ------------------------------------------------------ the loop's reports */ const LOOP_LEVELS = ["critical", "warning", "suggestion"]; +export const ROUND_ROLES = ["both", "reviewer", "fixer"]; const LOOP_REASONS = ["tests", "findings", "blocked", "conflict", "other"]; const LOOP_CAN = ["resume", "ask", "fix", "finalize", "dashboard"]; const TASK_ID = /^\d+\.\d+$/; @@ -1707,9 +1719,153 @@ export function loopSuggestProblems(v) { return p; } +/** + * Problems with a `roundOutcome` (what a Review Loop round reports), as + * sentences naming the field; an empty array when it is good. Rules are the + * overview's Data Model. `state` is the merged session, which holds the + * round's stamp and the report doc the outcome names. + */ +export function roundOutcomeProblems(o, state) { + const p = []; + const bad = (field, rule) => p.push(`roundOutcome.${field} ${rule}`); + if (!isPlainObject(o)) return ["roundOutcome must be an object"]; + const prose = (field, s) => { + if (typeof s === "string") p.push(...proseProblems(s, `roundOutcome.${field}`)); + }; + const stamp = state?.loop || {}; + if (!isPosInt(o.round)) bad("round", "must be a positive integer"); + else if (o.round !== stamp.round) bad("round", `must be ${stamp.round}, this session's round`); + if (!ROUND_ROLES.includes(o.role)) bad("role", `must be one of ${ROUND_ROLES.join(", ")}`); + else if (o.role !== stamp.role) bad("role", `must be "${stamp.role}", this session's role`); + const role = ROUND_ROLES.includes(o.role) ? o.role : stamp.role; + if (o.result !== "passed" && o.result !== "failed") bad("result", 'must be "passed" or "failed"'); + if (o.result === "passed") { + if (o.reason !== null) bad("reason", "must be null when the round passed"); + } else if (o.result === "failed" && !LOOP_REASONS.includes(o.reason)) { + bad("reason", `must be one of ${LOOP_REASONS.join(", ")} when the round failed`); + } + if (!oneLine(o.summary, 200)) bad("summary", "must be one line of 1 to 200 characters"); + else prose("summary", o.summary); + if (!oneLine(o.subject, 100)) bad("subject", "must be one line of 1 to 100 characters"); + else prose("subject", o.subject); + + if (role === "both" || role === "reviewer") { + // A report is a doc the agent already posted: docs carry no kind field, + // so the outcome names the doc by its id. + if (typeof o.report !== "string" || !(state?.docs || []).some((d) => d && d.id === o.report)) { + bad("report", "must name a report doc already posted in this session"); + } + } else if (o.report !== undefined && typeof o.report !== "string") bad("report", "must be a doc id when present"); + + if (!isPlainObject(o.review)) bad("review", "must be an object { critical, warning, suggestion, fixed, unfixed, suggestions }"); + else { + const r = o.review; + for (const level of LOOP_LEVELS) if (!isNonNegInt(r[level])) bad(`review.${level}`, "must be a non-negative integer"); + for (const list of ["fixed", "unfixed", "suggestions"]) { + if (!Array.isArray(r[list])) bad(`review.${list}`, "must be an array"); + else if (r[list].length > 50) bad(`review.${list}`, "has at most 50 entries"); + else { + r[list].forEach((f, i) => { + const at = `review.${list}[${i}]`; + if (!isPlainObject(f)) return bad(at, "must be an object { title, file, line? }"); + if (!oneLine(f.title, 200)) bad(`${at}.title`, "must be one line of 1 to 200 characters"); + else prose(`${at}.title`, f.title); + if (!relativePath(f.file)) bad(`${at}.file`, "must be a relative path inside the project"); + if (f.line !== undefined && !isPosInt(f.line)) bad(`${at}.line`, "must be a positive integer when present"); + }); + } + } + } + + if (role === "both" || role === "fixer") { + if (!isPlainObject(o.tests)) bad("tests", "must be an object { ran, passed, summary }"); + else { + if (typeof o.tests.ran !== "boolean") bad("tests.ran", "must be true or false"); + if (typeof o.tests.passed !== "boolean") bad("tests.passed", "must be true or false"); + if (typeof o.tests.summary !== "string" || /[\r\n]/.test(o.tests.summary)) bad("tests.summary", "must be a one-line string"); + else prose("tests.summary", o.tests.summary); + } + } else if (o.tests !== undefined && !isPlainObject(o.tests)) bad("tests", "must be an object when present"); + return p; +} + +const REVIEW_END_REASONS = ["clean", "cap", "person", "failed"]; + +/** + * The Review Loop's `loopEnd` (`kind: "review"`): why the run ended, the report + * doc, what Continue and the partial diff offer, the Suggestions pick, and + * after sign-off (`signedOff`) the note on what it did. `report` and + * `partial.diff` name docs on the page, as `evidence` does for the other kinds. + */ +function reviewLoopEndProblems(e, state) { + const p = []; + const bad = (field, rule) => p.push(`loopEnd.${field} ${rule}`); + const prose = (field, s) => { + if (typeof s === "string") p.push(...proseProblems(s, `loopEnd.${field}`)); + }; + const onPage = (id) => typeof id === "string" && (state?.docs || []).some((d) => d && d.id === id); + if (!oneLine(e.line, 200)) bad("line", "must be one line of 1 to 200 characters"); + else prose("line", e.line); + if (!REVIEW_END_REASONS.includes(e.reason)) bad("reason", `must be one of ${REVIEW_END_REASONS.join(", ")}`); + if (!onPage(e.report)) bad("report", "must be the id of a doc on the page"); + if (typeof e.canContinue !== "boolean") bad("canContinue", "must be true or false"); + if (typeof e.canSquash !== "boolean") bad("canSquash", "must be true or false"); + if (e.signedOff !== undefined && typeof e.signedOff !== "boolean") bad("signedOff", "must be true or false when present"); + if (e.note !== undefined) { + if (!oneLine(e.note, 200)) bad("note", "must be one line of 1 to 200 characters"); + else prose("note", e.note); + } + if (!Array.isArray(e.can) || !e.can.every((c) => LOOP_CAN.includes(c))) { + bad("can", `must be an array with entries from ${LOOP_CAN.join(", ")}`); + } + if (e.partial !== undefined) { + if (!isPlainObject(e.partial)) bad("partial", "must be an object { files, added, removed, diff }"); + else { + for (const k of ["files", "added", "removed"]) if (!isNonNegInt(e.partial[k])) bad(`partial.${k}`, "must be a non-negative integer"); + if (!onPage(e.partial.diff)) bad("partial.diff", "must be the id of a doc on the page"); + } + } + if (e.suggestions !== undefined) { + if (!Array.isArray(e.suggestions)) bad("suggestions", "must be an array"); + else if (e.suggestions.length > 50) bad("suggestions", "has at most 50 entries"); + else { + const seen = new Set(); + e.suggestions.forEach((s, i) => { + const at = `suggestions[${i}]`; + if (!isPlainObject(s)) return bad(at, "must be an object { id, title, file, line? }"); + if (typeof s.id !== "string" || !/^s[0-9]{1,3}$/.test(s.id)) bad(`${at}.id`, "must look like s1"); + else if (seen.has(s.id)) bad(`${at}.id`, "must be unique"); + else seen.add(s.id); + if (!oneLine(s.title, 200)) bad(`${at}.title`, "must be one line of 1 to 200 characters"); + else prose(`${at}.title`, s.title); + if (s.file !== "" && !relativePath(s.file)) bad(`${at}.file`, "must be a relative path inside the project or empty"); + else prose(`${at}.file`, s.file); + if (s.line !== undefined && !isPosInt(s.line)) bad(`${at}.line`, "must be a positive integer when present"); + }); + } + } + if (e.open !== undefined) { + if (!Array.isArray(e.open)) bad("open", "must be an array"); + else if (e.open.length > 50) bad("open", "has at most 50 entries"); + else { + e.open.forEach((f, i) => { + const at = `open[${i}]`; + if (!isPlainObject(f)) return bad(at, "must be an object { title, file, line? }"); + if (f.level !== undefined && f.level !== "critical" && f.level !== "warning") bad(`${at}.level`, 'must be "critical" or "warning" when present'); + if (!oneLine(f.title, 200)) bad(`${at}.title`, "must be one line of 1 to 200 characters"); + else prose(`${at}.title`, f.title); + if (!relativePath(f.file)) bad(`${at}.file`, "must be a relative path inside the project"); + if (f.line !== undefined && !isPosInt(f.line)) bad(`${at}.line`, "must be a positive integer when present"); + }); + } + } + return p; +} + /** * Problems with a `loopEnd` (the app's word on how the loop ended), given the - * merged state so `evidence` can be checked against the docs on the page. + * merged state so `evidence` (or, for a Review Loop's `kind: "review"`, `report` + * and `partial.diff`) can be checked against the docs on the page. */ export function loopEndProblems(e, state) { const p = []; @@ -1718,7 +1874,8 @@ export function loopEndProblems(e, state) { const prose = (field, s) => { if (typeof s === "string") p.push(...proseProblems(s, `loopEnd.${field}`)); }; - if (e.kind !== "stopped" && e.kind !== "finished") bad("kind", 'must be "stopped" or "finished"'); + if (e.kind === "review") return reviewLoopEndProblems(e, state); + if (e.kind !== "stopped" && e.kind !== "finished") bad("kind", 'must be "stopped" or "finished" (or "review" for a Review Loop)'); if (!oneLine(e.line, 200)) bad("line", "must be one line of 1 to 200 characters"); else prose("line", e.line); if (e.evidence !== undefined) { @@ -1772,7 +1929,8 @@ export function loopEndProblems(e, state) { // Loop mode adds four optional keys that a blank state does not hold (absent, // not null): `loop: { driving: true, strength? }` (set by `open --loop`), `loopExpect` // (the app's judging criteria), `loopOutcome` (the skill's report) and -// `loopEnd` (the app's ending). +// `loopEnd` (the app's ending). A Review Loop round adds `roundOutcome` and +// stamps `loop: { driving, round, role, scopeFile }`. export function blankState({ sid, workflow, title, project, specDir }) { return { schema: SCHEMA, @@ -1809,7 +1967,7 @@ export function switchWorkflow(state, { workflow, title, specDir }) { // A blank state holds no `loop`, `loopExpect`, `loopOutcome` or `loopEnd`, // so a hop never carries them over; `open --loop` stamps `loop` again after // the switch, and the app restamps `loopExpect` on its next look. - for (const key of ["loop", "loopExpect", "loopOutcome", "loopEnd"]) delete next[key]; + for (const key of ["loop", "loopExpect", "loopOutcome", "loopEnd", "roundOutcome"]) delete next[key]; if (state.chat) next.chat = state.chat; return next; } diff --git a/src/web-console/public/answers.js b/src/web-console/public/answers.js index ba1f47a..b254154 100644 --- a/src/web-console/public/answers.js +++ b/src/web-console/public/answers.js @@ -733,6 +733,13 @@ const LOOP_SKILL = SKILLS.find((s) => s.appOnly && s.card); export const LOOP_ENTRY = LOOP_SKILL ? { skill: LOOP_SKILL.skill, command: "Desktop app only", workflow: null, appOnly: true, ...LOOP_SKILL.card } : null; +// The Review Loop's card, the second app-only entry: same shape, own setup screen. +const REVIEW_LOOP_SKILL = SKILLS.find((s) => s.appOnly && s.card && s !== LOOP_SKILL); +export const REVIEW_LOOP_ENTRY = REVIEW_LOOP_SKILL + ? { skill: REVIEW_LOOP_SKILL.skill, command: "Desktop app only", workflow: null, appOnly: true, ...REVIEW_LOOP_SKILL.card } + : null; +// Every app-only card, in the order the dashboard draws them. +export const APP_ONLY_ENTRIES = Object.freeze([LOOP_ENTRY, REVIEW_LOOP_ENTRY].filter(Boolean)); export const OUTSIDE_APP_LINE = "Runs only in the Plan2Code desktop app."; // A workflow by the name its dashboard card gives it ("Implement"), for the @@ -851,7 +858,7 @@ export function cardAvailability(entry, scan, sel, lookup = stateFor) { const hasAgents = Boolean(scan && scan.hasAgents); const state = sel && sel.state && sel.state !== "unrecognized" ? sel.state : null; const next = sel ? Boolean(state) && NEXT_FOR_STATE[state] === entry.skill : entry.skill === "plan2code-0-pathfinder"; - const rule = skillByName(entry.skill) || (entry.appOnly ? LOOP_SKILL : null); + const rule = skillByName(entry.skill) || (entry.appOnly ? SKILLS.find((s) => s.appOnly && s.skill === entry.skill) || LOOP_SKILL : null); if (!rule || !rule.states) return ON; // The three cards whose rules read the scan rather than the spec. diff --git a/src/web-console/public/app-bridge.js b/src/web-console/public/app-bridge.js index 851b964..795c102 100644 --- a/src/web-console/public/app-bridge.js +++ b/src/web-console/public/app-bridge.js @@ -40,7 +40,8 @@ export function onAppMessage(kind, handler) { /** * Hear the app's answers to the Implementation Loop's named requests: * `loop-facts` (what agent a loop would use), `loop-start-result`, - * `loop-notify-test-result` and the three stop-screen results. `store` is the page object and `redraw` its + * `loop-notify-test-result` and the three stop-screen results, then the Review Loop's + * `review-loop-facts` and `review-loop-start-result`. `store` is the page object and `redraw` its * render; they are handed in so this file keeps importing nothing. */ export function wireLoopMessages(store, redraw) { @@ -59,6 +60,31 @@ export function wireLoopMessages(store, redraw) { store.loopStart = { ok: data.ok === true, error: data.ok === true ? null : String(data.error || "The app did not start the loop.") }; redraw(); }); + // The Review Loop's own answers: its facts, and the result of its Start. + onAppMessage("review-loop-facts", (data) => { + store.reviewFacts = data.facts && typeof data.facts === "object" ? data.facts : null; + redraw(); + }); + onAppMessage("review-loop-start-result", (data) => { + // Cancel in the app's confirm: nothing started, so the setup is as it was. + if (data.ok === true && data.started === false) { + store.reviewStart = null; + if (store.reviewLoopSetup) store.reviewLoopSetup.starting = false; + redraw(); + return; + } + store.reviewStart = { ok: data.ok === true, error: data.ok === true ? null : String(data.error || "The app did not start the Review Loop.") }; + if (!store.reviewStart.ok && store.reviewLoopSetup) store.reviewLoopSetup.starting = false; + redraw(); + }); + // The end screen's presses (Continue, Keep or Discard, Sign off, the finished + // screen's next step): the answer clears the pressed state and keeps any error. + for (const kind of ["review-loop-continue-result", "review-loop-partial-result", "review-loop-sign-off-result", "review-loop-next-result"]) { + onAppMessage(kind, (data) => { + store.reviewAction = { kind, ok: data.ok === true, error: data.ok === true ? null : String(data.error || "The app could not do that.") }; + redraw(); + }); + } onAppMessage("loop-notify-test-result", (data) => { store.loopNotifyTest = { waiting: false, ok: data.ok === true, sent: data.sent === true, error: data.ok === true ? null : String(data.error || "The app could not send the test.") }; redraw(); diff --git a/src/web-console/public/app.js b/src/web-console/public/app.js index c5ca2e7..7c0ce51 100644 --- a/src/web-console/public/app.js +++ b/src/web-console/public/app.js @@ -22,7 +22,7 @@ import { adopt, askSuggestions, banner, clearBanner, connect, fillSky, fitGrowBox, loadState, markSent, maybeWelcome, render, renderFooter, renderSidebar, renderWhere, save, startClock, startLooks, stagedPayload, syncWorkspaceScope, wakeHoldsChime, wireAsk, wireCards, wireChrome, wireCleanup, wireDashboard, wireDocs, wireEnding, - wireActivities, wireLoopSetup, wireHelp, launchSkill, sendLearning, beginLearningSave, renderLearningRow, learningBlocked, openHelpOn, openLoopSetup, wireLooks, wireNotepad, wirePrefs, wireWorkspace, + wireActivities, wireLoopSetup, wireHelp, launchSkill, sendLearning, beginLearningSave, renderLearningRow, learningBlocked, openHelpOn, openLoopSetup, openReviewLoopSetup, wireLooks, wireNotepad, wirePrefs, wireWorkspace, openPrefs, markSaved, confirmUnsaved, loadAgentsView, wireAgentsView, hasUnsaved, unsavedName, saveOpen, discardOpen, focusOpen, renderCard, send, refreshLessonsSend, } from "./screens/core.js"; @@ -37,7 +37,7 @@ import { sound } from "./sound.js"; // and the few calls a screen makes into another are handed to state.js first. onSave(save); useHooks({ - launchSkill, sendLearning, beginLearningSave, renderLearningRow, learningBlocked, openHelpOn, openLoopSetup, askSuggestions, banner, clearBanner, fitGrowBox, markSent, maybeWelcome, renderFooter, renderSidebar, renderWhere, stagedPayload, syncWorkspaceScope, + launchSkill, sendLearning, beginLearningSave, renderLearningRow, learningBlocked, openHelpOn, openLoopSetup, openReviewLoopSetup, askSuggestions, banner, clearBanner, fitGrowBox, markSent, maybeWelcome, renderFooter, renderSidebar, renderWhere, stagedPayload, syncWorkspaceScope, openPrefs, markSaved, confirmUnsaved, loadAgentsView, wireAgentsView, hasUnsaved, unsavedName, saveOpen, discardOpen, focusOpen, renderCard, send, refreshLessonsSend, }); diff --git a/src/web-console/public/index.html b/src/web-console/public/index.html index 3cc72c3..d285b82 100644 --- a/src/web-console/public/index.html +++ b/src/web-console/public/index.html @@ -2511,6 +2511,9 @@ that skips what is not worth fixing and records each skip, or by level (Critical, Warning, Suggestion). +
  • + Review rounds per phase (default 2): when a phase's own review leaves Critical or Warning, fresh reviewers run up to this many more rounds before the phase is committed. +
  • It uses the launch agent and model the app is running, and it needs permission checks off: with them on, an agent would diff --git a/src/web-console/public/loop-parts.js b/src/web-console/public/loop-parts.js new file mode 100644 index 0000000..52a1bd9 --- /dev/null +++ b/src/web-console/public/loop-parts.js @@ -0,0 +1,262 @@ +// Plan2Code Web Console - the parts both loop setup screens draw, so neither screen imports the other; defines only. +// +// The Implementation Loop's screen (screens/loop-setup.js) and the Review Loop's +// (screens/review-loop-setup.js) share these: the field builders, the strength +// words, the notification fields with their checks, and the silence input. The +// page's shape test keeps a screen from importing another screen, so what two +// screens use lives here, beside state.js. + +import { el } from "./render.js"; +import { page } from "./state.js"; + +export const STRENGTH_WORDS = [ + ["thrifty", "Thrifty"], + ["balanced", "Balanced"], + ["best", "Best"], +]; +export const MATCH_SESSION = "Match my session"; + +export const DEFAULT_NOTIFY_PARAM = "message"; +// What the setup can send a notification to. `name` is the label for the field +// the person names, on the kinds that have one. +export const NOTIFY_KINDS = [ + { id: "query", label: "A web address, with the message in its query string", placeholder: "https://example.com/hook", hint: "The app calls this address with a GET.", name: "Query string name for the message" }, + { id: "discord", label: "Discord webhook", placeholder: "https://discord.com/api/webhooks/...", hint: "In Discord: Edit Channel, Integrations, Webhooks, then Copy Webhook URL." }, + { id: "slack", label: "Slack webhook", placeholder: "https://hooks.slack.com/services/...", hint: "An Incoming Webhook URL from your Slack app's settings." }, + { id: "teams", label: "Microsoft Teams webhook", placeholder: "https://...", hint: 'In Teams: Workflows, the template "Post to a channel when a webhook request is received", then copy its URL.' }, + { id: "google-chat", label: "Google Chat webhook", placeholder: "https://chat.googleapis.com/v1/spaces/...", hint: "In the space: Apps & integrations, Webhooks, then copy the URL." }, + { id: "json", label: "A web address, with the message in a JSON body", placeholder: "https://example.com/hook", hint: "The app sends a POST with a JSON object holding the message, for any other service.", name: "JSON field name for the message" }, +]; + +export const hasMapping = (resolved) => Boolean(resolved) && Object.keys(resolved).length > 0; + +/** + * What is wrong with the web address fields as typed, or "". The server checks + * again on save; this is the line that shows while typing. + */ +export function notifyProblem(url, param, kind = "query") { + const address = url.trim(); + if (!address) return ""; + if (!/^https?:\/\//i.test(address)) return "The web address must start with http:// or https://."; + let good = /^https?:\/\/[^/?#@]+([/?#][!-~]*)?$/i.test(address) && !/[^!-~]/.test(address); + if (good) { + try { + good = Boolean(new URL(address).hostname); + } catch { + good = false; + } + } + if (!good) return "That is not a web address the app can call. Leave out any user name or password, and percent-encode spaces and accents."; + const named = NOTIFY_KINDS.some((k) => k.id === kind && k.name); + if (named && !/^[A-Za-z0-9._~-]{1,64}$/.test(param.trim() || DEFAULT_NOTIFY_PARAM)) return "The name can only use letters, digits, and - _ . ~"; + return ""; +} + +/** + * The chat service a pasted address belongs to, or "". A webhook needs a POST: + * a GET to a Discord webhook answers 200 and posts nothing, so staying on the + * query string kind would look like it worked. + */ +export function kindForUrl(url) { + let parsed; + try { + parsed = new URL(url.trim()); + } catch { + return ""; + } + const host = parsed.hostname.toLowerCase(); + const under = (domain) => host === domain || host.endsWith(`.${domain}`); + if ((under("discord.com") || under("discordapp.com")) && parsed.pathname.startsWith("/api/webhooks/")) return "discord"; + if (host === "hooks.slack.com") return "slack"; + if (host === "chat.googleapis.com") return "google-chat"; + if (under("logic.azure.com") || under("powerplatform.com") || under("powerautomate.com")) return "teams"; + return ""; +} + +export function field(label, hint) { + const box = el("div", "loop-field"); + box.appendChild(el("p", "loop-label", label)); + if (hint) box.appendChild(el("p", "loop-hint", hint)); + return box; +} + +export function toggle(id, text, checked, onChange) { + const label = el("label", "loop-switch"); + const input = el("input"); + input.type = "checkbox"; + input.id = id; + input.checked = checked; + input.addEventListener("change", () => onChange(input.checked)); + label.append(input, el("span", null, text)); + return label; +} + +export function radios(name, options, current, onChange) { + const group = el("div", "loop-radios"); + group.setAttribute("role", "radiogroup"); + for (const [value, text, detail] of options) { + const label = el("label", "loop-radio"); + const input = el("input"); + input.type = "radio"; + input.name = name; + input.id = `loop-${name}-${value}`; + input.checked = current === value; + input.addEventListener("change", () => input.checked && onChange(value)); + const body = el("span", "loop-radio-body"); + body.appendChild(el("span", "loop-radio-text", text)); + if (detail) body.appendChild(el("span", "loop-radio-detail", detail)); + label.append(input, body); + group.appendChild(label); + } + return group; +} + +/** A plain select: [value, text, disabled?] options, the chosen value, a change handler. */ +export function select(id, label, options, value, onChange) { + const box = el("select", "loop-select"); + box.id = id; + box.setAttribute("aria-label", label); + for (const [v, text, disabled] of options) { + const o = el("option", null, text); + o.value = v; + o.disabled = Boolean(disabled); + box.appendChild(o); + } + box.value = value; + box.addEventListener("change", () => onChange(box.value)); + return box; +} + +/** The "stuck after this many minutes" number input, bound to `f.silenceMinutes`. */ +export function silenceField(f, text = "Count the agent as stuck after this many minutes with no activity") { + const silence = el("label", "loop-number"); + silence.appendChild(el("span", null, text)); + const silenceInput = el("input", "is-compact loop-text loop-narrow"); + silenceInput.type = "number"; + silenceInput.id = "loop-silence"; + silenceInput.min = "1"; + silenceInput.max = "60"; + silenceInput.step = "1"; + silenceInput.value = String(f.silenceMinutes); + silenceInput.addEventListener("input", () => { + f.silenceMinutes = Number(silenceInput.value); + }); + silence.appendChild(silenceInput); + return silence; +} + +/** + * The "Send a notification" field: kind, address, the name for the message, the + * per-step toggle and Send a test. `s` is the screen's state (`starting`, + * `notifyKindChosen`), `f` its form (`notifyKind`, `notifyUrl`, `notifyParam`, + * and the toggle's key). `o` says what the toggle is called and keys on, and what + * Send a test does (`onTest`, required); the Implementation Loop's screen takes the + * other defaults. + */ +export function notifyFields(s, f, options = {}) { + const o = { + intro: + "When the loop waits on your answer or ends, except when you stop it yourself, the app sends a short message saying which, with the project, the phase, what it built and how long it took. Leave the address empty to send nothing.", + phasesId: "loop-notify-phases", + phasesKey: "notifyPhases", + phasesText: "Also tell me when each phase is complete", + ...options, + }; + const notify = field("Send a notification", o.intro); + const kindLabel = el("label", "loop-number"); + kindLabel.appendChild(el("span", null, "Send to")); + const kindSelect = el("select", "is-compact loop-text"); + kindSelect.id = "loop-notify-kind"; + for (const kind of NOTIFY_KINDS) { + const option = el("option", null, kind.label); + option.value = kind.id; + kindSelect.appendChild(option); + } + kindSelect.value = f.notifyKind; + kindLabel.appendChild(kindSelect); + const kindHint = el("p", "loop-hint"); + const notifyInput = el("input", "is-compact loop-text"); + notifyInput.type = "text"; + notifyInput.inputMode = "url"; + notifyInput.id = "loop-notify-url"; + notifyInput.value = f.notifyUrl; + notifyInput.maxLength = 2000; + notifyInput.setAttribute("aria-label", "Web address to call"); + const paramRow = el("div"); + const paramLabel = el("label", "loop-number"); + const paramText = el("span"); + paramLabel.appendChild(paramText); + const paramInput = el("input", "is-compact loop-text loop-param"); + paramInput.type = "text"; + paramInput.id = "loop-notify-param"; + paramInput.value = f.notifyParam; + paramInput.placeholder = DEFAULT_NOTIFY_PARAM; + paramInput.maxLength = 64; + paramLabel.appendChild(paramInput); + paramRow.appendChild(paramLabel); + const phasesRow = toggle(o.phasesId, o.phasesText, f[o.phasesKey], (v) => { + f[o.phasesKey] = v; + }); + const notifyWarn = el("p", "loop-warn"); + const testRow = el("div", "loop-test"); + const testButton = el("button", "btn", "Send a test"); + testButton.type = "button"; + testButton.id = "loop-notify-test"; + testButton.addEventListener("click", () => o.onTest()); + testRow.appendChild(testButton); + const testLine = notifyTestLine(); + if (testLine) testRow.appendChild(testLine); + const showNotify = () => { + const kind = NOTIFY_KINDS.find((k) => k.id === f.notifyKind); + kindSelect.value = kind.id; + kindHint.textContent = kind.hint; + notifyInput.placeholder = kind.placeholder; + paramText.textContent = kind.name || ""; + paramRow.hidden = !kind.name || f.notifyUrl.trim() === ""; + phasesRow.hidden = f.notifyUrl.trim() === ""; + const problem = notifyProblem(f.notifyUrl, f.notifyParam, kind.id); + notifyWarn.textContent = problem; + notifyWarn.hidden = !problem; + testButton.disabled = Boolean(problem) || f.notifyUrl.trim() === "" || Boolean(page.loopNotifyTest && page.loopNotifyTest.waiting) || s.starting; + }; + // What a test said was about the address as it was. + const forgetTest = () => { + if (page.loopNotifyTest && !page.loopNotifyTest.waiting) { + page.loopNotifyTest = null; + testRow.querySelector("p")?.remove(); + } + }; + notifyInput.addEventListener("input", () => { + f.notifyUrl = notifyInput.value; + forgetTest(); + // A pasted webhook picks its own kind, unless the person chose one here. + const service = kindForUrl(f.notifyUrl); + if (service && f.notifyKind === "query" && !s.notifyKindChosen) f.notifyKind = service; + showNotify(); + }); + kindSelect.addEventListener("change", () => { + f.notifyKind = kindSelect.value; + forgetTest(); + s.notifyKindChosen = true; + showNotify(); + }); + paramInput.addEventListener("input", () => { + f.notifyParam = paramInput.value; + forgetTest(); + showNotify(); + }); + showNotify(); + notify.append(kindLabel, notifyInput, kindHint, paramRow, phasesRow, notifyWarn, testRow); + return notify; +} + +/** The line beside Send a test, or null with nothing to say. */ +export function notifyTestLine() { + const test = page.loopNotifyTest; + if (!test) return null; + if (test.waiting) return el("p", "loop-why", "Waiting for the app's confirm..."); + if (!test.ok) return el("p", "loop-error", test.error); + if (test.sent) return el("p", "loop-why", "Sent, and the address answered OK. Check that the message arrived."); + return null; +} + diff --git a/src/web-console/public/review-loop-end.js b/src/web-console/public/review-loop-end.js new file mode 100644 index 0000000..ae1665a --- /dev/null +++ b/src/web-console/public/review-loop-end.js @@ -0,0 +1,201 @@ +// Plan2Code Web Console - how a Review Loop run ends: the stop screens, the sign-off and the finished screen; defines only. + +import { el } from "./render.js"; +import { field, toggle } from "./loop-parts.js"; +import { blockBody } from "./doc-files.js"; +import { docs } from "./selectors.js"; +import { tellApp } from "./app-bridge.js"; +import { page, redraw } from "./state.js"; + +// The app's `loopEnd` with `kind: "review"` (patches.mjs reviewLoopEndProblems): +// reason why it ended: clean, cap, person or failed +// report a doc on the page holding the Markdown report +// partial after Stop now: the partial diff doc and its stats, until Keep or Discard +// suggestions, canSquash, canContinue, open, signedOff, note +// Before sign-off the card offers Continue (when allowed), the Suggestions pick, +// the squash switch and Sign off; after it, the finished screen's three ways on. + +const HEADINGS = { + clean: "Clean", + cap: "Stopped at the round cap", + person: "Stopped by you", + failed: "Failed", +}; + +// What the card remembers across redraws, keyed by the ending it belongs to: +// the ticked Suggestions, the squash switch, and which press is waiting on the app. +let ticks = { key: null, picks: new Set(), squash: false }; +let pressed = { key: null, what: "" }; +let lastKey = null; + +// The ending a press belongs to. Keep or Discard reposts the same ending without +// its partial changes, so a press waiting on the app ends with that change. +function endKey(end) { + return `review|${end.line}|${end.reason}|${end.signedOff ? "signed" : "open"}|${end.partial ? "partial" : "whole"}`; +} + +// The ending the ticks and the squash switch belong to: the same through Keep +// or Discard, so what the person ticked is not cleared by settling the partial changes. +function tickKey(end) { + return `review|${end.line}|${end.reason}|${end.signedOff ? "signed" : "open"}`; +} + +function button(label, id, cls, disabled, onClick) { + const b = el("button", "btn" + (cls ? " " + cls : ""), label); + b.type = "button"; + b.id = id; + b.disabled = disabled; + b.addEventListener("click", onClick); + return b; +} + +function stats(partial) { + const row = el("p", "diff-totals review-end-stats"); + row.appendChild(el("span", null, `${partial.files} ${partial.files === 1 ? "file" : "files"} changed, `)); + row.appendChild(el("span", "diff-plus", `+${partial.added}`)); + row.appendChild(document.createTextNode(" ")); + row.appendChild(el("span", "diff-minus", `-${partial.removed}`)); + return row; +} + +function where(item) { + if (!item.file) return ""; + return item.line ? `${item.file}:${item.line}` : item.file; +} + +/** How a Review Loop run ended, drawn from the app's `loopEnd`. */ +export function renderReviewLoopEnd(end) { + const key = endKey(end); + if (lastKey !== key) { + lastKey = key; + page.reviewAction = null; + } + const ticked = tickKey(end); + if (ticks.key !== ticked) ticks = { key: ticked, picks: new Set(), squash: false }; + const failed = + page.reviewAction && !page.reviewAction.ok ? page.reviewAction.error : page.loopAction && !page.loopAction.ok ? page.loopAction.error : ""; + const busy = pressed.key === key && !failed; + const press = (what, kind, extra) => { + if (page.gone || busy) return; + pressed = { key, what }; + page.reviewAction = null; + page.loopAction = null; + tellApp(kind, extra); + redraw(); + }; + + const card = el("article", "card handoff loop-end review-end"); + card.appendChild(el("p", "card-kicker", end.signedOff ? "Review Loop finished" : "Review Loop ended")); + const heading = end.signedOff ? "Signed off" : HEADINGS[end.reason] || end.line; + card.appendChild(el("h2", "loop-end-heading review-end-heading", heading)); + if (end.line) card.appendChild(el("p", "loop-line review-end-line", end.line)); + if (end.note) card.appendChild(el("p", "callout is-info review-end-note", end.note)); + + const report = docs().find((d) => d.id === end.report); + if (report) { + const read = el("button", "btn sm review-end-report", "Read the full report"); + read.type = "button"; + read.addEventListener("click", () => { + page.view = "doc:" + report.id; + redraw(); + }); + card.appendChild(read); + } + + if (end.signedOff) { + drawFinished(card, end, busy, press); + } else { + drawStop(card, end, busy, press); + } + if (failed) card.appendChild(el("p", "loop-error review-end-error", failed)); + return card; +} + +function drawPartial(card, end, busy, press) { + const partial = end.partial; + const box = el("section", "review-end-partial"); + box.appendChild(el("h3", null, "What Stop now left")); + box.appendChild(stats(partial)); + const doc = docs().find((d) => d.id === partial.diff); + const block = doc && (doc.blocks || []).find((b) => typeof b.diff === "string" || typeof b.text === "string"); + if (block) { + const view = el("div", "review-end-diff"); + view.appendChild(blockBody(block, doc)); + box.appendChild(view); + } + box.appendChild(el("p", "loop-end-hint", "Keep leaves these changes in your files. Discard takes them out and cannot be undone.")); + const row = el("div", "btn-row"); + row.appendChild(button("Keep these changes", "review-end-keep", "primary", busy, () => press("keep", "review-loop-partial", { keep: true }))); + row.appendChild(button("Discard them", "review-end-discard", "", busy, () => press("discard", "review-loop-partial", { keep: false }))); + box.appendChild(row); + card.appendChild(box); +} + +function drawStop(card, end, busy, press) { + if (end.partial) drawPartial(card, end, busy, press); + // While the partial work is undecided the app refuses Continue, so it is not offered. + if (end.canContinue && !end.partial) { + const choice = el("div", "loop-end-choice"); + const label = end.reason === "cap" ? "Run one more round" : "Continue"; + choice.appendChild(button(label, "review-end-continue", "", busy, () => press("continue", "review-loop-continue"))); + choice.appendChild(el("p", "loop-end-hint", "Pick the review up again with the same setup.")); + card.appendChild(choice); + } + + const suggestions = Array.isArray(end.suggestions) ? end.suggestions : []; + if (suggestions.length) { + const pick = field("Suggestions", "Nothing is ticked. Ticked ones are applied in one last pass, with their own check and commit."); + pick.classList.add("review-end-suggestions"); + for (const s of suggestions) { + const label = toggle(`review-end-pick-${s.id}`, "", ticks.picks.has(s.id), (on) => { + if (on) ticks.picks.add(s.id); + else ticks.picks.delete(s.id); + }); + label.classList.add("review-end-pick"); + const text = label.querySelector("span"); + text.appendChild(el("strong", null, s.title)); + const at = where(s); + if (at) text.appendChild(el("code", "review-end-where", at)); + pick.appendChild(label); + } + card.appendChild(pick); + } + if (end.canSquash) { + const sq = field("Commits"); + sq.appendChild(toggle("review-end-squash", "Squash the round commits into one", ticks.squash, (on) => (ticks.squash = on))); + card.appendChild(sq); + } + const row = el("div", "btn-row"); + row.appendChild( + button("Sign off", "review-end-signoff", "primary", busy || Boolean(end.partial), () => press("sign-off", "review-loop-sign-off", { picks: [...ticks.picks], squash: ticks.squash })) + ); + card.appendChild(row); + card.appendChild( + el("p", "loop-end-hint", end.partial ? "Keep or discard the partial changes first, then sign off." : "Sign off finishes the run, with or without picks.") + ); +} + +function drawFinished(card, end, busy, press) { + const actions = el("div", "loop-end-actions review-end-next"); + const add = (label, id, hint, primary, onClick) => { + const choice = el("div", "loop-end-choice" + (primary ? " is-recommended" : "")); + choice.appendChild(button(label, id, primary ? "primary" : "", busy, onClick)); + choice.appendChild(el("p", "loop-end-hint", hint)); + actions.appendChild(choice); + }; + add("PR Prep", "review-end-pr-prep", "Get the branch ready for a pull request.", true, () => press("pr-prep", "review-loop-next", { next: "pr-prep" })); + if (Array.isArray(end.open) && end.open.length) { + add("Fix what's left by hand", "review-end-quick-task", "Start a Quick task with the Critical and Warning findings still open.", false, () => + press("quick-task", "review-loop-next", { next: "quick-task" }) + ); + } + add("Back to the dashboard", "review-end-dashboard", "Leave this screen and pick another skill. Your work stays as it is.", false, () => press("dashboard", "loop-dashboard")); + card.appendChild(actions); +} + +/** The end card is no longer drawn (Continue started another round): a press and + * the ending it belonged to are over, so the next ending starts with live buttons. */ +export function forgetReviewEnd() { + pressed = { key: null, what: "" }; + lastKey = null; +} diff --git a/src/web-console/public/screens/core.js b/src/web-console/public/screens/core.js index 433cccd..2944ae6 100644 --- a/src/web-console/public/screens/core.js +++ b/src/web-console/public/screens/core.js @@ -68,6 +68,7 @@ import { import { sound } from "../sound.js"; import { renderConfirm, renderDashboard } from "./dashboard.js"; import { renderLoopSetup } from "./loop-setup.js"; +import { renderReviewLoopSetup } from "./review-loop-setup.js"; import { renderLaunching, renderWaiting } from "./starting.js"; import { attachFiles, findSetAside, heldNotes, noteImages, pendingNotes, purgeImages } from "../uploads.js"; import { closeMentions } from "../mention-box.js"; @@ -82,6 +83,7 @@ import { framed, linkLeavesPage, onAppMessage, shortcutIdFor, startNewSession, t import { openPrefs as openPrefsDialog } from "./prefs-dialog.js"; import { continueButton } from "../continue-button.js"; import { askOfflineFlipped, askState, declineOpen, renderAside, renderAsk, renderSubagents, renderSubagentsButton } from "./ask.js"; +import { forgetReviewEnd } from "../review-loop-end.js"; import { renderHandoff, renderLoopEnd, renderHomeButton, renderStopButton, renderStopControls, renderStopping, renderFooterDashboard, stopInProgress, stopWarning } from "./ending.js"; import { renderNotepadButton } from "./notepad.js"; import { renderActivities } from "./activities.js"; @@ -107,6 +109,7 @@ export { wireEnding } from "./ending.js"; export { wireNotepad } from "./notepad.js"; export { wireActivities } from "./activities.js"; export { openLoopSetup, wireLoopSetup } from "./loop-setup.js"; +export { openReviewLoopSetup } from "./review-loop-setup.js"; const $ = (id) => document.getElementById(id); @@ -450,6 +453,7 @@ export function adopt(body) { if (!isDashboard() || finish()) { page.dashPick = null; page.loopSetup = null; + page.reviewLoopSetup = null; } // A launch (or an ending) mid wake-up: cut it short rather than play on // over a page that is no longer the menu. @@ -1419,6 +1423,9 @@ export function renderStatus() { // still has presses on offer the move is theirs; with none, it is done. if (page.S.loopEnd) { const end = page.S.loopEnd; + if (end.kind === "review") { + return end.signedOff ? say("point", "Signed off. Pick what happens next.") : say("point", "The Review Loop ended. Sign off when you are ready."); + } const moves = Array.isArray(end.can) ? end.can.length : 0; if (!moves) return say("done", "The loop is done."); return say( @@ -1805,6 +1812,7 @@ function paintMain(main) { if (isDashboard() && !finish()) { if (page.local.launching) renderLaunching(main); else if (page.loopSetup) renderLoopSetup(main); + else if (page.reviewLoopSetup) renderReviewLoopSetup(main); else if (page.dashPick) { // A spec-switch under an open confirm can gray the pick out. Rather // than offer START on a card that cannot launch, drop back to the @@ -1816,7 +1824,7 @@ function paintMain(main) { } } else renderDashboard(main); // Review from the Learning banner: the lessons card, over the menu. - renderLessonsDialog(!page.local.launching && !page.loopSetup && !page.dashPick); + renderLessonsDialog(!page.local.launching && !page.loopSetup && !page.reviewLoopSetup && !page.dashPick); return; } renderLessonsDialog(false); @@ -1849,6 +1857,7 @@ function paintMain(main) { // How the Implementation Loop ended, from the app's `loopEnd`: its own // screen, ahead of any card the last phase left behind. + if (!page.S.loopEnd) forgetReviewEnd(); if (page.S.loopEnd && !finish()) { const card = renderLoopEnd(page.S.loopEnd); card.classList.add("is-primary"); @@ -2601,9 +2610,10 @@ export function wireChrome() { // Escape is the confirm pane's Back — but not while a dialog has it. Native // dialogs close themselves on the same key; backing out of the pick at the // same time would be two undos for one press. - if (e.key === "Escape" && (page.dashPick || page.loopSetup) && isDashboard() && !finish() && !document.querySelector("dialog[open]")) { + if (e.key === "Escape" && (page.dashPick || page.loopSetup || page.reviewLoopSetup) && isDashboard() && !finish() && !document.querySelector("dialog[open]")) { page.dashPick = null; page.loopSetup = null; + page.reviewLoopSetup = null; redraw(); } }); diff --git a/src/web-console/public/screens/dashboard.js b/src/web-console/public/screens/dashboard.js index 9ba4d49..2345d50 100644 --- a/src/web-console/public/screens/dashboard.js +++ b/src/web-console/public/screens/dashboard.js @@ -30,6 +30,7 @@ import { SKILL_CATALOG, catalogEntry, LOOP_ENTRY, + APP_ONLY_ENTRIES, OUTSIDE_APP_LINE, launchVariant, SPEC_STATE_LABELS, @@ -296,16 +297,17 @@ export function renderDashboard(main) { let shown = 0; for (const g of CATALOG_GROUPS) { const entries = SKILL_CATALOG.filter((e) => e.group === g.id && (!hide || available(e))); - // The desktop app's Implementation Loop card closes its group. Outside the - // app it is always drawn, grayed, so the feature can be found. - const loopCard = LOOP_ENTRY && LOOP_ENTRY.group === g.id && (!page.inApp || !hide || available(LOOP_ENTRY)); - if (!entries.length && !loopCard) continue; - shown += entries.length + (loopCard ? 1 : 0); + // The desktop app's Implementation Loop and Review Loop cards close their + // group. Outside the app they are always drawn, grayed, so the features can + // be found. + const loopCards = APP_ONLY_ENTRIES.filter((e) => e.group === g.id && (!page.inApp || !hide || available(e))); + if (!entries.length && !loopCards.length) continue; + shown += entries.length + loopCards.length; const section = el("section", "dash-group"); section.appendChild(el("h3", "dash-group-title", g.title)); const grid = el("div", "dash-grid"); for (const e of entries) grid.appendChild(dashCard(e, menu)); - if (loopCard) grid.appendChild(dashCard(LOOP_ENTRY, menu)); + for (const e of loopCards) grid.appendChild(dashCard(e, menu)); section.appendChild(grid); wrap.appendChild(section); } @@ -752,6 +754,8 @@ async function readHandoff(h) { } } +const REVIEW_LOOP_SKILL = "plan2code-review-loop"; + function dashCard(entry, menu) { const presentation = entry.appOnly ? loopPresentation(entry, menu) : cardPresentation(entry, scan(), selSpec(), menu); // The agent's `recommend` and detail describe the initially selected spec. @@ -784,6 +788,8 @@ function dashCard(entry, menu) { title.appendChild(document.createTextNode(entry.title)); b.appendChild(title); b.appendChild(el("span", "dash-card-blurb", entry.blurb)); + // A line only the desktop app shows (the Review card's pointer to the Review Loop). + if (entry.appNote && page.inApp) b.appendChild(el("span", "dash-card-detail", entry.appNote)); if (presentation.detail) b.appendChild(el("span", "dash-card-detail", presentation.detail)); if (!presentation.on && presentation.reason) b.appendChild(el("span", "dash-card-off", presentation.reason)); @@ -793,8 +799,8 @@ function dashCard(entry, menu) { b.appendChild(foot); b.addEventListener("click", () => { - // The loop card opens its own setup screen instead of a confirm pane. - if (entry.appOnly) return hooks.openLoopSetup(selSpec()); + // A loop card opens its own setup screen instead of a confirm pane. + if (entry.appOnly) return entry.skill === REVIEW_LOOP_SKILL ? hooks.openReviewLoopSetup(selSpec()) : hooks.openLoopSetup(selSpec()); page.dashPick = entry; redraw(); }); @@ -803,7 +809,7 @@ function dashCard(entry, menu) { if (entry.appOnly) { const wrap = el("div", "dash-card-wrap"); wrap.appendChild(b); - wrap.appendChild(loopHelpLink()); + wrap.appendChild(loopHelpLink(entry)); return wrap; } return b; @@ -814,13 +820,17 @@ function dashCard(entry, menu) { // pre-selected: a person opts into running unattended. function loopPresentation(entry, menu) { if (!page.inApp) return { on: false, reason: OUTSIDE_APP_LINE, recommended: false, detail: "" }; + if (entry.skill === REVIEW_LOOP_SKILL && loopDriving()) { + return { on: false, reason: "A loop is running. Stop it from the banner at the top of the window first.", recommended: false, detail: "" }; + } return { ...cardPresentation(entry, scan(), selSpec(), menu), recommended: false }; } // "How the loop works" under the card: a real button styled as a link, a // sibling of the card button inside its wrapper. -function loopHelpLink() { - const a = el("button", "dash-card-link", "How the loop works"); +function loopHelpLink(entry) { + const review = entry && entry.skill === REVIEW_LOOP_SKILL; + const a = el("button", "dash-card-link", review ? "How the Review Loop works" : "How the loop works"); a.type = "button"; a.addEventListener("click", () => hooks.openHelpOn("loop")); return a; diff --git a/src/web-console/public/screens/ending.js b/src/web-console/public/screens/ending.js index 77e09c6..3ba9ebb 100644 --- a/src/web-console/public/screens/ending.js +++ b/src/web-console/public/screens/ending.js @@ -55,6 +55,7 @@ const LOOP_LOCK_TITLE = "The loop is building. Stop it from the banner at the to import { docSavedNote, downloadDoc } from "../doc-files.js"; import { startNewSession, tellApp } from "../app-bridge.js"; import { pendingNotes } from "../uploads.js"; +import { renderReviewLoopEnd } from "../review-loop-end.js"; // The end of the session, and the only screen in this page whose job is to // send someone somewhere else. @@ -239,6 +240,7 @@ function loopEndKey(end) { * its agent made; the report behind the button holds them all). */ export function renderLoopEnd(end) { + if (end.kind === "review") return renderReviewLoopEnd(end); const card = el("article", "card handoff loop-end"); const finished = end.kind === "finished"; card.appendChild(el("p", "card-kicker", finished ? "Loop finished" : "Loop stopped")); diff --git a/src/web-console/public/screens/help-dialog.js b/src/web-console/public/screens/help-dialog.js index e94cff0..0ba2b23 100644 --- a/src/web-console/public/screens/help-dialog.js +++ b/src/web-console/public/screens/help-dialog.js @@ -272,6 +272,8 @@ function buildHelp() { } li.appendChild(strong); li.appendChild(document.createTextNode(" " + (e.help || e.blurb))); + // The app-only pointer (Review's line about the Review Loop), shown in the app. + if (e.appNote && page.inApp) li.appendChild(el("span", "help-app-note", " " + e.appNote)); list.appendChild(li); } cards.append(head, list); diff --git a/src/web-console/public/screens/loop-setup.js b/src/web-console/public/screens/loop-setup.js index cbb04f7..b5cd6b8 100644 --- a/src/web-console/public/screens/loop-setup.js +++ b/src/web-console/public/screens/loop-setup.js @@ -11,6 +11,7 @@ import { hooks, page, redraw, saveNow } from "../state.js"; import { SKILL_CATALOG } from "../answers.js"; import { postJson } from "../net.js"; import { tellApp, wireLoopMessages } from "../app-bridge.js"; +import { DEFAULT_NOTIFY_PARAM, MATCH_SESSION, NOTIFY_KINDS, STRENGTH_WORDS, field, hasMapping, notifyFields, notifyProblem, radios, select, silenceField, toggle } from "../loop-parts.js"; let justPicked = ""; // the strength node picked a moment ago, which alone plays its grow // Suggest for me was pressed and has just come back (answer, time-out or failed @@ -34,26 +35,9 @@ const AFTER_LAST = [ ["run-finalize", "Run Finalize automatically", "Finalize starts by itself once every phase is built."], ]; -const STRENGTH_WORDS = [ - ["thrifty", "Thrifty"], - ["balanced", "Balanced"], - ["best", "Best"], -]; -const MATCH_SESSION = "Match my session"; // How long Suggest for me waits on the dashboard agent before it gives the field back. export const SUGGEST_WAIT_MS = 120000; -const DEFAULT_NOTIFY_PARAM = "message"; -// What the setup can send a notification to. `name` is the label for the field -// the person names, on the kinds that have one. -const NOTIFY_KINDS = [ - { id: "query", label: "A web address, with the message in its query string", placeholder: "https://example.com/hook", hint: "The app calls this address with a GET.", name: "Query string name for the message" }, - { id: "discord", label: "Discord webhook", placeholder: "https://discord.com/api/webhooks/...", hint: "In Discord: Edit Channel, Integrations, Webhooks, then Copy Webhook URL." }, - { id: "slack", label: "Slack webhook", placeholder: "https://hooks.slack.com/services/...", hint: "An Incoming Webhook URL from your Slack app's settings." }, - { id: "teams", label: "Microsoft Teams webhook", placeholder: "https://...", hint: 'In Teams: Workflows, the template "Post to a channel when a webhook request is received", then copy its URL.' }, - { id: "google-chat", label: "Google Chat webhook", placeholder: "https://chat.googleapis.com/v1/spaces/...", hint: "In the space: Apps & integrations, Webhooks, then copy the URL." }, - { id: "json", label: "A web address, with the message in a JSON body", placeholder: "https://example.com/hook", hint: "The app sends a POST with a JSON object holding the message, for any other service.", name: "JSON field name for the message" }, -]; const SMART_DETAIL = "A fresh agent reads the review's findings and fixes the ones worth fixing. A skipped Critical stops the phase."; /** Called by the page's start-up: hear the app's answers to the loop's requests. */ @@ -97,6 +81,7 @@ export async function openLoopSetup(spec) { const { phasesLeft, branch, pending, suggestedQuickCheck, remembered, saved, picks, resolved, ...setup } = answer; mine.form = { review: setup.review !== false, + reviewRounds: Number.isInteger(setup.reviewRounds) && setup.reviewRounds >= 0 && setup.reviewRounds <= 6 ? setup.reviewRounds : 2, fixMode: setup.fixMode === "levels" ? "levels" : "smart", fix: Array.isArray(setup.fix) ? [...setup.fix] : LEVELS.map(([k]) => k), commit: setup.commit !== false, @@ -154,8 +139,6 @@ function ensureResolved(s) { }); } -const hasMapping = (resolved) => Boolean(resolved) && Object.keys(resolved).length > 0; - /** This spec's saved word for a phase, or "" for Match my session. */ function pickOf(form, spec, phase) { const list = form.strengths && form.strengths[spec]; @@ -220,87 +203,6 @@ export function startBlock(form, facts, appFacts) { return ""; } -/** - * What is wrong with the web address fields as typed, or "". The server checks - * again on save; this is the line that shows while typing. - */ -export function notifyProblem(url, param, kind = "query") { - const address = url.trim(); - if (!address) return ""; - if (!/^https?:\/\//i.test(address)) return "The web address must start with http:// or https://."; - let good = /^https?:\/\/[^/?#@]+([/?#][!-~]*)?$/i.test(address) && !/[^!-~]/.test(address); - if (good) { - try { - good = Boolean(new URL(address).hostname); - } catch { - good = false; - } - } - if (!good) return "That is not a web address the app can call. Leave out any user name or password, and percent-encode spaces and accents."; - const named = NOTIFY_KINDS.some((k) => k.id === kind && k.name); - if (named && !/^[A-Za-z0-9._~-]{1,64}$/.test(param.trim() || DEFAULT_NOTIFY_PARAM)) return "The name can only use letters, digits, and - _ . ~"; - return ""; -} - -/** - * The chat service a pasted address belongs to, or "". A webhook needs a POST: - * a GET to a Discord webhook answers 200 and posts nothing, so staying on the - * query string kind would look like it worked. - */ -export function kindForUrl(url) { - let parsed; - try { - parsed = new URL(url.trim()); - } catch { - return ""; - } - const host = parsed.hostname.toLowerCase(); - const under = (domain) => host === domain || host.endsWith(`.${domain}`); - if ((under("discord.com") || under("discordapp.com")) && parsed.pathname.startsWith("/api/webhooks/")) return "discord"; - if (host === "hooks.slack.com") return "slack"; - if (host === "chat.googleapis.com") return "google-chat"; - if (under("logic.azure.com") || under("powerplatform.com") || under("powerautomate.com")) return "teams"; - return ""; -} - -function field(label, hint) { - const box = el("div", "loop-field"); - box.appendChild(el("p", "loop-label", label)); - if (hint) box.appendChild(el("p", "loop-hint", hint)); - return box; -} - -function toggle(id, text, checked, onChange) { - const label = el("label", "loop-switch"); - const input = el("input"); - input.type = "checkbox"; - input.id = id; - input.checked = checked; - input.addEventListener("change", () => onChange(input.checked)); - label.append(input, el("span", null, text)); - return label; -} - -function radios(name, options, current, onChange) { - const group = el("div", "loop-radios"); - group.setAttribute("role", "radiogroup"); - for (const [value, text, detail] of options) { - const label = el("label", "loop-radio"); - const input = el("input"); - input.type = "radio"; - input.name = name; - input.id = `loop-${name}-${value}`; - input.checked = current === value; - input.addEventListener("change", () => input.checked && onChange(value)); - const body = el("span", "loop-radio-body"); - body.appendChild(el("span", "loop-radio-text", text)); - if (detail) body.appendChild(el("span", "loop-radio-detail", detail)); - label.append(input, body); - group.appendChild(label); - } - return group; -} - function factRow(list, label, value) { const row = el("div", "loop-fact"); row.appendChild(el("dt", null, label)); @@ -348,22 +250,6 @@ export function renderLoopSetup(main) { main.appendChild(pane); } -/** A plain select: [value, text, disabled?] options, the chosen value, a change handler. */ -function select(id, label, options, value, onChange) { - const box = el("select", "loop-select"); - box.id = id; - box.setAttribute("aria-label", label); - for (const [v, text, disabled] of options) { - const o = el("option", null, text); - o.value = v; - o.disabled = Boolean(disabled); - box.appendChild(o); - } - box.value = value; - box.addEventListener("change", () => onChange(box.value)); - return box; -} - /** * The rising-bar badge of the Subagents tab for a strength level: bars up to * `level` (1 to 3) are on. Level 0 (Match my session) has no rank, so it draws @@ -521,7 +407,7 @@ function applySuggestion(s, answer, resolved) { } /** The "Strength per phase" field: the toggle, Set all to, and one row per phase left. */ -function strengthField(s, redo) { +export function strengthField(s, redo) { stopWatchingLine(); const f = s.form; const resolved = s.facts.resolved; @@ -697,6 +583,7 @@ function drawBody(pane, s) { const review = field("Review"); review.appendChild(toggle("loop-review", "Review each phase with a fresh agent before it counts", f.review, (v) => ((f.review = v), redo()))); + review.appendChild(roundsField(f)); form.appendChild(review); if (f.review) { @@ -735,95 +622,7 @@ function drawBody(pane, s) { after.appendChild(radios("afterlast", AFTER_LAST, f.afterLast, (v) => ((f.afterLast = v), redo()))); form.appendChild(after); - const notify = field( - "Send a notification", - "When the loop waits on your answer or ends, except when you stop it yourself, the app sends a short message saying which, with the project, the phase, what it built and how long it took. Leave the address empty to send nothing." - ); - const kindLabel = el("label", "loop-number"); - kindLabel.appendChild(el("span", null, "Send to")); - const kindSelect = el("select", "is-compact loop-text"); - kindSelect.id = "loop-notify-kind"; - for (const kind of NOTIFY_KINDS) { - const option = el("option", null, kind.label); - option.value = kind.id; - kindSelect.appendChild(option); - } - kindSelect.value = f.notifyKind; - kindLabel.appendChild(kindSelect); - const kindHint = el("p", "loop-hint"); - const notifyInput = el("input", "is-compact loop-text"); - notifyInput.type = "text"; - notifyInput.inputMode = "url"; - notifyInput.id = "loop-notify-url"; - notifyInput.value = f.notifyUrl; - notifyInput.maxLength = 2000; - notifyInput.setAttribute("aria-label", "Web address to call"); - const paramRow = el("div"); - const paramLabel = el("label", "loop-number"); - const paramText = el("span"); - paramLabel.appendChild(paramText); - const paramInput = el("input", "is-compact loop-text loop-param"); - paramInput.type = "text"; - paramInput.id = "loop-notify-param"; - paramInput.value = f.notifyParam; - paramInput.placeholder = DEFAULT_NOTIFY_PARAM; - paramInput.maxLength = 64; - paramLabel.appendChild(paramInput); - paramRow.appendChild(paramLabel); - const phasesRow = toggle("loop-notify-phases", "Also tell me when each phase is complete", f.notifyPhases, (v) => { - f.notifyPhases = v; - }); - const notifyWarn = el("p", "loop-warn"); - const testRow = el("div", "loop-test"); - const testButton = el("button", "btn", "Send a test"); - testButton.type = "button"; - testButton.id = "loop-notify-test"; - testButton.addEventListener("click", () => sendTest(s)); - testRow.appendChild(testButton); - const testLine = notifyTestLine(); - if (testLine) testRow.appendChild(testLine); - const showNotify = () => { - const kind = NOTIFY_KINDS.find((k) => k.id === f.notifyKind); - kindSelect.value = kind.id; - kindHint.textContent = kind.hint; - notifyInput.placeholder = kind.placeholder; - paramText.textContent = kind.name || ""; - paramRow.hidden = !kind.name || f.notifyUrl.trim() === ""; - phasesRow.hidden = f.notifyUrl.trim() === ""; - const problem = notifyProblem(f.notifyUrl, f.notifyParam, kind.id); - notifyWarn.textContent = problem; - notifyWarn.hidden = !problem; - testButton.disabled = Boolean(problem) || f.notifyUrl.trim() === "" || Boolean(page.loopNotifyTest && page.loopNotifyTest.waiting) || s.starting; - }; - // What a test said was about the address as it was. - const forgetTest = () => { - if (page.loopNotifyTest && !page.loopNotifyTest.waiting) { - page.loopNotifyTest = null; - testRow.querySelector("p")?.remove(); - } - }; - notifyInput.addEventListener("input", () => { - f.notifyUrl = notifyInput.value; - forgetTest(); - // A pasted webhook picks its own kind, unless the person chose one here. - const service = kindForUrl(f.notifyUrl); - if (service && f.notifyKind === "query" && !s.notifyKindChosen) f.notifyKind = service; - showNotify(); - }); - kindSelect.addEventListener("change", () => { - f.notifyKind = kindSelect.value; - forgetTest(); - s.notifyKindChosen = true; - showNotify(); - }); - paramInput.addEventListener("input", () => { - f.notifyParam = paramInput.value; - forgetTest(); - showNotify(); - }); - showNotify(); - notify.append(kindLabel, notifyInput, kindHint, paramRow, phasesRow, notifyWarn, testRow); - form.appendChild(notify); + form.appendChild(notifyFields(s, f, { onTest: () => sendTest(s) })); const check = field("Quick check", "A command the app runs after each phase, such as npm run build. The page never runs it."); const checkInput = el("input", "is-compact loop-text"); @@ -844,20 +643,7 @@ function drawBody(pane, s) { const retry = field("If a phase crashes or goes quiet"); retry.appendChild(toggle("loop-retry", "Retry it once", f.retryOnce, (v) => ((f.retryOnce = v), redo()))); - const silence = el("label", "loop-number"); - silence.appendChild(el("span", null, "Count the agent as stuck after this many minutes with no activity")); - const silenceInput = el("input", "is-compact loop-text loop-narrow"); - silenceInput.type = "number"; - silenceInput.id = "loop-silence"; - silenceInput.min = "1"; - silenceInput.max = "60"; - silenceInput.step = "1"; - silenceInput.value = String(f.silenceMinutes); - silenceInput.addEventListener("input", () => { - f.silenceMinutes = Number(silenceInput.value); - }); - silence.appendChild(silenceInput); - retry.appendChild(silence); + retry.appendChild(silenceField(f)); retry.appendChild(el("p", "loop-hint", "No activity means no file changes, in the project or the agent's session, so allow for your slowest build or test run. Waiting on your answer does not count.")); form.appendChild(retry); @@ -895,16 +681,6 @@ function drawBody(pane, s) { pane.appendChild(foot); } -/** The line beside Send a test, or null with nothing to say. */ -function notifyTestLine() { - const test = page.loopNotifyTest; - if (!test) return null; - if (test.waiting) return el("p", "loop-why", "Waiting for the app's confirm..."); - if (!test.ok) return el("p", "loop-error", test.error); - if (test.sent) return el("p", "loop-why", "Sent, and the address answered OK. Check that the message arrived."); - return null; -} - function gitButton() { const b = el("button", "btn", "Open the Git board"); b.type = "button"; @@ -915,6 +691,30 @@ function gitButton() { return b; } +/** "Review rounds per phase": fresh reviewer rounds after a phase's own review, off with Review. */ +function roundsField(f) { + const box = el("label", "loop-number"); + box.appendChild(el("span", null, "Review rounds per phase")); + const input = el("input", "is-compact loop-text loop-narrow"); + input.type = "number"; + input.id = "loop-review-rounds"; + input.min = "0"; + input.max = "6"; + input.step = "1"; + input.value = String(f.reviewRounds); + input.disabled = !f.review; + input.addEventListener("input", () => { + f.reviewRounds = Number(input.value); + }); + box.appendChild(input); + const wrap = el("div", null); + wrap.appendChild(box); + wrap.appendChild( + el("p", "loop-hint", f.review ? "When a phase's own review leaves a Critical or a Warning, fresh reviewers run up to this many more rounds before the phase is committed. 0 turns them off." : "Applies only with Review on") + ); + return wrap; +} + /** The form as the console saves it (exported for the page tests). */ export function setupBody(f, s) { const body = { ...f, quickCheck: f.quickCheck.trim(), notifyUrl: f.notifyUrl.trim(), notifyParam: f.notifyParam.trim() || DEFAULT_NOTIFY_PARAM }; diff --git a/src/web-console/public/screens/review-loop-setup.js b/src/web-console/public/screens/review-loop-setup.js new file mode 100644 index 0000000..0fbc932 --- /dev/null +++ b/src/web-console/public/screens/review-loop-setup.js @@ -0,0 +1,433 @@ +// Plan2Code Web Console - the Review Loop's setup screen, drawn by the page from the console's saved setup and the app's facts; defines only. +// +// The dashboard's Review Loop card opens this in place of the cards. Nothing +// here runs an agent: Start saves the picks through POST /review-loop-setup, +// then sends them to the desktop app (`review-loop-start { setup }`), which +// confirms in its own window. Its field builders come from ../loop-parts.js, shared with +// the Implementation Loop's screen. The notification address belongs to the +// Implementation Loop's setup: this screen shows it and, when changed, saves it +// there (POST /loop-setup), because the app reads it from that file alone. + +import { el } from "../render.js"; +import { hooks, page, redraw } from "../state.js"; +import { specList } from "../selectors.js"; +import { postJson } from "../net.js"; +import { tellApp } from "../app-bridge.js"; +import { MATCH_SESSION, STRENGTH_WORDS, field, hasMapping, notifyFields, notifyProblem, radios, select, silenceField, toggle } from "../loop-parts.js"; + +const SCOPES = [ + ["branch", "Branch against main, with uncommitted changes", "Everything this branch changed since it left main, plus what is not committed yet."], + ["uncommitted", "Uncommitted changes only", "Only what is changed in your working tree right now."], + ["spec", "A spec's work", "The files the chosen spec's phases built."], +]; + +export const HANDS_OFF_LINE = "Please do not edit this project's files while rounds run: anything changed goes into the round."; +export const REVIEWER_NOTE = "Each round's reviewer runs fresh, whatever the Subagents switch says; the switch still governs other helpers."; +export const COMMIT_FIRST_LINE = "Commit my current changes first as Work before Review Loop"; +const CAP_HINT = "Rounds stop sooner on a clean one. You can always add a round later, one at a time, up to 6 in all."; + +/** + * Open the screen for `spec` (the picker's selected spec object, or null). The + * saved setup and the read-only facts come from the console; the agent and its + * helpers come from the app. A spec pre-fills the picker and the spec scope. + */ +export async function openReviewLoopSetup(spec) { + if (page.gone || page.pendingResult || page.local.launching) return; + const dir = spec && spec.dir ? spec.dir : ""; + page.reviewStart = null; + page.loopNotifyTest = null; + page.reviewLoopSetup = { spec: dir, loaded: false, failed: false, form: null, facts: null, problems: [], starting: false, resolvedFor: undefined, notifyKindChosen: false }; + tellApp("review-loop-facts"); + redraw(); + const mine = page.reviewLoopSetup; + let res; + try { + res = await fetch("/review-loop-setup?facts=1" + (dir ? "&spec=" + encodeURIComponent(dir) : ""), { cache: "no-store" }); + } catch { + res = null; + } + if (page.reviewLoopSetup !== mine) return; + const answer = res && res.ok ? await res.json().catch(() => null) : null; + if (page.reviewLoopSetup !== mine) return; + if (!answer) { + mine.failed = true; + redraw(); + return; + } + const facts = page.reviewFacts; + mine.form = { + scope: ["branch", "uncommitted", "spec"].includes(answer.scope) ? answer.scope : "branch", + spec: typeof answer.spec === "string" ? answer.spec : "", + cap: Number.isInteger(answer.cap) ? answer.cap : 3, + commit: answer.commit !== false, + agreeCommit: false, + suggestions: answer.suggestions === true, + strength: typeof answer.strength === "string" ? answer.strength : "", + silenceMinutes: Number.isInteger(answer.silenceMinutes) ? answer.silenceMinutes : 20, + notifyRounds: answer.notifyRounds === true, + notifyKind: (facts && facts.notifyKind) || "query", + notifyUrl: (facts && facts.notifyUrl) || "", + notifyParam: (facts && facts.notifyParam) || "message", + }; + // The picker's spec lives in the form; the saved one only matters on the spec scope. + if (dir) mine.form.spec = dir; + mine.facts = { branch: typeof answer.branch === "string" ? answer.branch : "", pending: Number.isInteger(answer.pending) ? answer.pending : null, resolved: undefined }; + mine.loaded = true; + redraw(); +} + +const reviewAgent = () => (page.reviewFacts && typeof page.reviewFacts.agent === "string" ? page.reviewFacts.agent : ""); + +/** The facts' notify values arrive with the app's answer, which can follow the setup: take them while the fields are still as saved. */ +function adoptNotify(s) { + const facts = page.reviewFacts; + if (!facts || s.notifyAdopted || !s.form) return; + s.notifyAdopted = true; + if (!s.form.notifyUrl) s.form.notifyUrl = facts.notifyUrl || ""; + s.form.notifyKind = facts.notifyKind || s.form.notifyKind; + s.form.notifyParam = facts.notifyParam || s.form.notifyParam; +} + +/** Read the agent's strengths once the app has said which agent it is (the two answers come in either order). */ +function ensureResolved(s) { + if (!page.reviewFacts || s.resolvedFor === reviewAgent()) return; + const agent = reviewAgent(); + s.resolvedFor = agent; + if (!agent) { + s.facts.resolved = null; + return; + } + fetch("/review-loop-setup?agent=" + encodeURIComponent(agent), { cache: "no-store" }) + .then((res) => (res.ok ? res.json() : null)) + .catch(() => null) + .then((answer) => { + if (page.reviewLoopSetup !== s || s.resolvedFor !== agent) return; + s.facts.resolved = answer && answer.resolved && typeof answer.resolved === "object" ? answer.resolved : null; + redraw(); + }); +} + +function close() { + page.reviewLoopSetup = null; + page.reviewStart = null; + redraw(); +} + +/** + * Why Start is grayed, or "" when it can go, in the spec's order. Exported for + * the page's unit tests. + */ +export function reviewStartBlock(form, facts, appFacts) { + if (!form || !facts) return "Loading the setup..."; + if (!appFacts) return "Asking the app..."; + if (appFacts.running) return "A loop is already running in this window. Stop it from the banner first."; + if (appFacts.promptSupport === false) return "This agent cannot be started with a first prompt."; + if (form.scope === "spec" && !form.spec) return "Pick the spec whose work to review."; + if (form.commit && facts.pending !== null && facts.pending > 0 && !form.agreeCommit) { + return `${facts.pending} uncommitted ${facts.pending === 1 ? "change needs" : "changes need"} your say-so: tick the box to commit ${facts.pending === 1 ? "it" : "them"} first, or turn commits off.`; + } + const problem = notifyProblem(form.notifyUrl, form.notifyParam, form.notifyKind); + if (problem) return problem; + return ""; +} + +/** The form as the console saves it (exported for the page tests). */ +export function reviewSetupBody(f) { + return { + scope: f.scope, + spec: f.scope === "spec" ? f.spec : "", + cap: f.cap, + commit: f.commit, + suggestions: f.suggestions, + strength: f.strength, + silenceMinutes: f.silenceMinutes, + notifyRounds: f.notifyRounds, + }; +} + +/** What the app is sent: the saved picks and whether the person agreed to the pre-run commit. */ +export function reviewStartMessage(f, facts) { + const dirty = facts && facts.pending !== null && facts.pending > 0; + return { ...reviewSetupBody(f), preRunCommitAgreed: Boolean(f.commit && dirty && f.agreeCommit) }; +} + +function factRow(list, label, value) { + const row = el("div", "loop-fact"); + row.appendChild(el("dt", null, label)); + row.appendChild(el("dd", null, value)); + list.appendChild(row); +} + +function agentLine(facts) { + if (!facts) return "Asking the app..."; + if (!facts.agent) return "No agent is chosen yet"; + const label = facts.agentLabel || facts.agent; + return facts.helpers ? `${label} (starts its own helpers: one session per round)` : `${label} (no helpers: a reviewer session, then a fixer session, each round)`; +} + +export function renderReviewLoopSetup(main) { + const s = page.reviewLoopSetup; + const pane = el("div", "dash-confirm loop-setup review-loop-setup"); + pane.appendChild(el("p", "card-kicker", "Step 3 · Review Loop")); + pane.appendChild(el("h2", "dash-title", "Set up the Review Loop")); + + if (s.failed) { + pane.appendChild(el("p", "loop-error", "The setup could not be read. Go back and try again.")); + } else if (!s.loaded) { + const wait = el("p", "dash-working"); + wait.append(el("span", "spinner tiny"), el("span", null, "Loading the setup...")); + pane.appendChild(wait); + } else { + drawBody(pane, s); + } + + const actions = el("div", "confirm-actions"); + const back = el("button", "btn ghost", "Back"); + back.type = "button"; + back.addEventListener("click", close); + actions.appendChild(back); + const help = el("button", "linky loop-help", "How the loop works"); + help.type = "button"; + help.addEventListener("click", () => hooks.openHelpOn("loop")); + actions.appendChild(help); + pane.appendChild(actions); + main.appendChild(pane); +} + +/** One strength for every round: Match my session, or a mapped word. Grayed when this agent maps none. */ +function strengthPick(s) { + const f = s.form; + const resolved = s.facts.resolved; + const appFacts = page.reviewFacts; + const box = field("Strength"); + const loading = !appFacts || resolved === undefined; + const none = !loading && (appFacts.strengthsMapped === false || !hasMapping(resolved)); + if (none) { + const gray = el("p", "loop-hint loop-strength-none"); + gray.append("This agent has no strengths mapped yet. "); + const link = el("button", "linky", "Map them in Agents & models"); + link.type = "button"; + link.addEventListener("click", () => hooks.openPrefs("agents")); + gray.appendChild(link); + box.appendChild(gray); + return box; + } + if (loading) { + box.appendChild(el("p", "loop-hint", "Asking the app which agent this loop uses...")); + return box; + } + const options = [["", MATCH_SESSION], ...STRENGTH_WORDS.map(([word, label]) => [word, resolved[word] ? label : label + " (not mapped)", !resolved[word]])]; + if (f.strength && !resolved[f.strength]) f.strength = ""; + box.appendChild( + select("review-loop-strength", "Strength for every round", options, f.strength, (v) => { + f.strength = v; + s.problems = []; + redraw(); + }) + ); + const row = f.strength ? resolved[f.strength] : null; + box.appendChild(el("p", "loop-hint", row ? [row.model, row.effort].filter(Boolean).join(", ") : "Rounds use the model and effort this window started with.")); + return box; +} + +function specPicker(s) { + const f = s.form; + const specs = specList(); + const wrap = el("div", "loop-spec-pick"); + const options = [["", "Choose a spec..."]]; + for (const sp of specs) options.push([sp.dir, sp.dir]); + // A spec the list does not hold (one picked on the dashboard that has since moved) stays visible. + if (f.spec && !specs.some((sp) => sp.dir === f.spec)) options.push([f.spec, f.spec]); + wrap.appendChild( + select("review-loop-spec", "Spec to review", options, f.spec, (v) => { + f.spec = v; + s.problems = []; + redraw(); + }) + ); + return wrap; +} + +function drawBody(pane, s) { + const f = s.form; + adoptNotify(s); + ensureResolved(s); + const appFacts = page.reviewFacts; + const redo = () => { + s.problems = []; + redraw(); + }; + + const lines = el("div", "loop-lines"); + for (const text of [ + "The app reviews your change in rounds, each in a fresh agent session. Round 1 looks at everything in scope; each later round looks only at what the round before it changed.", + "It stops on a clean round, at the round cap, or when you press a stop button on the banner at the top of the window. It never pushes.", + ]) { + lines.appendChild(el("p", "loop-line", text)); + } + lines.appendChild(el("p", "loop-line loop-hands-off", HANDS_OFF_LINE)); + pane.appendChild(lines); + + const facts = el("dl", "loop-facts"); + factRow(facts, "Agent", agentLine(appFacts)); + factRow(facts, "Branch", s.facts.branch || "unknown"); + factRow(facts, "Uncommitted changes", s.facts.pending === null ? "unknown" : String(s.facts.pending)); + pane.appendChild(facts); + + const form = el("div", "loop-form"); + + const scope = field("What to review"); + scope.appendChild(radios("reviewscope", SCOPES, f.scope, (v) => ((f.scope = v), redo()))); + if (f.scope === "spec") scope.appendChild(specPicker(s)); + form.appendChild(scope); + + const cap = field("Round cap", CAP_HINT); + const capLabel = el("label", "loop-number"); + capLabel.appendChild(el("span", null, "Stop after this many rounds (1 to 6)")); + const capInput = el("input", "is-compact loop-text loop-narrow"); + capInput.type = "number"; + capInput.id = "review-loop-cap"; + capInput.min = "1"; + capInput.max = "6"; + capInput.step = "1"; + capInput.value = String(f.cap); + capInput.addEventListener("input", () => { + f.cap = Number(capInput.value); + }); + capLabel.appendChild(capInput); + cap.appendChild(capLabel); + form.appendChild(cap); + + const commit = field("Commit"); + commit.appendChild(toggle("review-loop-commit", "Commit each round to the current branch", f.commit, (v) => ((f.commit = v), redo()))); + if (f.commit && s.facts.pending !== null && s.facts.pending > 0) { + commit.appendChild(toggle("review-loop-agree", COMMIT_FIRST_LINE, f.agreeCommit, (v) => ((f.agreeCommit = v), redo()))); + } + form.appendChild(commit); + + const sugg = field("Suggestions"); + sugg.appendChild(toggle("review-loop-suggestions", "Apply Suggestions on their own", f.suggestions, (v) => ((f.suggestions = v), redo()))); + sugg.appendChild(el("p", "loop-hint", "Off: Suggestions are listed in the report for you to pick. On: they are applied in one last pass.")); + form.appendChild(sugg); + + form.appendChild(strengthPick(s)); + + const reviewer = field("Reviewers"); + reviewer.appendChild(el("p", "loop-hint loop-reviewer-note", REVIEWER_NOTE)); + form.appendChild(reviewer); + + const retry = field("If a round goes quiet"); + retry.appendChild(silenceField(f, "Count the agent as stuck after this many minutes with no activity")); + retry.appendChild(el("p", "loop-hint", "No activity means no file changes, in the project or the agent's session, so allow for your slowest test run. A stuck round is retried once.")); + form.appendChild(retry); + + form.appendChild( + notifyFields(s, f, { + intro: "When the Review Loop needs you or ends, except when you stop it yourself, the app sends a short message naming the round. The address is the Implementation Loop's: changing it here changes it there. Leave it empty to send nothing.", + phasesId: "review-loop-notify-rounds", + phasesKey: "notifyRounds", + phasesText: "Also tell me when each round finishes", + onTest: () => sendTest(s), + }) + ); + pane.appendChild(form); + + const block = reviewStartBlock(f, s.facts, appFacts); + const gated = Boolean(block); + const foot = el("div", "loop-start"); + if (gated) { + const why = el("p", "loop-why", block); + why.setAttribute("role", "status"); + foot.appendChild(why); + } + if (s.problems.length) { + const bad = el("ul", "loop-problems"); + for (const p of s.problems) bad.appendChild(el("li", null, p)); + foot.appendChild(bad); + } + const waiting = s.starting && !page.reviewStart; + if (waiting) foot.appendChild(el("p", "loop-why", "Waiting for the app's confirm...")); + if (page.reviewStart && !page.reviewStart.ok) foot.appendChild(el("p", "loop-error", page.reviewStart.error)); + if (page.reviewStart && page.reviewStart.ok) foot.appendChild(el("p", "loop-why", "The Review Loop is starting...")); + const start = el("button", "btn primary", "Start the Review Loop"); + start.type = "button"; + start.id = "review-loop-start"; + start.disabled = gated || waiting || page.gone || page.pendingResult || Boolean(page.reviewStart && page.reviewStart.ok); + start.addEventListener("click", () => startReviewLoop(s)); + foot.appendChild(start); + pane.appendChild(foot); +} + +/** + * Save the notification fields into the Implementation Loop's setup, the only + * place the app reads them from. A project with no loop setup yet gets the + * loop's defaults beside the new address. Resolves to a problem line or "". + */ +async function saveNotify(s) { + const f = s.form; + const facts = page.reviewFacts || {}; + const url = f.notifyUrl.trim(); + const param = f.notifyParam.trim() || "message"; + if (url === (facts.notifyUrl || "") && f.notifyKind === (facts.notifyKind || "query") && param === (facts.notifyParam || "message")) return ""; + let current = null; + try { + const res = await fetch("/loop-setup", { cache: "no-store" }); + current = res.ok ? await res.json() : null; + } catch { + current = null; + } + if (!current) return "The notification address could not be saved. Try again."; + // The loop's own screen drops these two before it saves; the store rejects them as unknown fields. + const { remembered, saved, ...entry } = current; + const { status, body } = await postJson("/loop-setup", { ...entry, notifyKind: f.notifyKind, notifyUrl: url, notifyParam: param }); + if (status !== 200 || !body || body.ok !== true) { + return Array.isArray(body && body.problems) && body.problems.length ? body.problems.join(" ") : "The notification address could not be saved. Try again."; + } + // What the app now reads, so a second Start does not save it again. + if (page.reviewFacts) page.reviewFacts = { ...page.reviewFacts, notifyKind: f.notifyKind, notifyUrl: url, notifyParam: param }; + return ""; +} + +async function sendTest(s) { + const f = s.form; + if (!f.notifyUrl.trim() || notifyProblem(f.notifyUrl, f.notifyParam, f.notifyKind) || (page.loopNotifyTest && page.loopNotifyTest.waiting)) return; + s.problems = []; + page.loopNotifyTest = { waiting: true }; + redraw(); + const problem = await saveNotify(s); + if (page.reviewLoopSetup !== s) return; + if (problem) { + page.loopNotifyTest = null; + s.problems = [problem]; + redraw(); + return; + } + tellApp("loop-notify-test"); +} + +async function startReviewLoop(s) { + const f = s.form; + if (reviewStartBlock(f, s.facts, page.reviewFacts) || (s.starting && !page.reviewStart)) return; + s.problems = []; + page.reviewStart = null; + s.starting = true; + redraw(); + const problem = await saveNotify(s); + if (page.reviewLoopSetup !== s) return; + if (problem) { + s.starting = false; + s.problems = [problem]; + redraw(); + return; + } + const { status, body } = await postJson("/review-loop-setup", reviewSetupBody(f)); + if (page.reviewLoopSetup !== s) return; + if (status !== 200 || !body || body.ok !== true) { + s.starting = false; + s.problems = Array.isArray(body && body.problems) && body.problems.length ? body.problems : ["The setup could not be saved. Try again."]; + redraw(); + return; + } + tellApp("review-loop-start", { setup: reviewStartMessage(f, s.facts) }); + redraw(); +} diff --git a/src/web-console/public/skills.js b/src/web-console/public/skills.js index 5c3df1e..35c8884 100644 --- a/src/web-console/public/skills.js +++ b/src/web-console/public/skills.js @@ -42,10 +42,10 @@ // card the dashboard card (group, chip, title, blurb, about, and // `spec: true` when it takes the picked spec), or null; an // optional `help` is Help's line for the card when it differs -// from `blurb`, and `icon` names the `ci-*` symbol in +// from `blurb`, `appNote` is a line only the desktop app shows (card and Help), and `icon` names the `ci-*` symbol in // index.html's card-icons sheet drawn before the title // appOnly the entry is a card the desktop app alone offers (the -// Implementation Loop): no workflow, no installed skill, and no +// Implementation Loop and the Review Loop): no workflow, no installed skill, and no // list derived from the workflows (WORKFLOWS, the meter, the // resume command, Help's card list) holds it. `skill` is an id // only; `workflow` is null. Use FLOW_SKILLS for those lists. @@ -283,6 +283,32 @@ export const SKILLS = Object.freeze([ "Builds every remaining phase of the spec without you at the keyboard. Each phase gets a fresh agent that builds it and reviews it. The app checks the result against the spec, runs your quick check, commits, and moves on. It stops at the first phase that goes wrong and tells you why. Desktop app only.", }, }), + // The desktop app's Review Loop, a second app-only card beside the + // Implementation Loop: it runs review and fix rounds over a finished change, + // each round checked by a fresh reviewer. Any project state lights it; the + // setup screen picks the scope. + skill({ + skill: "plan2code-review-loop", + workflow: null, + appOnly: true, + label: "Review Loop", + name: "Review Loop", + pose: null, + builds: false, phased: false, metered: false, templates: false, + weight: null, started: null, ran: null, resume: null, + subagents: null, + states: "any", + greyed: null, + card: { + group: "pipeline", + chip: "Step 3", + title: "Review Loop", + icon: "loop", + blurb: "Review and fix in rounds on its own, each round checked by a fresh reviewer.", + about: + "Reviews a finished change and fixes what it finds, round after round, without you at the keyboard. The first round reviews everything in scope; each later round reviews only what the last round changed, with a reviewer that never saw the fix being written. It stops on a clean round, at the round cap, or when you say so, then hands back one report and the usual sign-off. Desktop app only.", + }, + }), skill({ skill: "plan2code-4-finalize", workflow: "finalize", @@ -343,6 +369,7 @@ export const SKILLS = Object.freeze([ title: "Review", icon: "review", blurb: "A second opinion on the changes. Problems ranked, and you pick what gets fixed.", + appNote: "In the app, the Review Loop runs review and fix rounds on its own.", about: "A fresh-eyes pass over what changed: bugs, gaps, and the things the builder was too close to see. Problems come back ranked with a suggestion each, you pick which ones get fixed, and it fixes them.", }, diff --git a/src/web-console/public/state.js b/src/web-console/public/state.js index a534a4a..5459cfd 100644 --- a/src/web-console/public/state.js +++ b/src/web-console/public/state.js @@ -130,6 +130,14 @@ export const page = { // The setup screen the dashboard's Implementation Loop card opened, or null // (screens/loop-setup.js owns the shape). loopSetup: null, + // The Review Loop's setup screen (screens/review-loop-setup.js owns the shape), what + // the app answered to `review-loop-facts`, and `{ ok, error }` once it answered a + // `review-loop-start`. + reviewLoopSetup: null, + reviewFacts: null, + reviewStart: null, + // `{ kind, ok, error }` once the app answered a press on the Review Loop's end screen. + reviewAction: null, loopFacts: null, loopStart: null, loopNotifyTest: null, diff --git a/src/web-console/public/styles/dashboard.css b/src/web-console/public/styles/dashboard.css index f79a80c..8289bb3 100644 --- a/src/web-console/public/styles/dashboard.css +++ b/src/web-console/public/styles/dashboard.css @@ -666,4 +666,13 @@ .loop-end-details { display: grid; gap: 10px; } .loop-end-details > summary { cursor: pointer; font-size: var(--fs-md); color: var(--ink-2); } .loop-end-details[open] > summary { margin-bottom: 8px; } +/* The Review Loop's end: the partial diff, the Suggestions pick and the finished screen. */ +.review-end-partial { display: grid; gap: 10px; } +.review-end-partial h3 { margin: 0; } +.review-end-stats { margin: 0; } +.review-end-diff { max-height: 420px; overflow: auto; border: 1px solid var(--rule); border-radius: 8px; } +.review-end-suggestions { display: grid; gap: 6px; } +.review-end-pick span { display: grid; gap: 2px; } +.review-end-where { font-family: var(--mono); font-size: var(--fs-xs); color: var(--ink-2); overflow-wrap: anywhere; } +.review-end-note { margin: 0; } .confirm-note > .confirm-note-retry { justify-self: start; } diff --git a/src/web-console/review-loop-setup.mjs b/src/web-console/review-loop-setup.mjs new file mode 100644 index 0000000..f59ce17 --- /dev/null +++ b/src/web-console/review-loop-setup.mjs @@ -0,0 +1,96 @@ +// Plan2Code Web Console - the Review Loop's setup, remembered per project. + +import path from "node:path"; + +import { ensureDir, HOME_DIR, readJson, withStateLock, writeJsonAtomic } from "./files.mjs"; +import { foldKey } from "./workspace.mjs"; + +// One file for the person, beside loop-setup.json, keyed by the folder a +// session runs in (FR-29: its own entry per project): +// +// { "schema": 1, "projects": { "": { ...setup, "saved": "" } } } +// +// Never under specs/: the server never writes into a project. The notify +// address and kind are not kept here: the Review Loop reads them from the +// Implementation Loop's setup (FR-26). +export const REVIEW_LOOP_SETUP_FILE = path.join(HOME_DIR, "review-loop-setup.json"); +export const REVIEW_LOOP_SETUP_LOCK = "review-loop-setup.json.lock"; + +const SCOPES = ["branch", "uncommitted", "spec"]; +const STRENGTH_WORDS = ["", "thrifty", "balanced", "best"]; +// A spec folder directly under specs/, no leading dot (the route's own rule). +const SPEC_KEY = /^specs\/[^/\\.][^/\\]*$/; + +export const REVIEW_LOOP_DEFAULTS = Object.freeze({ + scope: "branch", + spec: "", + cap: 3, + commit: true, + suggestions: false, + strength: "", + silenceMinutes: 20, + notifyRounds: false, +}); + +/** Problems with a setup entry, as sentences naming the field; empty when it is good. */ +export function reviewLoopSetupProblems(entry) { + if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return ["the setup must be an object"]; + const problems = []; + for (const key of Object.keys(entry)) { + if (!Object.hasOwn(REVIEW_LOOP_DEFAULTS, key)) problems.push(`"${key}" is not a setup field`); + } + if (!SCOPES.includes(entry.scope)) problems.push(`"scope" must be one of ${SCOPES.join(", ")}`); + if (typeof entry.spec !== "string" || (entry.spec !== "" && !SPEC_KEY.test(entry.spec))) { + problems.push('"spec" must be empty or a folder directly under specs/'); + } + if (!Number.isInteger(entry.cap) || entry.cap < 1 || entry.cap > 6) problems.push('"cap" must be a whole number from 1 to 6'); + for (const key of ["commit", "suggestions", "notifyRounds"]) { + if (typeof entry[key] !== "boolean") problems.push(`"${key}" must be true or false`); + } + if (!STRENGTH_WORDS.includes(entry.strength)) problems.push('"strength" must be empty, thrifty, balanced or best'); + if (!Number.isInteger(entry.silenceMinutes) || entry.silenceMinutes < 1 || entry.silenceMinutes > 60) { + problems.push('"silenceMinutes" must be a whole number from 1 to 60'); + } + return problems; +} + +function readStore() { + const saved = readJson(REVIEW_LOOP_SETUP_FILE, null); + const ok = saved && saved.schema === 1 && saved.projects && typeof saved.projects === "object" && !Array.isArray(saved.projects); + return ok ? saved : { schema: 1, projects: {} }; +} + +/** + * The setup for this project: the saved entry over the defaults, or the + * defaults alone. `remembered` says which, so the screen can tell a first + * visit from a returning one. A missing, unreadable or foreign-schema file + * reads as empty. + */ +export function readReviewLoopSetup(project) { + const saved = readStore().projects[foldKey(project)]; + if (saved && typeof saved === "object") return { ...REVIEW_LOOP_DEFAULTS, ...saved, remembered: true }; + return { ...REVIEW_LOOP_DEFAULTS, remembered: false }; +} + +/** Validate and save this project's setup; throws an Error listing the problems. */ +export function saveReviewLoopSetup(project, entry) { + const problems = reviewLoopSetupProblems(entry); + if (problems.length) { + const err = new Error(`the review loop setup is not valid: ${problems.join("; ")}`); + err.problems = problems; + throw err; + } + ensureDir(path.dirname(REVIEW_LOOP_SETUP_FILE)); + return withStateLock( + path.dirname(REVIEW_LOOP_SETUP_FILE), + () => { + const store = readStore(); + // Only the known fields are kept, in the defaults' order. + const known = Object.fromEntries(Object.keys(REVIEW_LOOP_DEFAULTS).map((key) => [key, entry[key]])); + store.projects[foldKey(project)] = { ...known, saved: new Date().toISOString() }; + writeJsonAtomic(REVIEW_LOOP_SETUP_FILE, { schema: 1, projects: store.projects }); + return readReviewLoopSetup(project); + }, + REVIEW_LOOP_SETUP_LOCK, + ); +} diff --git a/src/web-console/routes.mjs b/src/web-console/routes.mjs index edd1de1..51f9b74 100644 --- a/src/web-console/routes.mjs +++ b/src/web-console/routes.mjs @@ -35,6 +35,7 @@ import { SHOTS_DIR_NAME, SHOT_NAME, shotType, isOpen } from "./patches.mjs"; import { appendChat, currentConversation, pendingChatCount, typedCount } from "./inbox.mjs"; import { specKey } from "./workspace.mjs"; import { readLoopSetup, saveLoopSetup } from "./loop-setup.mjs"; +import { readReviewLoopSetup, saveReviewLoopSetup } from "./review-loop-setup.mjs"; import { takeSpecCarry } from "./spec-carry.mjs"; import { resolveStrengths } from "./strengths.mjs"; import { MARKERS, phaseChecklist } from "./spec-files.mjs"; @@ -136,6 +137,8 @@ const ROUTES = [ { path: "/workspace/browse", method: "POST", origin: true, run: workspaceBrowse }, { path: "/loop-setup", method: "GET", run: loopSetupGet }, { path: "/loop-setup", method: "POST", origin: true, run: loopSetupPost }, + { path: "/review-loop-setup", method: "GET", run: reviewLoopSetupGet }, + { path: "/review-loop-setup", method: "POST", origin: true, run: reviewLoopSetupPost }, { path: "/spec-carry", method: "POST", origin: true, run: specCarry }, { path: "/cancel", method: "POST", origin: true, run: cancel }, { path: "/ping", method: "POST", run: ping }, @@ -1878,6 +1881,41 @@ function loopSetupPost(req, res, ctx) { }); } +// The Review Loop's setup for this project (review-loop-setup.mjs). `?spec=` +// puts the spec and the spec scope into the answer without saving anything. +// `?facts=1` adds the read-only facts the screen shows (the branch and the count +// of uncommitted files, as the loop's setup reads them); `?agent=` adds that +// agent's resolved strengths. Neither is saved. +function reviewLoopSetupGet(req, res, ctx, url) { + let answer = readReviewLoopSetup(loopProject(ctx)); + const spec = url && url.searchParams.get("spec"); + if (spec !== null && spec !== undefined) { + if (!/^specs\/[^/\\]+$/.test(spec) || /^specs\/\./.test(spec)) return json(res, 400, { error: "spec must be a folder directly under specs/" }); + answer = { ...answer, spec, scope: "spec" }; + } + if (url && url.searchParams.get("facts") === "1") { + const state = ctx.readState() || {}; + const pending = state.scan && Number.isInteger(state.scan.pending) ? state.scan.pending : null; + answer = { ...answer, branch: state.branch || "", pending }; + } + const agent = url && url.searchParams.get("agent"); + if (agent) answer = { ...answer, resolved: resolvedStrengthsFor(agent) }; + return json(res, 200, answer); +} + +function reviewLoopSetupPost(req, res, ctx) { + return readBody(req, res, (err, body) => { + if (err && err.tooBig) return json(res, 413, { error: "too large" }); + if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { ok: false, problems: ["the setup must be a JSON object"] }); + try { + return json(res, 200, { ok: true, setup: saveReviewLoopSetup(loopProject(ctx), body) }); + } catch (e) { + if (Array.isArray(e.problems)) return json(res, 400, { ok: false, problems: e.problems }); + return json(res, 500, { error: String(e.message) }); + } + }); +} + // The spec the app's New Session carried over (spec-carry.mjs), taken once by // the fresh dashboard's page, which keeps it only if its picker lists that spec. function specCarry(req, res, ctx) { diff --git a/src/web-console/sessions.mjs b/src/web-console/sessions.mjs index e201009..f81af4f 100644 --- a/src/web-console/sessions.mjs +++ b/src/web-console/sessions.mjs @@ -306,6 +306,7 @@ export const PROTECTED_CONSOLE_FILES = new Set([ "workspaces.json", "loop-setup.json", "loop-reports.json", + "review-loop-setup.json", "spec-carry.json", "subagents.json", "pr-hosts.json", diff --git a/src/web-console/static.mjs b/src/web-console/static.mjs index ee2867c..a5911cc 100644 --- a/src/web-console/static.mjs +++ b/src/web-console/static.mjs @@ -36,6 +36,8 @@ export const SERVABLE = new Set([ "uploads.js", "sound.js", "looks.js", + "loop-parts.js", + "review-loop-end.js", "selectors.js", "strengths.js", "app.css", @@ -84,6 +86,7 @@ export const SERVABLE = new Set([ "screens/core.js", "screens/ending.js", "screens/loop-setup.js", + "screens/review-loop-setup.js", "screens/docs.js", "screens/cards.js", "screens/starting.js", From bcb6e43dbdff149ed11de1f18702d2c09c533615 Mon Sep 17 00:00:00 2001 From: Justin Parker Date: Sat, 28 Nov 2026 21:09:07 -0800 Subject: [PATCH 4/8] Keep four lessons from the Review Loop build AI Assisted --- .plan2code/lessons/general.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/.plan2code/lessons/general.md b/.plan2code/lessons/general.md index b857b3c..30ac462 100644 --- a/.plan2code/lessons/general.md +++ b/.plan2code/lessons/general.md @@ -16,17 +16,39 @@ - About: scripts/test-web-console-shape.mjs, .agents-docs/AGENTS-architecture-console-page.md - Noted: 2026-11-14, implement-review +### A new page module under src/web-console/public/ must be added to the file list in src/web-console/static.mjs, or the server answers 404 for it and the whole page never draws. +- Kind: correction +- About: src/web-console/static.mjs +- Why: The Review Loop screen was missing from the list and every page test timed out waiting for the page to draw, with no page error to point at it. +- Noted: 2026-11-28, implement-review + +### A new scripts/test-*.mjs file must be named in the test script of the root package.json as well as in scripts/test-lanes.json, or test-skill-scripts.mjs fails. +- Kind: correction +- About: package.json +- Why: Two new test files were listed in test-lanes.json only and the full npm test failed on it. +- Noted: 2026-11-28, implement-review + ### A no-hop dashboard request goes as a __ send; the agent answers with a top-level patch key checked in validate() (patches.mjs), and pointersForSend() maps it to console-launches.md. - Kind: convention - About: src/web-console/patches.mjs, src/web-console/pointers.mjs - Noted: 2026-11-17, quick-task +### A page screen never imports another screen (the shape test forbids it): what two screens share, such as the loop setup field builders, goes in a module beside state.js, like public/loop-parts.js. +- Kind: convention +- About: src/web-console/public/loop-parts.js +- Noted: 2026-11-28, implement-review + ### A test run of node install.js with a temp HOME still writes the plan2code shims into the real npm global bin, because npm's prefix does not follow HOME; also set npm_config_prefix to a temp folder. - Kind: correction - About: install.js - Why: A piped --update test run repointed the real plan2code shims at a temp folder until they were fixed by hand. - Noted: 2026-11-17, implement-review +### An extra review round in a loop phase reaches the driver through loop_driver::note_page: a Review page goes to rec.round_wait, because rec.sid still holds the phase's own session. +- Kind: how-it-works +- About: plan2code-app/src-tauri/src/loop_driver.rs +- Noted: 2026-11-28, implement-review + ### Before adding a class to the git board, grep styles/git.css for it: short names like git-tools and git-path are already taken (the Branches search row, the file path cell). - Kind: correction - About: src/web-console/public/styles/git.css From e0f82cc36bc7601069056cc1732dc4ea5b4d1ab8 Mon Sep 17 00:00:00 2001 From: Justin Parker Date: Sat, 28 Nov 2026 22:29:52 -0800 Subject: [PATCH 5/8] Give Help a Review Loop topic and open it from both Review Loop links AI Assisted --- .../AGENTS-architecture-console-design.md | 2 +- .../AGENTS-architecture-console-page.md | 2 +- .plan2code/lessons/general.md | 15 ++- .readme/web-console.md | 2 +- AGENTS.md | 2 +- CHANGELOG.md | 1 + scripts/test-web-console-session.mjs | 10 +- scripts/test-web-console-source.mjs | 17 +++ src/web-console/public/help.js | 1 + src/web-console/public/index.html | 108 ++++++++++++++++++ src/web-console/public/screens/dashboard.js | 2 +- .../public/screens/review-loop-setup.js | 4 +- 12 files changed, 152 insertions(+), 14 deletions(-) diff --git a/.agents-docs/AGENTS-architecture-console-design.md b/.agents-docs/AGENTS-architecture-console-design.md index 5a93c21..97ce418 100644 --- a/.agents-docs/AGENTS-architecture-console-design.md +++ b/.agents-docs/AGENTS-architecture-console-design.md @@ -60,7 +60,7 @@ Key design points: - **A loop stop leads with why and what to do next, in two places.** `evidence_markdown` in `loop_driver.rs` opens the report doc with a `> [!CAUTION]` box (the reason, then the stop line) and a `> [!TIP]` box (the advice); `render.js` draws a blockquote that opens with either marker as a colored `md-alert` and hides the marker. The stop card shows the same two as `.loop-why` and `.loop-advice` from `loopEnd.advice`. The advice is the failed phase's own `loopOutcome.nextStep` (one line, 300 characters, optional, only for a `failed` report that refused the phase), else `stop_advice()`'s words for the cause. `failed_words` puts the reason before the agent's summary, since a failed report's summary often reads like success. - **`validate()` in `patches.mjs` enforces four workflow rules mechanically**: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait. - **The palette is written twice for dark, and that duplication is the mechanism.** `@media (prefers-color-scheme: dark) :root:not([data-theme="light"])` follows the system; `:root[data-theme="dark"]` is the explicit choice from the colors panel. Drop the `:not()` and a system-dark browser overrides someone who asked for light. A chosen accent is applied as an inline custom property on `:root` (CSSOM, which the CSP allows), and the default is applied by REMOVING that override so the stylesheet's own per-theme values win. The server's `data-looks-accent` stand-in only lasts until `applyLooks()` runs, which removes it first thing — left on, its rule would beat "Reset this tab". -- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens ``, which replaced the old "What this page is" About dialog. Its 23 panels (in four groups, with a filter box above the tab list) and their icon sheet are hand-written HTML and SVG in `