# Plan2Code Web Console: design proposal **Status:** implemented in v2.4.0. Kept as the design record, because it explains *why* the thing is shaped the way it is. For how to use it, see [web-console.md](./web-console.md); for where the code lives, see [AGENTS-architecture.md](../.agents-docs/AGENTS-architecture.md). **Date:** 2026-09-20 **Scope:** an optional local browser UI that `plan2code-0-pathfinder` and `plan2code-1-plan` can offer at startup, built as a shared component other workflow steps can adopt later. --- ## 1. Why this is smaller than it looks Pathfinder is already written against a *delivery-channel abstraction*. Its rules say: > AskUserQuestion when available; prose Q blocks only as fallback. and `grilling.md` specifies the question object in full: a plain two-or-three-word header, the probe with its why-it-matters, two to four genuine options each described by its trade-off with exactly one named as the recommendation, plus an automatic `Other` escape hatch. That is a form. The console is not a new workflow, it is a **third delivery channel** alongside the structured tool and prose. The methodology, the file formats, the gates and the rules are untouched. Plan is the opposite: pure prose Q and A with seven phases and four named approval gates. But every one of its gates already resolves to a literal typed token (`approved`, `needs changes`, `approve / refine / abort`). That gives us the second half of the idea. ### The keystone: answers map back to the literal token Every console request carries two extra fields: | Field | Purpose | | --- | --- | | `fallbackText` | the exact terminal phrasing the prompt would have printed | | `token` | what each button resolves to: `approved`, `H`, `A`, `S 1,3,5`, `yes`, `skip` | Clicking **Approve** in the browser is then byte-identical to typing `approved` in the terminal. No prompt logic ever forks. If the console is absent, refused, or times out, the agent prints `fallbackText` and the session continues in the terminal with nothing lost. Mid-session switching in either direction is free, because the markdown files under `specs/` remain the only source of truth. This one decision is what keeps the integration from metastasising across twelve prompt files. --- ## 2. Hard constraints found during research These are verified, not assumed. They shape everything below. ### 2.1 The character limit is the binding constraint `scripts/validate-char-count.js` caps every flat `src/plan2code-*.md` at 20,000 characters since 2.4.1 (11,000 when the numbers below were measured), enforced by a husky pre-commit hook. Measured today: ``` 10995 5 plan2code-0-pathfinder.md <- 5 characters of headroom 10676 324 plan2code-1-plan.md 10835 165 plan2code-2-document.md ``` Neither target prompt can absorb the integration inline. **Trimming pathfinder by roughly 250 characters is a prerequisite task, not a nice-to-have.** Reference files are exempt from the limit, so all of the console contract lives in one. ### 2.2 Packaging needs zero installer code changes `computeExpectedSkills()` in `install.js` copies `additionalReferences` directories verbatim through `listFilesRecursive()`, which has no extension filter. The initial implementation fanned one shared source directory into two skills; the current installer fans it into every skill. Current packaging constraints: - Reference files are copied as `Buffer`s, so binary assets are supported; the shipped MP3 chimes exercise this path. Browser-served assets must also be added to the server's `SERVABLE` allow-list and covered by a test. - `skills/` is generated build output (committed, and checked for drift by `npm test`) and `buildSkills()` prunes files it doesn't expect. Assets must originate in `src/` and never be hand-placed. ### 2.3 `specs/` is gitignored, which is an argument *for* the server Three prompts repeat the warning that Glob silently fails on `specs/` and only a shell listing works. A Node server enumerating candidate spec directories server-side and handing the page a list is strictly better than either a terminal listing or a browser file input. ### 2.4 Formats that must round-trip byte for byte - `` comments - the `## User Feedback` table (exact field names `Rating`, `Reason`, `Went Well`, `Went Poorly`, pipes escaped as `\|`) - the five-state checkbox alphabet `[ ]` `[/]` `[x]` `[?]` `[!]`, with the invariant "never reset `[/]` to `[ ]`" - the handoff string `**Status:** Phase 3 Complete - Resume at Phase 4`, plain ASCII hyphen, single spaces The console carries all of these as opaque strings and never reformats them. ### 2.5 Two regex landmines - `plan2code-metrics` scrapes confidence with patterns like `/[Rr]equirements?[:\s|]+(\d{1,2})/` that **do not require a percent sign**. Nothing the console writes under `specs/` may contain bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed by a number. - The loop parses `TASK_COMPLETE`, `PHASE_COMPLETE` and friends. Pathfinder already forbids these tokens under `specs/`. Both are cheap to enforce mechanically in the server's write path. --- ## 3. Architecture ### 3.1 Placement ``` src/web-console/ console.mjs CLI: open | post | wait | status | stop server.mjs the HTTP server (spawned detached by `open`); routes.mjs lists its URLs files.mjs, sessions.mjs, patches.mjs, scan.mjs, ... paths, atomic writes, patch merge, validate(), the repo scan console.md the agent-facing contract public/index.html markup shell only public/app.js the client's entry (no inline script, see CSP below); screens/ and state.js hold the rest public/styles/ the stylesheet, joined by the server into /app.css public/render.js markdown tokens to DOM nodes public/vendor/marked.esm.js pinned 15.0.7, MIT, lexer only ``` Wired in with one data entry per consumer: ```js { source: 'plan2code-0-pathfinder.md', // ... additionalReferences: [{ source: 'web-console', target: 'web-console' }] } ``` Lands at `~/.agents/skills//references/web-console/` on all ~28 target agents. The server finds its own siblings via `path.dirname(fileURLToPath(import.meta.url))`. The agent needs an absolute path to invoke it. `ai-assist-git-pr` already establishes the convention, proven on Windows, and we reuse its wording: > `` = the directory containing this `SKILL.md` (its install location). Use the absolute path you loaded it from. ### 3.2 The transport, which is the genuinely hard part A turn-based agent must wait up to twenty minutes for a human. Claude Code's Bash tool caps at 600s and **harness-managed background tasks are not a safe place to wait**: there are open issues documenting them being killed at 5 to 20 minutes, killed on compaction, killed when a new prompt arrives, and leaked with no handle when spawned by subagents. Detached processes are explicitly immune. So: **split into two processes with deliberately different lifetimes.** ``` # once, at handoff node /references/web-console/console.mjs open --file request.json -> spawns server.mjs DETACHED, prints URL + session id, exits in under 300ms # repeatedly, until done node ... console.mjs wait --seconds 240 exit 0 -> stdout is the result JSON. Done. exit 10 -> {"status":"waiting","elapsed":"6m12s","answered":3,"total":7,...} Agent relays one line to the user and calls wait again. exit 20 -> server is dead. Agent restarts it, re-reports the URL. exit 30 -> human hit Cancel. ``` Why bounded rather than a single long block: - The deadline lives in our code, not the harness's. `--seconds 240` covers a 20-minute session in five turns. Drop to `--seconds 90` for harnesses with a 120s default (Cursor auto-backgrounds and cannot be told not to). - Every return is a free heartbeat: "still waiting, 3 of 7 answered, 6 minutes in" beats silence. - Interruption is survivable. Ctrl-C the agent, compact the context, restart: the next `wait` re-attaches, because state is on disk. The waiter uses `fs.watch` on the session **directory** (watching a file breaks on Windows when the file is replaced by rename) with a 500ms `stat` fallback as the authority, and pings `/health` every 5s for liveness. The result is delivered **through the filesystem**, not HTTP, which decouples the waiter from the server and is also the resumability story. **Optional push accelerator, Claude Code only:** at `start`, also fire a backgrounded `until [ -f /result.json ]; do sleep 2; done`. If it survives, submit-to-agent latency drops to near zero. If it gets killed, nothing breaks, because the poll loop is the source of truth. ### 3.3 Port, lifecycle, security | Concern | Decision | | --- | --- | | Port | `listen(0, '127.0.0.1')`, handle file in `os.tmpdir()///`. This is Jupyter's `jpserver-.json` pattern and RFC 8252 §7.3. A fixed port is fatal here: you run git worktrees, so two agents in two checkouts of one repo is routine, and a fixed port makes that silently wrong. | | Bind | the literal `127.0.0.1`, never `0.0.0.0`, never the string `localhost` (which may resolve to `::1` and produce the classic "server is up but the browser gets ECONNREFUSED" bug on Windows). | | Auto-open | best-effort, never fatal. Skip when `DISPLAY` and `WAYLAND_DISPLAY` are both unset, or `SSH_CONNECTION` / `REMOTE_CONTAINERS` is set. Honour `BROWSER=` and `--no-open`. | | Orphan prevention | a **server-side idle deadline** (30 min, bumped by any authenticated request) is the mechanism, not a nicety. Windows has no real SIGTERM, and a detached server with no console never sees `SIGINT`, so signal handlers cannot be relied on. Plus a 4h absolute cap, a `pagehide` beacon, an explicit `stop`, and a reap sweep on every `start`. | | Liveness test | `process.kill(pid, 0)` **and** a `/health` check whose returned session id matches the handle. PID reuse is real; the sid match is what disambiguates. | Security, six controls, about 60 lines: 1. Bind `127.0.0.1`. 2. **`Host` header allowlist.** This is the DNS-rebinding defence and the highest-value line in the server. Vite shipped GHSA-vg6x-rcgg-rjx6 for exactly this omission. 3. 128-bit token **in the URL path**, not the query string. Path placement also kills the Windows `cmd /c start` `&`-injection hazard, because the URL then contains no `&`. 4. First `GET /s//` sets `HttpOnly; SameSite=Strict` cookie and 302s to `/`. Token leaves the address bar, history and pasted screenshots; CSRF protection comes free. 5. `Origin` check on every mutating request. 6. Strict CSP with no `unsafe-inline`, which is why JS and CSS are separate files rather than one inlined HTML. **On whether XSS matters here.** The tempting argument is "it is the user's own machine and the model would not write `