Files
plan2code/.agents-docs/AGENTS-architecture.md
T
2026-11-02 13:22:59 -08:00

219 KiB
Raw Blame History

Architecture

Part of AGENTS.md — project guidance for AI coding agents.

Directory Structure

plan2code/
├── src/                        # Source workflow prompts (14 markdown files)
│   ├── plan2code-0-pathfinder-references/ # Reference files for pathfinder skill
│   │   ├── brief.md                        # Dated plain-English decision briefs
│   │   ├── chart.md                        # MODE A: destination + frontier grills, templates
│   │   ├── github-issues.md                # Issue-backed map (loaded only when Backend is github)
│   │   ├── grilling.md                     # Folded-in grilling + domain-modeling
│   │   ├── questions.md                    # On-disk question-file format + markers
│   │   ├── resolve.md                      # Per-type resolution + graduating the fog
│   │   ├── handoff.md                      # Clearing gate + PLAN-DRAFT handoff
│   │   └── 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)
│   │   ├── 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, xray, diagnose)
│   │   └── 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)
│   ├── plan2code-review-references/     # Reference files for review skill
│   │   ├── verification-protocol.md        # Deep verification + confidence calibration
│   │   ├── dimensions.md                   # 11 dimensions with detailed checklists
│   │   ├── false-positives.md              # Known false-positive patterns
│   │   ├── reviewer-brief.md               # Fill-in brief for the one fresh helper that runs the analysis
│   │   └── session-end.md                  # Next-step routing at review session end
│   ├── plan2code-init-update-references/ # Reference files for init-update skill
│   │   └── ai-agent-file-sync.md           # Step 7: replace AI configs with AGENTS.md refs
│   └── plan2code-4-finalize-references/ # Reference files for finalize skill
│       └── community-feedback-submission.md # STEP 6.5 payload schema + submission tiers
├── plan2code-bot/            # Autonomous end-to-end workflow test runner (TypeScript, tsup, Claude Agent SDK, vitest); user docs in .readme/test-bot.md
├── plan2code-metrics/        # Recursive self-improvement toolchain
│   ├── src/                    # TypeScript source
│   │   └── prompts/            # Internal AI prompt templates (no char limit)
│   └── dist/                   # Built output (tsup)
├── src/statusline-claude/       # Claude CLI status line (Node.js, zero deps, single file)
│   ├── statusline.js           # Self-contained: config, git, formatters, render
│   └── statusline-config.json  # Default config template
├── src/launcher/               # Global `plan2code` command (Node.js, zero deps)
│   ├── plan2code.js            # Opens /plan2code in Claude Code or Devin in the cwd (or a picked folder)
│   ├── models.json             # Curated model menu, copied to ~/.plan2code/bin/ on install
│   └── plan2code.ico           # Desktop shortcut icon (Windows)
├── src/web-console/            # Local browser UI bundled into every skill (Node.js, zero deps, no build)
│   ├── console.mjs             # CLI the agent drives: open, post, wait, chat, keep, status, stop, help
│   ├── server.mjs, routes.mjs, static.mjs, cmd-*.mjs, picker.mjs, and the by-job files (files, sessions, patches, scan, inbox, workspace, settings)
│   ├── console.md, console-*.md, notes/, building*.md # Agent-facing contract (console.md read once, the rest on demand)
│   └── public/                 # Page assets served to the browser
├── scripts/                    # Development scripts
│   ├── bench-web-console.mjs   # Start-path timing
│   ├── capture-screenshots.mjs # Stages web console screens and saves the docs screenshots (needs a local Chrome or Edge, through `playwright-core`)
│   ├── browser.mjs             # The one place a browser is launched (Chrome, then Edge, through `playwright-core`; `PLAN2CODE_TEST_BROWSER` forces one); page tests, the screenshots and the bench use it
│   ├── css-snapshot.mjs        # Dev-only: every element's computed style on every screen, both themes; take one before a stylesheet move and `--compare` after
│   ├── vendor-codemirror.mjs   # Dev-only: bundles the pinned CodeMirror 6 packages with esbuild into `public/vendor/codemirror.esm.js` (installed in a temp folder from `vendor-codemirror-lock.json`, never in the repo)
│   ├── check-skill-table.mjs   # src/plan2code.md "What each skill reads and writes" table vs each skill's prompt and references
│   ├── parse-check.mjs         # Imports every shipped browser module as real ESM
│   ├── screenshots/            # JSON payloads posted per shot (`ask` reuses `question.json`; `finish` follows `signoff.json`)
│   ├── test-web-console-*.mjs, web-console-test-helpers.mjs  # Web console suites, split by area (the page tests are `-page-*`, the source shape `-shape`), and their shared setup
│   ├── node-test.mjs, page-test-helpers.mjs  # `npm test`'s `node --test`, files at once capped at one per spare core; the page tests' browser sessions and their redraw-safe `styleOf()`, `stylesOf()`, `scrollCard()`
│   ├── test-launcher.mjs, test-getting-started.mjs  # Launcher suite; newcomer docs kept in step
│   ├── test-skill-scripts.mjs, test-script-<skill>.mjs, test-git-repo.mjs, skill-script-helpers.mjs, fixture-helpers.mjs  # Skill script suites and fixtures
│   └── validate-char-count.js  # Pre-commit character count validator
├── skills/                     # Generated, gitignored build output — one Agent Skill per src/ prompt
│   └── plan2code-<name>/       # SKILL.md plus references/ and scripts/ where present
│                               # Generated by npm run build:skills; consumed by skills add
├── .husky/                     # Git hooks (husky)
│   └── pre-commit              # Runs character count validation
├── .claude/                    # Repo-local Claude Code config (NOT installed by install.js)
│   └── skills/                 # Maintainer-only dev skills, e.g. plan2code-publish/, plan2code-model-update/
├── .github/ISSUE_TEMPLATE/      # bug.yml, idea.yml, config.yml (target of the console's feedback button)
├── .readme/                    # User guides linked from README (web-console.md, web-console-design.md, walkthrough.md, metrics.md, status-line.md, test-bot.md)
├── docs/                       # Landing page `index.html` served at plan2code.jparkerweb.com (GitHub Pages, `CNAME`) and assets
│   └── screenshots/            # Web console screenshots, <shot>-light.webp and <shot>-dark.webp (generated)
├── specs/                      # Feature specs (if any in-progress)
├── install.js                  # Interactive installer (Node.js)
├── package.json                # Root package (husky only, private: true)
├── version.json                # Version metadata
├── CHANGELOG.md, QUICK-REFERENCE.md, LICENSE
├── .gitattributes, .editorconfig  # Pin LF (see Code Style & Gotchas)
├── prototypes/, specs--completed/, dist/  # Local only, gitignored: design prototypes, archived specs, stale pre-2.2 build output. Ignore root dist/.
└── README.md                   # User documentation

Key Files

File Purpose
install.js Interactive installer — builds skills/ from src/, then delegates installation to the skills CLI
src/plan2code-*.md Source workflow prompts (the "source of truth")
skills/ Generated Agent Skills, gitignored build output regenerated by the installer (and npm run build:skills) before every skills add
scripts/validate-char-count.js Pre-commit validator ensuring all source prompts ≤ 20,000 chars
version.json Version metadata (name, version, description)
QUICK-REFERENCE.md User quick-reference card
src/statusline-claude/ Claude CLI status bar (see Status Line below)
src/launcher/plan2code.js Global plan2code command that opens the dashboard skill in Claude Code, Devin or Codex (installed by I and Advanced → E; also via Advanced → D). When the desktop app is installed (~/.plan2code/app/plan2code-app[.exe], or the file PLAN2CODE_APP names) and a display exists (Windows and macOS always; Linux needs DISPLAY or WAYLAND_DISPLAY), it opens the app after the agent and model questions with --project <folder> --agent <id> [--model <id>] and exits; --classic (never forwarded to the CLI) and a failed spawn keep the terminal flow. The app reads all three (project::launch_choice): the picker starts on --agent, and --model applies to that agent on every start and Restart (AgentManager::set_model); a model never applies to another agent
plan2code-app/ Tauri desktop app (Rust host, xterm panel, the console's dashboard in a frame; its own README). RELEASE-CHECKLIST.md lists the by-hand checks before each release. src-tauri/src/versions.rs compares the app's version (tauri.conf.json) with the installed skills' (~/.plan2code/bin/version.json) for the bar's Update skills line, which runs node ~/.plan2code/bin/plan2code.js update only when pressed
plan2code-app/src-tauri/src/attention.rs The taskbar signal's rules, pure and knowing nothing about Tauri: Signal (busy, ready, attention, plain), badge_for(signal, os, enabled) (Windows: green dot on ready, red on attention; macOS: red ! on attention only; Linux: count 1 on attention), should_flash(prev, next, focused, enabled) (once, only on a change into ready or attention while unfocused) and dot_rgba() (the dot's pixels, in the favicon's colors, which a test checks against public/favicon.js). main.rs applies the result through set_attention, set_taskbar_signal and clear_attention_cmd; the page asks with the attention and taskbar messages (public/app-bridge.js) and the switch is taskbarSignal in the app's own ~/.plan2code/app.json.
plan2code-app/src-tauri/src/quit_prompt.rs, task_dialog.rs The quit check shown while an agent runs. quit_prompt(last_signal) is pure: the page's last taskbar signal ready or plain is the waiting case ("Done for now?", Info icon), and busy, attention or none yet is the working case ("Leave while your agent is busy?", Warning icon). task_dialog.rs (Windows only) draws it with TaskDialogIndirect through winapi: a heading, Stay as the default, and the app's icon in the title bar, since the dialog plugin has no heading and Windows copies its icon into the title bar (the warning once showed twice). confirm_quit in main.rs runs it on its own thread; macOS and Linux use the plugin box with the same words, where Quit stays the default button (putting Stay first would make Esc quit). A page reload or an unanswered page clears the signal to none (clear_attention), so the box stays on the working words until the page reports again; QUIT_OPEN keeps a second box from stacking
plan2code-app/src-tauri/src/loop_driver.rs The Implementation Loop's driver. Its decisions are pure functions and carry the unit tests: phase_prompt() (the prompt each fresh phase session starts on), judge_outcome() (the skill's loopOutcome against the spec's marks and the setup), silence_expired(), should_retry() (one retry for a crash or silence, never for a real failure), open_question() and stop_line(). Around them sit the running record (app memory only), the watch thread and the stop and resume entry points. The app, not the agent, marks a loop phase done and commits it; the skill only builds and reports
plan2code-app/src-tauri/src/loop_commit.rs The loop's commit step, called by handle_outcome in a fixed order: prepare (subject, message), stage and check the staged names and sizes against a denylist (.env* except .example, .sample, .template; oversized files; a bad list unstages all and stops), save the phase file text, mark done, commit with its own limit, and on a failed commit restore the saved text only if the file still equals what the loop wrote (else stop with "marked, not committed", kept in the reports store). Stop now never commits; judge_outcome refuses missing task data and failed tests; the watcher runs under catch_unwind and counts unreadable sessions as silence; loop_state in main.rs redraws the strip after a reload
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-<date>.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/agents.rs Custom agents in the app: CustomAgent, the Agent handle over built-ins and custom entries, load_custom_agents, reading the Agents file below; the console side is src/web-console/agents.mjs
Desktop app install (install.js) installDesktopApp() downloads plan2code-app-<version>-<windows|macos|linux>-<x64|arm64>[.exe] and plan2code-app-<version>-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

Agents file

~/.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.

  • 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.
  • Rules: id matches ^[a-z0-9][a-z0-9-]{0,31}$, is not claude, devin or codex, and is unique; name is at most 60 characters and unique ignoring case; command is not blank. makeId(name, taken) makes the id from the name in kebab case (agent when nothing is left), with -2, -3 on a clash, at most 32 characters.
  • Bad entries: a bad entry is skipped with a warning naming it (agents[i], 0-based) and the rest still load, in all three readers. POST /agents instead refuses the save with { error, index, field }, and answers 409 while the file holds something GET /agents could not read, unless the body says replace: true.
  • Command line: buildArgs returns args with {prompt} filled (the prompt is appended when no argument holds it, and a blank prompt drops an argument that is exactly {prompt}), then modelArgs with {model} filled when a model is chosen, then bypassArgs when checks are off. Arguments travel as a list, never through a shell; the Windows cmd wrapper for a .cmd or .bat belongs to the launcher and the app.

Workflow Prompts (in src/)

File Step Purpose
plan2code.md — The dashboard: opens the web console's skill menu and launches the picked skill into its own session
plan2code-init.md Init Generate AGENTS.md as index + .agents-docs/ section files (progressive discovery)
plan2code-init-update.md Update Update AGENTS.md with learnings; detects and routes edits to .agents-docs/ files
plan2code-0-pathfinder.md 0 Chart a foggy idea as a map (local files, or GitHub Issues) of decision questions under specs/<idea>/pathfinder/, resolve them one at a time, hand a seeded PLAN-DRAFT to Step 1
plan2code-quick-task.md quick Lightweight planning for small tasks (standalone — not a pipeline step)
plan2code-1-plan.md 1 Requirements analysis & architecture
plan2code-1b-revise-plan.md 1b Mid-implementation revisions
plan2code-2-document.md 2 Create implementation specs
plan2code-3-implement.md 3 Execute implementation (phase by phase)
plan2code-3-implement-review.md 3 Execute one phase, run focused review and fixes, then request approval
plan2code-review.md review Post-implementation comprehensive review, analyzed by one fresh helper when the tool has one (verified in session; the report says who reviewed)
plan2code-4-finalize.md 4 Validate, summarize, feedback, archive (steps 1–7, +optional 6.5)
plan2code-handoff.md handoff Compact the conversation into a self-contained handoff document for a fresh session
plan2code-xray.md xray Explain how and why an area works (files, commits, PRs via gh when present), or rank the rough spots worth fixing into ARCHITECTURE-BRIEF-<date>.md for Pathfinder or Plan; never edits code
plan2code-diagnose.md diagnose Find a bug's cause under the find-the-cause-first habit (references/building-habits.md) and write it up as specs/<bug-name>/DIAGNOSIS-<YYYYMMDD>.md without fixing it, then offer Quick Task to fix it, or Plan when the fix is big. The dashboard scan reports such a folder as spec state diagnosed ("Bug diagnosed"), which lights Quick Task (suggested) and Plan. Once Quick Task marks the diagnosis Fixed (nothing past it in the folder) the state is fixed ("Bug fixed"): no pipeline card lights, the picker never pre-selects it, and Quick Task offers to archive it with specs.mjs archive
plan2code-changelog.md changelog Check the CHANGELOG version against the default branch, suggest editable entries for new work, keep package.json aligned, offer to commit the result through Git
plan2code-git.md git Branches, pull (with conflict help), push, publish and commits (clear message, suggested splits) on the web console's git board, or plain instructions in the terminal (switch to main, commit and push); asks before every push, publish and delete

Naming Convention

Workflow files follow a strict naming pattern:

  • The hub: plan2code.md (bare name — bare: true in SOURCE_PROMPTS, no suffix; it is the dashboard the rest hang off, not a step)
  • Utilities: plan2code-<name>.md (single dash)
  • Numbered steps: plan2code-<N>-<name>.md (single dash, number, single dash)

Examples:

  • plan2code-init.md (utility)
  • plan2code-1-plan.md (step 1)
  • plan2code-1b-revise-plan.md (step 1b)

Reference Files

Some workflows use companion reference files for depth that does not need to load on every invocation. The orchestrator (main workflow file) loads them via Read directives during execution.

Pattern: src/<source-filename-without-extension>-references/ (e.g., plan2code-review-references/). A file several skills read lives in src/shared-references/ instead and ships to each through additionalReferences (e.g., building-habits.md into Quick Task, Implement and Implement + Review).

How the installer handles them: the directory is copied verbatim to skills/<skill-name>/references/, so Read references/<file>.md resolves consistently for every agent. There is one output format, with no flat-file sibling directory or path rewrite.

Reference files are NOT subject to the 20,000 character limit. The review workflow pioneered this pattern (verification-protocol, dimensions, false-positives, session-end); the init-update workflow also uses it (ai-agent-file-sync for its Step 7), plan2code-4-finalize.md uses it for STEP 6.5 (community-feedback-submission), and plan2code-0-pathfinder.md leans on it hardest (brief, chart, github-issues, grilling, questions, resolve, handoff, trail — the orchestrator is a dispatcher, the depth lives in the references). Other workflows can adopt it when a source file carries detail that is only needed some of the time. The implement-review skill is a generated composition: additionalReferences in SOURCE_PROMPTS packages the canonical implement prompt, review prompt, and review reference directory into its own references/ directory so those workflows are reused without source duplication.

Skill Scripts

Anything a workflow step decides with one correct answer (parsing a spec's checkboxes, rebuilding Pathfinder's map markers, the commit message, which AI config files exist) lives in a script the agent runs, not in prose it follows. Prose keeps the judgment.

Source Ships to How
src/skill-scripts/<name>.mjs skills/<skill>/scripts/<name>.mjs Shared: a skill lists the ones it runs in scripts: [...] on its SOURCE_PROMPTS entry. Skills install independently, so each gets its own copy
src/skill-scripts/common.mjs every skill that has scripts SHARED_SCRIPTS_ALWAYS in install.js
src/<source>-scripts/<name>.mjs skills/<skill>/scripts/<name>.mjs A skill's own scripts, mirroring -references/. A name that collides with a shared script is a build error
version.json (repo root) skills/<skill>/scripts/version.json Copied at build, so an installed skill can report its version
Script Skills Does
specs.mjs plan, revise-plan, document, implement, implement-review, review, quick-task, finalize, handoff list / status (Phase Checklist, groups, task markers, numbering, the implement selection verdict, consistency checks) / metrics / mark / archive. Imports scanProject() from the bundled web-console/scan.mjs, so the dashboard and the skills share one spec classifier
commit-msg.mjs implement(-review), review, quick-task, finalize, init-update, git The <subject> / AI Assisted commit command (two -m flags), with optional git add
review-scope.mjs review, implement(-review), quick-task Review Mode's git fallback: files, lines, doc share, base branch
agents-md.mjs init, init-update AGENTS.md structure, budget, orphans, broken links, always-inline sections
agent-files.mjs init, init-update Detect and replace other agents' config files with AGENTS.md pointers
pathfinder.mjs (own) 0-pathfinder reconcile, frontier, claim, resolve, rule-out, trail, gate, lint, brief-data
feedback-payload.mjs (own) 4-finalize STEP 6.5's payload (real sha256 prompt hashes) and the gh / browser / print submission tiers
xray.mjs (own) xray hotspots (churn, files changed together, often-changed files with no test, from git log over a capped window) and history <path> (commits following renames, a blame summary, PR titles and first paragraphs through gh when signed in, and which sources were used). Read-only
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

Conventions (common.mjs): Node 18+ built-ins only; one JSON object on stdout (ok: false plus error, message, next on a handled failure, the same line on stderr); exit 0 ok, 1 crash, 2 bad arguments, 3 not found, 4 invalid or check failed, 5 refused; --help documents commands and exit codes; writes take --dry-run; PLAN2CODE_NOW pins the clock for tests. A SKILL.md names a script as node "<S>/<name>.mjs", where <S> is scripts/ beside it.

Tests: scripts/test-skill-scripts.mjs (installer plumbing and the shared scripts), scripts/test-script-<skill>.mjs (a skill's own), with fixtures from scripts/skill-script-helpers.mjs. Importing that module rebuilds skills/ unless npm_lifecycle_event is test (npm test has just built it). Git fixtures go through copyFixture() (scripts/fixture-helpers.mjs): built once per test file, copied per test, since every git process costs a few hundred milliseconds on Windows; a remote inside the fixture is added with slashed() so the copy's .git/config can be pointed at its own origin. They run the built skills/ tree, and one test fails if any SKILL.md or shipped reference names a <S>/<name>.mjs that skill does not ship. The per-skill scripts import ./common.mjs, which only sits beside them in the built tree, so run them from skills/, not src/.

Repo-Local Skills (.claude/skills/)

Maintainer-only skills committed to the repo but deliberately excluded from the generated skills/ product artifact:

  • plan2code-publish/ — publishes a GitHub Release after version files agree.
  • plan2code-changelog/ — validates release classification and keeps version files synchronized.
  • plan2code-model-update/ — refreshes the launcher's curated model menu (src/launcher/models.json) from devin models list and Claude Code's documented model aliases: shows a diff, applies only the changes the maintainer approves, validates the file and runs npm test. Terminal only, and it never commits.
  • sync-repo/ — decrypts the protected upstream-sync workflow in memory.

Do not run skills add against the repository root: recursive discovery also finds these maintainer skills. install.js targets skills/ and passes explicit workflow names instead. Global install/uninstall cleanup removes plan2code-* workflow skills from user skill directories; it never operates on this repository's .claude/skills/ directory, and sync-repo intentionally has no plan2code- prefix.

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, or the Review it now button on a finished quick task), so plan2code-3-implement and plan2code-quick-task also carry review.md and the review references, 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)
public/ (other files) index.html, favicon.svg (Planny peeking up from the tab bar, served as image/svg+xml) with favicon.png (the same icon at 192 px, served as image/png) as the fallback, vendor/marked.esm.js, the chimes (start-skill.mp3, bootup.mp3, start-stop.mp3, next.mp3, insert.mp3, sleeping.mp3; which moment plays which is SOUND_EVENTS in palette.js, one switch per event saved in looks.json), and a package.json that only says "type": "module", so Node (the server and the tests import the pure modules) parses them as ES modules without a reparse warning. The stylesheet is the files in public/styles/, joined by the server into the one /app.css the page asks for
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 above), 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
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
public/activities.js the list of activities (ACTIVITIES: each game's id, title, picker card line blurb and module path) an optional courses list (Mini golf's six course ids, which open a course dashboard), bestKey(id, course?), the flat looks.json key for its best score (activityBestSnake, one per golf course activityBestGolfPirate to activityBestGolfFrost, activityBestTrails, activityBestBugs, activityBestDrive, activityBestStack, activityBestBumper, activityBestRapids, activityBestFuse, activityBestHop, activityBestBounce, activityBestGhoul); lists Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road and Ghoul Rush, bestKeys(entry), every best key a game keeps, and documents the game contract including the course parts (courses and preview() on the export, setCourse() and course on the game), the optional pointer(type, x, y), release(name) (a game key let go) and lowerIsBetter; data only, imported by the page and by Node
public/activities/snake.js Snake: its rules as plain exported functions and the game contract (create({ canvas, tone, onScore }) returning start, pause, resume, key, tick, resize, score, state); it never runs a timer or listens for keys, so the Activities window drives it
public/activities/trails.js Light Trails: its rules as plain exported functions (newRound, newHeat, turn, boost, advance in 8 ms slices (where your crash is held for GRACE_MS, a turn in that time riding out of it; rivals get no grace), choose and room for the rivals' flood-fill steering, applyPower, spawnItem, closeRing), the ARENAS (rivals, sharpness and what each adds), the POWERS pads and the game contract; memo is the furthest arena reached; a read-only round getter for the tests only
public/activities/bugs.js Bug Hunt: its rules as plain exported functions (newRound, spawnWave, slotPos, advance in 8 ms slices over round.input, which key() and release() set, hurtBug, hurtBoss, hitShip, applyPower, ghostly, tentacleTip, bossRadius), the BUGS by first wave, the BOSSES every BOSS_EVERY waves, the POWERS, the SECTORS scenery and the game contract with release(); memo is the tally of DISCOVERIES as bits; a read-only round getter for the tests only
public/activities/drive.js Sunset Drive: its rules as plain exported functions (newRound, buildStage, which appends a stage of road and returns its forkAt, gateAt and fork, segAt, advance in 8 ms slices over round.input, which key() and release() set, boost, usePower (the oldest queued power-up, which space fires ahead of boost), hopHeight, checkTime), the POWERS in POWER_ORDER, the REGIONS (roads with their bonus, bends, hills, traffic, colors and props) in REGION_ORDER, the projection and drawing (sky, road far to near, props, traffic, Planny's car) and the game contract with release(); the next road is built only when the fork is chosen, and FORK_LEN must stay at least DRAW so it is built before it comes into view; memo is the roads found as bits; a read-only round getter for the tests only
public/activities/stack.js Stack Deploy: its rules as plain exported functions (newRound, spawnBlock, advance in 8 ms slices that slides the block between the walls, drop, which drops it where it was last drawn and returns { kept, sliced, perfect, miss }, isPerfect and zoneOf (3% of the block's width, the slide in PERFECT_MS, or round.minZone, the MIN_ZONE_PX floor the game sets at each resize, whichever is most, but never more than half the block's width, so a drop off the tower is never perfect), grow, speedAt, twistsAt, styleAt, comboPitch), the TWISTS by floor (speed ramp, either side and turning back, lag spikes, wind, rush hour, faster) and the STYLES of the tower, the drawing (sky by height, blocks per style, Planny riding the top, the dashed marker of the highest floor) and the game contract with pointer() (a press on the board drops) and release() (a held up drops once, not at every key repeat, and key(name, repeat) ignores a repeat the window marks, so up held through the countdown never drops at its first repeat); a press waits for the first tick after a start or a play-on, so an arrow that resumes never also drops; a miss holds the round running for OUTRO_MS while the camera pulls back over the whole tower; memo is the highest floor ever reached, saved on a pause and at the end; a read-only round getter for the tests only
public/activities/bumper.js Bumper Ring: its rules and physics as plain exported functions (newRound, newHeat, advance on a fixed 4 ms sub-step over round.input, which key() and release() set, push (accel toward the held direction, capped at the top speed that way, drag easing a car to the floor's own speed), collide (circle bounce with restitution BOUNCE; the faster car rams and gives SHOVE_BONUS more, takes that much less back; under IMPACT_SPEED it is a lean, no bounce and no shove, so a pushing match goes to the stronger push), dash, edgeGap and outOfRing (a car is out when its center is past the edge or over an open hole; round or, in the Hall of Mirrors, square), shrinkAt and nextShrinkIn (whole for SHRINK_START_MS, SHRINK_STEP a step to MIN_RING, then after SUDDEN_MS sudden death to LAST_RING, under one car's radius, so every heat ends), aim (a rival's push, dash and target per personality, with panic near the edge and a sharpness-scaled chance to misjudge), applyPower, spawnPad, creditKo (the last toucher within CREDIT_MS, your hit carried through a rival counting as yours, and a rival you rammed into another keeping your credit, the carry lasting CAROM_MS from your hit; the combo, the double and the bait bonus), rivalPower and arenaFor (each built once per arena, since the rules ask every slice), holeState), the ARENAS (rivals, sharpness, shrink pace, then endless Finals past the ninth), the RIVALS personalities and the POWERS pads, and the game contract with release(); a rival winds a dash up for WINDUP_MS (shorter when sharper) before it goes, which is the player's moment to step aside; a big hit holds the action for HIT_STOP_MS; memo is the furthest arena reached, which can pass 9; a read-only round getter for the tests only. Hand-tuned from the brief's starting numbers (the changes are listed under "As built" in game-ideas/bumper-ring.md), aiming for heats of 20 to 60 s from arena 2 on
public/activities/bumper-draw.js Bumper Ring's drawing: drawScene(ctx, view) from a plain view bumper.js builds (the round, the board geometry, the effects, the pill numbers), each arena's ring in its fixed palette (themeFor), the floor (ice, oil, holes, bumpers, the magnet, the warning bands), the cars (Planny upright at the wheel of a car in --accent, star eye and stick arms; rivals with a face each), the pills (laid out by hudLayout, which starts a row below rather than run into the ring's countdown or off the board), banners and the start and end strip, and readColors(canvas); decides nothing
public/activities/rapids.js Rapids Run: its rules as plain exported functions over a round on a river scrolling down a 64 unit wide field, 84 units of it on the board (newRound(seed), newRiver(seed), buildStretch(river, n, random) (a stretch's rows from its own seed, each row a center, width and island width: a calm opening, then drifts, narrows and islands, every bank slanting at most SLOPE a unit, every channel at least MIN_CHANNEL wide, then a BASIN_W basin on a boss stretch and the narrowing to the DAM_W dam; and its plan of foes, buoys and crates, none in the first SAFE_START (where you start again) or by the dam), ensureRiver, riverAt (a row's banks and island eased from the row before's, so they slant as drawn), channelsAt, channelAt, isWater, onLand (the hull sampled at seven points), placeAt (the start of a stretch, its dam whole and its plan loaded afresh), advance in 4 ms slices over round.input, which key() and release() set: steering eased in, the whirlpools' tug, the speed held (up, down or neither, times the stretch's pace), the battery drained (DRAIN a second cruising, more at speed), distance points, the guns (FIRE_MS, Spread's fan), shots against foes, the boss, the dam and buoys, the foes (skiffs and darters drift and turn at the banks, a darter swerves into your lane, gulls take off as you near and swoop across, sentries fire at you), the boss (spawnBoss holds the river and the battery; its volleys by kind), bolts, pickups (a buoy BUOY_CHARGE, the magnet's pull, crates), crashes (lose: a shield takes any crash but a flat battery and slides you off a bank; blinking for GRACE_MS after a restart), skims (SKIM_POINTS each SKIM_MS closer than SKIM_GAP at speed), the dam (hitDam, then past it the next stretch, with FLAWLESS_POINTS times it for no life lost), hurtFoe (the combo, up to MAX_COMBO), hurtBoss (a life back and a crate), applyPower, stretchFor (built once a stretch; past the eighth, Night Water 2, 3 and on), underBanner, screenY, seeded), the FOES, BOSSES, POWERS and STRETCHES, and the game contract with release() (held arrows steer, speed and slow, held space fires; a pause lets go of every key); memo is the furthest dam blasted, which can pass 8; a read-only round getter for the tests only. Tuned by a scratch sim: a careful bot clears a stretch in 20 to 35 seconds, and the battery runs flat for one that grabs too few buoys
public/activities/rapids-draw.js Rapids Run's drawing: drawScene(ctx, view) from one view object rapids.js refills each frame, in field units: the strip above the field in the page's colors with the pills (laid out by hudLayout, which starts a second row rather than run off the board and centers its rows in the strip), the river a look at a time (LOOKS: meadow, autumn, canyon, marsh, dusk and night, each in fixed colors, the look changing at each dam): banded banks, the water between them with shore lines and flow streaks carried downstream by the view's clock, pointed islands, trees or rocks; the dam ahead (hazard stripes, a crack for every share knocked out, a trickle once it is close to going) and the broken one behind; charge buoys, crates with their glyphs, whirlpools, skiffs, darters, mines, bank sentries aiming at you and gull drones with their shadows; the mini-boss and its health bar; Planny's jet-skimmer in your highlight with a white trim (so a blue highlight still shows on blue water), his wake, jets, arms to the bars (up when a dam or a boss goes), his box and his star eye in your highlight, bobbing with the star spinning after a crash; shots, bolts, sparks, rings, floating words (kept on the field by labelSpot), the combo's big number, the battery gauge beside the field (green, amber, then red and blinking under the low mark), banners, and the start and end strip with the big final score and a dot per named stretch whose dam you have blasted; readColors(canvas), lookColor, inkOn, contrast; decides nothing
public/activities/fuse.js Hot Potato: its rules as plain exported functions over a round on a 104 by 70 arena (newRound, newMatch(round, venue), which lights each bomb on a rival, never you, in a match's first fuse, advance in 8 ms slices over round.input, which key() and release() set, move (speed eased toward the held direction at GRIP, a dash holding its line, belts and ice from the floor), dash (a holder's dash is a numbered lunge), tag (a holder touching a runner with no bomb passes it, never inside NO_TAGBACK_MS of the bomb changing hands, nor back to the one who just passed it within TAGBACK_MS while three or more are left, tagBack, with tagSafe saying who is safe that way for the drawing; a fuse under PASS_FLOOR_MS, NO_TAGBACK_MS plus PASS_REACT_MS, is raised to it on any pass, once a fuse for each runner (bomb.lifted); your pass scores, a hot one under HOT_MS as passed steps the streak), burn (Freeze takes its share first), blast (the holder out, everyone near knocked back, the match over when that was you or one is left), nextFuse (a survivor with no bomb, the next shorter fuse from fuseFor, never more bombs than one for every two left), think (a holder chases by its own flood-fill path, weighted toward a boxed-in or dashless target; a runner without a bomb scores candidate spots by the holders' path distance against its own and flees to the best; personalities bend both), applyPower, spawnPickup, speedOf, clearLine, rivalPower and venueFor (each built once per venue), rivalColors(you)), the VENUES, LAYOUTS, RIVALS and POWERS, and the game contract with release() (key(name, repeat) never dashes on a repeat); a rival holder winds up (WINDUP_MS, shorter when sharp) or, a Trickster, feints (FAKE_MS) before a lunge, and a runner a lunge comes at dodges once a lunge at its venue's odds after its reaction time; the fuse ticks quicker and higher as it burns down, on one clock however many bombs burn (yours, else the shortest); a bomb whose fuse has run out passes to nobody; memo is the furthest venue reached, which can pass 9; a read-only round getter for the tests only. Tuned by a scratch sim (see "As built" in game-ideas/hot-potato.md)
public/activities/fuse-draw.js Hot Potato's drawing: drawScene(ctx, view) from one view object fuse.js refills each frame, in arena units: the strip above the arena in the page's colors with the pills (laid out by hudLayout, which starts a second row rather than run into the fuse and centers its rows in the strip), each venue's floor in its fixed palette (themeFor, venueColor), ice, running belts, the Rooftop's open edge, the things to run round, pickups, the runners (Planny on his feet with his star eye and stick arms, flailing while he holds a bomb, and still Planny when charred; arms and feet on the floor in limbInk(level), the ink that stands out from that venue's tiles; rivals with a mark per personality; a white ring with a dark edge at the feet of a runner safe from a tag-back; the charred waddle to the nearest wall and the fall from the roof), the bomb over its holder (a red ball with a <<< band, growing and glowing as it burns, flashing white while it cannot be passed, its fuse a shortening curl with a spark, the last seconds in big numbers (under the holder's feet when there is no room above, countY), a hop across on a pass), blast clouds, the Blackout's dark worked out once a frame in cells, the red edge pulse in a fuse's last second, banners and the start and end strip with the big final score, and readColors(canvas); decides nothing
public/activities/hop.js Crossing Rush: its rules as plain exported functions over a round on a strip COLS (11) cells wide of 30 to 40 lanes, VIEW_ROWS (14) on the board at once (newRound, newHeat(round, zone), which builds the heat's lanes from the round's seed, kept when a heat runs again, buildLanes(zone, seed) (groups of road, highway, ice, river, turtle, rapids or rail lanes with a grass row between each two, the zone's new thing first; the same seed builds the same lanes), advance in 8 ms slices (lanes flow, riders drift with their log, rivals choose, everyone is checked where they stand before any hop moves on, then hops and flights; hoppers home in the same slice finish by the moment each landed, a dead heat to you), hop(round, hopper, dir) (one cell, two with a Spring; a hopper counts in the cell it leaves for the first half and the one it lands on for the second; an icy lane slides it a cell more), laneAt, occupied(round, row, col, atMs) (a car or a train on it, or in a river no float or the edge, atMs ahead through shiftAt, which follows a lane's flips, surges and a Horn exactly), sendBack (to the last grass row, safeBelow, crediting a shove within SHOVE_CREDIT_MS), shove(round, from, to) (a cell the way from faces, only on a hopper inReach and never on one past the half of its hop home, once every SHOVE_MS), plan(round, hopper, random, power) (a look ahead of LOOKAHEAD to LOOKAHEAD_SHARP hops over the lanes as they will move, each hop followed by the hopper's wait where it lands; never a hop where it would be hit or fall in at full sharpness; a sloppy rival now and then hops on regardless), applyPower, zoneFor and rivalPower (each built once per zone), rivalColors(you), standings), the ZONES, RIVALS and POWERS, and the game contract with release() (key(name, repeat) hops once a press: never on a repeat, never again until the arrow is let go, never with the press that plays on, and with one hop queued behind the one in the air; a pause drops what is held and the queue); rivals wait REACT_MS down to a sharp rival's after each landing, a Bruiser shoves anyone beside it into a lane, a Tagalong follows a row behind you and shoves near the top, and a rival that lets a shove go weighs the next one only after SHOVE_LOOK_MS; memo is the furthest zone reached, which can pass 9; a read-only round getter for the tests only. Tuned by a scratch sim (see "As built" in game-ideas/crossing-rush.md)
public/activities/hop-draw.js Crossing Rush's drawing: drawScene(ctx, view) from one view object hop.js refills each frame, in board units: the strip above the field in the page's colors with the pills (laid out by hudLayout, which starts a second row rather than run into your place and centers its rows in the strip), the lanes in fixed colors (LANES, lookOf; pavement, grass with tufts, bushes and rocks, the checkered finish, roads with dashes and surge chevrons, icy roads, rivers with ripples and Rapids arrows, tracks with a signal that flashes while a train is coming), cars, vans, trucks, logs, turtles that sink and dive, the train, pickups, the hoppers (Planny on his stick feet with his star eye in every state: stretching mid-hop, spinning as he flies back, cheering, slumped when beaten; rival critters with a Hopper's ears, a Daredevil's goggles, a Bruiser's brow and a Tagalong's beak; arms and feet, and each rival's body edge, in limbInk(look), the ink that stands out from that lane), a Shield's ring and a Spring's coil, staggered stars, arrows at the edge for hoppers out of view, the Night Market's dark (soft lights cut from a layer the size of the field with one gradient made with the layer, or in steps with no second canvas), the race bar in the page's colors, banners, and the start and end strip with the big final score; every word kept on the field by labelSpot, and readColors(canvas), zoneColor; decides nothing
public/activities/bounce.js Bounce Road: the cars, the hazards against them, the scoring and the round, as plain exported functions over a round on a road scrolling up a 72 unit wide field, 90 units of it on the board (it re-exports every rule of bounce-road.js and bounce-rivals.js, so the suite imports one module): newRound(seed, random), advance in 4 ms slices over round.input, which key() and release() set (a jump press first, then your move, the rivals' think and move, the pads (a boost strip pushes you to NITRO_TOP for BOOST_MS even off the throttle, and the brake cuts it; a ramp launches any car crossing its lip quick enough RAMP_AIR the usual jump; a slick eases the steering at SLICK_EASE and makes a knock last for SLICK_MS), the bumps (collide: boxes pushed apart along the shallower overlap, side on a knock split by mass and harder for the car that did not steer in, end on speed passed forward, into a HEAVY truck's back at CRASH_CLOSE a crash; with Mega wheels a touch flattens; a close shave, NEAR_GAP or less between the boxes at speed and no touch, scores once), the barriers (a cone or a tire knocked flying slows you to CONE_SLOW; a block, pot or bucket nose first is a crash, from the side a push out), the hazards placed by the round's clock (a train hits a car on its track, a ball knocks a car by BALL_KICK, a sprinkler's jet pushes at SPRAY_PUSH, a drop falls DROP_FALL_MS after you come within DROP_TRIGGER, aimed at your line, and lies there after, a gust pushes at WIND_PUSH), then the ground (water or a hole under your middle a life, a flowerbed nose first a crash, a rival off the road out and yours within CREDIT_MS)), jump, land (on a car: flattened for its points times the chain up to MAX_CHAIN, a truck's roof HAUL_POINTS, the Monster a stomp, STOMP_POINTS, and on its last of BOSS_HP BOSS_POINTS times the lap and a life; on the road the chain ends, and the holes, trains, balls and barriers flown over and a ramp's big air score), stunt (a stunt's points times comboOf(streak): every COMBO_STEP stunts within STREAK_MS of each other one more, up to MAX_COMBO), lose (a Bubble throws you clear instead), applyPower, underBanner(round, y, cam) (a rival, a coming train, a ball or a thing still falling in the strip) and BANNER_Y, rivalColors(you)), the POWERS (Spring, Bubble, Nitro, Mega wheels) and the game contract with release() (key(name, repeat): held arrows drive and steer, space jumps once a press, never on a repeat or with the press that plays on, and a press up to JUMP_BUFFER_MS before a landing jumps on it; a pause lets go of every key and drops a press). A stage line scores STAGE_POINTS times the stage, TIME_POINTS a second under its par and, flawless, FLAWLESS_POINTS and a life back up to MAX_LIVES. Memo is the furthest stage reached, which can pass 10. A read-only round getter is for the tests only. Tuned by scratch bots: a careful bot clears all ten stages with no rivals on every seed tried (23 to 42 s a stage), and a bot with 150 ms reactions and 80 ms jump timing error reaches a median of stage 5 with the rivals out, stage 10 without
public/activities/bounce-draw.js Bounce Road's drawing: drawScene(ctx, view) from one view object bounce.js refills each frame, in field units: the strip above the field in the page's colors with the pills (laid out by hudLayout: stage, lives, Spring, Bubble, Nitro and Mega with their timers, the chain and the combo with its timer; a pill that would run off the board starts a second row), the road a chunk of CHUNK_ROWS rows at a time, drawn off screen once per road and scale, a few kept and copied each frame (rows from bounce-scenery.js), the layers over it (bounce-scenery.js), the landing rings (yours in your highlight, a rival's in red, the Monster's its own size), the cars through bounce-cars.js (every shadow first, upright, then every body with its tumble: Planny in your highlight with his box in the page's panel color and his star eye, arms to the wheel, up in the air or cheering, down at the end; each rival kind in its own style and color, the Cop's siren while it chases, the Monster's dents and a star per life left above it, headlights at Night Lights), sparks, rings, the dark of Night Lights, the chain's big number, the stage bar beside the field, banners, and the start and end strip with the big final score and a dot per stage reached; every word kept on the field by labelSpot, and readColors(canvas), limbInk, inkOn; decides nothing
public/activities/bounce-cars.js Bounce Road's cars, drawing only and no imports: drawCarBody(ctx, style, opts) draws one top-down toy car about the origin, nose up, filling w by h field units exactly (tires on the box's corners), in one of CAR_STYLES (STYLE_NAMES: Planny's convertible with his star eye and arms to the wheel, hatch, sedan, coupe, muscle, pickup, van, box truck, police, racer, taxi, jeep, monster) with flat-fill shading worked out from color and accent (shade, rgbOf), and options for roll (tilt), a jump (air: it draws the shadow and the lift itself), a pancake (squash), night beams, a siren bar, damage, a boost flame and brake lights, all moving parts on opts.clock; drawCarShadow and shadow: false for a shadows-first pass in screen space; carLength(style, w) for a style's natural length and carReach(style, opts) (with MARGINS) for what reaches outside the box
public/activities/bounce-scenery.js Bounce Road's scenery, drawing only: each stage's look in fixed colors (LOOKS: patio slabs, lawn stripes, kitchen tiles, garden, sand, a toy room's rug, a pond with lily pads, roof shingles, the night lawn with lamps and the Monster's dirt; lookOf, stageColor, contrast, better), drawRow (one row of the road in three passes over a chunk: the yard, the road's surface, the details: edges slanting from row to row, rivers, plank bridges with jagged broken ends, cracks, flowerbeds, rails across a crossing, cracked road over a pit, checkered stage lines, verge decor), and the layers drawn fresh each frame from the round's clock: drawTimed (a drawbridge lifting with its red lights, a swaying bridge where it is now, crumbled road gone to the pit), drawPads (running boost chevrons, ramps, slicks), drawBlocks (cones, toy blocks, pots, buckets, acorns and tires, knocked ones tumbling off), drawStars, drawSigns (a mark per hazard), drawItems, drawHazardsLow (crossing lights, the train, a rolling ball, a falling thing's growing shadow, a sprinkler's head), drawHazardsHigh (the jet, gust streaks, the thing still falling), drawNight and drawFireflies; decides nothing
public/activities/bounce-road.js Bounce Road's road, rules only: the jump math every hole is sized by (airMs(v), reach(v), LONGEST_JUMP, JUMP_FAIR, TOP_SPEED, MAX_SPEED), stageFor(n) (built once a stage: the ten of bounce-roads.js, then laps from LAP_FROM, quicker, keener, busier, the Monster at every Monster Mash) and stageName, newRoad(seed) and buildStage(road, n, random) (a stage's rows from its own seed, by the stage's piece weights: straights, cracks, rivers on bridges with one or two broken spans or a drawbridge, splits round flowerbeds, ramps before a crack with stars beyond, cone or block chicanes, crumbling road, train crossings, swaying bridges, boost strips, slicks, balls, sprinklers, drops and gusts; every hole after a RUNUP with a sign and no longer than MAX_HOLE, the bridge between two breaks long enough to land LONGEST_JUMP on), ensureRoad, groundAt(road, x, d, t) (a row's edges eased from the row before's; a drawbridge water while lifted, a swaying bridge shifted, crumbled road a hole), rowGone, spanAt, holesIn, firstAt, plainRow, safeSpot (no hole, water, timed part or rails for RESPAWN_RUN ahead), and where each timed thing is at a moment: swayOff, drawLift, crumbleAt (falling away CRUMBLE_DELAY after you reach it, at CRUMBLE_SPEED, under a fair speed), trainAt (on, and lit TRAIN_WARN_MS before), ballX, sprayAt, gustAt; plus seeded, GROUND, MARK, SPAN
public/activities/bounce-rivals.js Bounce Road's rivals, rules only: RIVALS (the Zigzag, Brick, Frog, Nudge, Hauler, Sneak, Bruiser, Racer, Cop and Monster: box, mass, speed, points, how readily each dodges, how often each comes, its car style and whether it comes from behind), makeCar, think(round, car, ms, random) (each kind's choice of speed and line: the Zigzag's weave, into your path when you follow; the Brick holding your lane and brake-checking from in front, then resting BRAKE_REST_MS or more; the Frog's hops toward you; the Nudge's chase and up to 1 + 2 times the stage's sharp swipes; the Hauler drifting to block; the Sneak dropping up to SNEAK_DROPS cones while you follow; the Bruiser slamming you within BRUISER_RANGE; the Racer passing then fleeing; the Cop sitting on your roomier side and leaning in to push you to the near edge for COP_MS, never on a bridge or by the water (nearWater), nor the Bruiser; the Monster keeping BOSS_AHEAD in front, hopping every BOSS_HOP_MS to come down where you will be and dropping tires; every rival rubber-banded to stay near you, swerving from under your landing as sharply as its stage allows, keeping to the narrowest road just ahead and the band a swaying bridge always covers, holding a slower car's speed, and hopping any hole, drawbridge, barrier or coming train, or flying off a ramp), spawnRival, pickKind (one of each special kind at a time), HEAVY, RIVAL_MIN_SPEED
public/activities/bounce-roads.js Bounce Road's ten stages as data (no imports): FIELD_W, FIELD_H, ROW, MAX_HOLE, LAP_FROM, and per stage its length, par time, road widths, piece weights (straights, holes, rivers, splits, ramps, chicanes, crumbling road, trains, swaying bridges, boost strips, slicks, balls, sprinklers, drops, gusts), crack and broken span lengths, bridge widths and shares of broken, double and drawbridge spans, flowerbed sizes, barrier and drop kinds, the rivals' count, kinds, pace and sharpness, power-ups, stars, and whether the Monster comes
public/activities/ghoul.js Ghoul Rush: its rules as plain exported functions over a round in one room of a haunted house seen side on, the view FIELD_W (96) by FIELD_H (54) units with y counted up, scrolled along a room hundreds of units long by round.camX (newRound(seed), the stage packs (PACKS, see ghoul-graveyard.js) merged into its tables and run where its own rules run, through a KIT of helpers; roomFor(id, depth) (built once per room and depth, the stages already cleared that run: the monsters quicker (pace, DEPTH_PACE a stage), let out sooner (every, DEPTH_EVERY), a bolt tougher (tough) and more of them out of wall doors (extra), each capped, the boss with BOSS_DEPTH_HP more hp a stage up to BOSS_DEPTH_MAX and more points (bossPoints)), roomName(spec, n), the run of stages (it starts in the hall, ROOMS[0]; out of the hall and out of each boss room the phase is pick with round.offer, OFFER_N stages from stagesLeft(round) shuffled by the random handed to advance; steerPick(round, dir) moves round.pick, pickStage(round, i) takes one once PICK_HOLD_MS has passed and enters its first room, round.stage/stageAt track the way through its rooms, round.cleared the stages done in order, and with none left the run is won: round.won, round.over, a won event), groundAt (ground pieces are solid blocks; a gap is a pit), shelfThere, footing (the highest surface within STEP_UP of a walker), jumpHeightAt(dx) (the suite's measure of what a jump clears), jump, moveYou (running at RUN_SPEED on the ground and in the air alike, a step of STEP_UP walked, a taller one a wall, shelves one way: jumped up through, landed on from above by crossing their line so no fall goes through one, dropped through with down; COYOTE_MS to still jump off an edge, a press JUMP_BUFFER_MS before landing jumps on it, up let go while rising cuts the jump to CUT_V), spawnMonster, solid (a crawler or a door's zombie still coming up, a gourdling still in the air or finding its feet, and a faded ghost can neither hurt nor be hit; a faded ghost within GHOST_CLEAR of you never turns solid), ghostSight, throwBone (timed to come down at your chest), aimAt (a bolt tilts toward the nearest monster or bone ahead within AIM_DY of your chest, by up to AIM_MAX), hurt, kill (points times chainMult(chain), the chain stepping for each kill within CHAIN_MS up to MAX_MULT, doubled for a headshot (the top HEAD_SHARE), a stomp or a chandelier; DROP_CANDY and DROP_POWER drops), lose, applyPower, advance in 4 ms slices over round.input, which key() and release() set: the timers, a jump press, the jump cut, your move, the door, the arena lock, the blaster (a bolt every FIRE_MS, RAPID_MS with Rapid fire, three with Spread shot, each flying SHOT_SPEED until a monster, a bone, the boss, a wall or SHOT_RANGE), the spawners (wall doors that hold while you are within DOOR_CLEAR, loose boards within CRAWL_NEAR, roosting bats within BAT_NEAR, the rest as the camera reaches them), the hurry zombies every HURRY_MS once the bonus is gone, the monsters (zombies lurch within LURCH_RANGE and never walk off an edge or onto a shelf, bats swoop in level passes at your chest turning BAT_TURN past you and never drop onto your head, ghosts drift through walls, skeletons wind up SKEL_WINDUP_MS and throw every SKEL_MS within SKEL_RANGE but not closer than SKEL_NEAR), the bosses (the Great Gourd waits GOURD_WAIT_MS, hops to where you stood (its shadow shows where) and slams down letting up to MAX_SEEDS gourdlings loose; Old Rattlebones' fight lives in ghoul-bones.js; shockwaves run WAVE_H high both ways at WAVE_SPEED; a stomp does STOMP_DAMAGE), the bones and shockwaves, the bolts, stomps (which bounce you at STOMP_V), the chandeliers (CHANDELIER_SHAKE_MS once you run under, then down on whatever is below), the hits (a Garlic shield takes one and sees off what touched you), the pickups, the crumbling boards (CRUMBLE_MS, back after CRUMBLE_BACK_MS) and a fall down a pit), underBanner(round, y) and bannerY, chainMult, seeded), the MONSTERS and BOSSES (with POWERS, TIMED, powerHere and the pickup points re-exported from ghoul-powers.js), NEW_TONES (the blips it asks tones.js for), and the game contract with release() (key(name, repeat): held arrows run, up jumps once a press, never on a repeat, never again until let go and never with the press that plays on, down drops through a shelf, held space fires and its release stops; a pause lets go of every key and drops a press); a hit or a fall costs one of START_LIVES, holds CRASH_MS and puts you back at the room's start (in a locked boss fight, the arena's, the boss's hp kept) for READY_MS, safe for SAFE_MS, the room's monsters and spawners back where they began; through the door ROOM_POINTS times the room, the bonus left (BONUS_START, dropping BONUS_STEP a second) and FLAWLESS_POINTS with no life lost; a boss beaten is its bossPoints and a life up to MAX_LIVES (9; the 1UP drops at weight 1.5); memo is the most stages cleared in one run; a read-only round getter for the tests only. Generic hooks the Mine added: a room's water spans (WATER_SPEED 0.65 of your speed and WATER_JUMP 0.93 of a jump on the floor in one, you.wet), you.dimMs/you.dimBy (an imp's stolen light, counted down in timers), the secondary weapons' round.arms, round.tap and the arm fields on a shot (see ghoul-arms.js). Tuned by a scratch bot: the Manor's rooms take a sharp bot 20 to 30 s each
public/activities/ghoul-draw.js Ghoul Rush's drawing: drawScene(ctx, view) from one view object ghoul.js refills each frame, in room units turned the right way up and scrolled by the camera: the strip above the field in the page's colors with the pills (laid out by hudLayout: the room, lives, the bonus, the chain with its window emptying, the key once held, the power-ups; a second row rather than run off the board, the rows centered in the strip), still layers CHUNK units of a room wide drawn off screen once per room and scale and copied each frame (a few kept; each room's look in fixed colors, LOOKS: wallpaper, moonlit windows, decor by room (portraits, bookcases, curtains, pots, ferns, rafters with cobwebs, headstones), wainscot, floorboards, pits, shelves, wall doors and loose boards), the crumbling boards, a wall door standing open, the chandeliers, the exit door (padlocked, then open and glowing), candy, power-ups and the key, the monsters (a zombie in a ragged shirt with mismatched eyes, lurching; a crawler's hand through the boards, then crawling; a bat with flapping wings; a sheet ghost fading in and out; a skeleton raising a bone; gourdlings), bones and shockwaves, the bosses (the Great Gourd with a carved glowing face and a red shadow where it will land; Old Rattlebones, drawn by ghoul-bones-draw.js) and the boss bar, Planny (his star eye in your highlight in every state, stick arms, one holding the flashlight blaster that flares as it fires, stepping, arms up in the air or cheering, spinning with an "o" when hit, slumped at the end, garlic circling him while he has some; arms and feet in limbInk(look)), the bolts, sparks, rings, floating words kept on the field by labelSpot, the chain's big number, banners (BANNER_SHADE) the stage pick (drawPicker: a card per stage offered with its picture, drawStagePicture, its first room's wall and moonlit window over its boss room's floor with its boss standing there drawn by the same BOSS_ART as in play, name, line and boss, the one picked out raised and edged in gold, stageColor its boss room's), and the start and end strip with the big final score and a dot per stage, lit in each cleared stage's color (gold for the record before a run); react(e, kit) turns each event into those effects and its blips, a monster's own sound through VOICES (each kind's tone in ghoul-sfx.js by act: appear (a runner's warn, a bat's wake, a wraith's notice), climb, hop, growl, lunge, shriek, dive, spit, throw, hurt (one every 140 ms), die, and a boss's wake, hop, slam, windup; a "throw" event names its thrower in by and a "spit" its spitter in kind); the stage packs' drawing (ART: an outdoor look draws its pack's backdrop instead of walls, graves for doors, and each pack's monsters, bosses, missiles, hazards and lights by kind; a pack may also draw sky (every frame, under the still layers, so its backdrop leaves the sky clear) and moving (what moves in its scenery, over the still layers)); readColors(canvas), contrast, lookOf; decides nothing
public/activities/ghoul-rooms.js Ghoul Rush's rooms and stages as data (no imports): the long hall every run starts in (ROOMS[0]), then STAGES (each an id, title, line and four room ids, the last a boss's, checked at load; stageById, roomById), FIELD_W, FIELD_H, FLOOR_Y, CEILING_Y, CHANDELIER_Y, and per room its look, name and line, length, ground pieces (pits between, steps and walls), shelves (crumble kind), start, key, door, candy rows, power-ups, spawns (zombies, wall doors, crawlers' boards, bats, ghosts, skeletons), chandeliers and boss (gourd, bones or a pack's, the last room of its stage); a door's fifth entry names what comes out of it (rotters out of the Graveyard's graves)
public/activities/ghoul-bones.js Old Rattlebones' fight, the East Wing's boss, as a boss pack in the shape of the stage packs (no imports; ghoul.js hands each rule its kit k; it plugs in through PACKS with bosses, boss and hazards, and ghoul.js re-exports BONES_KEEP, BONES_MS, BONES_RAGE_MS, BONES_WINDUP_MS and VOLLEY): 90 hp; every BONES_MS he winds up for a volley, a slam or the skull, picked at random by pickAct (never one three times running, the first a volley); the skull is a skull hazard that flies level at your chest SKULL_REACH past you and curves back to his neck while b.headless (no weak spot; a bolt to the skull does SKULL_HIT, eaten, with SKULL_STAGGER_MS between hits); at half his hp (BONES_RAGE) he shakes (BONES_SHAKE_MS), attacks every BONES_RAGE_MS, slams in a double (DOUBLE_GAP_MS), hurls bone rain (rain hazards: a shadow for RAIN_WARN_MS, then a bone) and raises skeletons (raise hazards, at most MAX_BONY alive or cracking).
public/activities/ghoul-bones-draw.js Old Rattlebones' drawing, boneArt(d) plugged into ghoul-draw.js's PACK_ART: the boss (headless while the skull is out, arms to the skull or up for rain, shaking with flaring eyes in his rage), the skull in flight, the bone rain's shadows and falling bones, the cracking floor, lights, react cases for his new events (skullWind, skullThrow, skullTurn, skullBack, rainWind, rainThrow, rainLand, bonesRage, raiseWind, raised), and LOSE_WORDS / LOSE_SOUNDS for skull and rain.
scripts/test-web-console-activities-ghoul-bones.mjs Old Rattlebones' suite: the random attack order, the volley and slam, the skull's flight and the headless window, the skull shot, the rage, the double slam, bone rain, the skeleton cap and the reactions.
public/activities/ghoul-graveyard.js Ghoul Rush's Graveyard stage pack, its rules (no imports: ghoul.js hands each rule a kit k of its own helpers). A stage pack is plain data and functions that ghoul.js merges into its own tables (PACKS): monsters (with perch: its spawn names its height, flies: a horde one comes in high), walkers/zombies/stackers/climbers (joining the sets of those names), act (start), solid, move, kill, horde (fields a horde one comes with), bosses, boss (one slice of its fight), guard (true while shots and stomps glance off, a bossBlock event) and hazards (by kind, one slice of a box on the floor that hurts while live; kept in round.hazards). Three more fields a stage may add (the Grounds does): cut (kinds the Hedge shears kill outright), weak (by boss kind, (boss, shot) => damage multiplier for a weak spot; bossHit then carries how: "weak" and weak: true) and cause (what a boss's touch is called when it costs a life). The Chapel adds more: tick(round, ms, k) (a stage-wide twist run first in every slice; it may set round.stunMs, which freezes you and every monster, boss, hazard and missile while bolts in flight still fly, and keeps its state in round.twist), stone (by kind, true while shots glance off and a stomp does nothing; glance event), shot(round, m, s, k, random) (the damage multiplier of a bolt that hit m, free to splash), target(round, s, k) (true when a bolt struck something of the pack's that is no monster, such as an organ pipe) and, on a monster, hasteMs and haste (its time runs faster while hasteMs is over 0). On the drawing side a look may be custom: true with a pack id (the pack's art then draws the whole wall, floor and shelves) and the art may return decor (by the look's decor name). On the drawing side a stage's art may also return react(e, k) (its own events; ghoul-draw.js's react falls through to ART.react, which returns true when it handled e), ground and shelf (the floor pieces and shelves of an outdoor look), waves and powers; a boss event must carry kind or its voice never plays. The Graveyard's: grasping hands (HANDS_*: lurk unseen, rise, grab, sink, creep under level ground after you), the mourner (wails every WAIL_MS, slowing you to SLOW_SHARE speed for SLOW_MS within WAIL_REACH; round.you.slowMs), the grave robber (digs in within ROBBER_DIG, comes up ROBBER_BEHIND behind you), the rotter (a zombie whose body-shot death leaves its legs walking), the carrion crow (perches, dives at your chest, climbs, dives again), and Mother Mourning (angel: weeps ANGEL_WEEP_MS as stone flinging headstones, turns ANGEL_TURN_MS, watches ANGEL_WATCH_MS when only she can be hurt and any move drops a fist hazard after FIST_WARN_MS; at ANGEL_RAGE her wings spread, the weep shorter, the watch longer, a shockwave each way as each weep begins)
public/activities/ghoul-graveyard-draw.js The Graveyard's drawing: LOOKS for its four rooms (outdoor: true, so ghoul-draw.js draws backdrop instead of walls: the night sky, stars, the moon, hills with dead trees, iron fences, mausoleums, fog and headstones) and graveyardArt(d), handed ghoul-draw.js's helpers, returning the open grave and openGrave a rotter climbs out of, monsters, bosses (Mother Mourning: hands over her face while she weeps, lowered with burning eyes while she watches, wings spread in a rage, cracks as she is worn down), missiles (a flung headstone), hazards (a stone fist: its shadow, then the fist) and lights
public/activities/ghoul-grounds.js Ghoul Rush's Grounds stage pack, its rules (no imports; same shape as the Graveyard's, plus the pack fields cut, weak and cause): the topiary beast (still while you face it, creep when your back is turned; events rustle and freeze), the rootling (trail, warn, up, sink; events rootWarn and rootUp), the lantern moth (flocks of three, quicker in the dark), the mulch crawler (pile, burst, crawl; event leaves), the Hedge shears' snip event, and the Groundskeeper (keeper: a scythe sweep along the floor (or, now and then, a high sweep hazard you stay on the ground under), a lobbed lantern fire hazard, his lantern a weak spot only while open (b.lit), and at half hp a mower with rev, charge and stall)
public/activities/ghoul-grounds-draw.js The Grounds' drawing: LOOKS for its four rooms (outdoor: true), groundsArt(d) returning monsters, bosses, hazards (the fire), waves (the scythe), powers (the shears), lights, backdrop, ground, shelf and react(e, k) for the Grounds' own events; its VOICES (each kind's tone per act, keeper.weak for a weak-spot hit instead of keeper.hurt, shears.snip for a cut instead of the dying cry), LOSE_WORDS and LOSE_SOUNDS, which ghoul-draw.js spreads into its own tables
public/activities/ghoul-chapel.js Ghoul Rush's Chapel stage pack, its rules (no imports; same shape as the Grounds', plus the pack hooks tick, stone, shot and target, and a room field toll): the gargoyle (perch as stone, wake, dive, return; events glance, gargoyleWake, gargoyleDive, gargoylePerch), the choir ghost (sings, giving nearby monsters hasteMs), the censer monk (smoke hazard), the bell bat (roost until the toll), the bell toll (tick: bellSwing, toll, tollEnd, round.stunMs), Holy Water's splash (shot, event holySplash) and the Choirmaster (choirmaster: four pipes in b.pipes that bolts hit through target, a guard while any sounds, columns of note hazards with one gap, a rage that brings pipes back one by one)
public/activities/ghoul-chapel-draw.js The Chapel's drawing: LOOKS for its four rooms (indoor but custom: true with pack: "chapel", so ghoul-draw.js hands the walls, floor and shelves to chapelArt(d)'s backdrop, ground and shelf), chapelArt(d) returning those plus decor (the room's pews, belfry, organ or stalls), monsters, bosses, hazards (smoke, the bell, notes), powers, lights and react(e, k); its VOICES (the bell has only swing and toll: the thaw after a toll is quiet on purpose), LOSE_WORDS and LOSE_SOUNDS
public/activities/ghoul-sanatorium.js Ghoul Rush's Blackmoor Sanatorium stage pack, its rules (no imports; same shape as the Chapel's, plus the pack fields unseen, harmless, platform and land, a room field flicker, round.blackout/round.twist for the lamps and the kit's fling): the orderly (reach, hold, a throw that costs no life, you.heldMs; events orderlyReach, orderlyGrab, orderlyThrow, saltsBreak), the gurney (parked as a floor you can stand on, rattle, roll, rest; gurneyRattle, gurneyRoll, gurneyRest), the flicker (m.unseen: bolts and touch go through it until a blackout, the Lantern's light or the Salts' glow; flickerShow), the specimen bloater (a jar missile with its own cause that lands as a formaldehyde hazard; jarWind, jarBreak), the lamps (tick: flickerWarn, lightsOut, lightsOn), the Salts and the Saw (shot) and the Night Matron (matron: b.beam cone, b.heat, b.cabinets, syringes, arms, rage; syringeWind, syringes, armWarn, armReach, matronRage)
public/activities/ghoul-sanatorium-draw.js The Sanatorium's art: LOOKS (indoor but custom: true with pack: "sanatorium" and noMoon, so sanatoriumArt(d)'s backdrop, ground and shelf draw the tiled walls, windows, decor, floors, the ward's cabinets, the baths' tubs and each room's boards), monsters (orderly with its grab pose, gurney, flicker with its fade and afterimage, specimen bloater), the matron with her cone cut by the floor and the cabinets, missiles (jar, syringe), hazards (formaldehyde, arm with its crack of light), powers (Salts, Saw), lights, react(e, k) and two generic hooks ghoul-draw.js calls: front(ctx, v) (over Planny and before the dark: the ceiling lamps, the tubs' water, the orderly's fingers, the Matron's heat on him) and dim(v) (the dark layer's alpha, raised in a blackout and in a stutter); its VOICES (borrowed tones; lights, salts and saw are no monsters), LOSE_WORDS and LOSE_SOUNDS
public/activities/ghoul-village.js Ghoul Rush's Hollow End Village stage pack, its rules (no imports; no new pack field: it uses tick, shot, land, weak (now handed (boss, shot, round, k)) and solid, and draws no random number): the moonrise (tick; round.twist = { moon, full, ms }, events fullMoon, villagerTurn, villagerWolf, houndGrow), the torch mob villager (a group of three, torchWind, the torch missile that lands as a torchfire hazard, torchLand; turned into a leaping wolf-man at full moon), the hanged man (hangedWarn, hangedDrop, hangedSnap, hangedHaul), the shutter ghoul (solid only while out; shutterRattle, shutterLunge, shutterPull), the moonhound (the hellhound's leap, grown at full moon), Wolfsbane's double damage and shying (baneShy) and the Beast of Hollow End (beastLeap, beastCling, beastPounce with a shadow hazard, beastLand, swipeWind, beastSwipe with a claw hazard, beastHowl, houndCall, beastMoon)
public/activities/ghoul-village-draw.js The Village's art: LOOKS (street, square and green outdoors, the inn a custom indoor look, all pack: "village"), villageArt(d) returning the world's hooks plus the monsters (the torch mob villager and the wolf-man it turns into over 800 ms, the hanged man on his rope, the shutter ghoul reaching out of a window, the moonhound with a glowing mane when grown), the beast (a werewolf in every move: cling with a glowing weak spot, bound, pounce, land, swipe, howl at the moon, rage), missiles (torch), hazards (torchfire, the landing shadow, the claw swipe), powers (Wolfsbane's badge), lights and react(e, k); its VOICES (borrowed tones, plus moon.full and bane.active), EVENT_VOICE (event to [kind, act], each played once; the hounds' call is quiet), LOSE_WORDS and LOSE_SOUNDS. Its header lists what the art reads off the rules
public/activities/ghoul-village-world.js The Village's world: the night sky and the moon that climbs and reddens with round.twist.moon (sky, drawn every frame under the still layers), the crooked timber-framed houses with a window for every shutter ghoul, the church and spire, the gallows, the green's far cottages, well and arena walls, the Crooked Inn (hearths, barrels, bar, lanterns, the moon in its windows), cobbles, planks and turf (ground), awnings, rooftops, balconies, tables, carts and thatch (shelf), and moving (curtains that twitch as you pass, fire, moonlight falling in), front (the full-moon wash, Wolfsbane's petals, the Beast's rage) and lights
public/activities/ghoul-mine-world.js The Deep Seam Mine's world (no imports; mineWorld(d) takes ghoul-draw.js's helpers): the rock wall with its strata and facets, the timber that holds it up (props and cap beams, scaffolds and galleries as shelf), rails and sleepers on the floor (ground), oil lamps on hooks with their flames and warm halos (moving) and their holes in the dark (lights, none in a blackout), the shaft's lining, walers, guide rails and headframe with the cage lift drawn on its cable over a winch wheel with a counterweight (cage, and its front bars in front), the tunnels' low roof, pipes, stalled pump, drips and knee-deep water with a lit surface and Planny's wake (front), the collapse's broken props, cracks, rubble heaps and buried cart, the seam's glittering ore vein, stalactites and galleries, and the rock hazard in its three states; layouts are worked out once per room from the room alone and kept. Scene tool: prototypes/ghoul-rush-tools/scene-mine-world.mjs
public/activities/ghoul-village-wolf.js The Village's werewolf, one skeleton for the Beast and a turned villager: poses (POSES: stand, rear, swipe, howl, crouch, leap, land, rest, cling, shy, down, sleep), mixPose to blend them, and wolfKit(d).figure to draw one
public/activities/ghoul-mine.js Ghoul Rush's Deep Seam Mine stage pack, its rules (no imports; draws no random number): uses tick, harmless, platform, solid, kill, weak and a boss's blackout (round.blackout). The rockfall (tick; a room field rocks in ms; the rock hazard in states warn, fall, rubble, events rockWarn, rockFall, rockLand; the Hard Hat's rockBounce), the noise you make (round.twist = { next, quiet, noise, reach, wade }, wade splashes), the knocker imp (touch steals light, not a life: you.dimMs and you.dimBy, impSteal, impDrop; the Hard Hat stops it), the canary ghost (canaryScream: three rocks), the dead miner (buried in the wall, minerDig, pickWind, pickSwing with a pick hazard, cause pickaxe), the blind crawler (blindLost, blindHear), the cage lift (a spawn row ["cage", x, lowest y, highest y], a platform kind that is not solid and never hurts), Dynamite placed in each room (its rules, the stick and blast hazards, dynThrow and dynBlast, moved to ghoul-arms.js) and the Tommyknocker (tommyKnock, sweepWind, tommySweep with a hammer hazard, tommyDark, tommySink, tommyKnockDark, tommyBurst, tommyRage; dazed double damage through weak)
public/activities/ghoul-mine-draw.js The Mine's art (the rooms in ghoul-mine-world.js, the Tommyknocker in ghoul-mine-tommy.js): LOOKS (custom: true, pack: "mine", always dark), mineArt(d) returning backdrop (rock, strata, timber props, oil lamps), ground (rails), shelf (timber landings), front (the water along the floor), dim (the blackout), monsters (imp, canary, miner, blind crawler, cage), the tommy boss, hazards (rock, stick, blast, pick, hammer), powers (Hard Hat, Dynamite), lights and react; its VOICES (borrowed tones), EVENT_VOICE, LOSE_WORDS and LOSE_SOUNDS. Its header lists every field the art reads off the rules; ghoul-draw.js shrinks Planny's glow and drops his cone while you.dimMs is over 0
public/activities/ghoul-mine-tommy.js The Tommyknocker's figure for ghoul-mine-draw.js: tommyKit(d) (no imports, ghoul-draw.js's helpers handed in) returns figure(ctx, v, b), a miner-giant half grown into the seam (stone shoulder with crystals, lantern on his helmet, a door-sized hammer) drawn by act: leaning on the hammer, the overhead knocks, the drawn-back sweep, rest, sinking, bursting out dazed with stars, raged cracks, hurt flash.
public/activities/ghoul-cart.js Ghoul Rush's Runaway Cart, the Mine's ride room, its rules (no imports; draws no random number): the first room where a pack takes Planny's movement over. It adds the pack fields ride (a list of (round, ms, k) => true hooks run each slice before the walking rules; one that returns true has moved him) and place (a list of (round, k) hooks run whenever he is put down in a room: a room set up, a respawn), uses target (the crates), and round.camLead (units the camera leads further). The cart (round.cart, null elsewhere) rides the room's ride.track polylines (slope speed, lean and brake, jump, air steering, ramp launch, landing on the line under it, derail into the chasm), ducks under ride.beams, wrecks on rubble and unbroken crates (two bolts break one), is chased by the boulder, passes checks (a life lost puts it back at the last) and halts at stop where the door opens; a ledge imp (ledgeimp) leaps into it and steals light, a canary's scream drops a slide of rubble on the track ahead. Exports flight, trackY, linesAt and linesOf for the unit suite. Events cartJump, cartLand, cartLaunch, cartBrake, cartDuck, crateHit, crateBreak, cartCrash, boulderNear, checkpoint, cartStop, ledgeLeap, slideWarn, slideFall; causes derail, beam, crash, boulder
public/activities/ghoul-cart-draw.js The Runaway Cart's art: LOOKS (custom: true, pack: "cart", always dark), cartArt(d) returning backdrop, ground, moving (every frame: the cave in cached parallax tiles over a chasm, the trestled track, ledge pillars, signal posts, rubble and the buffer stop in cached chunks, hanging lamps, signal lamps, crates, a slide's dust and pour; the cart too once it has stopped, so Planny walks out past it), front (the cart over Planny, the beams, the boulder, flying splinters, speed streaks, the foreground rock), lights (headlamp, hanging and far lamps, signals, beams), monsters (the ledge imp) and react; its VOICES (borrowed tones), EVENT_VOICE, LOSE_WORDS and LOSE_SOUNDS. It keeps its own offscreen layer cache (keyed by scale), draws no random numbers (a hash) and leaves short-lived bits in the view's fx (cartBits, cartPours, cartLand, cartStop). Its header lists every field the art reads off the rules
public/activities/ghoul-sfx-mine.js The Mine's own sounds as data (no imports): MINE_SFX with an empty tones and music until the user picks them; merged by ghoul-sfx.js via STAGE_SFX (its rooms play existing tracks, set in ROOM_MUSIC)
public/activities/ghoul-carnival.js Ghoul Rush's Midnight Carnival stage pack, its rules (no imports; draws no random number): uses tick (the ring of samples Mirror You reads and its bolts in round.twist), shot (Cotton Candy's slow, a marionette's string at the top of its body), target (a bolt crossing a marionette's string or one of the puppet's three), guard (the Ringmaster is open only with the puppet down), swoops (a balloon, a circus hound's leap), solid, kill and fourLegged. Grinner and its acid balloons, marionette (drops when you pass under), Mirror You (copies you 500 ms late, mirrored, its bolts cancel yours), strongman (barbells), circus hound, and the Ringmaster (a gantry over the ring that follows its puppet at a lag, the puppet stalking you and working to a fixed script of leap, stomp, whip and charge, three strings from the gantry to its head and hands that move with it, open 4 s when they are cut, rage with hounds from the cages); CARNIVAL_ROOMS lists the stage's rooms, with a place before the Big Top for the dark ride. The room field belts and Planny's you.belt (the funhouse's conveyor floors) are run by ghoul.js.
public/activities/ghoul-carnival-draw.js The Carnival's art: LOOKS (custom: true, pack: "carnival"), carnivalArt(d) returning the world's hooks (from ghoul-carnival-world.js) plus monsters, the ringmaster boss (gantry, puppet in each pose, strings, whip), missiles (barbell), hazards (foot, whip, charge), waves (the puppet's), powers (Cotton Candy), front (Mirror You's bolts, Cotton Candy's glow), lights and react, and VOICES (borrowed tones), EVENT_VOICE, LOSE_WORDS, LOSE_SOUNDS. Its header lists what the art reads off the rules.
public/activities/ghoul-carnival-world.js The Carnival's world (no imports; carnivalWorld(d) takes ghoul-draw.js's helpers): the night sky with a Ferris wheel (sky), tents, booths and swagged bulbs on the Midway, the Hall of Mirrors' gilded panels and glints, the Funhouse's crooked walls, spiral discs and clown-mouth door, the Big Top's striped canvas, ring curb, crowd, trapeze boards, gantry rail and cages (open once the Ringmaster rages), and the belts' chevrons (moving).
public/activities/ghoul-sfx-carnival.js The Carnival's own sounds as data (no imports): CARNIVAL_SFX with an empty tones and music until the user picks them; merged by ghoul-sfx.js via STAGE_SFX (its rooms play existing tracks, set in ROOM_MUSIC)
public/activities/ghoul-ride.js The Carnival's dark ride (a bonus round) as a pack (RIDE), the rules ported from prototypes/ghoul-rush-ride/gallery.html. Pack fields ride (returns true, so Planny never walks; steps the ride in 16 ms steps), place (makes round.gallery, the ride's state) and a new pointer (the mouse, handed on by ghoul.js's pointer(type, x, y)); the entities (K: pop, lant, axe, chand, door, hand, head, eyes, boss, inno, mir, web, mini), hit tests with aim assist, the duck zone, hearts through kit.lose, the grade (5 to 9 dice, perf.dice). Events ride<Name> (SOUNDS), causes CAUSES. Its own seeded random stream; draws no Math.random
public/activities/ghoul-ride-scenes.js The dark ride's scene table as data (12 rooms, lengths, speeds, spawn rows in author coordinates), no imports
public/activities/ghoul-ride-core.js The ride's shared basics: the 96 by 54 field's constants, math helpers, the bound state G (a live import), rnd/rand (seeded) and vrand (visual)
public/activities/ghoul-ride-draw.js The ride's art entry (rideArt(d, die): field(ctx, v) draws the whole field by phase, tick the cascade's sounds); ghoul-draw.js hands over to it when round.gallery is set. Parts: ghoul-ride-gfx.js (canvas helpers), ghoul-ride-draw-kinds.js (animatronics, mini-bosses, the Barker), ghoul-ride-draw-sets.js (the 12 sets, far walls, aisle, near layer), ghoul-ride-draw-hud.js (car and Planny, HUD, duck strip, reticle, title, end cascade)
public/activities/ghoul-ride-gfx.js The ride's drawing helpers: the bound 2D context and the short fill, stroke and shape calls the ride's art is written in
public/activities/ghoul-ride-draw-kinds.js The ride's drawn things: every figure, beast, lantern, blade, door, hand, head, mirror, web and boss, a port of the prototype's draw code (prototypes/ghoul-rush-ride/gallery.html)
public/activities/ghoul-ride-draw-sets.js The ride's rooms drawn: each room's far wall, set pieces front and back, aisle and the near pillars, a port of the prototype's world draw
public/activities/ghoul-ride-draw-hud.js The ride's car and the screen around it: Planny in his car, blood and sparks, the lens, the hearts, the progress bar, the room plaque, the aim, the title and the cleared card
public/activities/ghoul-ride-voices.js The ride's LOOKS, VOICES, EVENT_VOICE, LOSE_WORDS, LOSE_SOUNDS and react (every ride<Name> event plays tone ghoulRide<Name>)
public/activities/ghoul-sfx-ride.js The ride's synthesized sounds as tones (ghoulRide<Kind>) and its music ghoulRideDrone (RIDE_SFX, merged by ghoul-sfx.js)
public/activities/ghoul-frozen.js Ghoul Rush's Frozen Lake stage pack, its rules (imports only burrow from the Graveyard; draws no random number): uses tick (thin ice, the blizzard, the Widow's spikes, web and barrels), place, unseen, solid, kill, target, land, weak, cause, guard, swoops and slides. The generic slippery-ice rule (iceRun, room field ice) and thin-ice rule (stepThin, room field thin, round.thin), the under-ice hand, snow shade (unseen, footprints), Frozen Ghoul (slides, shatters into shards), Ice Wraith (its dive freezes), Hot Cocoa, the Frost Widow (veil, barrels, weak spot, blizzard, spikes, web, rage) and FROZEN_ROOMS. Every constant is exported and documented in its header
public/activities/ghoul-frozen-draw.js The Frozen Lake's art: LOOKS (custom: true), frozenArt(d) returning the world's hooks (from ghoul-frozen-world.js) plus monsters, the Frost Widow boss, hazards (shards, spikes, webs, barrels, the flare and its fire), powers (Hot Cocoa), front, lights and react, and VOICES (borrowed tones), EVENT_VOICE, LOSE_WORDS, LOSE_SOUNDS. Its header lists what the art reads off the rules
public/activities/ghoul-frozen-world.js The Frozen Lake's world (no imports; frozenWorld(d) takes ghoul-draw.js's helpers): the night sky with moon, aurora and far mountains (sky), the huts, the Lodge's fallen roof, the Black Ice and the Widow's web (backdrop, ground with the ice's gloss, shelf), and moving (open water in the holes, thin ice drawn from round.thin, never from spec.ground, the faces under the Black Ice, falling snow) and lights. Draws no random number
public/activities/ghoul-flare.js The Road Flare's rules (useFlare, stepFlareFly, stepRoadFire; no imports, handed the helpers by ghoul-arms.js): a lob that lands as a patch of fire, burns monsters on a tick, melts a Frozen Ghoul at once, shows a shade and melts the Widow's veil; never hurts Planny
public/activities/ghoul-sled.js The Coffin Sled (the Frozen Lake's bonus round) as a pack (SLED), modeled on the Runaway Cart (ghoul-cart.js): pack fields ride, place and target; the track of ice lines with cracks, headstones, drifts, low branches, hands, icicles and popping ghouls, checkpoints, hearts through the Cart's bonus machinery and the grade (3 to 9 dice). Adds no monster, boss or hazard kind and draws no random number; every number is an exported constant documented in its header
public/activities/ghoul-sled-draw.js The Coffin Sled's art: LOOKS, VOICES (borrowed tones), EVENT_VOICE, LOSE_WORDS, LOSE_SOUNDS and sledArt(d) (the sky, hills, ice and things by moving, the lid, the lows and foreground flakes by front); no random numbers. Its header lists what the art reads off the rules
public/activities/ghoul-sfx-frozen.js The Frozen Lake's own sounds as data (no imports): FROZEN_SFX with an empty tones and music until the user picks them; merged by ghoul-sfx.js via STAGE_SFX (its rooms play existing tracks, set in ROOM_MUSIC)
public/activities/ghoul-sfx-sled.js The Coffin Sled's own sounds as data (no imports): SLED_SFX with an empty tones and music until the user picks them; merged by ghoul-sfx.js (the room plays the Graveyard's ghoulGraves)
public/activities/ghoul-sfx-chapel.js The Chapel's own sounds as data (no imports): CHAPEL_SFX, its tones (the 35 picked ghoul<Kind><Act> sounds of the gargoyles, choir ghosts, monks, bell bats, the Choirmaster, the bell and Holy Water's splash) and music (ghoulNave, ghoulTower, ghoulLoft, ghoulChoir, named in ROOM_MUSIC), merged by ghoul-sfx.js via STAGE_SFX
public/activities/ghoul-sfx-sanatorium.js Blackmoor Sanatorium's own sounds as data (no imports): SANATORIUM_SFX, its tones (the 38 picked ghoul<Kind><Act> sounds of the orderlies, gurneys, flickers, specimen bloaters, the Night Matron, the lamps, Smelling Salts and the Bone Saw) and music (ghoulAdmissions, ghoulBaths, ghoulTheater, ghoulWard, named in ROOM_MUSIC), merged by ghoul-sfx.js via STAGE_SFX
public/activities/ghoul-sfx-village.js Hollow End Village's own sounds as data (no imports): VILLAGE_SFX, its tones (the 42 picked ghoul<Kind><Act> sounds of the torch mob, hanged men, shutter ghouls, moonhounds, the Beast, the full moon and Wolfsbane) and music (ghoulStreet, ghoulInn, ghoulSquare, ghoulGreen, named in ROOM_MUSIC), merged by ghoul-sfx.js via STAGE_SFX
scripts/test-web-console-activities-ghoul-chapel.mjs The Chapel's suite: each monster, the bell toll and its freeze, Holy Water's splash, the Choirmaster's pipes, notes and rage, a voice for every act, each event playing exactly one picked sound, and every picked tone present in the merged tones and in ghoul-sfx-chapel.js
scripts/test-web-console-activities-ghoul-sanatorium.mjs The Sanatorium's suite: the orderly's reach, hold and throw (and the Salts), the gurney's park, rattle, roll and rest and its floor, the flicker's unseen state, the lamps' timing, the specimen's jar and puddle, both power-ups (stage-only), the Matron's cone, heat, cabinets, syringes, arms and rage, endless lives for every new cause, and a voice for every act
scripts/test-web-console-activities-ghoul-village.mjs The Village's suite: the rooms, the moonrise timing, the turn and the grow at full moon (and the per-room reset), the villager's group, torch and fire, the hanged man's drop, the shutter ghoul hit only while out, the moonhound, Wolfsbane (stage-only, double damage, shying), the Beast's wall leap, cling weak spot, pounce shadow, swipe, howl and its cap, the rage, endless lives for every new cause, no random draws, and a voice for every act and event
scripts/test-web-console-activities-ghoul-mine.mjs The Mine's suite: the rooms and the cage rows, rockfall timing, aim and crush, the Hard Hat (stage-only, bounce), the imp's light steal (no life, ended by a shot or a stomp, blocked by the hat), the canary's scream and its three rocks, the miner's dig and swing, the blind crawler losing and hearing you (and the water's louder steps), water slowing you, the cage carrying Planny, Dynamite (a double tap, the bag, the blast), every Tommyknocker move including the dark, the decoy, the burst, the dazed double damage and the rage cap on imps, no random draws, endless lives for every new cause, and a voice for every act and event
scripts/test-web-console-activities-ghoul-carnival.mjs The Carnival's suite: the rooms and the belts, grinners and their balloon cap, balloons and their acid, the marionette's drop and its string, Mirror You (the delay, the mirrored moves, jumps, its bolts and their canceling, stunned by a pie), the strongman, the circus hound (a swoop, duckable), Cotton Candy, the Custard Pie, every Ringmaster move (stalk, leap, charge, stomp, whip, the strings following, open, rage, hounds, the script), no random draws, endless lives for every new cause, and a voice for every act
scripts/test-web-console-activities-ghoul-grounds.mjs The Grounds' suite: each monster's behavior, the shears, the Groundskeeper's moves and phases, a voice for every act, each event playing exactly one picked sound, and every picked tone present in the merged tones
public/activities/ghoul-picker-draw.js The choice of stage, its drawing: pickerArt(d), handed ghoul-draw.js's helpers (lookOf, label, roundRect, circle, BOSS_ART, drawGourdFire, GOLD), returning drawPicker (a card per stage offered: its picture of its rooms with its boss standing there, its name, line and boss, the pick raised and edged in gold, and how to choose), drawSelect (the stage select for testing: every stage in a list, two columns past 8, the one picked out with its picture and a chip per room) and stageColor (a stage's boss room's color, also the tally dots'). Split from ghoul-draw.js to keep it under the 3,000-line cap
public/activities/ghoul-powers.js Ghoul Rush's power-ups and pickups (no imports: ghoul.js hands its rules a kit, POWER_KIT, of landing, MAX_LIVES and the numbers they need): POWERS (each power-up's name, line, color, ms if timed, drop weight, and its rule, the Lantern's dark), TIMED, PILL_WORDS, FLAP_CLEAR, HOURGLASS_MS, CANDY_POINTS, POWER_POINTS, CRYSTAL_POINTS, powerHere(round, kind) (whether a power-up can turn up in the room as it is now; a new rule, such as a stage-only power-up, goes in POWERS and is checked here), pickPower, applyPower(round, kind, kit) (ghoul.js exports it bound to its kit as applyPower(round, kind)) and pickups (candy, placed and dropped power-ups, crystals up high and the key, taken by touch; drops fall and fade). Split from ghoul.js to keep it under the 3,000-line cap
public/activities/ghoul-arms.js Ghoul Rush's secondary weapons (imports only ghoul-powers.js; a pack in PACKS, ARMS): the double tap (pressFire, releaseFire, called from the game's key() and release(), never from round.input.fire, so bots never throw), the bag round.arms (useArm, armOnTop: a ride room skips what needs a floor), each weapon's rule (a shot with arm through moveShots, or a hazard), and armBossDamage (scaled to depth, capped at ARM_BOSS_SHARE of a boss's hp a fight). Weapons' names, bundles and caps are in POWERS (arm: true, weight 0), the stage's own in STAGE_ARMS, the kill drop band in armDrop, all in ghoul-powers.js.
public/activities/ghoul-arms-draw.js The weapons' art (armsArt(d)): their badges (powers), hazards, shot for one in flight, pill for the HUD's icon and count, front (stars over the dazed), lights and react. Dynamite's stick, blast and badge stay in ghoul-mine-draw.js.
public/activities/ghoul-rockets.js The Bottle Rocket's rules, the common weapon every stage sells: one use lights three rockets, one ahead, one up and one behind
public/activities/ghoul-rockets-draw.js The Bottle Rocket's drawing (rocketArt(d)): the muzzle's flash and smoke, the flared rocket on a stick with a glowing head, the fountain of sparks it sheds and the burst when it goes off
public/activities/ghoul-pans.js The Cast-Iron Skillet's rules, the East Wing's weapon: three pans that circle Planny, then spiral outward until they are off screen
public/activities/ghoul-sfx-arms.js The weapons' tones (ARMS_SFX), merged by ghoul-sfx.js like a stage's. A first pass, not yet picked by ear.
scripts/test-web-console-activities-ghoul-arms.mjs The weapons' suite: the double tap through the keys (repeats, feathering, hammering), the bag and its pill, each weapon, bosses (scale, cap, guards, the half-hp drop), placement in every room, the drop band's single draw, ride rooms, drawing and sounds.
public/activities/ghoul-run.js Ghoul Rush's run flow (no imports: ghoul.js hands its rules RUN_KIT, the room and stage tables, the timings and the helpers that set a room up, and binds them): newRound, setupRoom/resetRoom, the stage pick (stagesLeft, nextRoom, steerPick, pickStage), the stage select for testing (openSelect, steerSelect, takeSelect: a practice round, round.practice, that keeps no best score or record), camera, respawn, lockArena, clearRoom, and a room's monster supply (spawners, horde, hurry). ghoul.js re-exports newRound, stagesLeft, steerPick, pickStage, steerSelect and takeSelect, and its game answers stageSelect(). Split from ghoul.js to keep it under the 3,000-line cap, with the same random draws in the same order
public/activities/ghoul-dice.js Ghoul Rush's Lucky die rules (no imports: ghoul.js hands them DICE_KIT): MAX_DICE (9), ROLL_MS, TUMBLE_MS, SAVED_TIME_MS, markRest (the last solid ground Planny stood on), reviveSpot, beginRoll (called by lose when round.dice > 0 and not round.infinite: the round holds in the phase roll), rollDice (one die at a time from advance's random, events diceStart, diceRoll, diceFace, diceSaved, diceFail; a six revives with the Garlic shield and SAFE_MS, and blows apart every monster in view in a room without a boss (diceBlast, kills with how: "luck", points but no drops); no six hands the loss back to takeLife)
public/activities/ghoul-bonus.js Ghoul Rush's bonus rounds, the rules (imports only MAX_DICE; no random numbers): a room with bonus: true (the Runaway Cart; the Carnival's dark ride is meant to follow) gets round.bonusRound = { hearts, max, dice, over, won, perf } on entering it (null elsewhere; round.bonus is already the time bonus score). A life lost in it is a heart lost through the same lose/takeLife (so Garlic, the safe moment and round.infinite work as ever; no Lucky die is rolled for a heart); the last heart gone calls endBonus(round, false) from respawn (no dice, no game over, the run's lives untouched), and a finish alive calls endBonus(round, true) from clearRoom (diceFor: BONUS_FLOOR 3 plus up to 6 by hearts, clean obstacles, acts and a steady hand, added to round.dice up to MAX_DICE). A room's pack notes its performance in bonusRound.perf (total, hits, acts, goal, steady); both ends hold the phase "clear" for the card (CARD_MS, CARD_LOST_MS) and set bonusRound.result. Events bonusStart, bonusEnd; heartsText(b) is the HUD pill
public/activities/ghoul-bonus-draw.js The bonus rounds' art (bonusArt(d, die)): card ("BONUS CLEARED! +N LUCKY DICE" with the dice tumbling in, or the short "BONUS LOST"), react (the intro banner, the end, the hearts-left float) and tick (a click for each die landed)
public/activities/ghoul-dice-draw.js The Lucky die's art (diceArt(d): the small drop, the rolling die on a panel placed away from Planny, the sweeping "LUCKY-SAVE" word, and react for the dice events, which plays ghoulLuckySave once on the revive)
public/activities/ghoul-gameover-draw.js The lost end screen's "G A M E - O V E R" (gameOverBanner(d), dropAt): nine letters dropping in with a stagger and one bounce, then bobbing on a sine wave under a slow pulse, red and bone with a dark shadow, drawn above the score panel and never on a win. ghoul.js keeps ticking the clock on the lost end screen (view.overMs) and plays the mechanical laugh track there: ghoulLaughTrack, ghoulLaughTrack2 and ghoulLaughTrack3 in ghoul-sfx.js, one second apiece (a tone may not pass 1.2 s).
public/activities/ghoul-monsters-draw.js The generic monsters' art (monsterArt(d), no imports; ghoul-draw.js hands it its helpers ellipse, circle, line, rotate, turned, eye and the colors): drawZombie, drawZombieKin, drawHuntsman, drawCrawler, drawBat, drawGhost, drawSkeleton, drawGourdling, drawHound, drawSpider, drawWraith, drawSpitter and the missiles drawBoneShape and drawGlob. Split from ghoul-draw.js to keep it under the 3,000-line cap
public/activities/pills.js The pills every game but Mini golf draws along its top (no imports): drawPill(ctx, x, y, w, h, text, color, fill, textY) on one opaque dark backing, PILL, the same in light and dark and over any scene, a timer's share still left tinted at PILL_TINT, and the text in pillInk(color, tinted): the pill's own color when it reads at PILL_CONTRAST (4.5:1) on the backing (and on the tint while a timer runs), else the least step toward white that does, so warnings stay red; lives are the one solid pill: a pill in the LIVES color is drawn on LIVES_BACK in white (LIVES_INK), its text from livesText(n) (a heart per life up to five, ♥ xN past that, ♡ at none); pillTint and pillContrast for the unit suite
public/activities/golf.js Mini golf: six eighteen-hole courses, one round at a time; its rules and physics as plain exported functions (newRound(courseId), holesOf, coursePar, strike, advance on a fixed 4 ms sub-step, nextHole, total, toPar, predictPath for the spyglass, moverAt, gateShut, plus ice that barely slows the ball and wells that pull it in or push it away), the POWERUPS held for the next putt (round.held, then round.active for that putt), the arcade swing (startSwing, setPower, meterAt, meterZone, swingShot: a ping-pong power meter, slow at the bottom and fast at the top, with a MAX band that boosts and an overswing band that shanks; a shot clock in advance() that starts the meter after SHOT_CLOCK_MS and dribbles the ball after METER_TRIPS trips; all on the round's own clock), the pop-up gags, and the game contract with pointer() (the aim follows the pointer, a press swings, a press held on a roll fast-forwards), release() (held arrows turn the aim, held space fast-forwards) and lowerIsBetter, courses (the dashboard's cards), preview(canvas, id, w, h) (a course's card art) and setCourse(id); deterministic (no Math.random()), a read-only round getter for the unit suite only
public/activities/golf-draw.js Mini golf's drawing: drawCourse(ctx, view) from a plain view golf.js builds, each hole in its theme's fixed palette (pirate, cave with its darkness and glows, or a newer course's look from golf-looks.js, asked first for its grounds, water, tunnels, gates and wells), ice, the scorecard and banners in the course's voice, a bare view for the dashboard's card art, knownGround/knownLiquid for the unit suite, and readColors(canvas), which reads the --golf-* properties styles/activities.css mixes from the tokens for the ball, pills and scorecard; decides nothing
public/activities/golf-decor.js Mini golf's scenery and props for Pirate Cove and the Caves of Doom: each decor kind (sharks, ships, parrots, bats, torches, eyes, a dragon) on its layer, the looks of bumpers, movers and spinners, and the power-up icons, each asking the hole's course look first (decorKinds(theme) lists a theme's scenery); drawing only, moving with the round's clock
public/activities/golf-holes.js Mini golf's courses: COURSES, the six eighteen-hole courses in dashboard order (Pirate Cove, Caves of Doom, Dino Valley, Candy Carnival, Cosmic Glow, Frosty Peaks), courseById, HOLE_COUNT, FRONT_NINE, COURSE_W, COURSE_H
public/activities/golf-kit.js Mini golf's course kit, data only: COURSE_W, COURSE_H, the helpers course files build holes with (pt, rect, wall, bump, pad, deco), hole(def, defaults) (what a hole holds: theme, quip, ground, liquid, tee, cup, outline, walls, bumpers, sand, ice, water, slopes, wells, bridges, spinners, tunnels, movers, gates, powerups, decor) and course(), which freezes a course with its name, card line, cover hole and voice
public/activities/golf-course-pirate.js Mini golf's Pirate Cove course: its eighteen holes and its voice (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only
public/activities/golf-course-cave.js Mini golf's the Caves of Doom course: its eighteen holes and its voice (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only
public/activities/golf-course-dino.js Mini golf's Dino Valley course: its eighteen holes and its voice (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only
public/activities/golf-course-candy.js Mini golf's Candy Carnival course: its eighteen holes and its voice (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only
public/activities/golf-course-space.js Mini golf's Cosmic Glow course: its eighteen holes and its voice (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only
public/activities/golf-course-frost.js Mini golf's Frosty Peaks course: its eighteen holes and its voice (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only
public/activities/golf-looks.js Mini golf's course looks by theme id, and the look contract (palette, liquids, grounds, rough, tunnel, lights, and the looks of bumpers, movers, spinners, gates, wells and scenery)
public/activities/golf-look-dino.js How Dino Valley is drawn: its palette, ground, water, props and scenery; drawing only, moving with the round's clock
public/activities/golf-look-candy.js How Candy Carnival is drawn: its palette, ground, water, props and scenery; drawing only, moving with the round's clock
public/activities/golf-look-space.js How Cosmic Glow is drawn: its palette, ground, water, props and scenery; drawing only, moving with the round's clock
public/activities/golf-look-frost.js How Frosty Peaks is drawn: its palette, ground, water, props and scenery; drawing only, moving with the round's clock
public/activities/golf-paint.js Mini golf's shared canvas helpers (polygon, circle, ellipse, radial, fill, stroke, line, label, turned, t, scatter, bounds), no imports, so the drawing files and the looks share them without import loops
public/app.js the page's entry and the only page file that starts anything: the start-up block. index.html loads it; it imports screens/core.js and the screens beside it
public/doc-files.js a document as the page shows it, and as a file: blocks, Markdown and HTML download
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/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
public/palette.js the highlight colors, the sound events and the card widths, as data (importable by Node so a test can check every shade in both themes)
public/render.js Markdown to DOM, safely: no HTML string is ever produced, only nodes built with createElement and textContent; also the shared page helpers (el, md, copyButton, lightDismiss)
public/selectors.js what the page reads off its state: the questions, the finish, the scan, who has the ball
public/send-state.js whether Send is available, and what its button says
public/skills.js the skill list: every per-skill fact the console uses (card, order, start pose, launch scoring, subagent opt-in, which spec states light its card), data only, imported by the page and by Node; the older tables (SKILL_CATALOG, START_POSES, CONSOLE_WORKFLOWS and the rest, in answers.js) are lookups on it. Each entry also carries weight (what its launch and run score on the meter, or null), started and ran (the meter's labels for them, or null), resume ("overview", "folder" or null: what the resume command takes after the skill's command) and an optional card.help (Help's line for the card when it differs from blurb). WORKFLOWS (every entry's workflow, in order) and isWorkflow() are what the CLI checks a --workflow against. The meter's WEIGHTS, LAUNCH_LABELS and RUN_LABELS, resumeCommand(), Help's card list and cmd-help's workflow list are all derived from it, so a new skill is one entry here, not an edit to each of those
public/sound.js the sound cues: which plays, one at a time, held until the first click
public/spec-states.js the spec states (diagnosed, fixed, exploring, mapped, planned, documented, building, built, unrecognized): each one's picker label, the card it is the natural next step for and its recommendation, data only; which cards a state lights lives in skills.js, how a folder maps to a state in classifySpec() in scan.mjs
public/state.js the page's shared state (page.S the server's truth, page.local what is staged) and the redraw() / save hooks every screen calls; defines only
public/tones.js the activities' sound engine, all synthesized in the browser. Three parts: a shared kit of rich one-shot sounds (RICH: layers of parts played together, each a wave or a noise (noise, pink, brown) with its own delay, gain, attack, a sweeping filter and vibrato: explode, smash, skid, whoosh, splashBig, fanfare, gameOver and some fifty more, up to 1.2 s, at most MAX_VOICES parts sounding at once), held hums (hum(id, name, level, pitch), called every frame a game wants it: oscillators and noise through one filter that follows the pitch, pulsed for an engine's strokes; a hum not asked for within HUM_HOLD_MS fades by itself, so a paused or closed game goes quiet without saying so, hushTones() quiets every one and the Activities window calls it whenever it stops ticking; at most MAX_HUMS; shared ones car, toycar, electric, outboard, river, wind, cycle, fuse, haunt, squeal, meter, swarm, train, crowd), and each game's own extras in public/activities/<id>-sfx.js ({ tones, hums }, plain objects, names prefixed with the game id, merged and frozen here; a name may be defined once across all of them, which scripts/test-web-console-tones.mjs checks along with every spec's shape and every name a game's source asks for). Everything plays through one compressor. The older single blips (BLIPS): tone(name, level, pitch) with an optional loudness from 0 to 1 and an optional pitch that scales every frequency, kept between 0.25 and 4, unlockTones(); Snake's blips plus golf's putt, wall, bump, cup, ace (a three-note rise), splash, power (a power-up, three notes), tunnel, boom (a cannon putt), sizzle (lava) and fall (the pit), the countdown's count and go, Stack Deploy's thunk, slice and perfect, which it pitches up a scale step for each perfect in a row, and Bumper Ring's ram, pitched and leveled by how hard the hit, and rev, a rival winding up a dash, and Hot Potato's tick, the fuse, which it ticks quicker and pitches higher as the fuse burns down, and pop, a pass, and Crossing Rush's hop, which it pitches up a step for each quick hop forward in a row, boing, a send-back, bell, a train coming, and horn, and Bounce Road's engine, a soft low triangle hum it plays every few frames while you pick up speed (quiet once you cruise or coast), pitched up with your speed, spring, a jump, pitched with your speed, and squash, a rival flattened, pitched up a step for each in a chain, and beat, a low thump while your wheels run on the verge (it borrows the other games' blips for its hazards and rivals), and Rapids Run's pew (a shot, a short soft triangle played quietly about seven times a second while fire is held), charge (a buoy taken), lowcell (the low battery's two-note beep, quicker the lower it runs), dambreak (a dam bursting) and skim (a bank skimmed at speed, pitched up the more you have skimmed), and Ghoul Rush's ghoulBlast (the blaster's bolt, a short soft triangle repeated while fire is held), zombiePop (a kill, pitched up a step for each in the chain), ghoulStomp, ghoulBoo, ghoulRoar and zombieGroan (now kept for the other games and the tests: Ghoul Rush's monsters speak with their own voices from ghoul-sfx.js), ghoulCandy (pitched up for candy in quick succession), batSwoop (a bat's kill), doorUnlock (the key), doorThrough (the door to the next room) and creakBoard (a crawler coming up, a chandelier or a crumbling board about to go), all soft triangles and sines), silent while Play sounds is off; separate from sound.js's cue queue
public/music.js the games' chiptune music: a small sequencer over tones.js's context and compressor (audioOut()). A game calls music(name, intensity) from its tick; the track fades out within MUSIC_HOLD_MS once it stops being asked for, picks up again on the bar it left, asking for a different track crossfades the two over CROSSFADE_S (the old one keeps playing as it fades, so a new level is not a cut), and hushMusic() stops it at once. Tracks are note data under music in each game's activities/<id>-sfx.js ({ bpm, rush, voices, patterns, order }: pulse, triangle and noise-drum voices, each joining once the intensity reaches its from; a step a token, A4, - to hold, . a rest, A3^037 an arpeggio, drums k s h o), read by compileTrack() and booked LOOKAHEAD_S ahead on the audio clock. The window plays it only while Play sounds, Play game sounds and Play game music (looks.gameMusic, off by default) are all on
public/activities/snake-sfx.js · public/activities/golf-sfx.js · public/activities/trails-sfx.js · public/activities/bugs-sfx.js · public/activities/drive-sfx.js · public/activities/stack-sfx.js · public/activities/bumper-sfx.js · public/activities/rapids-sfx.js · public/activities/fuse-sfx.js · public/activities/hop-sfx.js · public/activities/bounce-sfx.js · public/activities/ghoul-sfx.js each game's own sound effects as data, { tones, hums } in the shapes tones.js documents, every name prefixed with the game id (driveEngine, ghoulMoan), merged and frozen by tones.js; no imports, but for ghoul-sfx.js, which merges each Ghoul Rush stage's own ghoul-sfx-<stage>.js into its tones, hums and music
public/activities/ghoul-sfx-graveyard.js The Graveyard's own sounds as data (no imports): GRAVEYARD_SFX, its tones (the picked ghoul<Kind><Act> sounds of the grasping hands, mourners, grave robbers, rotters and their legs, carrion crows and Mother Mourning) and music (ghoulLychgate, ghoulGraves, ghoulMausoleums, ghoulAngel, named in ROOM_MUSIC), merged by ghoul-sfx.js after the house's own. Every new stage gets its own ghoul-sfx-<stage>.js, listed in STAGE_SFX there
public/activities/ghoul-sfx-grounds.js The Grounds' own sounds as data (no imports): GROUNDS_SFX, its tones (the 32 picked ghoul<Kind><Act> sounds of the topiary beasts, rootlings, lantern moths, mulch crawlers, the Groundskeeper and the Hedge shears' snip) and music (ghoulMaze, ghoulTopiary, ghoulGazebo, ghoulYard, named in ROOM_MUSIC), merged by ghoul-sfx.js after the house's own via STAGE_SFX
public/uploads.js pictures and documents attached to a note: chips, trays, re-encoding, upload, retry
public/screens/ask.js the Ask chat, the Subagents tab, and attaching files to notes
public/screens/cards.js question cards: every kind, the pager, settled and in-flight records
public/screens/cleanup.js User Preferences' Cleanup section, on the System tab
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, and the first-open wake-up
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 page locks while state.loop.driving is set (loopDriving() in selectors.js) until the app posts loopEnd; Activities, Notebook, Help and Preferences stay usable
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
public/screens/git-host.js hosts the git board: tabs, panels and what each click sends
public/screens/help-dialog.js the Help dialog and the first-run Welcome (named so it is never confused with the pure help.js). Help reads right in both modes: a phrase that differs under the desktop app carries its app wording in data-app (swapped in by renderAppWording()), and a paragraph that differs is a .for-browser / .for-app sibling pair, switched by :root.in-app (set in core.js from page.inApp, rule in help.css). The older render*Help() functions patch a few ids the same way. scripts/test-web-console-page-help.mjs sweeps every topic's visible text in each mode for the other mode's wording
public/screens/looks.js User Preferences: the look and sound controls, which save as they change
public/screens/agents-view.js User Preferences' Agents & models tab: a summary table (Claude, Devin, Codex, added agents, a v3 orchestrator row) with Found / Not found on PATH badges, and Edit opening one agent's form. Each form edits a draft; Save sends the saved list with only that draft swapped in (POST /models or POST /agents), Discard drops it. hasUnsaved, saveOpen and discardOpen feed the dialog's unsaved prompt
public/screens/prefs-dialog.js User Preferences as a dialog: its four tabs (wired by tabs.js from PREFS_TABS), openPrefs(tab) (the one way in, loading Agents & models each time), the fading Saved mark beside a fieldset (markSaved), Back to default for the tab on screen, and confirmUnsaved(), the in-dialog Save / Discard / Keep editing prompt before Close, Esc, a backdrop click, a tab switch or Back to summary leaves an unsaved agent edit. Other screens reach it through hooks
public/screens/starting.js the launching, starting and waiting screens, with Planny's poses
public/screens/workspace.js the read-only Workspace of extra folders, and @mentions
public/styles/ask.css The Ask pane and its Quick question chat
public/styles/dashboard.css The dashboard: the menu, the spec picker, its confirm and the launching pane
public/styles/docs.css Documents and the doc tools
public/styles/ending.css The end of a session: the hand-off and the stopping screen
public/styles/git.css The git board
public/styles/help.css The help dialog, its diagrams and its tabs
public/styles/looks.css The looks button and the highlight swatches
public/styles/prefs.css User Preferences' side list of tabs, the strip below 720 px, the Saved mark, the Agents & models table (its Models column hidden below 720 px), badges and one-agent form (one column below 720 px), and the in-dialog unsaved prompt (new classes only: the Subagents dialog shares .looks)
public/styles/pieces.css Shared pieces: cards, options, settled answers, pager, forms, checklist, markdown and the modal
public/styles/planny.css Planny the mascot: the flight, his moods and variants, and the wake-up
public/styles/poses.css The start-screen poses, one per skill. After the dashboard on purpose: its narrow-window rules override the dashboard's
public/styles/responsive.css Print, then the narrow-window rules: last, so its overrides come after everything they override
public/styles/shell.css The page shell: banner, top bar and meter, layout, sidebar, aside, footer, waiting and arrival
public/styles/tokens.css Colors, type, sizes and the light and dark themes: the variables every other file reads
public/help.js the Help dialog's PURE rules: HELP_TABS (20 tabs: ids, order, labels, diagram flags; every tab uses the chosen highlight color; Implementation Loop sits right after Watching a build, The git board right after it, and Activities right after Ask a quick question), helpTabFor() (which tab opens, FR-8 order, first match wins: finished → Stopping and finishing, server gone or agent adrift → When something looks stuck, opened from the Workspace dialog → Your workspace, then Ask, the Subagents tab → Helpers (subagents), a red-meter dashboard → Session meter, dashboard, a doc or the Overview, a git session → The git board, a build, else What this page is) and helpKeyTarget() (roving arrow keys, Home, End, wrapping; a re-export of tabs.js's tabKeyTarget). No module-scope DOM, so node --test covers it
public/tabs.js the WAI-ARIA tabs shared by Help and User Preferences: wireTabs() (buttons and panel links, roving tabindex, automatic activation, aria-orientation switching at 720 px, an optional beforeSelect guard) and the pure tabKeyTarget()
public/prefs.js User Preferences' PURE rules: PREFS_TABS (Appearance, Agents & models, System, Sounds & activities, with hints and the sections each holds), prefsOpenTab() and prefsResetScope() (the looks keys Back to default resets per tab, or null)
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
public/git-board.js PURE, one import (pr-url.js): the git board's rules from a state.git snapshot: branch order and the Remote only fold at REMOTE_FOLD 50, whether a new branch name is free, which buttons show and are enabled, whether the board still waits on the agent (boardAwaiting(): from a click until the agent's next post, not just until wait collects it), the plain sentence each click sends as reply, the "Last refreshed" line, which files start ticked in the commit dialog, and the pull-request link; the next step (ten rules, nextStep()), the tab that owns it, per-tab badges (tabBadges()), the busy mode and per-control gate (busyMode(), controlAllowed()), the tab to show (pickTab()), and the create-panel sources and clean-up groups. app.js only renders what it says
public/git-board-view.js No DOM access of its own: drawGitBoard(ctx) draws the tabbed board (header, tab strip with Done with git, the card slot, step strip, Changes / Branches / Sync) from the helpers it is handed (el, md, copyButton), every control through one gate; screens/git-host.js hosts it, and scripts/test-web-console-git-board.mjs drives it with a recording fake el
public/pr-url.js PURE, no imports: prUrl(), the "open a pull request" link for the GitHub, GitLab, Azure DevOps and Bitbucket shapes (null for an unknown kind, no web address, or a non-https result). git-repo.mjs re-exports it, and the board's base picker rebuilds the link in the browser with the same code
public/workspace.js PURE, no imports: the Workspace's name rules (nameProblem(), NAME_MAX, defaultName(), freeName() for the -2 suggestion), the footer label and its width tiers (footerLabel(), FOOTER_TIERS) and changeLine(), the Workspace: … reply line an agent is handed per change. Imported by the server, cmd-chat.mjs, cmd-post-wait.mjs, workspace.mjs and the page
public/meter.js PURE, imports only skills.js: the session meter. WEIGHTS (the events that are not a skill's own launch, merged with each skill's weight from skills.js; its keys are also RUN_EVENTS, the run events post accepts), LAUNCH_COUNTED (workflows whose launch itself scores), the built-phase sizing (TASK_EVENTS, the keys of TASK_BONUS: implement-phase +0 and implement-review-phase +1; isTaskCount() accepts a whole tasks from 1 to MAX_TASKS 999; runPoints() scores such a run ceil(tasks / TASKS_PER_POINT) (3) plus its bonus, and any other run its WEIGHTS value), ANSWERS_PER_POINT 2 (answer entries score per skill run, floor(count / 2)), breakdownFrom() (the click-the-ring list: one row per scoring entry plus one answers row per skill run), pointsFrom() (the count, its sum, folded from ledger.ndjson and deduplicated by id, never stored), levelFor() with YELLOW_AT 5 / RED_AT 10, ringFraction() (full at RING_FULL 15), WORDS, tooltipFor(), RED_BANNER and meterView()
public/mentions.js PURE, no imports: the @name popover's logic — mentionAt() finds an @partial at the caret, matchNames() filters the workspace names, applyMention() splices a pick in and returns the new caret. Used by the Ask box, notes and text answers
public/favicon.js The tab icon's status bar. faviconState({ mood, spin }) (PURE) maps the call renderStatus() makes for Planny's line to busy (the spinning ring), ready (point), attention (adrift, gone, or work without the ring — the stale line) or plain (done, happy); a finished screen gets no special case, so one still offering a press points and lights ready (the desktop app's taskbar dot follows), a stranded press is attention, and only all done or paused is plain; faviconSvg() is FAVICON_BODY (kept equal to favicon.svg by a test) plus a bar along the bottom edge in the FAVICON_COLORS color (busy dashed on a white strip, so the states differ by pattern; the rest solid); setFavicon() swaps both <link rel=icon> hrefs only on a change — the SVG as a data URL, the PNG link drawn through a canvas. Called from say() in renderStatus(), which runs every second
public/app-bridge.js The messages the page posts to the desktop app that frames it. framed() is true inside a frame; tellApp(kind, extra) posts { plan2code: kind }, a named request with no free text: looks (the highlight's dark shades, from applyLooks(), for the app bar's buttons), agent-continue (the in-app continue button on the Not running line: the app types the keystrokes continueKeys() in plan2code-app/ui/meter.js names into the agent's terminal, continue and Enter, then under Claude Code its send-now chord ctrl+x ctrl+s, so a word queued behind a stuck turn is delivered) new-session (the meter popover's New Session: the app presses its own bar button, confirm and all) and activities-full ({ on }, an Activities game going in or out of full screen: the app lays the console's frame over its bar and terminal and puts the window in full screen, and out of it only if it put it there; taskbarSwitch() checks the boolean, and the window permissions are in capabilities/default.json). Nothing outside a frame
public/subagents.js PURE, no imports: the Subagents switch. SUBAGENT_WORKFLOWS / offered() (the opt-in table, one entry per non-null subagents field in skills.js, each with its default instruction), cleanSetting() ({ on, instruction, max, strength } or { error }: bad, too-long past 2,000 characters, max outside 1-20, strength not one of STRENGTHS; strength is balanced, thrifty, best or session, missing reads as balanced, saved per project and skill in each subagents.json entry and sent as a Helper strength: line in the "on" block), FRAME_LINES, blockFor(setting, told) (the Subagents: lines and subagents field an agent is owed, given the session setting and its cursor; never says "off" to an agent not told "on"), checkHelper() / checkHelpers() (the helpers house rule) and the page's view rules showSwitch(), switchLabel(), helperRows(), showTab(), CHECKIN_LINE. Imported by the server, the cmd-*.mjs files, patches.mjs, settings.mjs, the page and the tests; in SERVABLE and preloaded
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
public/notepad.js PURE, no imports: the Notebook's rules. SAVE_DEBOUNCE_MS 800, RETRY_STEPS_MS (1 s up to 30 s), NOTE_MAX_BYTES / NOTEPAD_MAX_IMAGES / TAB_NAME_MAX / NOTEPAD_MAX_TABS / IMAGE_ID_RE / TAB_ID_RE (kept equal to notepads.mjs by a test), noteBytes(), the save-state reducer nextSave(state, event) from SAVE_START (states idle, pending, saving, saved, failed, too-long; it returns the timer to arm), saveStatus() (the status line's words), unsaved() (what beforeunload asks on), keepsText() (unsaved or too long: a reopen never replaces the editor's text then), tabSwitch() (whether leaving a tab must save it first), NOT_LOADED, EDITOR_NOT_LOADED, errorSentence() (one sentence per /notepad refusal, else a lost connection), the tab rules cleanTabName(), nameTaken(), tabNameProblem(), moveTab(), dropTab() and the two-confirm delete nextDelete() / DELETE_STAGES, and step() (wrapping through the pictures)
public/screens/notepad.js the Notebook: #btn-notepad in the top bar on every screen (disabled while the server is gone, renderNotepadButton() in the render pass), #notepad-modal, the one CodeMirror editor (made on first open by a dynamic import of notepad-editor.js), the page's view of the notepad as { tabs, activeId }, the name form (New tab and Rename, never window.prompt), the in-modal two-step delete, and autosave through nextSave() to POST /notepad/text?tab=<id>, flushed on close, when the page is hidden and before a switch. The editor stays read-only until the first read lands, so nothing typed into an empty editor is saved over a note. Every save and every picture is bound to the tab it was made in: saveTab is fixed when the change is made, a picture entry carries its tab, and a switch waits for the save (settled()), stays put with "Not saved yet, so staying on this tab." when it cannot, and drops a deleted tab's unsaved text without sending it
public/screens/activities.js Activities: #btn-activities (the die right of the megaphone), #activities-modal, the one frame timer (requestAnimationFrame, swappable with setTickSource() for the page tests), the keys (arrows, W/A/S/D, space, P, Esc; stopped at the dialog so none reach the page behind; CHEAT_CODE, typed on a game's board, turns on endless lives through the game's cheat(on) until the round starts over, and dropCheats() turns it off on leaving for the picker or closing; STAGE_CODE, the same arrows then S, calls the game's stageSelect() where it has one, Ghoul Rush's practice stage select) and pauseAll(), which a new question, a finish, a hidden page, a window blur and a close all go through and which never resumes a game (it also sends a pointer game a cancel, dropping a drag). Canvas pointer events (down, move, up, cancel, with pointer capture) go to a game with pointer(), and key releases to a game with release(); a press on a paused board resumes without starting a drag. While paused, any game key or a board click resumes, except while a round is held: a question or finish that pauses a round on an open window holds it, the banner adds #activities-unpause (Unpause game) beside Go to it, and only that button plays on (play() refuses a held round), since a key or click already on its way used to dismiss the banner unread. Go to it, or closing the window any other way, lets the hold go, and a banner with nothing left to say drops it. Every start and play-on first counts down 3, 2, 1 (COUNT_FROM, 700 ms a number, setCountdownMs() for the page tests, which set 0 unless they test it): the game is already running, the frame timer just does not tick it, and game keys, overlay clicks and board presses wait, while P and Esc still pause. With two or more games listed the window opens on the picker (view: "picker" or "game", applyView()): a card button per game (drawPicker(), covers in COVERS drawn as SVG with cv-* token classes, since the page's policy refuses a style attribute) with its blurb, best and a Last played or Round paused tag, arrows walking the cards (moveFocus()), and #activities-back (All games) back to it. One game at a time: pick() drops the last game from games when another is picked, and openActivities() goes straight back into a paused round. The last pick is kept as lastActivity and gets the focus; lowerIsBetter games keep the lowest round as the best; the header shows the current game's best (paintTitle()). renderActivities() in the render pass compares myTurn() and finish() with the last render and shows the banner with Go to it. Loads a game with import() when it is picked and keeps it until another is picked; setActivityList() lets a test list a stub second game, which brings up the picker
public/notepad-tabs.js the tab bar: createTabs({ onSwitch, onChange }) with draw(tabs, activeId) (role="tab" buttons, roving tabindex, arrow keys, Alt+arrows to reorder, F2 and double-click to rename, native drag and drop with an .is-drop-before mark that only a tab drag lights, focus kept across redraws, #notepad-empty and #notepad-body toggled) and focusTab(). No fetches: it calls back, and screens/notepad.js owns every request
public/notepad-editor.js the Notebook's live-preview editor on CodeMirror 6 (makeCodeMirrorEditor(parent, { onChange, label }) returning { getValue, setValue, setReadOnly, focus, destroy }). A ViewPlugin decorates only the lines in view from the Markdown syntax tree: heading line classes cm-h1 to cm-h6, bullets drawn as a widget, the marks around bold, links, quotes and a heading hidden on every line the selection is not on. The editor sits in a shadow root (.notepad-cm-host), because CodeMirror writes its rules as a <style> element, which style-src 'self' refuses, and adopts them as a constructed stylesheet inside a shadow root. setValue() is setState(): not reported through onChange, and the undo history is cleared (so each tab starts with a clean one)
public/notepad-editor.css the one stylesheet of that shadow root, linked from notepad-editor.js (a <link> inside the root, in SERVABLE, not in CSS_ORDER): heading sizes, bullets, quote, code and link looks on the console's tokens (custom properties inherit across the boundary, so both themes work). Rules that meet CodeMirror's own base theme use div.cm-editor for the specificity
public/vendor/codemirror.esm.js CodeMirror 6 (state, view, language, commands, lang-markdown, MIT), bundled into one minified ES module by scripts/vendor-codemirror.mjs (sha256 4ff96d58fc1a5497eb933426bd2d160d2fb0cf490de8bb9302c304096c71c1d4, the six top-level versions in the script and the file's header comment, everything they pull in pinned by scripts/vendor-codemirror-lock.json and installed with npm ci, so the same lock gives the same bytes). Never edited by hand: change a version in the script and run node scripts/vendor-codemirror.mjs --update-lock (needs npm and network; the packages install in a temp folder, never in the repo), or without the flag to rebuild from the lock
public/styles/notepad.css the notebook's own rules: the top bar button, the dialog, the tab bar and its tools, the name form, the delete question, the empty state and the pictures. The editor's look is notepad-editor.css, inside its shadow root
public/styles/activities.css the Activities rules: the die in the top bar, the Notebook-sized dialog, the board and its state overlay, the your-turn banner in the highlight color, the picker and the notes
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/)
public/chat.js the Quick question chat's PURE rules, shared by the server and the page: CHAT_LIMIT / CHAT_MAX_CHARS / CHAT_MAX_ATTACHMENTS (the combined image + document cap; CHAT_MAX_IMAGES is kept as an alias of it), chatOffline() (the server's 409 offline guard), and the page's view model (chatView, sendState, nextAbout, contextOptions, unreadDot / shouldChime). Ask context is the { history, about } model: nextAbout() records the last 3 places visited in history and sets about only when the person picks one from + Add context (contextOptions() lists that history plus This spec); dropping it or a successful send clears it, so the page never attaches context on its own. Imports only answers.js, no module-scope DOM, so node --test covers it
public/starters.js PURE, no imports: the Role list (ROLES, ROLE_NOT_SET, normalizeRole(), needsRoleNudge(): the dashboard banner shows until looks.json carries any role), the 19 starter templates (Markdown ## heading sections, shape pinned by a test) and their per-role orders (TEMPLATES, TEMPLATE_ORDERS, templatesFor(), templateSwap() for the replace prompt), and the Ask starter sets (STARTER_SETS, STARTER_SET_FOR, startersFor()). Imported by the page's looks and screens and by the tests; in SERVABLE, preloaded by index.html and parse-checked. The page owns the wording; a skill only flags its fresh-idea text card with "templates": "idea"
public/answers.js the page's PURE answer-shaping logic (what an answer reads as, what a placeholder offers, whether a send carries an answer at all). Kept out of the page's entry because app.js cannot be imported outside a browser, so anything left in it is untestable. The scripts/test-web-console-*.mjs tests import it directly.
public/labels.js taskLabel() / activityLabel(): rewrites a build's Task 4.2 of 6 activity line to Task 2 of 6 (only for implement / implement-review; a plan's Task 2.1 is a real section number). A separate module for the same reason as answers.js: pure, so node --test can import it
public/boot.js playWake(): the dashboard's first-open wake-up. Self-contained (it owns its timers, the listeners that swallow input mid-run and the one measured glide transform; the page's stir() callback times the nudge between the click and the boot, which screens/dashboard.js fills with one snore; skipEl — the muted Skip button, and Escape — ends the run early with onSkip as the cue to silence queued sounds) and free of module-scope DOM access, so it can be imported by the tests and kept out of the screens' render paths; GLIDE_AT_MS / DONE_AT_MS are its timings
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). 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), read only when asked for

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 is the Agents & models tab, a summary table 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.

  • 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) 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 /overview is the one route that reads a project file. 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=.

  • 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), 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 }. 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 twelve 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 (pendingWorkspace 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 } (paths and names only), 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 eleven 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.

  • 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 20 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, -git, -qa, -speed, -hardening). 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 table above, which the docs-table test (same file) checks.

Building an Activities game: the rules every game follows, so a new one plays like the rest.

  • Lives are prominent. A game with lives draws them as the lives pill: livesText(round.lives) in the LIVES color from pills.js, placed right after the level/stage pill, which drawPill() draws solid pink with a heart per life. Never a plain ♥ N on the dark backing: that was hard to read at a glance. The unit suite checks every game with lives for it.
  • Every game with lives takes the endless-lives code. Typing up, down, up, down, left, right, left, right, B, A, space on the board gives endless lives until the round starts over or the person leaves the game (CHEAT_CODE in screens/activities.js, which calls the game's cheat(true) and cheat(false) on leaving for the picker or closing). A game with lives answers cheat(on) by setting round.infinite, never takes a life while it is set (if (!round.infinite) round.lives -= 1), lets start() make a new round without it, and shows livesText(Infinity) ("♥ x∞") in its lives pill. scripts/test-web-console-activities.mjs checks every listed game whose round has lives.
  • Banners never get in the way. A banner over the board ("Hit!", a new level, a power-up) is placed on the frame it first shows, on the part of the board away from the player, and fades to BANNER_SEE_THROUGH (0.12) over BANNER_FADE_MS while the player, or anything the player must react to (a diving bug, a bomb, a rival, a hazard, the road over a hill), is in its strip; Snake's bannerRow() and underBanner() are the model. Give the banner object a see field, multiply the draw's alpha by it, and export the strip check (underBanner) for the unit suite.
  • The window owns pausing. A game never resumes itself; screens/activities.js decides when a key or click plays on, including the hold on a question or finish (see the row above), so a game needs nothing of its own for it. Full screen is the window's too (setFull(): the button, F, and a turn or finish putting it back; fitFull() sizes the game to the whole screen (black bars where its shape leaves room) and docks the overlaid panel in a bar that holds it, data-dock="side" or "below", or floats it, "float", shrunk to the score while a round plays and the pointer is still; and tells the desktop app activities-full); a game only sees a bigger resize(), so a new game needs nothing for it, as long as its resize() sets the canvas's CSS size.
  • Every moment has a sound, and moving things hum. A game plays a one-shot through the tone it is handed for each event worth hearing (a hit, a pickup, a level, a new best, game over) and keeps continuous things (an engine, a motor, wind, water, a fuse, a monster close by) going with hum(id, name, level, pitch) from its tick, pitch following speed. Never a one-shot every frame: a repeating cue is throttled by a timer in the round. Its own sounds live in activities/<id>-sfx.js, named with the game id; the shared kit is in tones.js. create() defaults tone and hum to no-ops, since the suites make games with neither, and a sound never changes the game's state.

Status Line

Optional Claude Code status bar living in src/statusline-claude/. Three-line bar beside a Planny icon: two content lines with a dashed rule between, showing model (+ effort), project/worktree, branch, uncommitted diff stats, session duration + cost, context window usage, and plan/quota usage.

Design constraints:

  • Zero runtime dependencies — statusline.js is self-contained (config loader, git helpers, formatters, render). Copied verbatim to ~/.claude/plan2code-statusline.js on install; no bundler step.
  • Stdin-driven — all data comes from Claude Code's stdin JSON (model, workspace, context_window, rate_limits, cost). No API calls, no auth, no background processes.
  • Silent failure — outer try/catch around main() plus process.exit(0) on missing stdin guarantees the script never crashes the CLI. All git ops are timeout-bounded (1.5s) and non-git workspaces short-circuit via isGitRepo() (walks up to 10 parent dirs looking for .git).
  • Atomic settings writes — installer writes ~/.claude/settings.json via temp file + rename so a crash never leaves the file truncated.
  • Custom-config respect — installer detects non-plan2code statusLine entries, prompts before replacing, and backs up to statusline-previous.json. Uninstall only removes settings.statusLine if it points to the plan2code bundle.

Layout:

src/statusline-claude/
├── statusline.js           # Self-contained: config, git, formatters, render
├── statusline-config.json  # Default config template
└── README.md               # User docs: install, config, debugging

Adaptive plan-usage display: the formatter auto-selects between 5h/7d rate-limit percentages (Pro/Max/Teams — when rate_limits present in stdin) and Nk in · Nk out session-token counts (Bedrock/Vertex/PAYG — when rate_limits absent). Segment is hidden when neither shape is available.

Installer integration lives in install.js under the STATUS LINE INSTALLATION section (installStatusLine, uninstallStatusLine). Included in Advanced → E (Everything); also available individually via Advanced → S.

Global plan2code Command

Typing plan2code in any directory opens the dashboard skill against the current project, in that directory, in one of three CLIs (the CLIS table in the launcher):

CLI Runs
Claude Code claude /plan2code [--permission-mode bypassPermissions] [args]
Devin devin [--permission-mode bypass] [args] -- /plan2code
Codex codex [--dangerously-bypass-approvals-and-sandbox] [args] $plan2code (Codex starts a skill with $name; the launch line follows Codex's documentation)

The bracketed flags (each entry's bypassArgs; a custom agent's own bypassArgs) go in only when permission prompts are off. Right after the agent is chosen, and only when it has such a flag, chooseBypass() asks Turn <CLI>'s permission prompts off? with Yes as the default; --keep-permissions (never forwarded) answers no, and with no TTY on stdin the prompts are off, as before. When the desktop app will take over, the question is skipped (its launch card has its own tick) and asked only if the app fails to start. The installer prints no warning about it.

On a terminal it first prints a Planny banner (renderBanner()). With more than one on PATH it asks Plan2Code opens inside an AI coding agent. Pick which one to use: as a numbered menu, the last pick pre-selected and marked (last used) (Enter keeps it; a number or a CLI id also works); with one installed it uses that without asking, printing Opening with <CLI>… (as does a --cli pick); with none it exits 127 and prints SKILL_STEPS: how to install an agent, cd into the project, and type /plan2code ($plan2code in Codex). An uninstalled --cli pick prints that CLI's own steps after its error (its install command, cd into the project, then plan2code --cli <id> or its prompt). --cli claude / devin / codex (or --cli=<name>) skips the menu and is never forwarded; an unknown name exits 2, an uninstalled one 127. The pick is saved as lastCli in ~/.plan2code/launcher.json, merged beside lastFolder. Before spawning, unless the forwarded args carry --model / --model= (or, for Codex, -m), it asks Which model should <CLI> use? from models.json plus the user's additions, Enter keeping the model the CLI last used — Ctrl+C at any launcher prompt exits 130. With no TTY on stdin there is no menu (last pick, else the first installed) and no model question: it prints that the CLI will use the model last used in it (switch it in that CLI on its own, or pass --model <name>). Headings, numbers, defaults, retry lines and the plan2code: error prefixes are colored with paint() (the escape values of install.js's COLORS, copied), stdout only when stdout is a TTY and stderr only when stderr is, and never when NO_COLOR is set; piped runs print plain text and no banner. Other arguments are forwarded to the CLI (plan2code --model opus), and its exit code is passed back. plan2code update is the one subcommand: it is never forwarded and opens no agent, it runs npx --yes --allow-git=all git+https://github.com/jparkerweb/plan2code.git --update, so install.js --update reinstalls what ~/.plan2code/install.json lists. On every other start, before spawning the CLI, it prints one line when a newer release is out (Plan2Code v<latest> is out (you have v<installed>). Run: plan2code update), compared against ~/.plan2code/bin/version.json and read from the console's cached release check (~/.plan2code/console/update-check.json); it never waits on the network, and when the cache is missing or stale it refreshes it in a detached background process so the next start knows. Tests: scripts/test-launcher.mjs (run by npm test) spawns the launcher against stand-in claude/devin/codex commands and a temp home.

Design constraints:

  • Stable copy, not the package dir — the installer normally runs from an npx cache directory npm may delete, so installLauncher() copies src/launcher/plan2code.js to ~/.plan2code/bin/plan2code.js and the shims point there. Beside it go update-check.mjs (the web console's release check, for the terminal notice) and a version.json (the installed version). (The metrics/bot wrappers point into __dirname and don't have this protection.)
  • npm-style shims — written into npm's global bin (npm config get prefix; <prefix>/bin off Windows): an sh shim everywhere, plus .cmd and .ps1 on Windows, so cmd.exe, PowerShell and Git Bash all resolve it. On macOS/Linux, when the npm bin isn't writable (system Node), it falls back to ~/.local/bin.
  • Marker-based ownership — every shim contains plan2code-launcher; uninstallLauncher() removes only files carrying it, leaving any other plan2code bin alone.
  • Resolving the CLI — the launcher walks PATH (+ PATHEXT on Windows) itself. An .exe is spawned directly; a .cmd/.bat wrapper goes through cmd.exe /d /s /c with quoted args, since Node refuses to spawn batch files without a shell. The installer warns only when neither claude nor devin is on PATH.
  • No bin-name overlap — the installer's own bin in package.json is plan2code-install (→ install.js), so plan2code belongs to the launcher alone. npx runs a package's only bin whatever it's named, so the README's npx … plan2code.git command is unaffected; keep it the only bin, or npx will need -c plan2code-install.
  • --pick-folder is shortcut-only — the launcher strips it before building the CLI's args. The shortcut runs the CLI menu, then the folder picker, then the model menu. With it, a native folder picker chooses the cwd instead: on Windows, the Explorer-style IFileOpenDialog (FOS_PICKFOLDERS) via powershell -STA -EncodedCommand, its C# interop (WINDOWS_PICKER_SOURCE) passed in an env var and compiled with Add-Type (~0.5s), with a TopMost owner form so it doesn't open behind the console — Windows PowerShell's FolderBrowserDialog is the old tree-only dialog, and is kept only as the fallback when Add-Type is blocked (Constrained Language Mode, AppLocker); osascript choose folder on macOS, and zenity then kdialog on Linux (only when DISPLAY/WAYLAND_DISPLAY is set). If there's no picker, or the picker fails, it falls back to a typed Project folder [last]: prompt. A picker that exits 0/1 with nothing printed means the person canceled, so the launcher exits 0. The picker starts on the last pick, stored in ~/.plan2code/launcher.json. From the shortcut, a non-zero exit other than Ctrl+C (130 / 0xC000013A) waits for Enter so the error doesn't vanish with the window. Typed in a terminal, plan2code behaves exactly as before.

Desktop shortcut — after the shims are written, installLauncher() (now async) calls offerDesktopShortcut(). It asks Also add a Plan2Code shortcut to your desktop? (y/N), skips the question when stdin isn't a TTY, and refreshes an existing marked shortcut without asking. installDesktopShortcut() writes it to the real desktop ([Environment]::GetFolderPath('Desktop') on Windows, which covers OneDrive redirection; xdg-user-dir DESKTOP on Linux; ~/Desktop otherwise):

OS File Runs
Windows Plan2Code.lnk (written by WScript.Shell) pwsh.exe (else Windows PowerShell) -NoLogo -ExecutionPolicy Bypass -File "<bin>\plan2code.ps1" --pick-folder, icon src/launcher/plan2code.ico (the web console's Peek-a-boo favicon, 16–256 px) copied to ~/.plan2code/bin/plan2code.ico
macOS Plan2Code.command (0755) exec "<bin>/plan2code" --pick-folder in Terminal
Linux plan2code.desktop (0755, Terminal=true, gio … metadata::trusted) "<bin>/plan2code" --pick-folder, Icon= the web console's favicon.png copied to ~/.plan2code/bin/plan2code.png

The macOS and Linux shortcuts carry the plan2code-launcher marker as a comment line. A .lnk has nowhere to hide one (its Description is the hover tooltip), so it's recognized by what it runs: the UTF-16 strings plan2code.ps1 and --pick-folder stored in the file (plan2code.cmd also matches, so shortcuts from before the PowerShell switch get refreshed). uninstallLauncher() removes only a recognized shortcut, plus the icons (plan2code.ico, plan2code.png), bin/models.json and launcher.json (never the user's ~/.plan2code/models.json). A shortcut failure prints a warning and never fails the command install.

Installer integration lives in install.js under the PLAN2CODE COMMAND section (installLauncher, uninstallLauncher, plus the shortcut helpers). install() awaits it after a successful skills install (so I and Advanced → E get it), U removes it, and Advanced → D installs it alone. Every global install writes ~/.plan2code/install.json, the install record listing the pieces installed (skills, launcher, statusline, loop, metrics, bot); install.js --update (what plan2code update runs) reinstalls exactly those, with no menu and never uninstalling, or with no record the skills and the plan2code command. After an install, printGettingStarted() prints the three steps (cd into the project, start Plan2Code, pick a card) and, when no agent CLI is on PATH, how to get one.