Files
plan2code/.agents-docs/AGENTS-architecture-console-design.md

50 KiB

Architecture: web console design points

Part of AGENTS.md and the Architecture index: project guidance for AI coding agents.

Key design points:

  • First-run Welcome. The first dashboard a person sees (after the wake-up finishes) opens #welcome-modal. Any close (button, Esc, backdrop) saves looks.welcomeSeen: true to looks.json, which survives "Back to default". Help's first tab has a Show the welcome again link (data-action="welcome"). Logic: maybeWelcome() / openWelcome() in screens/help-dialog.js.

  • Top-bar icons. #btn-looks (gear) opens #looks-modal, titled User Preferences (see User Preferences below). #btn-feedback (megaphone) is a plain link to https://github.com/jparkerweb/plan2code/issues/new/choose, backed by .github/ISSUE_TEMPLATE/bug.yml and idea.yml (config.yml sets blank_issues_enabled: false). DEFAULT_ACCENT in palette.js is ocean.

  • Version in Help. GET /version reads version.json beside server.mjs, falling back to ../../version.json for a run from src/ (the /version route in routes.mjs). renderHelpVersion() in screens/help-dialog.js fills #help-version. computeExpectedSkills() in install.js injects the root version.json into every references/web-console/, so a version bump changes every skill.

  • User Preferences is four tabs in a side list. Appearance (Theme, Card width, Highlight color, Role), Agents & models, System (Cleanup, and Desktop app inside the app only) and Sounds & activities (Sounds, Activities), a sideways strip below 720 px. The tabs are the static <section class="prefs-panel"> panels in #looks-modal, each fieldset in exactly one (its data-section, listed in PREFS_TABS), wired by the shared public/tabs.js (wireTabs(), the same helper Help uses: helpKeyTarget() re-exports its tabKeyTarget()). public/prefs.js is the pure part: PREFS_TABS, prefsOpenTab() (the gear and the dashboard's Set up preferences both open Appearance; nothing is remembered between opens) and prefsResetScope() (Back to default resets only the shown tab's looks keys, and is hidden on Agents & models and System). screens/prefs-dialog.js owns openPrefs(tab), the one way in, the Saved mark and the unsaved prompt; screens/looks.js keeps the look and sound controls, which save to looks.json as they change; screens/agents-view.js mounts the Agents & models tab, a master-detail split over today's models.json and agents.json (formats unchanged) whose per-agent form has its own Save and Discard: Save sends the last saved list with only that form's draft swapped in, so another form's half-typed edit is never written. The split's components live under screens/agents/ (data, list editor, summary, form); the mount owns all state and every fetch and hands them one ctx.

  • Models in User Preferences. GET / POST /models in routes.mjs read the shipped ~/.plan2code/bin/models.json and read/write the user's ~/.plan2code/models.json (SHIPPED_MODELS_FILE / USER_MODELS_FILE in files.mjs), edited from each built-in agent's form on the Agents & models tab. PLAN2CODE_MODELS_DIR relocates both for tests. The launcher reads the same two files for its model menu.

  • The wait is bounded. wait --seconds 240 exits 0 (answers), 10 (still waiting, message: "Waiting on your answer in the web console" to relay), 20 (server gone, resume it) or 30 (canceled). The agent loops. Nothing blocks for the whole time a person takes.

  • A turn is one command, and the CLI does the bookkeeping. Agent speed is model round trips and typed tokens, not the console (bench-web-console.mjs --roundtrip: Send→agent ~70 ms, post→page ~180 ms), so the CLI absorbs every step with one right answer: consume() marks the agent working when it hands over a submit (markWorking()), and wait hands the turn back (markWaiting()) when it starts with an open question, a finish, or on the dashboard or git board; post --wait <N> posts and waits in one process; settle: true | [ids] (settleItems() in patches.mjs) records the latest send's cards as answered from their submitted; a new or reopened question with no stated status sets waiting and waiting drops quietMinutes (settleAgent()); a doc whose content changed with no version moves up one (mergeDocs()); a chat reply with no id is r<re>; doc blocks with file (and select: "tasks", doc-level refresh: true) are read from the worktree by resolveDocFiles() before the merge, refusing paths outside it; and a hop (__launch, __dashboard, __commit, __pickup) comes with resume (the exact open --resume command) and skillFile (hopFor()), a pick-up also with handoffFile. The wait loop's health check runs beside the 50 ms polling instead of blocking it, and is aborted on exit. help <topic> prints any contract file; help topics lists them. token defaults to the option key in the page's tokenFor(), and nothing reads fallbackText, so the contract no longer asks for either.

  • The CLI hands the agent its terminal line. open, post and wait (exits 0 and 10) print terminalLine: "→ Look at the web console: <url>" (terminalLine() in sessions.mjs), and console.md asks the agent to end every terminal message with the latest one verbatim, so the tool builds the line rather than the model. In wait it is added to the printed result only; the collected result.json on disk never carries it. open also prints swept: { sessions, scratch, handoffs } when it found anything to clean.

  • State fields written by open, not the agent. Every open (fresh or resume) records state.worktree and state.branch from repoRoots() — the branch is read off <gitdir>/HEAD on the walk that already finds the gitdir ("" on a detached HEAD or outside git; env-relocated repos ask git, as before) — and the page shows them in the footer as the workspace label (footerLabel(): folder · branch, or folder + N folders · branch once folders are added, stepping down through narrower tiers); a click opens the Workspace dialog. state.wake = true is set only by a fresh open --workflow dashboard and deleted by every resume (server restart, launch, Back to the dashboard); the page also keeps a per-sid sessionStorage guard so a reload never replays it.

  • looks.width is a person-level preference alongside theme, accent and sounds in looks.json. CARD_WIDTHS in public/palette.js (narrow 720, comfortable 880 — default — wide 1080, ultrawide 1440) is read by the page (cardWidth() validates a saved value) and by routes.mjs, which paints data-width on first load; styles/tokens.css maps data-width onto the single --card-width variable that every column rule uses.

  • GET /agents-doc is the other route that reads a project file (the dashboard's AGENTS.md tab, right after Dashboard, shown while the project has an AGENTS.md). A dashboard session only; it serves AGENTS.md or one markdown file directly under .agents-docs/ (?file=, default AGENTS.md; readAgentsDoc() in sessions.mjs allows exactly those two shapes and realpaths the file inside the root), as text/markdown with no-store, or a 204 for anything else. The page links .agents-docs/ files in place through md()'s link option (renderAgentsDoc() in screens/docs.js).

  • GET /overview reads a project file too. It serves <spec>/overview.md as text/markdown with cache-control: no-store (so the Overview tab is always fresh), or with ?file=map / ?file=draft the spec's pathfinder/map.md / live PLAN-DRAFT-*.md (the dashboard's Map and Plan draft tabs, shown only while the spec has no overview; readSpecFile() picks the file and names it in x-spec-file), or an empty 204 when there is no such file (normal for most specs, and no failed request in the browser console). A dashboard session honors ?spec= only when it equals a dir in state.scan.specs; every other workflow uses state.specDir and ignores the query. The root is state.worktree (fallback state.project), and readSpecFile() (which readOverview() wraps) resolves and realpaths the file and refuses anything outside the root's realpath, so ../, absolute paths and outward symlinks all get the same 204, as do an unscanned ?spec= and an unknown ?file=.

  • The Prototypes tab reads a spec's prototypes/ folder. GET /prototypes lists its .md and .html files (204 when none), GET /prototype?name= serves one .md, and POST /open-prototype (origin-checked) hands one .html to the system's default opener through openFile() in open-link.mjs (one argument, no shell). The spec is chosen as /overview chooses it (specInView()); listPrototypes(), readPrototype() and prototypeHtmlPath() in sessions.mjs take a bare file name only and refuse any file whose realpath is not directly in the folder. The page shows the tab after the spec file tabs, on the dashboard and in a session alike (loadPrototypes(), called from loadOverview()).

  • Month-old sessions are deleted whole. open lists staleSessions() (directories matching the session-id pattern whose state.json mtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) and staleScratch() (top-level regular .json / .mjs files in the console folder older than 30 days, never looks.json or console-dir — PROTECTED_CONSOLE_FILES — never a directory or symlink) before it prints, and removes them after; removeSessions() / removeScratch() re-check every name against the session-id pattern / the scratch-name rule before deleting — not the age, the skipped sid or the file type, which the stale* listing already decided, so never hand them names that did not come from it. console.md tells agents to write temporary payload files into the session's own folder so they go with it.

  • User Preferences → System → Cleanup deletes on demand, from a list the server makes. POST /cleanup (origin-checked) with { scan: true } returns cleanupFindings(): { items: [{ id, where, name, kind, bytes, folder? }], bytes } (folder on notepad: items only), ids session:<sid> (the staleSessions() rule, and every file in the folder that old too, never the serving sid), console:<name> (anything at the top of the console home but PROTECTED_CONSOLE_FILES, sessions and runtime, directories too) and root:<name> (anything at the top of ~/.plan2code but KEPT_PLAN2CODE_ENTRIES: console, bin, launcher.json, install.json, models.json, handoffs, notepads, app, app.json, agents.json, prototypes, learning), notepad:<key> (a month-old notepad, whole; see Notebook below) and completed:<name> (each folder or link directly under the session worktree's specs--completed/ whose newest mtime is older than the session age, 30 days; loose files there stay; the server passes project: sessionWorktree() || PROJECT, and without a project the archive is never scanned). Both stray kinds must be untouched for STRAY_GRACE_MS (an hour, by the newest lstat mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold workspaces.json.lock and writeJsonAtomic()'s <file>.<pid>.tmp, which live for milliseconds. root: is only scanned when the console home is <PLAN2CODE_MODELS_DIR or ~/.plan2code>/console, so a test or dev home never reaches the real folder. Paths never go to the page. { delete: [id] } runs removeCleanup(), which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning { removed, bytes, failed, refused, refusal }. So Cleanup is the one place the server deletes in a project, and it keeps a completed spec git could not give back: completedSpecs() marks each completed: item tracked only when git ls-files lists it and git ls-files --others lists nothing inside (outside a repository, or gitignored as specs--completed/ is by default, it is untracked), and removeCleanup() refuses an untracked one into refused, with refusal the line the page's status shows. Nothing records a backup copy, so tracked by git is the only way through. The page always shows the list before Delete these.

  • The console's path is stated, not searched for. Each Interface line names references/web-console/ beside the SKILL.md and the ~/.plan2code/console/console-dir fallback; the prompts with room (all but pathfinder, plan, document and finalize, which sit near the char limit) also name the canonical global install path ~/.agents/skills/<skill>/references/web-console/ (the skills CLI's real store; every agent dir links into it), and every console.mjs open writes HERE to ~/.plan2code/console/console-dir (only open, so a help or dev run from src/ never repoints it) so a later session can read the path from a fixed place. Without these the agent hunts the skill install dirs on every session.

  • open needs no payload, and runs first. --file and --title are optional (the title defaults to the folder name). Every skill's Interface line puts node "<D>/console.mjs" open --workflow <w> BEFORE reading console.md or the project, and a test (every skill opens the console before it reads anything) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by startStage() in screens/starting.js from <template id="start-poses"> in index.html and animated under .pose in styles/poses.css; each SKILLS entry's pose in skills.js is the list (START_POSES/startPose() in answers.js read it), and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (.waiting-pane, agent working with an activity and nothing to ask). posePane() keeps the pane on screen across renders when the pose is unchanged — renderMain() holds any :scope > [data-pose] child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.

  • The dashboard scan knows whether the folder is a git repository. scanProject() returns { hasAgents, isGit, pending, specs }; isGit comes from insideGitRepo(), the same filesystem walk findRoots() does (no git process, linked worktrees and submodules count, a set GIT_DIR / GIT_WORK_TREE / GIT_COMMON_DIR counts as a repo). The Git card is never grayed, since a clean tree still has branches to switch, pull and push. When isGit is false the card shows GIT_INIT_NOTE ("Not a git repository yet: it offers to start one") as its detail line; a scan with no isGit counts as a repo. In a repo, pending is pendingFiles() in sessions.mjs, which calls countPending() in git-repo.mjs: one bounded git status --porcelain -z under GIT_OPTIONAL_LOCKS=0 (null when git cannot say) counting modified, staged, deleted and untracked paths. Above 0 the detail line is pendingNote(n) ("3 files to commit"); 0 and null show no note. A finish with commit: true puts a Commit it now button on the finished screen (commitOffer(), renderCommitOffer()); its __commit press makes the agent resume as git in the same session and run the commit flow above the board. open --resume treats any switch into git (this press, or Changelog's "Commit this now?") as a hop, like a dashboard launch: switchWorkflow() blanks the page, finish and the last run's state.git included, and draft.json goes. Without that, the old finish outlived the switch, and the page sat on the old ending above the new questions and the board. A confirm item may carry files: [{ path, state }], drawn as a collapsed table by filesTable(). Subagents is on by default for the sixteen opted-in skills (defaultSetting()); a saved Off stays off.

  • The start path is timed, and open is built around it. Measure with node scripts/bench-web-console.mjs (--browser-delay 900 for a real Chrome launch, --roundtrip for Send→agent and post→page, PLAN2CODE_CONSOLE_TRACE=1 on open for a step timeline). Four things make it fast, and each is load-bearing:

    • No git process. repoRoots() in sessions.mjs finds the common dir and worktree top by walking to .git (following gitdir: and commondir files) — each git rev-parse cost 150ms+ on Windows. It asks git only when GIT_DIR/GIT_WORK_TREE/GIT_COMMON_DIR relocate the repo, and uses the native realpath so an 8.3 short name keys the same project git would.
    • The socket handover. open spawns the server first, then binds the loopback port itself (the first listen() blocks ~50ms on Windows, overlapped with the server's boot), launches the browser on that URL immediately (Chrome via start takes ~900ms to its first request, the longest step of all), and hands the listening socket to the server over IPC (bindLoopback()/handOff() in sessions.mjs, --handoff in server.mjs). Requests queue in the socket until the server takes it; one open already accepted is passed across as a socket and acknowledged (conn-held) before the channel is closed. No channel, or no socket within 3s, and the server binds its own port; open then opens the real URL.
    • The first paint needs no fetch. routes.mjs (renderIndex()) renders index.html with the session's title, badge and saved theme (data-theme, data-looks-accent, matched by accent rules generated from palette.js and appended to the joined stylesheet by static.mjs) and the whole first state as an inline <script type="application/json" id="boot"> (every < escaped; data blocks are not executed, so the CSP is unchanged). modulepreload hints fetch every module in parallel, the page draws in the same task as the script runs, and /events?have=<key> skips the opening frame when the page already holds that exact state. The chimes load on first use, not at start-up.
    • Reads are stat-gated. fileStamp() (mtime:size:ino) decides whether state.json, result.json and looks.json changed before anything reads or parses them — per request, per heartbeat and in the 1s poll; the parsed state is cached (readState() returns it; /submit clones before editing). wait stats result.json every 50ms instead of parsing it every 400ms. Static assets are held in memory for the server's life and revalidate by ETag.
  • The Workspace and the session meter live beside state.json, one writer each, and outlive every hop. Three session files, none of which switchWorkflow() ever touches, so both survive dashboard → skill → dashboard (a new console session starts with a count of 0, and with the folders remembered for its folder and spec, below):

    File Writer Holds
    workspace.json the server (workspace.mjs) the folders (id, path, name, description, original, nested), version, the changes log, missing ids, and remote (remoteWarning() in sessions.mjs, computed by the server at boot)
    ledger.ndjson console.mjs append-only, one JSON line per entry. Meter events: launch (every fresh open and every resume into another workflow), run (a post's run, id scoped by launch, with tasks when a built phase reports one) and answer (one per item the person answered in a collected send, written by ledgerAnswers(), id <launch>:answer:<send stamp>:<item>). Also folder-issue reports
    workspace-cursor.json console.mjs the last workspace version handed to the agent; advanced after the print, never backwards

    The page changes the workspace only through five routes: GET /workspace (?check=1 re-stats every folder first), POST /workspace/add (path resolved against state.worktree, ~ expanded, case-insensitive duplicate check on win32/darwin; not-a-folder, duplicate, bad-name, name-taken + suggest), POST /workspace/edit, POST /workspace/remove (the original folder refuses) and POST /workspace/browse (one picker at a time, 409 busy; 404 no-picker when remote is set or no picker exists; PLAN2CODE_PICKER_ECHO stands in for the dialog in tests). stateFrame() carries workspace (folders, missing, remote, the current launch's folder issues) and meter (meterView() over the ledger), and both files are on the 1s poll; it also carries an optional update once the boot-time release check (update-check.mjs) finds a newer release. The agent hears of the workspace through open output (workspace: { folders, missing? }, which also seeds the cursor) and then each change once, as workspace: [...] plus Workspace: … reply lines on wait exit 0 or chat; a change alone never ends a wait slice (pendingWorkspaceChanges() in workspace.mjs on exit 10). post and open --file lift run and folderIssue out of the patch into the ledger, never into state.json; an unknown event or a malformed issue is exit 3. Remembered workspaces. workspace.mjs keeps ~/.plan2code/console/workspaces.json (WORKSPACES_FILE, under PLAN2CODE_CONSOLE_HOME in tests): projects[<case-folded worktree>] = { path, project, specs: { "specs/<name>": … } }, each entry { original: { name, description }, folders: [{ path, name, description, nested? }], at }. rememberedWorkspace() answers spec, else project, else nothing; initialWorkspace(worktree, entry) builds from it, both in the server's first workspaceNow() and in open's read-only workspaceOnOpen(), so they agree. workspace.json carries scope (the spec key or ""). Every user change (bumpWorkspace, not missing/found) calls rememberWorkspace(). setScope() swaps the list, logging removed/added/renamed/described changes so the cursor stays truthful; POST /workspace/scope { spec } (the dashboard picker, on selection and before a launch) seeds an unsaved spec from the project's list, and followSpecDir() (state poll, boot) moves the scope to a posted specDir, saving the current list as an unsaved spec's. Two writers, each a read-modify-write of one key: the server and console.mjs forget --spec (Finalize Step 6). The contract is in console-workspace.md and console-meter.md, and building.md (per-phase run), so the skill prompts stay unchanged.

  • The Subagents switch is a standing instruction, injected only on change. The page's icon button (#btn-subagents, after Write a brief) and #subagents-modal show only when the frame's subagents block says offered && supported. offered comes from public/subagents.js; supported means the latest { "type": "open" } line in events.ndjson carries caps: ["subagents"] (latestOpenCaps()), so an older skill copy's open hides the button. Four places hold it, one writer each:

    File Writer Holds
    ~/.plan2code/console/subagents.json server.mjs per project folder → workflow: { on, instruction, max }, instruction: null being the shipped default; on PROTECTED_CONSOLE_FILES
    <session>/subagents-setting.json the server (settings.mjs) { workflow, on, instruction, max, revision }: synced from the store at boot and on any workflow change (serverSubagents().sync in settings.mjs), revision bumped only by a real change
    <session>/subagents-cursor.json console.mjs { revision, state }, the last block handed over; open resets it, and it moves only after the print
    state.json → helpers console.mjs post the helpers the agent reports, merged by id, checked by checkHelpers() plus the prose scan; dropped by switchWorkflow() on a dashboard hop

    POST /subagents (origin-checked; 400 not-offered / bad / too-long / max) saves the store and bumps the session setting. consume(), cmdChat(), deliverChat() and open append blockFor()'s lines last in reply and the subagents field; a change alone never ends a wait slice. The page's Subagents tab (before Ask) draws state.helpers through helperRows(). Helpers never reach the meter ledger. Contract: console-subagents.md.

  • The filesystem is the transport. Sessions live in ~/.plan2code/console/sessions/<sid>/, deliberately not under specs/, so the console cannot trip the metrics scraper or any marker parser, and survives git clean. A result written after the agent dies is picked up by the next session.

  • Attachments on notes and quick questions live in <sid>/uploads/, never in the project: images as <uuid>.jpg, documents as <uuid>.<ext> with ext from DOC_TYPES in answers.js (text, code, PDF). The browser re-encodes images to JPEG and sends raw bytes to POST /upload as image/jpeg; documents go as-is as application/octet-stream, the extension taken by docExt() from the uncut x-p2c-name. readRaw(req, limit, cb) in routes.mjs caps images at MAX_BODY (4 MB) and documents at MAX_DOC_BYTES (10 MB), and drains rather than destroys so the client gets its 413. Images need the FF D8 FF magic; documents pass checkDocument() in sessions.mjs (%PDF- for PDF, strict UTF-8 with no NUL for text), else 415. The server names the file with crypto.randomUUID(). GET /uploads/<id>.<ext> serves images as image/jpeg and documents under a fixed type (application/pdf, else text/plain) with nosniff and, on text, CSP sandbox (a sandboxed PDF cannot open in the viewer), so a browser can show but never run one; recordSubmitted() writes every send's note onto its item as sentNote { at, text, images, files, suggest? } (paths and names only; suggest only when the action's is exactly true, the Ask for suggestions chip, which always writes a thread entry, note or not, and is left out of the submitted event's ids so the card's staged pick stays), which noteAwaiting() in answers.js turns into the Sent box's attachment links and the Notes pane's pending note until the agent's next thread message; DELETE /uploads/<id>.<ext> takes any allowed extension; both stay contained under uploads/. isOwnUpload() returns the kind ("image" / "file" / false), and attachmentsOk() makes /submit comments and /chat messages carry images only in images[] and documents only in files[], this session's uploads only, at most 5 together (MAX_ATTACHMENTS). A comment's reply gains one Image: <path> (<name>) or File: <path> (<name>) line per attachment, in attach order; a chat entry's lines come from chatReplyLines(), its images first, then its files. sweepUploads() bounds disk growth, and the session sweep removes the whole session a month after that. A note attachment a spec file cites is copied out first by console.mjs keep (--session --upload --name --spec [--from]): it checks both paths (the upload must sit under the session's uploads/, and the spec folder under state.project, real paths included, so a symlinked folder cannot carry the copy outside), copies with COPYFILE_EXCL and reuses an existing copy, prints { ok, path, link, image, reused } with a forward-slash link relative to --from, and logs a keep event. It is the agent's hand, not the server's: it runs in the agent's shell only when the agent decides to cite a file, so the server still never writes into a project.

  • Answers carry their terminal token. Each item ships fallbackText and token, so a click resolves to the literal word the prompt already expects (approved, a, skip). No workflow needs a second code path, and declining the console degrades to prose with nothing lost.

  • A build tells the page how long silence is normal. The page calls a working agent stuck after two minutes without a post, which is right for a conversation and wrong for a twenty-minute build task. agent.quietMinutes (1 to 60, counted only while working) stretches the stuck, adrift and Send-grace thresholds; quietLimitMs() in answers.js is the one rule.

  • A finished quick task's review button is a request through the wait loop, like the brief: { "i": "__review" } or { "i": "__done" }. The agent keeps waiting after posting a finish that carries review, and takes the review up by posting "finish": null, which puts the session back to work. Implementation's review needs no such machinery: it is a verdict on the sign-off card, asked before approval, so the session never left work to take it up.

  • Back to the dashboard is the same kind of post-finish request. A finish with finish.dashboard: true shows the button; a press arrives as { "i": "__dashboard", "type": "dashboard" }, and the agent runs open --resume <sid> --no-open --workflow dashboard then posts "finish": null with a fresh menu. The agent waits ~10 minutes after the finish for it (alongside __review / __done on a quick task); after that the page swaps the button for the /plan2code command. finish.command is optional — without one the page shows the "All done" line — and validate() rejects a <placeholder> command and a non-boolean dashboard. The session-level actions are therefore __brief, __stop, __launch, __review, __done and __dashboard; a new post-finish button should copy this precedent.

  • Continue here, Update CHANGELOG first and Ask prompt blocks. Three small additions on the same pattern. Continue here is page-only: continueOffer(fin) (public/answers.js) reads finish.command, and when it starts with a Plan2Code skill (and the finish is not a pause) screens/ending.js draws a button beside the Next step block, hidden when the session meter is red; the press is the dashboard's own { "i": "__launch", ... } through sendAfterBuild("launch", offer), so the agent writes nothing new (startsClean() cleans the page for the hop, except out of Git and into Review; a same-skill next step keeps the workflow, so the agent posts "finish": null). Update CHANGELOG first is finish.changelog: true, accepted by validate() only on quick-task and finalize (a paused finish is exempt from that check and the page ignores the flag), and it belongs with commit: true; the press is __changelog, a HOP_ACTIONS entry in cmd-post-wait.mjs that resumes as changelog, whose "Commit this now?" yes carries on to Git. Ask prompt blocks are contract only (console-chat.md → Prompts to carry away): the page already draws a Copy button on every fenced block.

  • __dashboard also arrives mid-workflow. A left-pointing triangle (#btn-home, filled with --accent) sits left of Stop session on every non-dashboard page. Its state comes from the pure homeButtonState() in answers.js: hidden on the dashboard, on a finish and during a stop, and otherwise gated by the same turnGate() Stop now uses (the person's turn, unless the agent has gone adrift). The confirm (#home-modal) reuses stopWarning(), and the submit carries the staged answers plus __dashboard, with HOME_REPLY. With no finish on the page, the agent treats it as a stop that lands on the menu: it saves its place as for __stop, then resumes as the dashboard with "finish": null + menu, with no finish and no stop in between (console-stop.md → "Back to the dashboard, mid-workflow"; building.md for builds). local.homeward drives Planny's "Saving your place and opening the dashboard…" line until the through-the-dashboard reset clears it.

  • Handoffs live outside every repo, in ~/.plan2code/handoffs/, and the console owns them (handoffs.mjs; the console ships in every skill, so the Stop flow, the Handoff skill and the dashboard all reach it through console.mjs). handoff new --workflow <w> --skill <s> [--spec specs/<x>] [--title <t>] [--from-stop] claims one for this checkout and prints { ok, id, path, meta } (exit 2 bad usage, 3 a bad value). Off the dashboard the Stop modal offers Stop with a handoff (#stop-handoff, suggested) above Just stop and save (#stop-go); the first sends __stop with handoff: true and STOP_HANDOFF_REPLY, and wait adds handoffSkill (the built Handoff skill's SKILL.md, handoffFor()); console-stop.md gives the order (answers, save, handoff new --from-stop, write, paused finish naming the file, stop). On a dashboard, cmdOpen() adds scan.handoffs (listHandoffs(worktree)) and scan.handoffsDir after scanProject(), which stays handoff-free because specs.mjs list shares it. The picker draws them as dashed .spec-chip.is-handoff chips after the specs (specSel = "handoff:<id>"); a picked one replaces the skill cards with renderHandoffPreview(): Pick it up here, Read it all (GET /handoff?id=, served only for an id in the dashboard's own state.scan.handoffs), Copy for a new conversation (handoffCopyText()) and Delete (openHandoffDelete(), one step). Pick it up sends { "i": "__pickup", "type": "pickup", "handoff": <id> }; HOP_ACTIONS.pickup (pickupHop()) reads the stored .json only, never the page, and falls back to Quick Task with fallback: true when the record, its skill or its spec is gone, or the Handoff skill wrote it (resuming that skill would only write another handoff); markPickedUp() stamps usedAt as the hop is printed, so the next scan drops the chip. Delete sends __delete with handoff in place of spec, and the agent runs delete-handoff --handoff <id> (removeHandoff(), exit 3 on a refusal, nothing touched). open sweeps handoffs untouched for 30 days (staleHandoffs(), the .json's mtime, else the .md's), picked up or not, and reports them in swept.handoffs; Cleanup never lists the folder (KEPT_PLAN2CODE_ENTRIES).

  • Notebook: the person's, one per folder, in ~/.plan2code/notepads/, in named tabs, and the agent's only when the person sends a tab. notepads.mjs is the store's one owner (PLAN2CODE_NOTEPADS_DIR moves it for tests). The folder is the session's worktree, else its project (notepadRoot() in routes.mjs), keyed <folder-name>-<12 hex> by notepadKey() (the hash over foldKey(), so case-only path differences match on Windows and macOS, and two worktrees get two notepads). Layout: meta.json ({ v: 2, folder, created }), tabs.json ({ v: 1, order: [id], last, tabs: { id: { name, created, sent? } } }, the index and the only place order and the last tab live) and, per tab, tabs/<id>/note.md with tabs/<id>/images/<uuid>.jpg and <uuid>.thumb.jpg; a tab id is 12 hex. Every write takes the folder's notepad.lock; a read never creates a file, so only the person's edits age a notepad. A delete removes the tab from the index first, then its folder, and the next write sweeps away a tab folder the index no longer names (a delete that crashed half way). Migration: the first shape (v: 1, one note.md and images/ at the top) reads as one virtual tab, Notes, with the fixed id LEGACY_TAB_ID, and a read writes nothing; the first write moves the files into tabs/<LEGACY_TAB_ID>/ and writes tabs.json last, so a crash in the middle is finished by the next write and never loses a file. A tabs.json that does not hold up is set aside as tabs.json.corrupt and rebuilt from the tab folders. Routes: twelve, placed after /upload in ROUTES (the shape test pins the order): GET /notepad[?tab=<id>] ({ tabs, last, tab: { id, text, savedAt, images } }, with the tab's text, savedAt and images repeated at the top), POST /notepad/text?tab= ({ text }, 1 MB, 413 too-long), POST /notepad/image?tab= and POST /notepad/thumb?id=<uuid>&tab= (raw image/jpeg the page re-encoded with reencode(), 4 MB, 200 pictures per tab: 415 not-jpeg, 413 too-large, 409 too-many), POST /notepad/image/delete?tab= ({ id }), POST /notepad/tab ({ name }), /notepad/tab/rename ({ id, name }), /notepad/tab/delete ({ id }), /notepad/tab/order ({ order }, every id once) /notepad/tab/last ({ id }) and /notepad/tab/sent ({ id, workflow, spec? }, markTabSent(): sets sent: { workflow, spec?, at } on the tab, replacing an earlier one; workflow one of pathfinder, plan, quick-task, revise-plan, spec matching ^specs/[A-Za-z0-9._-]+$, else 400 bad-sent), and GET /notepad/images/<tab>/<uuid>[.thumb].jpg (matched on the raw request line like /uploads/, served through imagePath()'s realpath containment, no-store). A text or picture request with no ?tab means the last tab used (and makes Notes when there is none), so an unchanged client keeps working. The ten POSTs are origin-checked, and every refusal is a NotepadError turned into { error } (bad-name, duplicate-name, too-many-tabs, no-such-tab beside the picture and text codes). None of them writes to the session folder or events.ndjson, and console.mjs and the cmd-*.mjs files never import notepads.mjs (a source test pins it; sessions.mjs loads it lazily for Cleanup only, listing and removing whole notepads), so nothing in a notepad reaches state.json or anything wait prints except a tab the person sends (see Send to a skill). The editor, and the CSP. CodeMirror 6 replaced OverType 2.6.1 after a spike (typing at 200 KB measured about 24 ms a key against about 99 ms, and real heading sizes): public/vendor/codemirror.esm.js is one minified file (about 500 KB) made by the dev-only scripts/vendor-codemirror.mjs from scripts/vendor-codemirror-lock.json, never installed in the repo, and loaded by a dynamic import only when the Notebook first opens. CodeMirror writes its rules as a <style> element, which style-src 'self' refuses, so the editor lives in the open shadow root of .notepad-cm-host where it adopts them as a constructed stylesheet, and its own look is public/notepad-editor.css, a <link> inside the root. Custom properties inherit across the boundary, so both themes work; page tests reach the editor with Playwright's CSS locators (they pierce open shadow roots) and read its text from EditorView.findFromDOM(), since lines the cursor is not on draw without their Markdown marks. CodeMirror's own rules win a tie in specificity (they are adopted after the linked sheet), so notepad-editor.css writes div.cm-editor .cm-scroller for the few it overrides. scripts/test-web-console-page-notepad.mjs fails on any securitypolicyviolation with the notepad open. Upgrading CodeMirror: change a version in scripts/vendor-codemirror.mjs, run node scripts/vendor-codemirror.mjs --update-lock (npm and network; it installs in a temp folder), update the sha256 in the files-table row, then run the two notepad test files. Tabs on the page: screens/notepad.js binds every save and picture to the tab it was made in (a switch waits for the save, and stays put when it cannot), public/notepad-tabs.js draws the bar, and public/notepad.js holds the name, order and delete rules as pure code. Send to a skill (page-only, so the agent reads a tab only when the person sends the box it fills). noteSwitchShows(entry, scan, sel) in public/answers.js decides whether a lit card's confirm pane offers "Start with a note from your Notebook": cardAvailability().on and either Pathfinder, Plan or Quick Task with no spec picked (Start fresh), or Revise plan with a spec picked whose scan entry has no planChange (scan.mjs sets it from a **Plan change:** line in the active phase file not followed by (applied <date>): or (dropped <date>):). Switched on, screens/dashboard.js reads GET /notepad and GET /notepad?tab=, lists the tabs (empty ones grayed, sent badge), previews the whole tab and ticks pictures (defaultNoteTicks(), first MAX_ATTACHMENTS = 5 ticked, toggleNoteTick() allows no more), notes a text over NOTE_LONG_BYTES (51200) as a "Long tab" and adds + note: <tab> to the command line. At Start, launchSkill() keeps page.local.noteSend = { tab, text, pictures, workflow, spec? }; the __launch action and launchReply() carry nothing of the tab, and screens/core.js keeps noteSend over the clean hop only for the launched workflow. The skill's notes (notes/pathfinder.md, plan.md, quick-task.md, revise-plan.md) mark the idea box (Revise plan's "What should change" box) "fill": "note", a field patches.mjs accepts on text items only and with that value only (exit 3 otherwise). When the first open such card appears, the page fills it once (draft and staged answer from noteSend.text, pictures fetched from /notepad/images/ into attachFiles(), a 404 picture skipped, a missing tab leaves the box empty with a banner) and clears noteSend; console.md documents fill. The sent mark follows whatever send carried the filled box: markSent() posts /notepad/tab/sent with page.local.noteSent, so Send, and Stop or Back to the dashboard (screens/ending.js sends staged answers with them), all mark it, while Start alone records nothing. Once filled, the box is an ordinary draft (its text in the session's draft.json through pushDraft(), its pictures in uploads/), which the agent never reads before a send. The Notebook shows sent as a badge after the tab's name (notepad-tabs.js) and a muted "Sent to · " line under the editor (screens/notepad.js). Cleanup. No sweep at open touches a notepad, and notepads is in KEPT_PLAN2CODE_ENTRIES, so the folder is never a stray. cleanupFindings() lists a notepad as one notepad:<key> item (with folder from meta.json, labeled "Notebook for " by screens/cleanup.js, the key when it is missing) only when staleNotepads() finds the newest file in it (newestMtime() in files.mjs, which recurses to any depth, so tab folders count) SESSION_MAX_AGE_MS (30 days) old or more; removeCleanup() removes the whole folder through removeNotepad() (key checked against NOTEPAD_KEY_RE, contained in notepadsDir(), a link refused).

  • A Bug fixed spec deletes in one step. Its chip shows a visible Delete (.spec-chip-del-label) instead of the hover ✕, openDeleteConfirm() gives it a fixed-bug warning and a Delete it button, and deleteStep() sends __delete on the first press, with no name to type. chipDetail() drops the scan's repeated "bug fixed" detail under the label.

  • The Quick question chat is a second, append-only channel beside the card slot. The page's Ask tab (always last, every workflow, still there after a finish) posts to POST /chat (a message, or { reset: true } for New conversation) and POST /chat/decision (Approve / Decline on an edit the agent proposed). The server is the only writer of <sid>/chat.ndjson (one JSON line per message / decision / reset, each with a seq; appendChat() in inbox.mjs); console.mjs is the only writer of <sid>/chat-cursor.json (the last seq handed over, advanced only after printing) and of the agent's replies in state.json → chat.replies (merged by id, checked by validateChat(): real re, proposal paths outside the running specs/<idea>/). The server never writes chat into state.json — post read-modify-writes it under withStateLock() — and stateFrame() merges inbox and replies into the frame's chat block (conversation, messages, typed, limit, offline) in memory. /chat never checks pendingResult(), so neither channel can block the other. wait keeps its exit codes 0/10/20/30: exit 0 gains chat (or is type: "chat" with no actions), and the instant console.mjs chat answers 0/10/20 without touching result.json, which builds run after every task. Guards: 10 typed messages per conversation (409 limit), 4,000 characters (400 too-long), own uploads only, of the right kind (400 image, 400 file), 409 offline when chatOffline() says no agent is there, 409 stale for an old conversation. A hop through the dashboard keeps the conversation: switchWorkflow() carries chat.replies across and the page keeps its Ask state, so only New conversation appends a reset after the opening one. A lone reset never ends a wait slice (deliverableChat()); it rides along with the next message.

  • 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 "Back to default".

  • Help is in the page, built on first open. The ? button (#btn-about) opens <dialog id="help-modal">, which replaced the old "What this page is" About dialog. Its 22 panels and their icon sheet are hand-written HTML and SVG in <template id="help-content"> in index.html (after #start-poses), cloned into #help-panels the first time ? is pressed (except the dashboard topic's card list: buildHelp() fills its .help-cards from SKILL_CATALOG and CATALOG_GROUPS at that moment, in the dashboard's order), so first load builds nothing and Help still reads fully once the server is gone. help.js supplies the tab list and rules, screens/help-dialog.js the wiring (tab buttons, roving focus, renderAbout() for the live connection line on tab 1, lightDismiss(), and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a style= attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a data-fact span a test checks against the constant it comes from.

  • Stuck sessions are explained twice, in Help and on the status line. stuck ("When something looks stuck") is the second tab in HELP_TABS; its panel opens with a help-callout ("Check this first": Plan2Code often waits for a permission in the terminal, which the page cannot see) and four You see / Likely cause / Do this rows before the diagram. The quiet and Not running status lines carry a "What to check" button (openHelpOn("stuck")) inside the existing role="status" element, so it exists only while the symptom shows. Every finished and paused screen gets a "Before you close this" panel from renderCloseGuide() in renderHandoff() (Safe to close, Start fresh, Carry on). Tests in scripts/test-web-console-source.mjs check the tab order, the callout and rows, and the renderCloseGuide call.

  • Markdown is rendered to DOM nodes, never to an HTML string (public/render.js), so agent-authored text that quotes a hostile source cannot execute. Only marked.lexer() is used.

Tests: npm test runs, in order, validate-char-count.js, install.js --build-skills, parse-check.mjs, check-skill-table.mjs, then one node --test over the skill-script tests (test-skill-scripts.mjs, test-script-*.mjs, test-git-repo.mjs), test-launcher.mjs, test-getting-started.mjs and the web console's test-web-console-*.mjs, so they run in parallel, one process each. The console tests are split by area (-session, -lifecycle, -logic, -server, -chat, -chat-stress, -workspace, -subagents, -concurrency, -source, -shape, -git, -git-board, -qa, -speed, -hardening, -embed, -handoffs, -in-app, -loop, -notepad, -pointers, -skills, -spec-states, -state, -tones), plus the -page-* browser suites and the per-game -activities* suites. Their shared setup is scripts/web-console-test-helpers.mjs: importing it gives the file its own console home (so workspaces.json, subagents.json, looks.json and sessions never collide across files) and registers the stop --all cleanup. -session and -lifecycle each run an ordered chain of tests on one session of their own; everything else opens a session per test. A new test goes in the file for its area, after the tests it depends on. The parse check exists because node --check parses a .js file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in scripts/, not src/web-console/, because everything under the latter ships into every skill.

Adding a file under public/: a page module needs SERVABLE in static.mjs and a <link rel="modulepreload"> in index.html. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a module missing from it 404s and the page dies at import with no useful error (the import-fetch test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after app.js and slows the first paint. A screen goes in public/screens/, imports only state.js and the pure modules (never another screen), and is imported by screens/core.js; the import guard in scripts/test-web-console-shape.mjs fails naming a screen that breaks either rule. A stylesheet goes in public/styles/ and on CSS_ORDER in static.mjs, never on SERVABLE; the joined-stylesheet test fails when the folder and the list disagree. Every new file also needs its row in the files tables (the server and contract in the console file, a public/ file in the page file, a game file in Activities or the Ghoul Rush files), which the docs-table test (same file) checks.