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

16 KiB

Architecture: web console server and contract

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

The web console is split by area: this file (the server, the CLI and the agent contract files), the page (every public/ file), the design points (why it is built as it is) and Activities (the games). Each file below has one row in exactly one of these tables.

Web Console

Optional local browser UI shipped with every skill. Source lives in src/web-console/ and is fanned into each skill by an additionalReferences: [{ source: 'web-console', target: 'web-console' }] entry in SOURCE_PROMPTS, landing at skills/<skill>/references/web-console/. The bare plan2code skill is the hub: it opens the console as --workflow dashboard, the page draws the skill menu itself (from each SKILLS entry's card in public/skills.js, through SKILL_CATALOG in public/answers.js, kept in sync with the install set by a test), and a card click reaches the agent as a { "i": "__launch", "skill": ..., "workflow": ... } send — the dashboard then resumes its own session under the launched skill's workflow (open --resume <sid> --workflow <w> restates workflow/title/specDir on the live server) and runs that skill's file. plan2code-review now has a console of its own AND still runs inside builds on the page (a review verdict on Implementation's sign-off card, the Review it now button on a finished quick task, or Finalize's Step 2.5 final review, offered on every run), so plan2code-3-implement, plan2code-quick-task and plan2code-4-finalize also carry review.md, the review references and review-scope.mjs, the same way implement-review does. CONSOLE_WORKFLOWS in public/answers.js, built from the same SKILLS list, decides whether a copied hand-off asks the next session for the console.

File Role
console.mjs the CLI the agent drives: open, post, wait, chat (the instant Quick question check), keep (copy a cited note attachment into specs/<idea>/attachments/), delete-spec, handoff new, delete-handoff (both on handoffs.mjs), status, stop, help (a compact summary for an agent that found the binary but not console.md; help <topic> prints one contract file, help topics lists them). post --wait <N> posts and waits in one command
server.mjs HTTP server, spawned detached by open (never as a harness background task, which get killed on compaction and at assorted timeouts)
cmd-chat.mjs the chat command: hand over Quick questions now, never waiting
cmd-help.mjs the help command: the CLI's usage and the contract's topic files; the usage's workflow list and its build sessions come from WORKFLOWS and isBuild() in skills.js
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
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
cmd-post-wait.mjs post and wait: publish a patch, then collect what the person sent
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), 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
agent-lookup.mjs where an agent lives on this machine: loadAgentList() reads the shipped bin/agents.json (built-in agents and starter templates; optional keeps an absent file silent); findAgent() gives one command its found / outside / missing state, the path and which search found it (PATH, the Windows saved PATH, npm's global bin, the entry's installDirs), with {bypass} / {model} placeholders expanded to the user's picks. Used by GET /agents, POST /agents/use-path, the launcher's chooseCli() and the Windows picker
inbox.mjs the Quick question chat's inbox beside the card slot
console-docs.md the topic file for docs in a patch (tabs of blocks), named by the console at the first patch that carries docs; not read up front. Byte-budgeted with the card and the notes in scripts/test-console-wire-budgets.mjs
pointers.mjs which topic file the console names and when: once per session per topic, remembered in the session folder (pointers.json), reset by a resume
patches.mjs checking and merging an agent's patch into the session state: validate() (the house rules; allows templates only as "idea" on a text item, anything else exits 3), the patch merge, resolveDocFiles() and applyPatch()
routes.mjs every URL the page can call, in one ordered list (ROUTES, walked by handle()); server.mjs hands each request to it
scan.mjs what the dashboard knows about the repo: scanProject(), classifySpec() (a folder's files to a spec state), TASK_LINE_RE (re-exported from spec-files.mjs) and removeSpec()
sessions.mjs a session's roots and handle files (repoRoots(), healthOk(), attachmentName(): the kept-file name <slug>-<id8>.<ext>, the same upload always gets the same name, readOverview()) and the console folder's housekeeping: the three sweeps open runs fire-and-forget after it prints (sweepUploads(), staleSessions() / removeSessions(), staleScratch() / removeScratch()) and cleanupFindings() / removeCleanup() for User Preferences → System → Cleanup
settings.mjs the person's saved console settings: Subagents and pull-request hosts
spec-files.mjs no imports: how a spec's markdown files are read, MARKERS, TASK_LINE_RE, TASK_ID_RE, CHECKBOX_RE, STATUS_RE, statusOf() and countTasks(); shared by scan.mjs, patches.mjs and src/skill-scripts/specs.mjs (through consoleModule())
static.mjs serving the page's own files: SERVABLE (the allow-list), TYPES, caching and ETags, the accent colors, and CSS_ORDER + joinedStyles(), the one place the cascade order is stated
workspace.mjs the session's extra folders, and the folders remembered per project and spec
strengths.mjs the server-side name for public/strengths.js (a re-export)
strengths key (src/launcher/models.json, ~/.plan2code/models.json) per agent, thrifty/balanced/best rows of {model, effort?}; a user row beats the shipped one, and a row whose model is not in the agent's Models list is ignored. models.rs strengths_for and the JS resolver are held to scripts/fixtures/strength-cases.json (change the fixture first, then both)
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 <id>.json ({ v: 1, id, title, worktree, project, spec, workflow, skill, written, fromStop, usedAt }), the agent writing <id>.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
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/<folder-name>-<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/<id>/note.md with tabs/<id>/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/<LEGACY_TAB_ID>/ 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/)
console.md the core of the agent-facing contract, read once per conversation (every skill ships the same copy, so a dashboard hop never re-reads it): starting, the turn (post --wait, the exit codes, handling a send, settle), posting, the payload and its kinds, documents (including file blocks), the house rules, and an index of the topic files below with the moment each is read. A test caps it at 24,000 characters
console-finish.md · console-stop.md · console-chat.md · console-workspace.md · console-subagents.md · console-launches.md · console-meter.md · console-attachments.md · console-trouble.md topic files, each read only when its moment first comes: finishing (the finish and its buttons), stop requests (the way home mid-workflow, stopWarning, resuming a pause), Quick questions, the Workspace, standing instructions and helper reports, dashboard launches and the menu payload, the session meter's run events (read only when a run is refused: the notes inline every run), keeping a cited note attachment, and recovery
notes/<workflow>.md per-workflow notes (init for both inits, pathfinder with Briefs, plan, revise-plan, document, implement for both builds, loop for a build the desktop app's Implementation Loop runs with --loop (where it reports a loopOutcome instead of asking for sign-off), quick-task, review, finalize, handoff, changelog, git, xray, diagnose, pr-prep, test). Each skill's Interface line reads <D>/console.md and its own notes file right after open; a test checks every skill names one that exists
building.md · building-review.md the build half of the contract, for implement, implement-review and quick-task: progress posts (agent.activity, agent.quietMinutes, file blocks re-read with refresh), the chat check between tasks, questions mid-build and stop requests; building-review.md is the review run on the page (the sign-off's review verdict, Review it now, Implement + Review's Stage 2, Finalize's Step 2.5), read only when asked for