Compare commits

...
50 Commits
Author SHA1 Message Date
jparkerweb cedc3300ed Merge pull request #16 from jparkerweb/v3-orchestrator
Plan2Code v3.0.0: desktop app, Implementation Loop, strength-matched helpers, custom agents, PR Prep and Write missing tests
2026-11-05 21:58:11 -08:00
jparkerweb 8bace16e06 Pace the keys in the in-app full-screen test so the browser's late answers cannot undo the next one
AI Assisted
2026-11-05 20:47:41 -08:00
jparkerweb e87148ad10 Pin Math.random in the Activities logic tests so a rare roll cannot fail one at random
AI Assisted
2026-11-05 20:26:49 -08:00
jparkerweb 23ac3a9c19 Fix two Ubuntu flakes: try more road for a Bounce Road rival, and wait for the board's focus before the last F press
AI Assisted
2026-11-05 20:05:02 -08:00
jparkerweb a0ac6eb655 Hand every page test a page that has gone quiet, and retry the @ list until it names the project
AI Assisted
2026-11-05 19:44:35 -08:00
jparkerweb 958c0f4ccc Let the page go quiet before typing in the Markdown answer box test
AI Assisted
2026-11-05 19:25:50 -08:00
jparkerweb 959554d127 Make the Ask send self-healing and let the page go quiet before scrolling in tests, so late redraws stop failing them
AI Assisted
2026-11-05 19:05:59 -08:00
jparkerweb fc2921c848 Retype the @ in the session modules test if a redraw swallowed it
AI Assisted
2026-11-05 18:51:33 -08:00
jparkerweb e0b64e5895 Let the note tray go quiet before the Ask picview test opens a picture
AI Assisted
2026-11-05 18:34:52 -08:00
jparkerweb 7139d0340c Cache the apt packages and the npm downloads in CI
AI Assisted
2026-11-05 18:21:09 -08:00
jparkerweb e23ef8b3ec Fix two Windows flakes: wait for a disabled Markdown field to open before filling it, and give the installer tests 60s for a slow runner
AI Assisted
2026-11-05 17:55:13 -08:00
jparkerweb 7336b7fcc5 Wait for both full-screen messages in the in-app Activities test: the list already ended in false
AI Assisted
2026-11-05 17:49:03 -08:00
jparkerweb 4265eda68b Drop the npm cache from the npm test job: the repo does not track a root lockfile
AI Assisted
2026-11-05 17:18:38 -08:00
jparkerweb 15019dbc88 Speed up CI: cancel superseded PR runs, Ubuntu only on pull requests, and a fast prose job for docs-only changes. Put Before you start above the install command again
AI Assisted
2026-11-05 17:12:49 -08:00
jparkerweb 2e2edd538a Condense the v3.0.0 changelog to its main features, set the release date, and rebuild the landing page around the desktop app
AI Assisted
2026-11-05 17:08:41 -08:00
jparkerweb 807b6b038c Wait for the events stream to connect before posting the submit it must report
AI Assisted
2026-11-05 15:17:00 -08:00
jparkerweb 8922d2e391 Wait for the Welcome to appear before dismissing it in the session page tests
AI Assisted
2026-11-05 14:55:14 -08:00
jparkerweb 4352f3027d Fix two macOS-only test races: wait for F to fill the screen, and pick a mention from the page instead of clicking a list that repaints
AI Assisted
2026-11-05 14:35:56 -08:00
jparkerweb da6b738fc8 Fix two flaky page tests: wait for the editor before scrolling a card, and poll for the saved Welcome instead of a waitForFunction that returned at once
AI Assisted
2026-11-05 14:16:34 -08:00
jparkerweb 8ddf37911e Fix CI: tests follow Activities starting off, findAgent fixture uses a portable path, Ghoul Rush eye test waits for the eye
AI Assisted
2026-11-05 13:50:17 -08:00
jparkerweb 17f98e62b5 Let coverage read take a runner folder so relative lcov paths resolve, and fix Handoff's script path
AI Assisted
2026-11-05 11:39:04 -08:00
jparkerweb 2cb174ecf0 Make the console survive locked files and private handles, and start with Activities off
AI Assisted
2026-11-05 11:38:59 -08:00
jparkerweb c52244bee1 Keep metrics and bot out of plan2code update unless run from a git checkout, and end shims cleanly
AI Assisted
2026-11-05 11:38:59 -08:00
jparkerweb 0b6a376915 Refuse run ids that could leave the runs folder and stop replacements being read as patterns
AI Assisted
2026-11-05 11:38:58 -08:00
jparkerweb b17213322c Harden the app's loop commit gate, agent launch and file writes, and tighten workflow permissions
AI Assisted
2026-11-05 11:38:57 -08:00
jparkerweb 30fd1134ea Add a Reconnect to agent button where the agent has gone quiet
AI Assisted
2026-11-05 10:03:09 -08:00
jparkerweb 6376a68f85 Add Flock Dash, the thirteenth Activities game, with sounds and music
AI Assisted
2026-11-05 07:57:21 -08:00
jparkerweb e924cf5cde Fix Light Trails so a turn on a Wide Trail does not crash into your own side cells
AI Assisted
2026-11-05 07:57:13 -08:00
jparkerweb 8491764273 Ask once before Finalize's rating questions, with a No thank you
AI Assisted
2026-11-04 20:20:50 -08:00
jparkerweb 7f95dabd00 Add Ask a question to a stopped loop and stop the agent on Back to the dashboard
AI Assisted
2026-11-04 20:13:43 -08:00
jparkerweb 81d14c8e78 feat: run each loop phase on its own strength (Thrifty, Balanced, Best)
AI Assisted
2026-11-04 19:23:52 -08:00
jparkerweb e963513a8a Offer Skip on two of Diagnose's opening questions
AI Assisted
2026-11-04 19:23:33 -08:00
jparkerweb 9583b68a2e Make the git board's next-step Commit button commit the ticked files
AI Assisted
2026-11-04 13:27:23 -08:00
jparkerweb cc02631ab5 Play recorded songs in Light Trails and add lives and power-ups
AI Assisted
2026-11-04 13:12:56 -08:00
jparkerweb cc97161a23 Show a cleared pick and a new question in one banner
AI Assisted
2026-11-04 13:12:42 -08:00
jparkerweb bc2c7c6c41 Add Ask for suggestions chip, thread tag, stale-pick pruning and agent line
AI Assisted
2026-11-04 12:39:16 -08:00
jparkerweb f8a0a6bfc7 Add the headless Ask for suggestions send and its server flag
AI Assisted
2026-11-04 12:09:43 -08:00
jparkerweb eb235dd91e fix: show the fake agent's output when loop_driver's generations wait times out
AI Assisted
2026-11-04 10:24:10 -08:00
jparkerweb 7f1851fbb9 Test when the Send button is available and what it says
AI Assisted
2026-11-04 10:24:09 -08:00
jparkerweb 7509b09b81 Keep the shared-state test in step with the collapsed terminal flag
AI Assisted
2026-11-04 10:24:08 -08:00
jparkerweb bf23d7eeea Tighten PR Prep and Test after their first runs
AI Assisted
2026-11-04 10:24:07 -08:00
jparkerweb ff1c793633 Add Snake and Light Trails music, dealt fresh each round
AI Assisted
2026-11-04 10:24:06 -08:00
jparkerweb 6cd7a7ff80 Add the Test skill: find untested code and write tests in the project's style
AI Assisted
2026-11-03 21:42:36 -08:00
jparkerweb 88c72dc2ce Add the PR Prep skill: check plan, readiness verdict and PR description
AI Assisted
2026-11-03 21:26:10 -08:00
jparkerweb 82298d256c Add test command discovery and a check runner, and offer a test map in Init
AI Assisted
2026-11-03 21:04:32 -08:00
jparkerweb aecc3afb4c Add the test map reader and two-way test matcher scripts
AI Assisted
2026-11-03 20:53:42 -08:00
jparkerweb e681d1f70d Add Ghoul Rush's finale at Marrow Manor: the House's three kills, two rides and the ending
AI Assisted
2026-11-03 20:32:49 -08:00
jparkerweb be31f6af89 Merge pull request #15 from jparkerweb/notepad
Add Notebook tabs and a CodeMirror editor, rename Notepad to Notebook…
2026-10-20 12:03:06 -07:00
jparkerweb 50acdc8216 Merge pull request #14 from jparkerweb/notepad
Notepad
2026-10-19 20:03:17 -07:00
jparkerweb a19dc6c5df Merge pull request #13 from jparkerweb/feature/utility-updates
Feature/utility updates
2026-10-18 17:24:09 -07:00
268 changed files with 32729 additions and 915 deletions

No files matched your search

+67 -19
View File
@@ -5,7 +5,7 @@
``` ```
plan2code/ plan2code/
├── src/ # Source workflow prompts (17 markdown files) ├── src/ # Source workflow prompts (19 markdown files)
│ ├── plan2code-0-pathfinder-references/ # Reference files for pathfinder skill │ ├── plan2code-0-pathfinder-references/ # Reference files for pathfinder skill
│ │ ├── brief.md # Dated plain-English decision briefs │ │ ├── brief.md # Dated plain-English decision briefs
│ │ ├── chart.md # MODE A: destination + frontier grills, templates │ │ ├── chart.md # MODE A: destination + frontier grills, templates
@@ -16,9 +16,9 @@ plan2code/
│ │ ├── handoff.md # Clearing gate + PLAN-DRAFT handoff │ │ ├── handoff.md # Clearing gate + PLAN-DRAFT handoff
│ │ └── trail.md # Every-response map visual + pathed resume command │ │ └── trail.md # Every-response map visual + pathed resume command
│ ├── shared-references/ # Reference files shared across skills │ ├── shared-references/ # Reference files shared across skills
│ │ ├── building-habits.md # Find the cause, test first, pin behavior (quick-task, implement, implement-review) │ │ ├── building-habits.md # Find the cause, test first, pin behavior (quick-task, implement, implement-review, test)
│ │ ├── helper-strength.md # How strong a model and how much effort each helper gets (init, init-update, pathfinder, plan, revise-plan, document, quick-task, implement, implement-review, review, finalize, xray, diagnose) │ │ ├── helper-strength.md # How strong a model and how much effort each helper gets (init, init-update, pathfinder, plan, revise-plan, document, quick-task, implement, implement-review, review, finalize, xray, diagnose, pr-prep, test)
│ │ └── 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) │ │ └── test-runs.md # Choosing what tests to run: targeted per task and phase, full suite only where the plan puts it (document, implement, implement-review, quick-task, review, finalize, pr-prep, test)
│ ├── plan2code-review-references/ # Reference files for review skill │ ├── plan2code-review-references/ # Reference files for review skill
│ │ ├── verification-protocol.md # Deep verification + confidence calibration │ │ ├── verification-protocol.md # Deep verification + confidence calibration
│ │ ├── dimensions.md # 11 dimensions with detailed checklists │ │ ├── dimensions.md # 11 dimensions with detailed checklists
@@ -29,8 +29,8 @@ plan2code/
│ │ └── ai-agent-file-sync.md # Step 7: replace AI configs with AGENTS.md refs │ │ └── ai-agent-file-sync.md # Step 7: replace AI configs with AGENTS.md refs
│ ├── plan2code-4-finalize-references/ # Reference files for finalize skill │ ├── plan2code-4-finalize-references/ # Reference files for finalize skill
│ │ └── community-feedback-submission.md # STEP 6.5 payload schema + submission tiers │ │ └── community-feedback-submission.md # STEP 6.5 payload schema + submission tiers
│ ├── skill-scripts/ # Scripts shared across skills: install.js copies the ones a skill lists into skills/<skill>/scripts/ (specs, commit-msg, review-scope, agents-md, agent-files, common) │ ├── skill-scripts/ # Scripts shared across skills: install.js copies the ones a skill lists into skills/<skill>/scripts/ (specs, commit-msg, review-scope, agents-md, agent-files, glob, test-map, test-match, test-commands, run-check, common)
│ └── plan2code-<skill>-scripts/ # A skill's own scripts, same copy rule (pathfinder, finalize, changelog, git and xray each have one) │ └── plan2code-<skill>-scripts/ # A skill's own scripts, same copy rule (pathfinder, finalize, changelog, git, xray, pr-prep and test each have one)
├── plan2code-bot/ # Autonomous end-to-end workflow test runner (TypeScript, tsup, Claude Agent SDK, vitest); user docs in .readme/test-bot.md ├── 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 ├── plan2code-metrics/ # Recursive self-improvement toolchain
│ ├── src/ # TypeScript source │ ├── src/ # TypeScript source
@@ -142,6 +142,8 @@ plan2code/
| `plan2code-handoff.md` | handoff | Compact the conversation into a self-contained handoff document for a fresh session | | `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-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-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-pr-prep.md` | pr-prep | Get a branch ready for review: pick the checks its changes need from the project's `## Test map` (or its config files), let the person trim the plan, run it, give Ready, Ready with notes or Not ready, and write a PR description to copy (following the repo's template) with the create-a-PR link; offers to save `PR-READINESS-<date>.md` into the branch's spec folder; never commits, pushes or opens the PR |
| `plan2code-test.md` | test | Write missing tests: ask where to look, find source files no test covers (matching, plus real coverage when the project already has a coverage tool, offered first), show a plan opening with how this project writes tests, then write and run unit and integration tests; escalates past 8 source files, 8 new test files or 2 runners to a PLAN-DRAFT for Plan, hands a real bug to Diagnose, never changes source code |
| `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-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 | | `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 |
@@ -182,7 +184,14 @@ Anything a workflow step decides with one correct answer (parsing a spec's check
|---|---|---| |---|---|---|
| `specs.mjs` | plan, revise-plan, document, implement, implement-review, review, quick-task, finalize, handoff, diagnose | `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 | | `specs.mjs` | plan, revise-plan, document, implement, implement-review, review, quick-task, finalize, handoff, diagnose | `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` | | `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, finalize | Review Mode's git fallback: files, lines, doc share, base branch | | `review-scope.mjs` | review, implement(-review), quick-task, finalize, pr-prep, test | Review Mode's git fallback: files, lines, doc share, base branch |
| `glob.mjs` | init, init-update, pr-prep, test | The glob subset (`**`, `*`, `?`, `{a,b}`) as a RegExp, and forward-slash path normalizing; imported by `test-map.mjs` and `test-match.mjs` |
| `test-map.mjs` | init, init-update, pr-prep, test | `read` / `write` the project test map (one `\| Area \| Paths \| Run \| Shared \|` table under `## Test map` in `AGENTS.md`, or behind one link to `.agents-docs/`); every line outside the table stays byte-identical |
| `test-match.mjs` | pr-prep, test | `covers` (changed files to the map rows and tests that cover them, plus shared-ground hints), `gaps` (source files no test covers, ranked by recent change) and `nearest` (existing tests to read for style) |
| `test-commands.mjs` | init, init-update, pr-prep, test | `discover`: the whole-suite command, per-folder runners, lint/types/build checks, coverage commands already present and the language's built-in runner, from config files only |
| `run-check.mjs` | pr-prep, test | Run one command with a timeout, kill its process tree on timeout, and classify it `passed`, `failed`, `timeout` or `not-started` with the output's tail |
| `pr-prep.mjs` (own) | pr-prep | `template` (the PR template and its headings), `pr-url` (the create-a-PR link through `git-repo.mjs`) and `spec` (the branch's spec folder for the save offer). Read-only |
| `coverage.mjs` (own) | test | `read --lcov` / `--go-func`: coverage output as per-file lines, hits and percent, plus the total. Read-only, runs no tool |
| `agents-md.mjs` | init, init-update | AGENTS.md structure, budget, orphans, broken links, always-inline sections | | `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 | | `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` | | `pathfinder.mjs` (own) | 0-pathfinder | `reconcile`, `frontier`, `claim`, `resolve`, `rule-out`, `trail`, `gate`, `lint`, `brief-data` |
@@ -193,7 +202,7 @@ Anything a workflow step decides with one correct answer (parsing a spec's check
**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. **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/`. **Tests:** `scripts/test-skill-scripts.mjs` (installer plumbing and the shared scripts), `scripts/test-script-<skill>.mjs` (a skill's own, and the newer shared scripts: `test-script-test-map.mjs`, `test-script-test-match.mjs`, `test-script-test-commands.mjs`, `test-script-run-check.mjs`, `test-script-pr-prep.mjs`, `test-script-coverage.mjs`), 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/`) ## Repo-Local Skills (`.claude/skills/`)
@@ -237,9 +246,9 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `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()`) | | `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 | | `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 | | `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.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`, `activityBestFlock`); lists Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, `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/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; it also holds the music's rules: `MUSIC_TRACKS`, `dealMusic(random, last)` (a round's shuffle of the ten tracks, never opening on the last round's opener), `trackFor(deck, level)` and `heat(round)` (the snake's speed as 0.3 to 1, so the lead and drums are in from the first step) |
| `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/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` (a Mystery becoming another pad), `pickPower` (by each pad's `from` arena, a Heart only under `MAX_LIVES`), `fireLaser`, `hyperjump`, `awardLives` (a life every `LIFE_SCORE` points, the mark moving on at the cap), `spawnItem`, `closeRing`), the `ARENAS` (rivals, sharpness and what each adds), the `POWERS` pads (Boost, Phase, Eraser, Slow-mo, Coin, Heart, Shield held across heats until a crash in your grace pops it, Laser with `LASER_SHOTS`, Score x2 through one `gain()` every score goes through, Wide Trail with its side cells in `rider.wide`, Coin Rain whose `rain` coins never hold back a pad, Hyperjump, Mystery) and the game contract; `START_LIVES` is 5; memo is the furthest arena reached; a read-only `round` getter for the tests only; it also holds the music's rules: `MUSIC_TRACKS` (its five songs) and `dealMusic(random, last)` (a shuffle of them, never opening on `last`); a run plays the deal one song after another, each in full from the top (asking with `{ restart: true }` until the music takes it), moves on when `music()` answers `"ended"`, deals again after the last, and a new run deals afresh, never opening on the song the last run was playing; its tones and hums play `SFX_LOUDER` times as loud through tones.js's `louder`, all but the engine drones (`DRONES`), kept low under the songs |
| `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/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/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/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 |
@@ -247,6 +256,8 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `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/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.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/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/flock.js` | Flock Dash: its rules as plain exported functions over a round scrolling right to left over a 96 by 54 unit field (`newRound(seed)`, `steer` (the leader eased up and down inside the `BAND_MIN` to `BAND_MAX` band at the left), `recordPath`, `placeFlock`, `screenX`, `collect` and `spawnStrays` (a stray joins the flock, the combo up to `MAX_COMBO` within `COMBO_MS`), `buildStage(seed, n)` (a stage's hazards by distance from its own seed, a clear `SAFE_START` and `SAFE_END`, and `clearGap` keeping a way through), `moveHazards`, `hazardHits`, `snapAt` (a snap drops the birds behind the one hit, `scattered` for `SCATTER_MS` so they can be picked up again), `hitLeader` (a life, or a shield; `GRACE_MS` after), `reachPortal` (the jet stream portal, the V of `V_POINTS` a bird when the flock has `min`, `FLAWLESS_POINTS` for no snap or life lost, and the final portal that sways), `applyPower` (crates: tailwind, shield up to `MAX_SHIELDS`, magnet), `banner`, `bannerRow`, `underBanner`, `advance` in `SLICE_MS` slices, `teaser`, `seeded`, `dealMusic`), the `STAGES` table (eight stages, each with its speed, length, stray gap, portal `min`, hazard weights and gap; the place to tune the difficulty), the `HAZARDS` (balloon, gust, stream, cluster, storm, kite, each from its own stage) and `POWERS`, and the game contract with `release()` (held arrows steer, a pause lets go of every key); the round also carries `events` (what the draw and the sounds react to) and `warned` (one gust or storm warning each); memo is the furthest stage reached. The flock is a recorded path with running arc length: follower k sits `k * SPACING` behind the leader along it, so it copies every turn at any speed. `MUSIC_TRACKS` names the five songs, dealt afresh each round |
| `public/activities/flock-draw.js` | Flock Dash's drawing: `drawScene(ctx, view)` and `hudLayout` from one view object `flock.js` refills each frame, in field units: the sunset sky (`SKIES`, one palette per stage: the sun sinking, clouds, a rim light from stage 6 and stars on the last), the hazards (balloons and bunches, the head-wind's warning band and gust, slipstreams, thunderheads with their flash and bolt, kites on their strings), the strays and scattered birds, the flock, Planny as the lead bird with a star for an eye, crates and the magnet ring, the tailwind streaks, the portal and the V, the pills (laid out by `hudLayout`, which shrinks them to fit the board), banners, and the end strip with the final score, the best and the teaser; `readColors(canvas)`; 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.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/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.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`) |
@@ -268,7 +279,28 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `public/activities/ghoul-rush/core/ghoul-fight.js` | Bosses and damage: a boss's fight and fall, hurting and killing a monster, losing a life. | | `public/activities/ghoul-rush/core/ghoul-fight.js` | Bosses and damage: a boss's fight and fall, hurting and killing a monster, losing a life. |
| `public/activities/ghoul-rush/core/ghoul-play.js` | The play loop: `KIT` and `RUN_KIT`, the blaster and bolts, hits, stomps, timers, one slice of play, and `advance()`. | | `public/activities/ghoul-rush/core/ghoul-play.js` | The play loop: `KIT` and `RUN_KIT`, the blaster and bolts, hits, stomps, timers, one slice of play, and `advance()`. |
| `public/activities/ghoul-rush/core/ghoul-window.js` | The game's contract with the Activities page: `create`, keys and pointer, what events set off, `ROOM_MUSIC`, the view handed to the drawing. | | `public/activities/ghoul-rush/core/ghoul-window.js` | The game's contract with the Activities page: `create`, keys and pointer, what events set off, `ROOM_MUSIC`, the view handed to the drawing. |
| `public/activities/ghoul-rush/stages/marrow/ghoul-marrow.js` | The finale's rules: Marrow, the house itself. Kill I, The Lawn: its windows, moves and retreat. Not plugged in yet. | | `public/activities/ghoul-rush/stages/marrow/ghoul-marrow.js` | The finale's rules (`MARROW`, a pack in `PACKS`): Marrow, the house itself, the boss of `FINALE` (`core/ghoul-rooms.js`: after `RUN_STAGES` stages a run goes there with no offer, and clearing its last room wins). Kill I, The Lawn (room `lawn`): the house stands at the arena's right and YOU are kept `WALL_GAP` off it; its real hit box sits at the room's far end and is always `guard`ed, so only its twelve `WINDOWS` hurt it, through the pack's `target` (`windowShot`: the first lit window at a bolt's height; each holds `ceil(bossHp / 12)`, `b.hp` their sum; a bolt past the far wall is spent). Windows are `dark`, `lit` (a few at a time, `LIT_N`, `LIT_MS`, `RELIGHT_MS`) or `out` for good, kept in `round.marrow` across a life lost; rows open by windows out (`rowsOpen`). Moves by weighted `pickMove` (shingles, carpet, pickets; bricks and doormen from phase 1; stomp in phase 2; and only while YOU are up in the oak, `isHigh`, `HIGH_WEIGHTS`: lightning, a `marrowBolt` hazard that glows on YOUR branch then strikes down to it, and crows out of the door's mouth, the Graveyard's carrion crows marked `houseCrow`, at most `CROWS_CAP`). After the kill `b.t` runs the retreat (`retreatStep`: sag, a false "YOU ESCAPED!", a laugh, the sink, `b.gone`, which lifts the wall to its standing front door) |
| `public/activities/ghoul-rush/stages/marrow/ghoul-marrow-draw.js` | The finale's drawing: `LOOKS` (`lawn`, `pack: "marrow"`), `VOICES` (the House's acts, tones in `ghoul-sfx-marrow.js`), `LOSE_WORDS`, `LOSE_SOUNDS` and `marrowArt(d)`: the storm on the hill, the dead oak whose branches are the shelves, the mailbox, the house as a face (its windows lit, shuttered or shot out, the door its mouth), its hazards and waves, its retreat (drawn through its fall: `LINGERS` in `ghoul-draw.js`), lights and every event's look and sound |
| `public/activities/ghoul-rush/stages/marrow/ghoul-sfx-marrow.js` | The finale's own sounds as data (no imports): `MARROW_SFX` with `tones` (a `ghoulMarrow<Act>` tone per act of the House, first drafts until the sound vote); merged by `ghoul-sfx.js` via `STAGE_SFX`; the lawn borrows the Drowning Pool's track until its own is picked |
| `public/activities/ghoul-rush/rides/mat/ghoul-mat-room.js` | Down the Hatch's room as data, written by `prototypes/ghoul-rush-tools/gen-mat.mjs --write` (`ready: true`; `ride.hearts` 3) |
| `public/activities/ghoul-rush/rides/mat/ghoul-mat.js` | Rules for the finale's first ride, Down the Hatch (pack `MAT`, state in `round.runner` with id `mat`): surfing the WELCOME mat down the House's throat, floor lines and gristle ledges over holes, ribs (jump), uvulas (duck), peristalsis squeezes that throb before they close (duck), swallowed furniture (shoot or jump, an act), bile stretches that speed YOU up, three hearts through `ride.hearts`, `mat`-prefixed events and causes, no random numbers |
| `public/activities/ghoul-rush/rides/mat/ghoul-mat-draw.js` | Down the Hatch's drawing: `LOOKS.mat` (pack `mat`), `VOICES` (`mat`, `matsqueeze`, `matfurn`), `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS` and `matArt(d)` (the throat in `moving`; uvulas, squeezes, the mat and the telegraph glyphs in `front`; `lights`, `react`) |
| `public/activities/ghoul-rush/rides/mat/ghoul-sfx-mat.js` | Down the Hatch's `ghoulMat*` tones, the user's picks (`MAT_SFX`, wired by `prototypes/ghoul-rush-tools/wire-mat-sounds.cjs`), and its track `ghoulMarrowMat` |
| `public/activities/ghoul-rush/stages/marrow/ghoul-dollhouse-room.js` | Kill II's room as data: the dollhouse (132 long, a 36-unit landing, floors at 6, 20 and 34 across the arena, stair landings at 13 and 27 at each end, door at 119.5, boss `marroweye`), `ready: true` |
| `public/activities/ghoul-rush/stages/marrow/ghoul-marrow-eye.js` | Kill II's rules as pack `EYE`: the Eye opens in one of nine rooms after a lamp flare, can be hit only through the pack's `target` (`eyeShot`) and clanks while flaring or shutting; in its last phase a false flare. Shades of the keepers beaten this run (`SHADE_MOVES`, one move each, `eyeShade` monsters out of `eyeDoorway` hazards). The lurch pushes YOU in the pack's `tick` and slides an `eyeDresser`. The retreat runs on `b.t` and keeps YOU off the door until `b.gone` |
| `public/activities/ghoul-rush/stages/marrow/ghoul-marrow-eye-draw.js` | Kill II's drawing: the dollhouse cutaway and nursery backdrop, floors and landings, lamps, the Eye, shades drawn small and pale through `d.bossArt`, every hazard, the retreat and the bone stair, the card picture, `lights`, `react`; `LOOKS`, `VOICES`, `LOSE_WORDS`, `LOSE_SOUNDS` |
| `public/activities/ghoul-rush/stages/marrow/ghoul-sfx-marrow-eye.js` | Kill II's `ghoulEye*` and `ghoulEyeShade*` tones, the user's picks (`EYE_SFX`, wired by `wire-eye-sounds.cjs`), and its track `ghoulMarrowRooms` |
| `public/activities/ghoul-rush/rides/bonestair/ghoul-bonestair-room.js` | The Bone Stair's room as data (`ready: true`), written by `prototypes/ghoul-rush-tools/gen-bonestair.mjs` |
| `public/activities/ghoul-rush/rides/bonestair/ghoul-bonestair.js` | The Bone Stair's rules, pack `BONESTAIR` (`ride`, `place`, `target`), state in `round.runner` with id `bonestair`: spiral flights with seams, the rubble's gap meter behind YOU, treads that give way, ribcages, skeletons, bone hands and masonry; causes and events prefixed `stair`; no random numbers; 3 hearts |
| `public/activities/ghoul-rush/rides/bonestair/ghoul-bonestair-draw.js` | The Bone Stair's drawing: `LOOKS.bonestair`, `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`, the telegraph glyphs, and `bonestairArt(d)`: the shaft, the bone treads, the columns, every obstacle, the rubble wall and its meter, and the Pit's dark |
| `public/activities/ghoul-rush/rides/bonestair/ghoul-sfx-bonestair.js` | The Bone Stair's `ghoulStair*` tones, the user's picks (`BONESTAIR_SFX`, wired by `wire-bonestair-sounds.cjs`), and its track `ghoulMarrowStair` |
| `public/activities/ghoul-rush/stages/marrow/ghoul-pit-room.js` | Kill III's room as data: the Pit (160 long, always dark, the heart's plinth with a pit each side, three ledges, door at 154, boss `marrowheart`), `ready: true` |
| `public/activities/ghoul-rush/stages/marrow/ghoul-marrow-heart.js` | Kill III's rules as pack `HEART`: the beat on `b.t` (`BEAT_MS` 1500 falling to 750), a `heartBeat` wave each way, the ribs open between beats (`guard` is `!b.open`), roots, ledge grabs, clots, falling chunks, a stopped beat and a double wave; bolts clamp at 1 hp, then HOLD FIRE (`round.flood`, the meter filled by `round.input.fire`, state on `round.heart`), the white-out, the last thump, the fall, and daylight with a door of light (`b.gone`) |
| `public/activities/ghoul-rush/stages/marrow/ghoul-marrow-heart-draw.js` | Kill III's drawing: `LOOKS.pit` (dark, `noLightning`), the cavern, the heart in ribs, roots and chains, every hazard and wave, the red flood, the HOLD FIRE meter and growing beam, the white-out and the daylight shaft; `VOICES.marrowheart` (`hold` is `ghoulStoryClick`), `LOSE_WORDS`, `LOSE_SOUNDS`, `react` |
| `public/activities/ghoul-rush/stages/marrow/ghoul-sfx-marrow-heart.js` | Kill III's `ghoulHeart*` tones, the user's picks (`HEART_SFX`, wired by `wire-heart-sounds.cjs`), and its track `ghoulMarrowPit` |
| `public/activities/ghoul-rush/story/ghoul-ending.js` | The ending's four pages (lights out, the road, morning, final notice) and their rules in phase `ending`: a lockout, typing finished first, a minimum time per page, a one-second fire hold to skip, `skipEnding`; it wins the run once at its end (`won` with `n: round.winN`) |
| `public/activities/ghoul-rush/story/ghoul-ending-draw.js` | `endingArt(d)` returns `{ card, react }`: four animated scenes in the story's layout; `react` answers only `endingPage` |
| `public/activities/ghoul-rush/story/ghoul-sfx-ending.js` | `ENDING_SFX`: the ending's `ghoulEnding*` tones, the user's picks (wired by `wire-ending-sounds.cjs`), and its track `ghoulMarrowEnding` (`ENDING_TRACK`) |
| `public/activities/ghoul-rush/draw/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-rush/draw/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-rush/core/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-rush/core/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-rush/stages/wing/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-rush/stages/wing/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). |
@@ -357,6 +389,12 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `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-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 | | `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 |
| `scripts/test-web-console-activities-ghoul-bog.mjs` | Gallows Bog's suite: the stage row and its rooms, the mud (slow, sink, jump, shelf, boots), each monster's behavior (the lurker's eyes and snap, the leech's latch, the wisp's light, the bog body's rise), the wisp lure and its fairness cap, the harpoon under the water, Old Mother Bog's wave, weak cauldron, muck, sink and resurface, every move (wind-up, telegraph event, effect, a clean dodge costs nothing, a hit a heart), the phase unlocks, cooldowns and caps, planks while standing, her fall clearing every hazard and add, a skilled bot that must kill her in 60 to 120 s on four seeds and an idle bot she kills, a voice for every act with exactly one picked sound per event, words and a sound for every cause, both cards, the round flow, drawing dark and lit, and a seeded bot on a draw that throws if the pack asks for a random number | | `scripts/test-web-console-activities-ghoul-bog.mjs` | Gallows Bog's suite: the stage row and its rooms, the mud (slow, sink, jump, shelf, boots), each monster's behavior (the lurker's eyes and snap, the leech's latch, the wisp's light, the bog body's rise), the wisp lure and its fairness cap, the harpoon under the water, Old Mother Bog's wave, weak cauldron, muck, sink and resurface, every move (wind-up, telegraph event, effect, a clean dodge costs nothing, a hit a heart), the phase unlocks, cooldowns and caps, planks while standing, her fall clearing every hazard and add, a skilled bot that must kill her in 60 to 120 s on four seeds and an idle bot she kills, a voice for every act with exactly one picked sound per event, words and a sound for every cause, both cards, the round flow, drawing dark and lit, and a seeded bot on a draw that throws if the pack asks for a random number |
| `scripts/test-web-console-activities-ghoul-marrow.mjs` | The finale's suite: the win condition (`RUN_STAGES` picks that never repeat, then the House with no offer, its stage card and the boss's, the win), the select listing it last at depth 0, the memo (one past every stage only on a win, never from practice) and the words that count `RUN_STAGES`; Kill I, The Lawn: the wall and the out-of-reach guarded box, every window hit from the surface serving its row and passed while shuttered, a window out for good across a life lost, rows opening by windows out, `pickMove`'s rules, each move's telegraph, hit (its cause) and dodge, the doormen's cap, endless lives, the retreat's beats in order and the door it leaves, a steady bot's fight length at full depth and an idle one's death, the voices, words and sounds, and drawing every state lit and dark |
| `scripts/test-web-console-activities-ghoul-mat.mjs` | Down the Hatch's suite: the track, every obstacle's telegraph, hit and dodge, the squeezes, bile, the grade, a good bot finishing and one that never dodges losing its three hearts without a game over |
| `scripts/test-web-console-activities-ghoul-eye.mjs` | Kill II's suite: the Eye's flare, opening and guard, a shade move for every boss in `STAGES`, the lurch and the dresser, the retreat, a bot's fight length, voices and drawing |
| `scripts/test-web-console-activities-ghoul-bonestair.mjs` | The Bone Stair's suite: the flights and seams, the rubble's meter, every obstacle's telegraph, hit and dodge, the grade, and the bot sims |
| `scripts/test-web-console-activities-ghoul-heart.mjs` | Kill III's suite: the beat and its waves, the ribs' window, every attack's warning, the clamp at 1 hp and HOLD FIRE, the white-out and the door of light, a bot's fight length, voices and drawing |
| `scripts/test-web-console-activities-ghoul-ending.mjs` | The ending's suite: the pages' rules, a press turning pages, holding fire to skip, the win once at the end, every scene drawn |
| `scripts/test-web-console-activities-ghoul-lantern.mjs` | The Drowned Lantern's suite: the room and its tables, the walk and the slide, steps on wood, the flare and the oil, the shrines, Mother's wake and rise and the boat, each hunter's rule (the Lurker's hearing, lane and dash, the guardian and roaming wisps, the leeches at the light's edge and their bite, the bodies that take only the still, Mother's hand and its gaps), hearts, endless lives and the grade, the clock, determinism (no random drawn), the balance (a bot that ignores the hunters loses every shrine order, one that plays them wins each with hearts left), the rule tags and banner marks, the hums, voices and drawing | | `scripts/test-web-console-activities-ghoul-lantern.mjs` | The Drowned Lantern's suite: the room and its tables, the walk and the slide, steps on wood, the flare and the oil, the shrines, Mother's wake and rise and the boat, each hunter's rule (the Lurker's hearing, lane and dash, the guardian and roaming wisps, the leeches at the light's edge and their bite, the bodies that take only the still, Mother's hand and its gaps), hearts, endless lives and the grade, the clock, determinism (no random drawn), the balance (a bot that ignores the hunters loses every shrine order, one that plays them wins each with hearts left), the rule tags and banner marks, the hums, voices and drawing |
| `public/activities/ghoul-rush/draw/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-rush/draw/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-rush/core/ghoul-powers.js` | Ghoul Rush's power-ups and pickups (no imports: `ghoul.js` hands its rules a kit, `POWER_KIT`, of `landing` 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-rush/core/ghoul-powers.js` | Ghoul Rush's power-ups and pickups (no imports: `ghoul.js` hands its rules a kit, `POWER_KIT`, of `landing` 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 |
@@ -410,9 +448,12 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `public/sound.js` | the sound cues: which plays, one at a time, held until the first click | | `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/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/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/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, and an optional fourth `louder` (a game lifting its sounds as a whole, up to `LOUDER_MAX`, also the fifth argument of `hum()`), `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/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, bar, voices, patterns, order }`, `bar` the steps in a bar when it is not 16, so the track resumes on a bar start and each pattern is whole bars: 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. It also plays recorded **songs**: mp3s a game names under `songs` in its sfx file (a name to a served path, merged by `tones.js` as `SONG_TABLES`, listed by `songNames()`), asked for the same way, one `<audio>` element each made on first use, at `SONG_PEAK` times the volume, faded over `SONG_FADE_MS`; a song plays once, never looped, `music()` returning `"playing"` or `"ended"` (which the window's wrapper passes back to the game), `{ restart: true }` taking it back to the top with `load()` (no seeking, since the server sends no byte ranges), and a song no longer asked for fades and pauses where it was. 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-rush/sfx/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/snake-sfx.js` · `public/activities/flock-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-rush/sfx/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`, and `snake-sfx.js`, which merges `snake-music.js` as its `music`; `trails-sfx.js` and `flock-sfx.js` have `songs` instead of `music` |
| `public/activities/snake-music.js` | Snake's ten music tracks as data (no imports): `SNAKE_MUSIC`, `{ bpm, rush, voices, patterns, order }` each, named `snake<Place>` and listed in `MUSIC_TRACKS` in `snake.js`. A round deals them in a fresh order, one to each level, so a run hears a different track at every level and none twice. They were picked on the pages in `prototypes/music/snake` (rhythm-first folk and world tunes led by something plucked or reedy, mostly dark or modal), and their bars are not all sixteen steps: 6/8 is 12, 7/8 is 14, ten beats is 20, twelve beats is 24, each pattern a whole number of its bars; merged by `snake-sfx.js` |
| `public/activities/light-trails/1.mp3` to `5.mp3` | Light Trails' five background songs, named `trailsSong1` to `trailsSong5` under `songs` in `trails-sfx.js` and listed in `SERVABLE`; re-encoded for size with ffmpeg (80 kbps stereo MP3 at 44.1 kHz, loudness-normalized to -16 LUFS with `loudnorm`, metadata stripped), about 7.6 MB together, and copied into every skill with the rest of the console. The server leaves them out of its start-up cache warm |
| `public/activities/flock-dash/1.mp3` to `5.mp3` | Flock Dash's five background songs, named `flockSong1` to `flockSong5` under `songs` in `flock-sfx.js` and listed in `SERVABLE`; re-encoded for size with ffmpeg the way Light Trails' were (80 kbps stereo MP3 at 44.1 kHz, loudness-normalized to -16 LUFS with `loudnorm`, metadata stripped), about 6.4 MB together, and copied into every skill with the rest of the console. The server leaves them out of its start-up cache warm; `flock.js` deals all five in a fresh order each round with `dealMusic()`, plays each in full one after another and deals again after the last, never opening on the song that just ended |
| `public/activities/ghoul-rush/stages/graveyard/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-rush/stages/graveyard/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-rush/stages/grounds/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/activities/ghoul-rush/stages/grounds/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, and the page's shared full-screen picture preview (`openPicview`, the `#picview` dialog every thumbnail opens) | | `public/uploads.js` | pictures and documents attached to a note: chips, trays, re-encoding, upload, retry, and the page's shared full-screen picture preview (`openPicview`, the `#picview` dialog every thumbnail opens) |
@@ -421,7 +462,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `public/screens/cleanup.js` | User Preferences' Cleanup section, on the System tab | | `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/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/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/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. `loopEnd.can` accepts `ask` (`LOOP_CAN` in `patches.mjs`); the app adds it first to every stop that offers `resume`, and the stopped screen's **Ask a question** wakes an ordinary agent on the same session |
| `public/screens/docs.js` | documents: tabs, blocks, print and download, and the brief button | | `public/screens/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/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/git-host.js` | hosts the git board: tabs, panels and what each click sends |
@@ -432,6 +473,11 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `public/screens/agents/agents-list-editor.js` | the one row-list editor behind the three argument lists and the models list: `listEditor({list, kind, field, placeholder, addLabel, optionalName, aria, onChange})` draws `div.agent-rows` (a Remove per row, an Add that appends and focuses the new row, edits written into the live list) | | `public/screens/agents/agents-list-editor.js` | the one row-list editor behind the three argument lists and the models list: `listEditor({list, kind, field, placeholder, addLabel, optionalName, aria, onChange})` draws `div.agent-rows` (a Remove per row, an Add that appends and focuses the new row, edits written into the live list) |
| `public/screens/agents/agents-summary.js` | the agents view's collection side: `renderSummary(ctx)` draws the left column for both modes (prefs rows with found badges, the shipped templates under "Or start from a template" and the orchestrator placeholder; setup pick rows, badges and templates), `drawSummaryPane(ctx)` draws the right pane while nothing is open (empty text, a picked template's note and Use this template, or the picked setup entry's state area: Start, Use it from here, install lines), plus `BADGES`/`drawBadge` | | `public/screens/agents/agents-summary.js` | the agents view's collection side: `renderSummary(ctx)` draws the left column for both modes (prefs rows with found badges, the shipped templates under "Or start from a template" and the orchestrator placeholder; setup pick rows, badges and templates), `drawSummaryPane(ctx)` draws the right pane while nothing is open (empty text, a picked template's note and Use this template, or the picked setup entry's state area: Start, Use it from here, install lines), plus `BADGES`/`drawBadge` |
| `public/screens/agents/agents-form.js` | the agents view's per-agent form: `drawForm(ctx)` draws the detail pane (the built-in's Models fold, or an added agent's identity fields plus folded Models and Command-line arguments sections), `renderDirty(ctx)` toggles the Unsaved badge and Save/Discard; the foot (Save, Discard, Save anyway on 409, Delete with inline confirm), `input.invalid[data-field]` marking and the `FORM_FOCUSABLE` focus save/restore | | `public/screens/agents/agents-form.js` | the agents view's per-agent form: `drawForm(ctx)` draws the detail pane (the built-in's Models fold, or an added agent's identity fields plus folded Models and Command-line arguments sections), `renderDirty(ctx)` toggles the Unsaved badge and Save/Discard; the foot (Save, Discard, Save anyway on 409, Delete with inline confirm), `input.invalid[data-field]` marking and the `FORM_FOCUSABLE` focus save/restore |
| `public/screens/agents/agents-strengths.js` | the "Strengths in the loop" fold under Models in an agent's form: `strengthsFold(ctx, agentId, draft, { models, hasEffort })` maps Thrifty, Balanced and Best to one of the agent's own models (and an effort for Claude and Codex), shows untouched rows as shipped with a "default" tag and changed rows with Reset, and keeps only changed rows in `ctx.strengthDrafts` for the form's Save |
| `public/strengths.js` | the loop's strength rule, shared by the page and the server: `resolveStrengths` and `nextStrength`, held to `scripts/fixtures/strength-cases.json` (the Rust twin is in `models.rs`) |
| `strengths.mjs` | the server-side name for `public/strengths.js` (a re-export) |
| `strengths` key (`src/launcher/models.json`, `~/.plan2code/models.json`) | per agent, `thrifty`/`balanced`/`best` rows of `{model, effort?}`; a user row beats the shipped one, and a row whose model is not in the agent's Models list is ignored. `models.rs` `strengths_for` and the JS resolver are held to `scripts/fixtures/strength-cases.json` (change the fixture first, then both) |
| loop setup `phaseStrength` / `strengths` | `loop-setup.mjs` keeps the per-project toggle and, per spec folder, a list of `{n, name, strength}` picks, pruned as specs finish and phases move (twin: `LoopSetup` in `loop_driver.rs`). `loop_driver.rs` starts a phase with `AgentManager::start_phase_on(prompt, model, effort, env)` and sets `PLAN2CODE_LOOP_STRENGTH` (thrifty, balanced or best) in its environment, which `cmd-open.mjs` reads to give the phase's helpers the same Helper strength line; a retry goes one step up with `models::next_strength` (Rust twin of `nextStrength`; a Match my session phase stays) |
| `public/screens/setup.js` | the agent-less setup screen (`workflow === "setup"`, opened by `plan2code` or the app when no agent can run): the "No agent yet" headline, Planny's setup pose, the agent list from `mountAgentsView` in setup mode, Check again, and the "Starting <Label>..." pane after a Start send (`{i:"__start"}` via `/submit`). `setupMoved(url)` disarms the 2-minute no-page notice once the `move` event lands | | `public/screens/setup.js` | the agent-less setup screen (`workflow === "setup"`, opened by `plan2code` or the app when no agent can run): the "No agent yet" headline, Planny's setup pose, the agent list from `mountAgentsView` in setup mode, Check again, and the "Starting <Label>..." pane after a Start send (`{i:"__start"}` via `/submit`). `setupMoved(url)` disarms the 2-minute no-page notice once the `move` event lands |
| `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 picking another agent leaves an unsaved agent edit. Other screens reach it through `hooks` | | `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 picking another agent 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/starting.js` | the launching, starting and waiting screens, with Planny's poses |
@@ -462,6 +508,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `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/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/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/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/continue-button.js` | The one control that wakes a quiet agent. `continueButton(label, cls)` is a button asking the app for `agent-continue` (held off 4 s after a press); `reconnectOffer(cls)` is that button labeled **Reconnect to agent** under the app and, in a browser, a line telling the person to type `continue` in their terminal. Used by the status line (`screens/core.js`: the dashboard's quiet, launch-saved and way-home-saved lines), the Ask tab (`screens/ask.js`, left of Send while the red no-agent line shows) and the saved-and-waiting launch screen (`screens/starting.js`, app only; a browser reads the hint). |
| `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), `terminal-open` (the in-app **terminal** button, shown in place of the word in every What to check line while the app's terminal panel is collapsed: the app presses the panel's own Collapse/View button, and only when collapsed; the app tells the page the panel's state with `terminal-state` `{ collapsed }` on the page's `console-ready` and on every change, heard through `onAppMessage` into `page.terminalCollapsed`), `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/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), `terminal-open` (the in-app **terminal** button, shown in place of the word in every What to check line while the app's terminal panel is collapsed: the app presses the panel's own Collapse/View button, and only when collapsed; the app tells the page the panel's state with `terminal-state` `{ collapsed }` on the page's `console-ready` and on every change, heard through `onAppMessage` into `page.terminalCollapsed`), `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 | | `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 | | `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 |
@@ -484,7 +531,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `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 | | `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.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 | | `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 | | `notes/<workflow>.md` | per-workflow notes (`init` for both inits, `pathfinder` with Briefs, `plan`, `revise-plan`, `document`, `implement` for both builds, `loop` for a build the desktop app's Implementation Loop runs with `--loop` (where it reports a `loopOutcome` instead of asking for sign-off), `quick-task`, `review`, `finalize`, `handoff`, `changelog`, `git`, `xray`, `diagnose`, `pr-prep`, `test`). Each skill's Interface line reads `<D>/console.md` and its own notes file right after `open`; a test checks every skill names one that exists |
| `building.md` · `building-review.md` | the build half of the contract, for `implement`, `implement-review` and `quick-task`: progress posts (`agent.activity`, `agent.quietMinutes`, `file` blocks re-read with `refresh`), the chat check between tasks, questions mid-build and stop requests; `building-review.md` is the review run on the page (the sign-off's `review` verdict, **Review it now**, Implement + Review's Stage 2, Finalize's Step 2.5), read only when asked for | | `building.md` · `building-review.md` | the build half of the contract, for `implement`, `implement-review` and `quick-task`: progress posts (`agent.activity`, `agent.quietMinutes`, `file` blocks re-read with `refresh`), the chat check between tasks, questions mid-build and stop requests; `building-review.md` is the review run on the page (the sign-off's `review` verdict, **Review it now**, Implement + Review's Stage 2, Finalize's Step 2.5), read only when asked for |
Key design points: Key design points:
@@ -530,7 +577,7 @@ Key design points:
`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`. `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. - **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. - **Attachments on notes and quick questions live in `<sid>/uploads/`**, never in the project: images as `<uuid>.jpg`, documents as `<uuid>.<ext>` with `ext` from `DOC_TYPES` in `answers.js` (text, code, PDF). The browser re-encodes images to JPEG and sends raw bytes to `POST /upload` as `image/jpeg`; documents go as-is as `application/octet-stream`, the extension taken by `docExt()` from the uncut `x-p2c-name`. `readRaw(req, limit, cb)` in `routes.mjs` caps images at `MAX_BODY` (4 MB) and documents at `MAX_DOC_BYTES` (10 MB), and drains rather than destroys so the client gets its 413. Images need the `FF D8 FF` magic; documents pass `checkDocument()` in `sessions.mjs` (`%PDF-` for PDF, strict UTF-8 with no NUL for text), else 415. The server names the file with `crypto.randomUUID()`. `GET /uploads/<id>.<ext>` serves images as `image/jpeg` and documents under a fixed type (`application/pdf`, else `text/plain`) with `nosniff` and, on text, CSP `sandbox` (a sandboxed PDF cannot open in the viewer), so a browser can show but never run one; `recordSubmitted()` writes every send's note onto its item as `sentNote { at, text, images, files, suggest? }` (paths and names only; `suggest` only when the action's is exactly `true`, the **Ask for suggestions** chip, which always writes a thread entry, note or not, and is left out of the `submitted` event's `ids` so the card's staged pick stays), which `noteAwaiting()` in `answers.js` turns into the Sent box's attachment links and the Notes pane's pending note until the agent's next thread message; `DELETE /uploads/<id>.<ext>` takes any allowed extension; both stay contained under `uploads/`. `isOwnUpload()` returns the kind (`"image"` / `"file"` / `false`), and `attachmentsOk()` makes `/submit` comments and `/chat` messages carry images only in `images[]` and documents only in `files[]`, this session's uploads only, at most 5 together (`MAX_ATTACHMENTS`). A comment's `reply` gains one ` Image: <path> (<name>)` or ` File: <path> (<name>)` line per attachment, in attach order; a chat entry's lines come from `chatReplyLines()`, its images first, then its files. `sweepUploads()` bounds disk growth, and the session sweep removes the whole session a month after that. A note attachment a spec file cites is copied out first by `console.mjs keep` (`--session --upload --name --spec [--from]`): it checks both paths (the upload must sit under the session's `uploads/`, and the spec folder under `state.project`, real paths included, so a symlinked folder cannot carry the copy outside), copies with `COPYFILE_EXCL` and reuses an existing copy, prints `{ ok, path, link, image, reused }` with a forward-slash link relative to `--from`, and logs a `keep` event. It is the agent's hand, not the server's: it runs in the agent's shell only when the agent decides to cite a file, so the server still never writes into a project.
- **Answers carry their terminal token.** Each item ships `fallbackText` and `token`, so a click resolves to the literal word the prompt already expects (`approved`, `a`, `skip`). No workflow needs a second code path, and declining the console degrades to prose with nothing lost. - **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 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. - **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.
@@ -558,6 +605,7 @@ Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --build-
- **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. - **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. - **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. - **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.
- **Its logic tests pin the dice.** A game rolls `Math.random` for roads, spawns and layouts, and an unlucky roll once failed a test on CI at random (Ghoul Rush's Eye, Bounce Road twice). Import `./seed-random.mjs` FIRST in every `scripts/test-web-console-activities*.mjs` file: it seeds `Math.random` (set `PLAN2CODE_TEST_SEED` to try another roll), so a test sees the same world on every run.
## Status Line ## Status Line
@@ -616,4 +664,4 @@ On a terminal it first prints a Planny banner (`renderBanner()`). With more than
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. 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. **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 those (metrics and bot only when run from a git checkout), 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.
+1 -1
View File
@@ -28,7 +28,7 @@
- **PLAN-DRAFT confidence numbers are scraped by regex:** `collector.ts` scrapes the latest `specs/<feature>/PLAN-DRAFT-*.md` prose. Overall confidence falls back to prose only when `<!-- METRICS_JSON ... -->` lacks `confidence` (`collector.ts:186-196`): `Confidence: 95%`, or a table row `| Confidence | 95` with no `%`. The four *breakdown* patterns (`collector.ts:200-203`) run on every draft, METRICS_JSON or not: `/[Rr]equirements?[:\s|]+(\d{1,2})/` and its siblings match a bare dimension word followed by whitespace, a colon, or a pipe and then digits. So a PLAN-DRAFT written by anything other than `/plan2code-1-plan` Phase 7 must keep `Confidence` followed by a number (with `%`, or as a table row) **and** bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed by a number off the page — including innocent table rows like `| Requirements | 11 |`. Otherwise the metrics pipeline records a planning-step confidence that no planning step produced. `/plan2code-0-pathfinder` works around this by hyphenating the labels (`Requirements-clarity 22/25`), which breaks the character class. - **PLAN-DRAFT confidence numbers are scraped by regex:** `collector.ts` scrapes the latest `specs/<feature>/PLAN-DRAFT-*.md` prose. Overall confidence falls back to prose only when `<!-- METRICS_JSON ... -->` lacks `confidence` (`collector.ts:186-196`): `Confidence: 95%`, or a table row `| Confidence | 95` with no `%`. The four *breakdown* patterns (`collector.ts:200-203`) run on every draft, METRICS_JSON or not: `/[Rr]equirements?[:\s|]+(\d{1,2})/` and its siblings match a bare dimension word followed by whitespace, a colon, or a pipe and then digits. So a PLAN-DRAFT written by anything other than `/plan2code-1-plan` Phase 7 must keep `Confidence` followed by a number (with `%`, or as a table row) **and** bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed by a number off the page — including innocent table rows like `| Requirements | 11 |`. Otherwise the metrics pipeline records a planning-step confidence that no planning step produced. `/plan2code-0-pathfinder` works around this by hyphenating the labels (`Requirements-clarity 22/25`), which breaks the character class.
- **Web console result-handoff invariant:** `result.json` holds answers a person pressed Send on. **An uncollected result (no `consumedAt`) is never overwritten and never deleted.** `/submit` and `/cancel` return 409 while one is pending, `open` clears the file only when it is already consumed, and `wait` stamps `consumedAt` **after** printing the result, never before, and exits by setting `process.exitCode` rather than calling `process.exit()`. That ordering is deliberate: an agent harness that kills a long shell command must not be able to land between "marked collected" and "handed over", and `process.exit()` can truncate an unflushed pipe. A repeat delivery is recoverable, a lost one is not. Two separate data-loss bugs came from breaking this in different places, and both were silent: the person sees "Sent", the agent never receives it. Any new code path that touches `result.json` must preserve the invariant, and `scripts/test-web-console-lifecycle.mjs` guards it (its "result handoff (regressions)" tests). Related: the server writes each submitted answer onto its item as `submitted`, and `validate()` in `patches.mjs` must keep excluding that field from the completion-marker and metrics-scraper scans, which are meant for agent-authored text only. A person who typed `TASK_COMPLETE` into an answer would otherwise make every later patch unpostable. - **Web console result-handoff invariant:** `result.json` holds answers a person pressed Send on. **An uncollected result (no `consumedAt`) is never overwritten and never deleted.** `/submit` and `/cancel` return 409 while one is pending, `open` clears the file only when it is already consumed, and `wait` stamps `consumedAt` **after** printing the result, never before, and exits by setting `process.exitCode` rather than calling `process.exit()`. That ordering is deliberate: an agent harness that kills a long shell command must not be able to land between "marked collected" and "handed over", and `process.exit()` can truncate an unflushed pipe. A repeat delivery is recoverable, a lost one is not. Two separate data-loss bugs came from breaking this in different places, and both were silent: the person sees "Sent", the agent never receives it. Any new code path that touches `result.json` must preserve the invariant, and `scripts/test-web-console-lifecycle.mjs` guards it (its "result handoff (regressions)" tests). Related: the server writes each submitted answer onto its item as `submitted`, and `validate()` in `patches.mjs` must keep excluding that field from the completion-marker and metrics-scraper scans, which are meant for agent-authored text only. A person who typed `TASK_COMPLETE` into an answer would otherwise make every later patch unpostable.
- **Web console oversized bodies:** `readBody()` and `readRaw()` (the `POST /upload` reader) in `routes.mjs` drain the rest of the body past `MAX_BODY` instead of calling `req.destroy()`, so an oversized body gets a 413 rather than a connection reset, and memory still stays capped. A new body reader must drain the same way. - **Web console oversized bodies:** `readBody()` and `readRaw()` (the `POST /upload` reader) in `routes.mjs` drain the rest of the body past `MAX_BODY` instead of calling `req.destroy()`, so an oversized body gets a 413 rather than a connection reset, and memory still stays capped. A new body reader must drain the same way.
- **Web console commands are tied to the directory `open` ran in:** `console.mjs` finds a running server through a handle file under a hash of the project directory (`handleFile(project, sid)` → `runtimeDirFor(project)` → `<RUNTIME_DIR>/<cwdHash(project)>/<sid>.json` in `sessions.mjs`, with `RUNTIME_DIR` = `os.tmpdir()/plan2code-console`, or `$PLAN2CODE_CONSOLE_HOME/runtime`), and the project is the working directory of `open` / `open --resume`. Run `status`, `chat`, `wait` and `stop` from that same directory. From anywhere else `status` says `live: false`, `chat` / `wait` report `server-gone` (exit 20) and `stop` stops nothing, while the server is in fact still running. It is easy to mistake for a crash when a scratch session is opened from the repo and then driven from its session folder; check `server.log` and `events.ndjson` (a real exit writes an `exit` event or a stack) before chasing one. - **Web console commands are tied to the directory `open` ran in:** `console.mjs` finds a running server through a handle file under a hash of the project directory (`handleFile(project, sid)` → `runtimeDirFor(project)` → `<RUNTIME_DIR>/<cwdHash(project)>/<sid>.json` in `sessions.mjs`, with `RUNTIME_DIR` = `os.tmpdir()/plan2code-console` (`-<uid>` on Linux and macOS, a 0700 folder with 0600 handles), or `$PLAN2CODE_CONSOLE_HOME/runtime`), and the project is the working directory of `open` / `open --resume`. Run `status`, `chat`, `wait` and `stop` from that same directory. From anywhere else `status` says `live: false`, `chat` / `wait` report `server-gone` (exit 20) and `stop` stops nothing, while the server is in fact still running. It is easy to mistake for a crash when a scratch session is opened from the repo and then driven from its session folder; check `server.log` and `events.ndjson` (a real exit writes an `exit` event or a stack) before chasing one.
- **Windows temp paths in web console tests:** `os.tmpdir()` can be an 8.3 short path (`C:\Users\JUSTIN~1.PAR\...`), while `server.mjs` canonicalizes its session dir with `fs.realpathSync.native` to the long form. Any test comparing a server-returned path (e.g. an upload's `path`) against the test's `session` must pass the test side through `fs.realpathSync.native()` first, and compare case-insensitively on Windows. - **Windows temp paths in web console tests:** `os.tmpdir()` can be an 8.3 short path (`C:\Users\JUSTIN~1.PAR\...`), while `server.mjs` canonicalizes its session dir with `fs.realpathSync.native` to the long form. Any test comparing a server-returned path (e.g. an upload's `path`) against the test's `session` must pass the test side through `fs.realpathSync.native()` first, and compare case-insensitively on Windows.
- **Web console assets:** `computeExpectedSkills()` copies references as `Buffer`s, so binary files are fine. Adding a `public/` file needs the three edits in Architecture → Web Console. The vendored `marked.esm.js` sha256 is in `.readme/web-console.md`. - **Web console assets:** `computeExpectedSkills()` copies references as `Buffer`s, so binary files are fine. Adding a `public/` file needs the three edits in Architecture → Web Console. The vendored `marked.esm.js` sha256 is in `.readme/web-console.md`.
- **The default highlight color lives in two places:** changing it means editing `DEFAULT_ACCENT` in `public/palette.js` and the light, system-dark and explicit-dark `--accent*` values in `public/styles/tokens.css`. No test ties them together. - **The default highlight color lives in two places:** changing it means editing `DEFAULT_ACCENT` in `public/palette.js` and the light, system-dark and explicit-dark `--accent*` values in `public/styles/tokens.css`. No test ties them together.
+2 -1
View File
@@ -76,6 +76,7 @@ The full `npm test` takes minutes and drives a browser per page suite. When a ch
| The launcher (`src/launcher/`) | `node --test scripts/test-launcher.mjs` | | The launcher (`src/launcher/`) | `node --test scripts/test-launcher.mjs` |
| A skill's script | `npm run build:skills`, then `node --test scripts/test-script-<skill>.mjs` (and `test-skill-scripts.mjs` for the shared plumbing) | | A skill's script | `npm run build:skills`, then `node --test scripts/test-script-<skill>.mjs` (and `test-skill-scripts.mjs` for the shared plumbing) |
| A workflow prompt (`src/plan2code-*.md`) | `node scripts/validate-char-count.js` and `node scripts/check-skill-table.mjs` | | A workflow prompt (`src/plan2code-*.md`) | `node scripts/validate-char-count.js` and `node scripts/check-skill-table.mjs` |
| A new skill or console workflow | First update the hand-written tables that list every workflow: the `SUBAGENT_WORKFLOWS` count and the meter's `WEIGHTS`, `LAUNCH_LABELS` and `RUN_LABELS` in `test-web-console-logic.mjs`, `notesFor` in `test-web-console-speed.mjs`, the event list in `src/web-console/console-meter.md` (checked by `test-web-console-chat-stress.mjs`) and a `BUDGETS.notes` entry in `test-console-wire-budgets.mjs`. Then run those four suites plus `test-web-console-skills.mjs` and `test-web-console-spec-states.mjs`; the PR Prep and Test build missed all five tables and only the full suite caught them |
| Docs or comments only | `node --test scripts/test-us-english.mjs scripts/test-line-endings.mjs` | | Docs or comments only | `node --test scripts/test-us-english.mjs scripts/test-line-endings.mjs` |
Run the full `npm test` when the change touches something many suites lean on: `web-console-test-helpers.mjs` or `page-test-helpers.mjs`, `looks.js` / `prefs.js` / `static.mjs` (the `SERVABLE` list), `skills.js`, `install.js`, the server's shared modules (`console.mjs`, `routes.mjs`); after a sync merge or a version bump; before opening a PR or cutting a release; and whenever you cannot say which suites a change reaches. Run the full `npm test` when the change touches something many suites lean on: `web-console-test-helpers.mjs` or `page-test-helpers.mjs`, `looks.js` / `prefs.js` / `static.mjs` (the `SERVABLE` list), `skills.js`, `install.js`, the server's shared modules (`console.mjs`, `routes.mjs`); after a sync merge or a version bump; before opening a PR or cutting a release; and whenever you cannot say which suites a change reaches.
@@ -125,7 +126,7 @@ The root `npm test` does not run the metrics or bot vitest suites; run them in t
|------|--------| |------|--------|
| `--build-skills` | Regenerate `skills/` from `src/`, pruning stale skills and reference files | | `--build-skills` | Regenerate `skills/` from `src/`, pruning stale skills and reference files |
| `--verify-skills` | Diff local `skills/` against `src/`; exits 1 on drift. Diagnostic only, the installer rebuilds anyway | | `--verify-skills` | Diff local `skills/` against `src/`; exits 1 on drift. Diagnostic only, the installer rebuilds anyway |
| `--update` | No menu: reinstall what `~/.plan2code/install.json` lists (skills, launcher, statusline, metrics, bot), never uninstalling; with no record, the skills and the `plan2code` command. `plan2code update` runs it through npx | | `--update` | No menu: reinstall what `~/.plan2code/install.json` lists (skills, launcher, app, statusline; metrics and bot only when run from a git checkout, since they run from the install folder, which npx's cache is not), never uninstalling; with no record, the skills and the `plan2code` command. `plan2code update` runs it through npx |
## How the Installer Works ## How the Installer Works
@@ -21,7 +21,7 @@ Run from the repo root (the folder holding `install.js` and `src/launcher/`). Ru
### Step 2 — Read the current files ### Step 2 — Read the current files
Read `src/launcher/models.json`. It has four keys: `_note` (a string), `claude`, `devin` and `codex` (each an array of `{ "id", "label" }`; `codex` is empty today, because Codex's docs name no models to verify and the launcher skips the model question for it). Keep the `_note` text exactly as read — Step 9 writes it back verbatim and the Validation rules check it. Read `src/launcher/models.json`. It has five keys: `_note` (a string), `claude`, `devin` and `codex` (each an array of `{ "id", "label" }`) and `strengths` (an object, see Step 4c). Keep the `_note` text exactly as read — Step 9 writes it back verbatim and the Validation rules check it.
Read `src/launcher/agents.json`. It has `schema` (currently `1`) and `agents`, a list of entries. Each entry carries `id`, `name`, `kind` (`builtin` or `template`), `command`, `prompt`, `args`, `bypassArgs`, `modelArgs`, and optional `note`. A `builtin` entry also carries `installUrl`, `install` (lists under `win`, `mac` and `linux`, each `{ label, run, note? }`) and `installDirs` (the same OS keys). Keep the file's shape and order exactly as read. Read `src/launcher/agents.json`. It has `schema` (currently `1`) and `agents`, a list of entries. Each entry carries `id`, `name`, `kind` (`builtin` or `template`), `command`, `prompt`, `args`, `bypassArgs`, `modelArgs`, and optional `note`. A `builtin` entry also carries `installUrl`, `install` (lists under `win`, `mac` and `linux`, each `{ label, run, note? }`) and `installDirs` (the same OS keys). Keep the file's shape and order exactly as read.
@@ -49,6 +49,10 @@ If the lookup fails or the page does not list aliases, say so, and switch to **g
Look up Codex's current model documentation (locate it on each run). Propose `codex` entries only for model ids the docs name explicitly. If they name none, say so and leave `codex` empty. If entries are added, the `_note` sentence about Codex goes stale; keep `_note` verbatim as everywhere else, but tell the maintainer so they can reword it by hand. If the lookup fails, use guided manual edits as in Step 3. Look up Codex's current model documentation (locate it on each run). Propose `codex` entries only for model ids the docs name explicitly. If they name none, say so and leave `codex` empty. If entries are added, the `_note` sentence about Codex goes stale; keep `_note` verbatim as everywhere else, but tell the maintainer so they can reword it by hand. If the lookup fails, use guided manual edits as in Step 3.
### Step 4c: Check the strengths mapping
`models.json` also has a top-level `strengths` object: for an agent id, the loop's `thrifty`, `balanced` and `best` words, each `{ "model", "effort"? }`. After Steps 3 to 4b settled the refreshed lists, check that every `strengths` row still names a `model` that is in that agent's refreshed list (an `effort` is kept only for an agent that takes one, and is `low`, `medium` or `high`). For a row whose model is **gone**, propose a replacement from the same family, one step lighter or stronger as the word implies (Thrifty lighter, Best stronger), and show it in Step 7's table as a `strengths.<agent>.<word>` change. Never add a mapping for an agent that has none: only agents already under `strengths` are checked.
### Step 5: Re-check the agent list against vendor docs ### Step 5: Re-check the agent list against vendor docs
For each entry in `agents.json`, locate the vendor's current install documentation on each run (search for it; do not use a remembered URL, since docs move and `installUrl` itself may be stale). Compare the file against what the docs say today: For each entry in `agents.json`, locate the vendor's current install documentation on each run (search for it; do not use a remembered URL, since docs move and `installUrl` itself may be stale). Compare the file against what the docs say today:
@@ -136,6 +140,7 @@ Check every rule before `npm test` (Step 10). They mirror the shipped-file tests
- Every entry in `claude`, `devin` and `codex` has a non-empty string `id` and a non-empty string `label`. - Every entry in `claude`, `devin` and `codex` has a non-empty string `id` and a non-empty string `label`.
- Ids are unique within each list, and labels are unique within each list. - Ids are unique within each list, and labels are unique within each list.
- No Devin id ends in `xhigh`, `max`, `fast` or `priority`. - No Devin id ends in `xhigh`, `max`, `fast` or `priority`.
- Every `strengths` row names a `model` that is in that agent's list in the same file, uses only the words `thrifty`, `balanced` and `best`, and no agent other than the ones already under `strengths` gains a mapping.
**`agents.json`:** **`agents.json`:**
+104 -3
View File
@@ -4,15 +4,80 @@ on:
push: push:
branches: [main] branches: [main]
pull_request: pull_request:
types: [opened, synchronize, reopened, labeled]
# Run the full three-system matrix by hand on any branch.
workflow_dispatch:
permissions:
contents: read
# A newer push to a pull request replaces its still-running checks. A push to main always
# finishes, so a merged change is never left half checked.
concurrency:
group: app-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# Speed: a pull request runs on Ubuntu only (the cheapest runner) unless it carries the
# `full-matrix` label; pushes to main and manual runs use all three systems. A change that
# touches only the website, the README, the changelog or similar skips the heavy jobs and runs
# the fast `prose` job instead, which keeps the checks that read those files.
jobs: jobs:
changes:
name: changes
runs-on: ubuntu-latest
outputs:
code: ${{ steps.diff.outputs.code }}
steps:
- uses: actions/checkout@v4.2.2
with:
fetch-depth: 0
- id: diff
shell: bash
run: |
set -euo pipefail
case "${{ github.event_name }}" in
pull_request) base="${{ github.event.pull_request.base.sha }}" ;;
push) base="${{ github.event.before }}" ;;
*) base="" ;;
esac
# A manual run, a new branch or a base git cannot find: run everything.
if [ -z "$base" ] || [ "$base" = "0000000000000000000000000000000000000000" ] || ! git cat-file -e "$base^{commit}" 2>/dev/null; then
echo "code=true" >> "$GITHUB_OUTPUT"
exit 0
fi
files="$(git diff --name-only "$base" HEAD)"
echo "Changed files:"; echo "$files"
# .readme/, AGENTS.md and .agents-docs/ are read by tests, so they count as code.
if [ -n "$files" ] && ! echo "$files" | grep -qvE '^(docs/|prototypes/|README\.md$|CHANGELOG\.md$|QUICK-REFERENCE\.md$|LICENSE$)'; then
echo "code=false" >> "$GITHUB_OUTPUT"
else
echo "code=true" >> "$GITHUB_OUTPUT"
fi
prose:
name: prose checks
needs: changes
if: needs.changes.outputs.code == 'false'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4.2.2
- uses: actions/setup-node@v4.4.0
with:
node-version: 20
- name: Versions agree
run: node scripts/check-versions.mjs
- name: Spelling, install command in the docs, line endings
run: node --test scripts/test-us-english.mjs scripts/test-getting-started.mjs scripts/test-line-endings.mjs scripts/test-check-versions.mjs
app: app:
name: app (${{ matrix.os }}) name: app (${{ matrix.os }})
needs: changes
if: needs.changes.outputs.code == 'true'
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
os: [windows-latest, macos-latest, ubuntu-latest] os: ${{ fromJSON(github.event_name == 'pull_request' && !contains(github.event.pull_request.labels.*.name, 'full-matrix') && '["ubuntu-latest"]' || '["windows-latest","macos-latest","ubuntu-latest"]') }}
defaults: defaults:
run: run:
working-directory: plan2code-app working-directory: plan2code-app
@@ -40,11 +105,29 @@ jobs:
key: cargo-${{ runner.os }}-${{ hashFiles('plan2code-app/Cargo.lock') }} key: cargo-${{ runner.os }}-${{ hashFiles('plan2code-app/Cargo.lock') }}
restore-keys: | restore-keys: |
cargo-${{ runner.os }}- cargo-${{ runner.os }}-
- name: Name this week for the apt cache
if: runner.os == 'Linux'
id: week
run: echo "week=$(date +%G-%V)" >> "$GITHUB_OUTPUT"
- name: Cache the Linux system packages
# The WebKit packages are hundreds of MB, and the runner's Ubuntu mirror is sometimes
# slow (one download took 7 minutes), so keep the downloaded .deb files. The key rolls
# over weekly so versions do not go stale; an older week still restores what it can.
if: runner.os == 'Linux'
uses: actions/cache@v6.1.0
with:
path: ~/apt-archives
key: apt-tauri-${{ runner.os }}-${{ steps.week.outputs.week }}
restore-keys: |
apt-tauri-${{ runner.os }}-
- name: Install Linux system packages - name: Install Linux system packages
if: runner.os == 'Linux' if: runner.os == 'Linux'
run: | run: |
mkdir -p "$HOME/apt-archives/partial"
sudo apt-get update sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev build-essential libxdo-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev xvfb sudo apt-get -o Dir::Cache::archives="$HOME/apt-archives" install -y libwebkit2gtk-4.1-dev build-essential libxdo-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev xvfb
# apt ran as root: hand the folder back so the cache step can read and save it.
sudo chown -R "$(id -u):$(id -g)" "$HOME/apt-archives"
- name: Install the app's packages - name: Install the app's packages
run: npm ci run: npm ci
- name: Vendor the xterm files cargo needs - name: Vendor the xterm files cargo needs
@@ -87,15 +170,33 @@ jobs:
node-tests: node-tests:
name: npm test (${{ matrix.os }}) name: npm test (${{ matrix.os }})
needs: changes
if: needs.changes.outputs.code == 'true'
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
os: [windows-latest, macos-latest, ubuntu-latest] os: ${{ fromJSON(github.event_name == 'pull_request' && !contains(github.event.pull_request.labels.*.name, 'full-matrix') && '["ubuntu-latest"]' || '["windows-latest","macos-latest","ubuntu-latest"]') }}
steps: steps:
- uses: actions/checkout@v4.2.2 - uses: actions/checkout@v4.2.2
- uses: actions/setup-node@v4.4.0 - uses: actions/setup-node@v4.4.0
with: with:
node-version: 20 node-version: 20
- name: Cache the npm downloads
# setup-node's own cache needs a tracked lockfile and the root has none, so cache npm's
# download folder directly (both places it lives: Linux and macOS, then Windows).
uses: actions/cache@v6.1.0
with:
path: |
~/.npm
~/AppData/Local/npm-cache
key: npm-${{ runner.os }}-${{ hashFiles('package.json', 'plan2code-metrics/package.json') }}
restore-keys: |
npm-${{ runner.os }}-
- run: npm install - run: npm install
- run: npm test - run: npm test
- name: Metrics tests
working-directory: plan2code-metrics
run: |
npm install
npm test
+13 -1
View File
@@ -14,8 +14,16 @@ on:
push: push:
tags: ['v*'] tags: ['v*']
# Read-only by default: the build jobs run dependency install scripts and build scripts, so
# only the publish job holds a write token.
permissions: permissions:
contents: write contents: read
# A release published after its tag push starts a second run for the same tag: queue it behind
# the first so two builds never upload over each other.
concurrency:
group: release-app-${{ github.event.release.tag_name || github.ref_name }}
cancel-in-progress: false
jobs: jobs:
build: build:
@@ -34,6 +42,8 @@ jobs:
shell: bash shell: bash
steps: steps:
- uses: actions/checkout@v4.2.2 - uses: actions/checkout@v4.2.2
with:
persist-credentials: false
- uses: actions/setup-node@v4.4.0 - uses: actions/setup-node@v4.4.0
with: with:
node-version: 22 node-version: 22
@@ -83,6 +93,8 @@ jobs:
name: attach to the release name: attach to the release
needs: build needs: build
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions:
contents: write
env: env:
GH_TOKEN: ${{ github.token }} GH_TOKEN: ${{ github.token }}
TAG: ${{ github.event.release.tag_name || github.ref_name }} TAG: ${{ github.event.release.tag_name || github.ref_name }}
+76 -29
View File
@@ -76,6 +76,10 @@ Scroll down for the utilities. Outside a git repository the **Git** card says so
- **An example you can accept.** Where a question comes with one, an *Autofill - **An example you can accept.** Where a question comes with one, an *Autofill
suggestion* button puts it in the box as a real answer for you to edit. It suggestion* button puts it in the box as a real answer for you to edit. It
disappears as soon as you have typed anything of your own. disappears as soon as you have typed anything of your own.
- **Ask for suggestions.** Unsure on a question with options to pick? The
*Ask for suggestions* button in the notes panel asks Plan2Code what it would
pick and why, and the answer comes back in the same panel. Anything you have
already ticked stays as it is.
- **Answers you have settled read as answers**, not as a form you might still be - **Answers you have settled read as answers**, not as a form you might still be
able to change: what you chose, stated in words, with everything else locked. able to change: what you chose, stated in words, with everything else locked.
- **A question you have sent is held** until Plan2Code answers it, showing - **A question you have sent is held** until Plan2Code answers it, showing
@@ -524,8 +528,8 @@ working in.
### Activities ### Activities
The **die** in the top bar, right of the megaphone, opens **Activities**: small The **die** in the top bar, right of the megaphone, opens **Activities**: small
games to play while you wait, say through a long build. Twelve ship today, games to play while you wait, say through a long build. Thirteen ship today,
**Snake**, **Mini golf**, **Light Trails**, **Bug Hunt**, **Sunset Drive**, **Stack Deploy**, **Bumper Ring**, **Rapids Run**, **Hot Potato**, **Crossing Rush**, **Bounce Road** and **Ghoul Rush**. The window opens on a **Snake**, **Mini golf**, **Light Trails**, **Bug Hunt**, **Sunset Drive**, **Stack Deploy**, **Bumper Ring**, **Rapids Run**, **Hot Potato**, **Crossing Rush**, **Bounce Road**, **Ghoul Rush** and **Flock Dash**. The window opens on a
**picker**: a card per game with a small cover scene, a line about it, its best **picker**: a card per game with a small cover scene, a line about it, its best
score, and a **Last played** tag on the one you played last, which also has the score, and a **Last played** tag on the one you played last, which also has the
focus. Click a card (or walk the cards with the arrows and press space or focus. Click a card (or walk the cards with the arrows and press space or
@@ -542,14 +546,17 @@ rivers, wind, light-cycle drones and the moans of nearby monsters run for as lon
the moment lasts, and crashes, splashes, explosions, pickups, combos, bosses, the moment lasts, and crashes, splashes, explosions, pickups, combos, bosses,
new bests and game over each get a sound of their own. A game can play new bests and game over each get a sound of their own. A game can play
chiptune music too, made the same way, which builds as play heats up (Sunset chiptune music too, made the same way, which builds as play heats up (Sunset
Drive has a song for each road, Ghoul Rush a track for each room, played at Drive has a song for each road, Snake a different one at every level, dealt from ten at
one steady level and fuller in a boss fight): turn on **Play game music** in **User Preferences → Sounds & the start of a round so none repeats, and Ghoul Rush a track for each room, played at
activities** (it starts off). **Play game sounds** there turns the games' one steady level and fuller in a boss fight), and Light Trails and Flock Dash play five
recorded songs each as background music, each in full, one after another in an
order shuffled for every run: turn on **Play activity music** in **User
Preferences → Sounds & activities** (it starts off). **Play activity sounds** there turns the games'
sounds (the 3, 2, 1 and the new-best burst included) and their music on or sounds (the 3, 2, 1 and the new-best burst included) and their music on or
off and leaves the page's own cues alone; the **Play sounds** switch above it off and leaves the page's own cues alone; the **Play sounds** switch above it
silences all of it, and a paused or closed game goes quiet at once. A game silences all of it, and a paused or closed game goes quiet at once. A game
with music has its own **Music** slider beside **Full screen**, which sets that with music has its own **Music** slider beside **Full screen**, which sets that
game's music volume and is remembered per game (Sunset Drive starts at 70, game's music volume and is remembered per game (Snake, Light Trails, Sunset Drive and Flock Dash start at 70,
Ghoul Rush at 65). Ghoul Rush at 65).
- **Snake** speeds up as it grows: 120 ms a step at its starting three cells, - **Snake** speeds up as it grows: 120 ms a step at its starting three cells,
@@ -640,25 +647,36 @@ Ghoul Rush at 65).
star eye, and one to three rivals each leave a glowing wall behind; a wall, a star eye, and one to three rivals each leave a glowing wall behind; a wall, a
trail (yours too), a crystal or another rider's head is out, and a rival's trail (yours too), a crystal or another rider's head is out, and a rival's
trail goes once it has faded. You get a split second of grace: about to trail goes once it has faded. You get a split second of grace: about to
ride into something, you hold in place for 150 ms first, and a turn pressed ride into something, you hold in place for 190 ms first, and a turn pressed
then rides out of it (the rivals get none). Arrows steer and space spends a **boost** then rides out of it (the rivals get none). Arrows steer and space spends a **boost**
charge for 1.4 seconds of speed (two charges a heat, up to three). A round charge for 1.4 seconds of speed (two charges a heat, up to three). A round
is a run of heats through nine arenas, each with its own scenery: Neon Grid, is a run of heats through nine arenas, each with its own scenery: Neon Grid,
Sunset Strip, Crystal Field, Warp Zone, Storm Front, Carnival, Glacier, Sunset Strip, Crystal Field, Warp Zone, Storm Front, Carnival, Glacier,
Volcano and the Golden Arena. Winning a heat moves you to the next arena; a Volcano and the Golden Arena. Winning a heat moves you to the next arena; a
crash costs one of your three lives and runs the heat again, and you and the crash costs one of your five lives and runs the heat again, and you and the
last rival out at once is a draw that costs nothing. Each arena brings last rival out at once is a draw that costs nothing. Every 750 points gives
something: a second rival and **power-up pads** at 2 (**Boost**, a charge; a life back (up to nine). Each arena brings something: a second rival and
**Phase**, ride through trails for 3 seconds; **Eraser**, wipes the trails **power-up pads** at 2 (**Boost**, a charge; **Phase**, ride through trails
around you; **Slow-mo**, the rivals crawl; coins; and from arena 4 a for 3 seconds; **Eraser**, wipes the trails around you; **Slow-mo**, the
**1UP**), **crystals** at 3, a third rival and a pair of **portals** at 4, rivals crawl; coins; a beating **Heart**, a life; and a **Shield**, held
**closing walls** at 5 (from 10 seconds in, the outer ring turns to stone from heat to heat until it takes a crash for you, wiping the trails around
every 3.5 seconds, flashing red first), and a second pair of portals at 6. you and riding on), **crystals** at 3 with a **Laser** (for 6 seconds it
The rivals ride sharper each arena, and grab a pad if they get there first. fires at any rival head in your line up to 16 cells ahead, cutting through
Points come for riding (a point a level every 6 cells), for each rival out trails but not crystals, three shots, each a rival out with the cut bonus)
while you still ride (10 a level, 5 more when it hit your trail), coins and and **Score x2** (8 seconds of double points), a third rival and a pair of
each heat won (25 a level). The start and end screens show the furthest **portals** at 4 with a **Wide Trail** (4 seconds of a wall three cells
arena you have reached and the next one waiting. across; you can turn onto the side cells you have just laid, so a corner
never crashes you) and **Coin Rain** (seven coins over the board), **closing walls**
at 5 (from 10 seconds in, the outer ring turns to stone every 3.5 seconds,
flashing red first) with a **Hyperjump** (straight out to the most open
space on the board), and at 6 a second pair of portals and a rainbow
**Mystery** pad that turns into any of the others. The first pad of each
kind in a run says it is new. The rivals ride sharper each arena, and grab
a pad if they get there first. Points come for riding (a point a level
every 6 cells), for each rival out while you still ride (10 a level, 5 more
when your trail or laser got it), coins and each heat won (25 a level). The
start and end screens show the furthest arena you have reached and the
next one waiting.
- **Bug Hunt** is an arcade shooter. Planny's ship slides along the bottom - **Bug Hunt** is an arcade shooter. Planny's ship slides along the bottom
(left and right move it, up and down a little too) and fires while space is (left and right move it, up and down a little too) and fires while space is
held. Each wave of bugs swoops in from the sides into a formation that sways held. Each wave of bugs swoops in from the sides into a formation that sways
@@ -982,8 +1000,12 @@ Ghoul Rush at 65).
and out of each boss's room you **choose the next stage** from two and out of each boss's room you **choose the next stage** from two
(one, once a single stage is left) never played that run, each card (one, once a single stage is left) never played that run, each card
showing the stage with its boss standing in it: left and right pick one showing the stage with its boss standing in it: left and right pick one
out, space or up goes in. Clear every stage and you **escape**, a win. out, space or up goes in. Clear six stages and the run takes you back to
Each stage cleared makes the next quicker and tougher. Every other room keeps a **horde** **Marrow Manor** for the finale, a fight against **the house itself**: on its
front lawn, shoot out every lit window, the only part of it that can be hurt,
while it throws its roof, its carpet and its fence at you, and calls down
lightning and sends crows out of its door the moment you climb the oak. Kill it and you
**escape**, a win. Each stage cleared makes the next quicker and tougher. Every other room keeps a **horde**
pouring in from the edges of the view, mostly ahead, so standing still is pouring in from the edges of the view, mostly ahead, so standing still is
never safe. **Zombies** shamble out of doors in the wall and sprint once never safe. **Zombies** shamble out of doors in the wall and sprint once
you are close, **crawlers** drag themselves up through loose boards, you are close, **crawlers** drag themselves up through loose boards,
@@ -1409,6 +1431,22 @@ Ghoul Rush at 65).
room starts again after a loss (a hit, a fall or the clock), a random room starts again after a loss (a hit, a fall or the clock), a random
power-up shimmers a few steps ahead of Planny on every restart until you power-up shimmers a few steps ahead of Planny on every restart until you
clear the room (never a 1UP, and not in the bonus rides). clear the room (never a 1UP, and not in the bonus rides).
- **Flock Dash** is a side-scrolling flight through a sunset sky, with Planny
as the lead bird. Hold up or down to climb and dive within a band in the
left part of the sky, and left or right to ease forward or back. Strays
drift in from the right; fly into one and it joins the flock, which
follows the exact path you flew, each bird a set distance behind the one
before. Balloons, gusts, slipstreams, storm clouds and kites are in the
way: a hit on the leader costs one of three lives, and a hit on the line
snaps it there, scattering the birds behind (fly back through them within
3 seconds or they are gone). Eight stages, each faster than the last,
each end at a jet stream portal: with enough birds the flock forms a V
and pays a bonus, and the final portal moves. Tailwind, shield and magnet
crates help, pickups in quick succession build a combo of up to x5, and a
stage with no snap and no bird lost pays a flawless bonus. Five recorded
songs play as background music in a shuffled order. The end screen's nudge
to play again names the next hazard or stage you have yet to reach, and the
furthest stage you reached is kept privately.
- **It never hides your turn.** A new question, a sign-off or a finish pauses - **It never hides your turn.** A new question, a sign-off or a finish pauses
the game at once and shows a banner with **Go to it**, which closes the window the game at once and shows a banner with **Go to it**, which closes the window
on that question, and **Unpause game**. While that banner is up, only on that question, and **Unpause game**. While that banner is up, only
@@ -1437,10 +1475,10 @@ Ghoul Rush at 65).
P or Esc during the count pauses again. P or Esc during the count pauses again.
- **Keys.** Arrows or W/A/S/D steer, space starts and plays (and boosts in - **Keys.** Arrows or W/A/S/D steer, space starts and plays (and boosts in
Light Trails, fires while held in Bug Hunt, burns nitro in Sunset Drive, Light Trails, fires while held in Bug Hunt, burns nitro in Sunset Drive,
where held up drives and held down brakes, drops the block in Stack Deploy, dashes in Bumper Ring, where held arrows push, fires while held in Rapids Run, where held up speeds up and held down slows, dashes in Hot Potato, where held arrows run, uses the oldest pickup in Crossing Rush, where an arrow hops once a press, jumps once a press in Bounce Road, where held up drives and held down brakes, and fires while held in Ghoul Rush, where held arrows run, up jumps once a press and down drops through a shelf), P pauses, R starts the round over (from the 3, 2, 1), F (or **Full screen** under the board) gives the game the whole screen and F or Esc puts it back, and Esc closes the window with the game paused. In full screen the board takes the whole screen, as big as its shape allows, with black bars where the shape leaves room, and a panel (the game's name, the score line, the game's **Music** slider for a game with music, Exit full screen) is laid over it: docked in the side bar when that bar is at least 220 px wide, in the bottom bar on a tall screen when that is at least 110 px tall, and otherwise floating in the top right corner (Sunset Drive's 16:9 board on a 16:9 screen), where it shrinks to the score line in the bottom right corner while a round plays and the pointer is still. The board never gives up room for the panel. The pointer hides after two still seconds. In the desktop app the page asks the app (`activities-full`) to lay the console over its bar and terminal and put the window in full screen, since the app's frame allows the page no full screen of its own. A question, a sign-off or a finish takes a full-screen game back to the window's own size as it pauses it. A page with no mouse or trackpad where held up drives and held down brakes, drops the block in Stack Deploy, dashes in Bumper Ring, where held arrows push, fires while held in Rapids Run, where held up speeds up and held down slows, dashes in Hot Potato, where held arrows run, uses the oldest pickup in Crossing Rush, where an arrow hops once a press, jumps once a press in Bounce Road, where held up drives and held down brakes, fires while held in Ghoul Rush, where held arrows run, up jumps once a press and down drops through a shelf, and climbs and dives in Flock Dash, where held up and down fly the leader and held left and right ease forward and back), P pauses, R starts the round over (from the 3, 2, 1), F (or **Full screen** under the board) gives the game the whole screen and F or Esc puts it back, and Esc closes the window with the game paused. In full screen the board takes the whole screen, as big as its shape allows, with black bars where the shape leaves room, and a panel (the game's name, the score line, the game's **Music** slider for a game with music, Exit full screen) is laid over it: docked in the side bar when that bar is at least 220 px wide, in the bottom bar on a tall screen when that is at least 110 px tall, and otherwise floating in the top right corner (Sunset Drive's 16:9 board on a 16:9 screen), where it shrinks to the score line in the bottom right corner while a round plays and the pointer is still. The board never gives up room for the panel. The pointer hides after two still seconds. In the desktop app the page asks the app (`activities-full`) to lay the console over its bar and terminal and put the window in full screen, since the app's frame allows the page no full screen of its own. A question, a sign-off or a finish takes a full-screen game back to the window's own size as it pauses it. A page with no mouse or trackpad
(touch only) shows "Activities need a keyboard." in place of the board. (touch only) shows "Activities need a keyboard." in place of the board.
- **Best scores** show beside the score while you play and after each round. - **Best scores** show beside the score while you play and after each round.
Snake, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road and Ghoul Rush keep their highest score. Mini golf keeps its lowest Snake, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash keep their highest score. Mini golf keeps its lowest
full round on each course, every course on its own, and a half-played round never counts. **Reset best scores** clears them after a full round on each course, every course on its own, and a half-played round never counts. **Reset best scores** clears them after a
second click to confirm. second click to confirm.
The line under the board is a pair of colored chips, Score and Best, with a The line under the board is a pair of colored chips, Score and Best, with a
@@ -1450,7 +1488,7 @@ Ghoul Rush at 65).
that beats a saved best ends with **New best!** on the end screen, and Mini that beats a saved best ends with **New best!** on the end screen, and Mini
golf, which only knows at the end, fires its sparks then. Reduced motion keeps golf, which only knows at the end, fires its sparks then. Reduced motion keeps
the colors and drops the movement. the colors and drops the movement.
- **Private.** Best scores, Snake's surprises found, Light Trails' furthest arena, Bug Hunt's finds, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, the most Ghoul Rush stages cleared in a run, the last pick and the **Show Activities** switch - **Private.** Best scores, Snake's surprises found, Light Trails' furthest arena, Bug Hunt's finds, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, the most Ghoul Rush stages cleared in a run, Flock Dash's furthest stage, the last pick and the **Show Activities** switch
(User Preferences → Sounds & activities, which hides the die everywhere) are saved in (User Preferences → Sounds & activities, which hides the die everywhere) are saved in
`~/.plan2code/console/looks.json`. Nothing about Activities reaches the agent `~/.plan2code/console/looks.json`. Nothing about Activities reaches the agent
or the session. or the session.
@@ -1561,6 +1599,12 @@ stopped, its actions sit beside a **Back to the dashboard** button that opens
a fresh dashboard in the frame, no agent needed, and its status line marks it a fresh dashboard in the frame, no agent needed, and its status line marks it
as your move rather than leaving a stale "starting" line behind. as your move rather than leaving a stale "starting" line behind.
A stopped loop also offers **Ask a question**, first in the row. The app ended
its agent when the loop stopped, so the Ask tab says no agent is available;
the button wakes an ordinary agent on the same page, without starting the loop
or changing anything, and **Resume the loop** is still there afterwards. **Back
to the dashboard** ends that agent too.
You don't have to finish first. On every skill but the dashboard itself, a You don't have to finish first. On every skill but the dashboard itself, a
small **triangle** pointing left, in your highlight color, sits beside *Stop small **triangle** pointing left, in your highlight color, sits beside *Stop
session*. Press it, confirm, and the agent saves your place exactly as a stop session*. Press it, confirm, and the agent saves your place exactly as a stop
@@ -1667,7 +1711,8 @@ When a newer Plan2Code release is out, the dashboard shows an **UPDATE
AVAILABLE** banner at the top. Click it for the details: the version you AVAILABLE** banner at the top. Click it for the details: the version you
have, the new one (linked to its Releases page) and the command that updates have, the new one (linked to its Releases page) and the command that updates
you, `plan2code update`, with a Copy button. It updates everything that was you, `plan2code update`, with a Copy button. It updates everything that was
installed (the skills, the `plan2code` command and any extras you added), with installed (the skills, the `plan2code` command, the app and the status line; the
metrics and bot extras only from a git checkout), with
no menu, and never uninstalls anything. If the `plan2code` command is not no menu, and never uninstalls anything. If the `plan2code` command is not
installed, the dialog also shows the install command, installed, the dialog also shows the install command,
`npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git`, to run `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git`, to run
@@ -1709,7 +1754,7 @@ The gear button in the top bar opens **User Preferences**, always on its first t
| **System** | Cleanup, and Desktop app (only inside the desktop app) | | **System** | Cleanup, and Desktop app (only inside the desktop app) |
| **Sounds & activities** | Sounds and Activities | | **Sounds & activities** | Sounds and Activities |
On Appearance and Sounds & activities each change saves the moment you make it, and a small **Saved** mark shows beside it. **Close** (or `Esc`) shuts the dialog. **Back to default** resets only the tab on screen: Appearance's four settings (Role back to *Not set*), or every sound and the two Activities switches (Show Activities and Play game sounds); Activities best scores stay. It is not shown on Agents & models or System, which have nothing to reset. On Appearance and Sounds & activities each change saves the moment you make it, and a small **Saved** mark shows beside it. **Close** (or `Esc`) shuts the dialog. **Back to default** resets only the tab on screen: Appearance's four settings (Role back to *Not set*), or every sound and the two Activities switches (Show Activities and Play activity sounds); Activities best scores stay. It is not shown on Agents & models or System, which have nothing to reset.
### Agents & models ### Agents & models
@@ -1717,6 +1762,8 @@ Most people never need this tab: Plan2Code finds the agents installed on the mac
**Models.** The `plan2code` launcher's model menu comes from `models.json`, which every install overwrites with the authors' curated list. Each built-in agent's form (Claude, Devin, Codex) shows that list under *Comes with Plan2Code*, and below it **Models you added**, each a model id and the name shown in the menu, for a model that came out before Plan2Code was updated. Additions are kept in `~/.plan2code/models.json` and survive updates, unless the curated list now includes them; **Remove** takes one out. Restart `plan2code` to see a change. You can always run `plan2code --model <id>`, or switch model inside your agent before running a skill. Devin ids ending `-xhigh` or `-max` are refused. Maintainers refresh the curated list, and the shipped agent list's install data, with the repo-local `/plan2code-launcher-update` skill, which shows a diff and changes only what they approve. **Models.** The `plan2code` launcher's model menu comes from `models.json`, which every install overwrites with the authors' curated list. Each built-in agent's form (Claude, Devin, Codex) shows that list under *Comes with Plan2Code*, and below it **Models you added**, each a model id and the name shown in the menu, for a model that came out before Plan2Code was updated. Additions are kept in `~/.plan2code/models.json` and survive updates, unless the curated list now includes them; **Remove** takes one out. Restart `plan2code` to see a change. You can always run `plan2code --model <id>`, or switch model inside your agent before running a skill. Devin ids ending `-xhigh` or `-max` are refused. Maintainers refresh the curated list, and the shipped agent list's install data, with the repo-local `/plan2code-launcher-update` skill, which shows a diff and changes only what they approve.
**Strengths in the loop.** Under *Models*, a fold of the same name maps **Thrifty**, **Balanced** and **Best** to one of that agent's own models (and an effort, for agents that take one). Rows you have not changed show as shipped, tagged *default*; a changed row has **Reset**. The Implementation Loop's **Strength per phase** setting reads these three words to start each phase, its retry and its helpers on the model you chose (see the Implementation Loop in the desktop app's guide). Saved with the agent's form in `~/.plan2code/models.json`.
**Agents.** An agent you add is an agent CLI Plan2Code did not find on its own, which the `plan2code` command and the desktop app can then start. Each one has a name, the command to run (a bare name looked up on `PATH`, or a full path), and optional fields: **Agents.** An agent you add is an agent CLI Plan2Code did not find on its own, which the `plan2code` command and the desktop app can then start. Each one has a name, the command to run (a bare name looked up on `PATH`, or a full path), and optional fields:
- **Start prompt**: `/plan2code` by default. Leave it blank to start the agent with nothing typed. - **Start prompt**: `/plan2code` by default. Leave it blank to start the agent with nothing typed.
@@ -1743,7 +1790,7 @@ Most people never need this tab: Plan2Code finds the agents installed on the mac
| You closed the tab | Open the link again. Everything is where you left it. After about two minutes with no tab open the link stops working: ask the agent to resume the session for a new one. | | You closed the tab | Open the link again. Everything is where you left it. After about two minutes with no tab open the link stops working: ask the agent to resume the session for a new one. |
| The link stopped working | Tell the agent. It restarts the session and gives you a new link. | | The link stopped working | Tell the agent. It restarts the session and gives you a new link. |
| Your agent session died while you were mid-answer | Press Send anyway. Your answers are written to disk and are never discarded, including when the session is restarted. The next session picks them up. | | Your agent session died while you were mid-answer | Press Send anyway. Your answers are written to disk and are never discarded, including when the session is restarted. The next session picks them up. |
| The page says Plan2Code is not running | It has not checked in for a few minutes. Look at the terminal: it may have finished its turn, hit an error, or be waiting on you there. If it is idle, type `continue` in the terminal and it picks your answers up. Answering here still works, and what you send is held for it. | | The page says Plan2Code is not running | It has not checked in for a few minutes. Look at the terminal: it may have finished its turn, hit an error, or be waiting on you there. If it is idle, type `continue` in the terminal and it picks your answers up (in the desktop app, the **continue** or **Reconnect to agent** button in the sidebar, beside Send on the Ask tab, and on a saved launch types it for you). Answering here still works, and what you send is held for it. |
| You are not sure anything is connected | The **?** at the top right opens Help. Its *What this page is* tab says what keeps the page alive and whether both halves are talking at that moment, and *When something looks stuck* covers what to check. | | You are not sure anything is connected | The **?** at the top right opens Help. Its *What this page is* tab says what keeps the page alive and whether both halves are talking at that moment, and *When something looks stuck* covers what to check. |
| You would rather use the terminal after all | Say so. Nothing is lost. | | You would rather use the terminal after all | Say so. Nothing is lost. |
@@ -1818,7 +1865,7 @@ exception being the note attachments the agent keeps for a spec, above):
| `~/.plan2code/console/sessions/<id>/uploads/` | images and documents attached to notes and quick questions | 30 days after the session was last touched | | `~/.plan2code/console/sessions/<id>/uploads/` | images and documents attached to notes and quick questions | 30 days after the session was last touched |
| `~/.plan2code/handoffs/<id>.md`, `<id>.json` | each handoff's document, and which checkout, spec and skill it belongs to and whether it was picked up (`handoffs.mjs` is their one owner) | 30 days after it was last touched, picked up or not | | `~/.plan2code/handoffs/<id>.md`, `<id>.json` | each handoff's document, and which checkout, spec and skill it belongs to and whether it was picked up (`handoffs.mjs` is their one owner) | 30 days after it was last touched, picked up or not |
| `~/.plan2code/notepads/<folder-name>-<12 hex>/` | your notebook for one folder: `meta.json`, `tabs.json` and, per tab, `tabs/<id>/note.md` and `tabs/<id>/images/` (`notepads.mjs` is their one owner; the agent never reads them, except a tab you send) | until you delete it through Cleanup, which offers it once its newest file is 30 days old | | `~/.plan2code/notepads/<folder-name>-<12 hex>/` | your notebook for one folder: `meta.json`, `tabs.json` and, per tab, `tabs/<id>/note.md` and `tabs/<id>/images/` (`notepads.mjs` is their one owner; the agent never reads them, except a tab you send) | until you delete it through Cleanup, which offers it once its newest file is 30 days old |
| `~/.plan2code/console/looks.json` | your role, theme, colors, sounds and card width, the Show Activities and Play game sounds switches (`hideActivities`, `activitySounds`), the last activity picked (`lastActivity`), best scores (flat `activityBest<Id>` keys: `activityBestSnake`, one per Mini golf course from `activityBestGolfPirate` to `activityBestGolfFrost`, `activityBestTrails`, `activityBestBugs`, `activityBestDrive`, `activityBestStack`, `activityBestBumper`, `activityBestRapids`, `activityBestFuse`, `activityBestHop`, `activityBestBounce`, `activityBestGhoul`) and each game's memo (`activityMemo<Id>`: Snake's surprises found, Light Trails' furthest arena, Bug Hunt's bugs, bosses and power-ups found, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's most stages cleared in a run) | always | | `~/.plan2code/console/looks.json` | your role, theme, colors, sounds and card width, the Show Activities and Play activity sounds switches (`hideActivities`, `activitySounds`), the last activity picked (`lastActivity`), best scores (flat `activityBest<Id>` keys: `activityBestSnake`, one per Mini golf course from `activityBestGolfPirate` to `activityBestGolfFrost`, `activityBestTrails`, `activityBestBugs`, `activityBestDrive`, `activityBestStack`, `activityBestBumper`, `activityBestRapids`, `activityBestFuse`, `activityBestHop`, `activityBestBounce`, `activityBestGhoul`) and each game's memo (`activityMemo<Id>`: Snake's surprises found, Light Trails' furthest arena, Bug Hunt's bugs, bosses and power-ups found, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's most stages cleared in a run) | always |
| `~/.plan2code/console/subagents.json` | your Subagents switch, instruction and limit, per project folder and skill | always | | `~/.plan2code/console/subagents.json` | your Subagents switch, instruction and limit, per project folder and skill | always |
| `~/.plan2code/console/sessions/<id>/subagents-setting.json`, `subagents-cursor.json` | this session's copy of the switch, and how far the agent has been told of it | with the session | | `~/.plan2code/console/sessions/<id>/subagents-setting.json`, `subagents-cursor.json` | this session's copy of the switch, and how far the agent has been told of it | with the session |
| `~/.plan2code/agents.json` | your custom agent CLIs (User Preferences → Agents & models), read by the `plan2code` command and the desktop app | always | | `~/.plan2code/agents.json` | your custom agent CLIs (User Preferences → Agents & models), read by the `plan2code` command and the desktop app | always |
+3 -3
View File
@@ -36,7 +36,7 @@ Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Status Line
## Web Console ## Web Console
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, private: the agent reads a tab only when you start Pathfinder, Plan, Quick Task or Revise plan from the dashboard with it and send the box it fills (an idea box marked `fill: "note"`, up to five ticked pictures attached), which then marks the tab sent via `POST /notepad/tab/sent`; the agent CLI never imports the store; removed only through Cleanup once a month untouched), **Activities** behind the top bar's die (twelve small games, Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road and Ghoul Rush, listed in `public/activities.js` with one module per game under `public/activities/` (Ghoul Rush is its own folder of modules, `public/activities/ghoul-rush/`) and a card line (`blurb`) each, a picker page of game cards once two are listed that plays one game at a time (another pick drops the last game's round), driven by `screens/activities.js` (keys, key releases for a game with `release()`, canvas pointer events for a game with `pointer()`, one frame timer), paused whenever the person's turn comes and resumed only by the person (while that pause's banner is up, only by its **Unpause game** button), best scores in flat `activityBest<Id>` keys in `looks.json` (lowest wins for a game that sets `lowerIsBetter`; Mini golf opens on a dashboard of its six 18-hole courses, one file each under `public/activities/golf-course-<id>.js`, and keeps a best per course, `activityBestGolf<Course>`), and one number a game may keep between sessions in `activityMemo<Id>` (Snake's tally of surprises found, Light Trails' furthest arena, Bug Hunt's tally of finds, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's most stages cleared in a run), never shown to the agent), a built-in 21-topic Help, the app-only **Implementation Loop** (a dashboard card and a setup screen drawn by the page, `public/screens/loop-setup.js`; the last setup remembered per project in `~/.plan2code/console/loop-setup.json`, owned by `loop-setup.mjs`; a page that locks while `state.loop.driving` is set, until the app posts `loopEnd`; a skill run with `--loop` reports a `loopOutcome` instead of asking for sign-off, per `notes/loop.md`), a first-run Welcome, User Preferences (gear: four tabs, Appearance, Agents & models, System and Sounds & activities, on the `public/tabs.js` helper Help also uses, with `public/prefs.js`, `screens/prefs-dialog.js` and `screens/agents-view.js`), an agent-less **setup** page (the `setup` workflow `plan2code` or the desktop app opens when no agent can run: each built-in's found / outside-PATH / missing state from `agent-lookup.mjs`, install lines, Check again, Use it from here, starter templates and Start, which hands the tab to the new agent through a token-guarded `POST /handover` and a `move` event; the app shows it in its window from a Set up an agent button instead) and a bug/idea link to GitHub issues. On opted-in skills (every workflow but the dashboard, Finalize, Changelog, Git and Handoff) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`), and a Helper strength choice (Balanced, Thrifty, Best, Match my session; rules in `src/shared-references/helper-strength.md`, shipped in the twelve helper skills); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; task files are read through `spec-files.mjs` (sLine truncated Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, private: the agent reads a tab only when you start Pathfinder, Plan, Quick Task or Revise plan from the dashboard with it and send the box it fills (an idea box marked `fill: "note"`, up to five ticked pictures attached), which then marks the tab sent via `POST /notepad/tab/sent`; the agent CLI never imports the store; removed only through Cleanup once a month untouched), **Activities** behind the top bar's die (thirteen small games, Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, listed in `public/activities.js` with one module per game under `public/activities/` (Ghoul Rush is its own folder of modules, `public/activities/ghoul-rush/`) and a card line (`blurb`) each, a picker page of game cards once two are listed that plays one game at a time (another pick drops the last game's round), driven by `screens/activities.js` (keys, key releases for a game with `release()`, canvas pointer events for a game with `pointer()`, one frame timer), paused whenever the person's turn comes and resumed only by the person (while that pause's banner is up, only by its **Unpause game** button), best scores in flat `activityBest<Id>` keys in `looks.json` (lowest wins for a game that sets `lowerIsBetter`; Mini golf opens on a dashboard of its six 18-hole courses, one file each under `public/activities/golf-course-<id>.js`, and keeps a best per course, `activityBestGolf<Course>`), and one number a game may keep between sessions in `activityMemo<Id>` (Snake's tally of surprises found, Light Trails' furthest arena, Bug Hunt's tally of finds, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's most stages cleared in a run, Flock Dash's furthest stage), never shown to the agent), a built-in 21-topic Help, the app-only **Implementation Loop** (a dashboard card and a setup screen drawn by the page, `public/screens/loop-setup.js`; the last setup remembered per project in `~/.plan2code/console/loop-setup.json`, owned by `loop-setup.mjs`; a page that locks while `state.loop.driving` is set, until the app posts `loopEnd`; a skill run with `--loop` reports a `loopOutcome` instead of asking for sign-off, per `notes/loop.md`), a first-run Welcome, User Preferences (gear: four tabs, Appearance, Agents & models, System and Sounds & activities, on the `public/tabs.js` helper Help also uses, with `public/prefs.js`, `screens/prefs-dialog.js` and `screens/agents-view.js`), an agent-less **setup** page (the `setup` workflow `plan2code` or the desktop app opens when no agent can run: each built-in's found / outside-PATH / missing state from `agent-lookup.mjs`, install lines, Check again, Use it from here, starter templates and Start, which hands the tab to the new agent through a token-guarded `POST /handover` and a `move` event; the app shows it in its window from a Set up an agent button instead) and a bug/idea link to GitHub issues. On opted-in skills (every workflow but the dashboard, Finalize, Changelog, Git and Handoff) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`), and a Helper strength choice (Balanced, Thrifty, Best, Match my session; rules in `src/shared-references/helper-strength.md`, shipped in the twelve helper skills); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; taskLine truncated
One agent list and one lookup rule serve the launcher, the console and the app: `src/launcher/agents.json` (the built-ins and starter templates with per-OS install data) and `src/web-console/agent-lookup.mjs` (`loadAgentList()` and `findAgent()`, both copied by `install.js` into `~/.plan2code/bin/`); the app carries a Rust twin held to the same cases by `scripts/fixtures/agent-lookup-cases.json`. One agent list and one lookup rule serve the launcher, the console and the app: `src/launcher/agents.json` (the built-ins and starter templates with per-OS install data) and `src/web-console/agent-lookup.mjs` (`loadAgentList()` and `findAgent()`, both copied by `install.js` into `~/.plan2code/bin/`); the app carries a Rust twin held to the same cases by `scripts/fixtures/agent-lookup-cases.json`.
Building or changing an Activities game: follow the game rules in [Architecture](./.agents-docs/AGENTS-architecture.md) ("Building an Activities game": lives in the solid lives pill, the endless-lives code (`cheat(on)`) in every game with lives, banners placed away from the player and see-through over what matters, pausing left to the window). Building or changing an Activities game: follow the game rules in [Architecture](./.agents-docs/AGENTS-architecture.md) ("Building an Activities game": lives in the solid lives pill, the endless-lives code (`cheat(on)`) in every game with lives, banners placed away from the player and see-through over what matters, pausing left to the window).
@@ -67,7 +67,7 @@ Details: [Code Style & Gotchas](./.agents-docs/AGENTS-code-style.md)
The project has a mascot called "Planny": a box with a star for an eye, stick arms and two small feet. He appears in installer output, workflow prompts, the loop, the Claude Code status line (box, star and feet, no arms) and the web console. ASCII variants are defined in the `MASCOT` constant in `install.js` and appear in workflow markdown files: arms down at rest, one arm waving when he is asking something, both arms up when he is celebrating. The eye is always the star. The project has a mascot called "Planny": a box with a star for an eye, stick arms and two small feet. He appears in installer output, workflow prompts, the loop, the Claude Code status line (box, star and feet, no arms) and the web console. ASCII variants are defined in the `MASCOT` constant in `install.js` and appear in workflow markdown files: arms down at rest, one arm waving when he is asking something, both arms up when he is celebrating. The eye is always the star.
The web console draws him as inline SVG in `src/web-console/public/index.html`, where he doubles as the page's state indicator: his star lights in the highlight color and he waves when something is yours to do, the star turns and his feet walk while the agent works, it goes green when all is done, he shows no arms at all when the agent is not answering, and he fades with his star shut when the connection drops. The parts are classed (`shell`, `eye`, `smile`, `foot`, and one `arms a-<mood>` set per mood) and `screens/core.js` switches mood with a single class, so the drawing stays in the markup and the styling in `styles/planny.css`. The nine skill start poses, the dashboard wake-up, `favicon.svg` / `favicon.js` and `src/launcher/plan2code.ico` all use the same design. The web console draws him as inline SVG in `src/web-console/public/index.html`, where he doubles as the page's state indicator: his star lights in the highlight color and he waves when something is yours to do, the star turns and his feet walk while the agent works, it goes green when all is done, he shows no arms at all when the agent is not answering, and he fades with his star shut when the connection drops. The parts are classed (`shell`, `eye`, `smile`, `foot`, and one `arms a-<mood>` set per mood) and `screens/core.js` switches mood with a single class, so the drawing stays in the markup and the styling in `styles/planny.css`. Every skill start pose, the dashboard wake-up, `favicon.svg` / `favicon.js` and `src/launcher/plan2code.ico` all use the same design.
``` ```
╭───╮ ╭───╮
@@ -103,7 +103,7 @@ When you make a mistake, get corrected, or discover something about this codebas
- Before deleting a test file that upstream split or removed, diff plan2code's copy against the rebranded upstream base and port the plan2code-only tests: v2.7.0's split of the web console suite would otherwise have dropped seven hardening tests (now in `scripts/test-web-console-hardening.mjs`). - Before deleting a test file that upstream split or removed, diff plan2code's copy against the rebranded upstream base and port the plan2code-only tests: v2.7.0's split of the web console suite would otherwise have dropped seven hardening tests (now in `scripts/test-web-console-hardening.mjs`).
- When a `CHANGELOG.md` heading gets a version number, set the same number in `version.json` (with its `releaseDate`), the root `package.json` and README's `Version X.Y.Z` line in the same change, then run `npm run build:skills`. The changelog skill only touches `package.json`: v2.9.0 nearly shipped with `version.json` at 2.8.1, and README's line sat at 2.6.0 for three releases. - When a `CHANGELOG.md` heading gets a version number, set the same number in `version.json` (with its `releaseDate`), the root `package.json` and README's `Version X.Y.Z` line in the same change, then run `npm run build:skills`. The changelog skill only touches `package.json`: v2.9.0 nearly shipped with `version.json` at 2.8.1, and README's line sat at 2.6.0 for three releases.
- When a page test (`scripts/test-web-console-page-*.mjs`) fails only on CI or only in a full run, look for a race with a redraw before suspecting the change, and fix the test, not the timeout: read styles and set scrolls through `styleOf()`, `stylesOf()` and `scrollCard()` in `page-test-helpers.mjs` (a card a redraw replaced reads "" for every style and scrolls nothing; `test-web-console-shape.mjs` now fails a raw `locator.evaluate` that does either), and wait for the page to hold what the next step needs before acting (the workspace frame before typing `@`, the notepad's drawn marks, a newly selected tab). Keep `npm test`'s file concurrency under `scripts/node-test.mjs`'s cap of one file per spare core: a flat `--test-concurrency=8` ran 8 browsers on 3 and 4 core runners and failed a different page test on every CI run. On a busy local machine, rerun the failing files alone first; the chat stress test and the session suite's "no submitted frame within 5s" cascade still fail that way under load. - When a page test (`scripts/test-web-console-page-*.mjs`) fails only on CI or only in a full run, look for a race with a redraw before suspecting the change, and fix the test, not the timeout: read styles and set scrolls through `styleOf()`, `stylesOf()` and `scrollCard()` in `page-test-helpers.mjs` (a card a redraw replaced reads "" for every style and scrolls nothing; `test-web-console-shape.mjs` now fails a raw `locator.evaluate` that does either), and wait for the page to hold what the next step needs before acting (the workspace frame before typing `@`, the notepad's drawn marks, a newly selected tab). Keep `npm test`'s file concurrency under `scripts/node-test.mjs`'s cap of one file per spare core: a flat `--test-concurrency=8` ran 8 browsers on 3 and 4 core runners and failed a different page test on every CI run. On a busy local machine, rerun the failing files alone first; the chat stress test and the session suite's "no submitted frame within 5s" cascade still fail that way under load.
- Run `npm test` and `cargo test` from a terminal outside the desktop app, or with `PLAN2CODE_IN_APP`, `PLAN2CODE_APP_TOKEN`, `PLAN2CODE_APP_VERSION`, `PLAN2CODE_APP_ANNOUNCE`, `PLAN2CODE_EMBED_ORIGIN` and `PLAN2CODE_CONSOLE_SID` unset (`env -u ... npm test`): inherited from the app they fail about 34 tests that check behavior outside the app (the update banner, the terminal line, cookies, open's browser launch), and a test console announces itself to the live window. A `cargo test` run mid-build once took the window over that way, then left an agent-less dashboard in it, and the build's question was never seen. The app now ignores sessions outside its console store (`take_announced` in `main.rs`), and the Rust console tests scrub the variables, but the JS suites do not. Before pushing a change under `plan2code-app/`, also run `cargo fmt --check` and `cargo clippy --workspace --all-targets -- -D warnings` there, not only `cargo test`: CI's `app` workflow fails on either, and the Rust code once reached a PR never formatted (20 files) with three clippy errors, one only macOS and Linux could see (see plan2code-app/README.md "Tests"). - Run `npm test` and `cargo test` from a terminal outside the desktop app, or with `PLAN2CODE_IN_APP`, `PLAN2CODE_APP_TOKEN`, `PLAN2CODE_APP_VERSION`, `PLAN2CODE_APP_ANNOUNCE`, `PLAN2CODE_EMBED_ORIGIN` and `PLAN2CODE_CONSOLE_SID` unset (`env -u ... npm test`): inherited from the app they fail about 34 tests that check behavior outside the app (the update banner, the terminal line, cookies, open's browser launch), and a test console announces itself to the live window. A `cargo test` run mid-build once took the window over that way, then left an agent-less dashboard in it, and the build's question was never seen. The app now ignores sessions outside its console store (`take_announced` in `main.rs`), and the Rust console tests scrub the variables, but the JS suites do not. Before pushing a change under `plan2code-app/`, also run `cargo fmt --check` and `cargo clippy --workspace --all-targets -- -D warnings` there, not only `cargo test`: CI's `app` workflow fails on either, and the Rust code once reached a PR never formatted (20 files) with three clippy errors, one only macOS and Linux could see (see plan2code-app/README.md "Tests"). `loop_driver` tests failing with `never saw ... agent generations` and no `ARGS` line in the output mean `target/debug/fake-agent` is older than its source (a file restored with an old time, so Cargo never rebuilds it): `touch plan2code-app/fake-agent/src/main.rs` and rerun. A stale binary once read as 2 real failures in PR Prep.
- Never fix CRLF by hand, one file at a time: run `npm run fix:eol` (`scripts/fix-line-endings.mjs`). Windows Python in text mode, among other tools, writes CRLF into files git keeps as LF; a whole session's edits once came out CRLF and 14 other files were found the same way. It now also runs as `pretest`, in the pre-commit hook and after every agent Write or Edit (see the LF gotcha in Code Style). - Never fix CRLF by hand, one file at a time: run `npm run fix:eol` (`scripts/fix-line-endings.mjs`). Windows Python in text mode, among other tools, writes CRLF into files git keeps as LF; a whole session's edits once came out CRLF and 14 other files were found the same way. It now also runs as `pretest`, in the pre-commit hook and after every agent Write or Edit (see the LF gotcha in Code Style).
- Bring the Windows folder picker (`picker.mjs`, copied into `src/launcher/plan2code.js`) to the front with an Alt tap before `SetForegroundWindow`, never with `windowsHide`, the owner form's `TopMost`, `HWND_TOPMOST` or `AttachThreadInput`: measured on Windows 11, `SetWindowPos(HWND_TOPMOST)` returns true while the dialog stays non-topmost behind the browser, and only the Alt tap made it the foreground window. Check with `GetForegroundWindow` from a second process, since no test can see it. - Bring the Windows folder picker (`picker.mjs`, copied into `src/launcher/plan2code.js`) to the front with an Alt tap before `SetForegroundWindow`, never with `windowsHide`, the owner form's `TopMost`, `HWND_TOPMOST` or `AttachThreadInput`: measured on Windows 11, `SetWindowPos(HWND_TOPMOST)` returns true while the dialog stays non-topmost behind the browser, and only the Alt tap made it the foreground window. Check with `GetForegroundWindow` from a second process, since no test can see it.
- Add any new file or folder Plan2Code writes at the top of `~/.plan2code/` to `KEPT_PLAN2CODE_ENTRIES` in `src/web-console/sessions.mjs` and to the Cleanup test in `scripts/test-web-console-server.mjs`: User Preferences → System → Cleanup offers every other entry there for deletion once it is an hour old, and the desktop app's `app/` and `app.json` were about to be listed. - Add any new file or folder Plan2Code writes at the top of `~/.plan2code/` to `KEPT_PLAN2CODE_ENTRIES` in `src/web-console/sessions.mjs` and to the Cleanup test in `scripts/test-web-console-server.mjs`: User Preferences → System → Cleanup offers every other entry there for deletion once it is an hour old, and the desktop app's `app/` and `app.json` were about to be listed.
+19 -91
View File
@@ -6,106 +6,34 @@ All notable changes to Plan2Code will be documented in this file.
### ✨ Added ### ✨ Added
- **desktop app**: a cross-platform app (Rust, Tauri) that is the single window for working with an AI agent. It opens the Plan2Code dashboard as its main surface, runs Claude Code, Devin or Codex in a pseudo-terminal panel it owns, and adds a **New Session** button that replaces the agent with a fresh one on a brief the app builds from its own record of the session, with the in-progress work and recent activity carried over. Every console page (Ask, Workspace, Help, Preferences, Git, Notebook) opens inside the app, not a separate browser tab. - **desktop app**: a cross-platform app (Rust, Tauri) that is the single window for working with an AI agent. It opens the Plan2Code dashboard as its main surface and runs Claude Code, Devin, Codex or your own agent in a terminal panel it owns, with every console page (Ask, Workspace, Help, Preferences, Git, Notebook) inside the window. **New Session** replaces the agent with a fresh one on a brief the app builds from its own record of the session, so in-progress work carries over. **Update skills** brings the installed skills level with the app, and the taskbar shows when Plan2Code needs you. `plan2code` opens the app when a desktop is available; `plan2code --classic` keeps the terminal-only flow.
- **desktop app**: **Update skills** in the bar brings the installed skills level with the app from the exact release the app ships, with live progress and a **Reconnect the console** offer once it finishes; an app older than the installed skills says so instead of trying to fix it by updating skills again. - **implementation loop**: the app builds a spec phase by phase, each phase in a fresh agent, and writes a report. **Set strength per phase** runs each phase on the model and effort of a chosen strength (Thrifty, Balanced, Best or Match my session), the loop strip and report show what each phase ran on, and the end screen offers **Back to the dashboard** and a way to ask a stopped loop a question. It replaces the `plan2code-loop` CLI (see Breaking).
- **desktop app**: the window's own title (and so its taskbar entry) now reads **Plan2Code - &lt;folder name&gt;** once a project is open, instead of a plain **Plan2Code** every window shares; two or more windows on different projects read apart without opening each one to check. - **helpers**: helpers (subagents) now run at a strength and effort matched to their job (`light`, `standard`, `strongest` or `inherit`), never tied to one model or vendor, and Plan and Revise Plan offer them too. In the web console, the **Subagents** dialog turns helpers on or off per project and skill and has a **Helper strength** choice (Balanced, Thrifty, Best or Match my session), and the Subagents tab shows what each helper ran with.
- **helpers**: a helper (subagent) no longer has to run on the session's own model and effort. A new shared reference, `helper-strength.md`, shipped in Pathfinder, Quick Task, Implement, Implement + Review and Review, matches each helper job to a strength (`light`, `standard`, `strongest` or `inherit`) and an effort (`low`, `medium` or `high`) from signals that can be checked, with floors, one-step escalation and a fallback order for tools that cannot set either, and never names a model or vendor. Review, Implement + Review and Pathfinder name the strength for the helpers they start, and the rules apply in terminal sessions too. - **custom agents**: add your own agent CLIs under **User Preferences → Agents & models** (saved in `~/.plan2code/agents.json`) and start them from `plan2code --cli <id>` or the app. When no agent can be used, a first-run **setup page** lists each built-in agent as found, found outside PATH or not found, with install commands for your OS, starter templates and **Check again**, then carries on once an agent is found.
- **helpers**: Plan and Revise Plan now offer helpers (subagents), with the web console's **Subagents** button in the top bar, on by default like the other opted-in skills. Each skill has its own rule for what is independent enough to hand off. Plan uses helpers for reading the sources the person names, mapping separate areas of the codebase in Phase 2, gathering evidence on each open tech choice in Phase 4, and one fresh cross-check of the PLAN-DRAFT against the conversation in Phase 7; questions, decisions, sign-offs and the writing of the PLAN-DRAFT stay with the session. Revise Plan uses read-only lookups on the code behind affected and at-risk completed tasks at Steps 1 and 2 and, only after approval and when a revision touches 3 or more phase files, one helper per phase file to apply the approved edits under `specs/`. The rules live in each skill's Helpers section, so they apply in terminal sessions too. `helper-strength.md` now ships in both, with a row for each new kind of helper job (Plan's recon reuses the lookups row) and the PLAN-DRAFT cross-check held at `standard` or above, like a review. - **pr-prep**: a new utility, **Get a PR ready** (`/plan2code-pr-prep`), picks the checks that cover your branch's changes, runs them, says Ready, Ready with notes or Not ready, and writes a PR description to copy. It never commits, pushes or opens the PR.
- **web console**: the Subagents dialog has a **Helper strength** choice under Helpers: **Balanced** (the default), **Thrifty**, **Best** or **Match my session**, saved per project and skill and delivered to the agent as a `Helper strength:` line. Helper reports may say what each helper ran with (`strength`, `effort`), and the Subagents tab shows each as a colored badge with a small three-bar level mark (teal for low, amber for medium, violet for high; the session's own model in plain gray), while screen readers still hear one line, such as "Standard, medium effort". - **test**: a new utility, **Write missing tests** (`/plan2code-test`), finds source files no test covers and, once you approve its plan, writes tests in the project's own style. It never changes source code. Both utilities read an optional **test map** (a `## Test map` table in `AGENTS.md`), which Init can propose.
- **web console**: picking a spec on the dashboard that is not documented yet now shows its main files as read-only tabs in the top bar, like the **Overview** tab of a documented spec: **Map** for a Pathfinder map (`pathfinder/map.md`) and **Plan draft** for Plan's live `PLAN-DRAFT-*.md`, each when it exists. Once the spec has an `overview.md`, Overview replaces them. - **activities**: a die in the console's top bar opens a window of thirteen small games to play while you wait: Snake, Mini golf (six 18-hole courses), Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash. A game pauses the moment Plan2Code needs you, has sounds and optional music, can go full screen, and keeps its best score privately. Off until you turn on **Show Activities** in **User Preferences → Sounds & activities**.
- **web console**: start Pathfinder, Plan or Quick Task (on **Start fresh**) or Revise plan (on a picked spec with no plan change waiting) from a Notebook tab. A lit card's confirm pane offers **Start with a note from your Notebook**, with the tab list, a preview of the whole tab and up to five ticked pictures (the first five start ticked; a tab over 50 KB says so). The skill's first box arrives filled with the tab's text and pictures, editable, and the agent reads it only once you send it; nothing about the tab rides the launch itself. The tab then shows a **sent** badge and a "Sent to <Skill> · <Date>" line in the Notebook, and the Notebook's privacy line now reads: the agent never reads your Notebook, and a tab reaches it only when you start a workflow with it. - **web console**: start Pathfinder, Plan, Quick Task or Revise plan from a **Notebook** tab: the skill's first box arrives filled with the tab's text and pictures, and the agent reads it only once you send it.
- **web console**: **Activities**, a die in the top bar right of the megaphone, opens a window of small games to play while you wait, say through a long build. The first is **Snake**, built in-house from local files (arrows or WASD, space or Enter to start, P or Enter to pause and play on, Esc to close). It speeds up as it grows and gets wilder each level: every new level opens in Slow-mo (which eases back to full speed as it runs out, never with a jolt), and every 5 foods brings something new (rocks that flash before they land, mystery boxes, portals, tail-cutting comets, chaos, then ice, where a turn slides two steps before it takes), five power-ups turn up on their own (Shield, Slow-mo, Magnet, Ghost, Scissors), a mystery box holds one of nine surprises (Jackpot, Gold rush, Lights out, Disco fever and more), each level serves its own fruit (an apple, then cherries, an orange, grapes, a banana, a strawberry, watermelon, a peach and a golden apple) on its own scenery (meadow, desert, lagoon, starry night, carnival, ice, volcano, gold), the last food of every odd level from 3 on is a crowned four-cell boss fruit that takes three bites, a runaway fruit on little feet hops away until you corner it or tire it out, quick eating builds a combo up to x5, and passing your best plays a fanfare. A level, power-up or surprise banner opens on the half of the board away from the snake and fades almost clear while the snake is under it or heading into it, so it never hides a crash. The start and end screens count the surprises you have found so far and hint at what waits next. The second is **Mini golf**: goofy holes seen from above on themed courses (see the course dashboard further down), among them Pirate Cove (a shark sea, cannonballs, a kraken, a ghost ship, a skull to putt through) and the Caves of Doom (dark but for the ball's light, with lava, a bottomless pit, mine carts, stone crushers and a sleeping dragon), played arcade style: the aim follows the mouse (or held arrows, turning faster the longer they are held) and points back at the cup after every stop, holding there until the mouse really moves so a click never swings it, one click or space starts a power meter beside the ball and a second sets the power (slow near the bottom for soft putts, fast near the top, with a gold MAX band for a 1.15x putt and a red overswing band past it that shanks the ball), a 6 second shot clock starts the meter for you, a meter left running dribbles the ball, and holding space or the mouse fast-forwards the roll, with par per hole, at most 8 strokes a hole, and its best kept as the lowest full round. Glowing power-up pads help the next putt: a free putt, a cannon shot, a ghost ball that floats over water, a cup magnet, a rubber duck that keeps its speed off walls, a huge cup, and a spyglass that shows where the putt will roll. With two games, a picker chooses between them. A new question, a sign-off or a finish pauses the game at once and shows a banner with **Go to it**, so a game never hides your turn; hiding the page or clicking away pauses it too. While that banner is up, nothing resumes until you click its **Unpause game** button, so a key or click already on its way cannot wave the banner away unread; after **Go to it**, or once you close and reopen the window, a game key or a click on the board plays on. Resuming puts the your-turn banner away until the next question. Every round start and every play-on after a pause counts down 3, 2, 1 first, so a game never moves before you are ready. The window's header shows the current game's best. Best scores (shown beside the score and after each round, cleared by **Reset best scores**; the score line is a pair of colored chips with a meter filling toward the best, which glows when you reach it, turns into a rainbow with a burst of sparks when you pass it, and ends the round with **New best!**) and the last pick are saved privately in `~/.plan2code/console/looks.json` and never reach the agent. **User Preferences → Sounds & activities → Show Activities** hides the die everywhere, and Help has a new Activities topic. - **web console**: answer boxes render Markdown live, **Ask for suggestions** asks Plan2Code what it would pick and why on an open question, a **Clear** button takes a one-answer question back to unanswered, a plan's Build order card has **Combine phases**, and a spec that is not documented yet shows its Pathfinder map and plan draft as read-only tabs.
- **web console**: Activities has a third game, **Light Trails**: every rider leaves a glowing wall behind it, and the last one still moving wins the heat. Arrows steer and space spends a boost charge (two a heat, up to three). Riding into something holds you in place for a split second first, so a turn pressed then still gets you out (rivals get no such grace). A round runs through nine arenas, from Neon Grid to the Golden Arena, each on its own scenery: a win moves you on, and a crash costs one of three lives and runs the heat again. Each arena brings a rival more (Zip, Bolt, then Echo, who ride sharper the further you go) or something new: power-up pads at 2 (Boost, Phase through trails, an Eraser that wipes the trails around you, Slow-mo for the rivals, coins and, from 4, a 1UP), crystals at 3, portals at 4 and walls that close in a ring at a time, flashing first, at 5. A rival out while you still ride scores points, and more when it hit your own trail. You ride with Planny's star eye, and the start and end screens show the furthest arena you have reached and what waits next. - **workflows**: Finalize offers a final review and asks once before its rating questions, Diagnose lets you skip two of its opening questions, and Git names `/plan2code-pr-prep` as the likely next step after a push.
- **web console**: Activities has a fourth game, **Bug Hunt**, an arcade shooter. Planny's ship slides along the bottom (the arrows move it, held space fires) and squashes waves of bugs that swoop in from the sides into a swaying formation, then break off and dive at you. The first waves each bring a new bug: the everyday **Bug**, a **Beetle** that splits in two, a zigzagging **Race condition**, an **Exception** that throws things, a **Null pointer** that shots pass through while it fades, and a **Firewall** that soaks up shots. Every fifth wave is a boss: the **Memory Leak**, which grows while you wait, the **Spaghetti Monster**, whose tentacles have to go first, and the **Heisenbug**, which is only there when you look, then round again, tougher. Squashed bugs drop coins and now and then a power-up (Spread shot, Rapid fire, Shield, Slow-mo, Magnet, Refactor, which cleans up the screen, and a 1UP), quick kills build a combo up to x5, and a wave cleared without a hit scores extra. The board is Snake's checkerboard scrolling past with bits of code drifting by, with new scenery every five waves (the Codebase, Legacy Code, Production, the Cloud), and the start and end screens count the 16 bugs, bosses and power-ups found so far. - **contributors**: `npm run play` opens the web console straight from `src/`, so a change shows on the next page reload without rebuilding or reinstalling.
- **web console**: Activities has a fifth game, **Sunset Drive**, a road racer against the clock. Planny drives a convertible down an endless road seen from behind, with bends, hills, traffic and scenery scrolling past: hold up to drive, down to brake, the arrows to steer, and space burns a nitro can for a burst of speed. The clock sits big in the top middle, blinking red and swelling on every tick in its last ten seconds. Each stage ends at a checkpoint that adds time, and just before it the road splits around a median: the side you keep to picks the next of six roads (Sunset Coast, Canyon Road, Maple Valley, Snowcap Pass, Neon City and Starlight Highway), each with its own sky, props, traffic and points bonus, the harder ones worth more. Coins, clocks and nitro cans line the road, a car passed close at speed scores a close call, and catching up with a car or hitting a palm, cactus or rock on the shoulder costs you speed. As the fork is called, a postcard of each road (its sky, hills, road and scenery, with its name and points bonus) shows in the top corner on its side, the side you are on lit. Spinning **?** boxes on the road hold power-ups, queued up to three: while one is held, space fires the oldest instead of a nitro can, and timed ones run side by side (one fired again while it runs adds its time). **Rocket Hop** leaps over the traffic and the shoulder, **Ghost Car** drives right through cars and props, **Coin Magnet** pulls in every coin across the road, **Monster Truck** flings the cars it hits into the sky for points and flattens props, and **Coin Storm** turns the traffic ahead into coins. The round ends when the clock runs out, and the start and end screens count the roads found so far.
- **web console**: Activities has a sixth game, **Stack Deploy**, a one-button tower stacker. A block slides back and forth above the tower and space, up or a click drops it: the overhang is sliced off and tumbles away, so the next block is narrower, and a block that misses the tower ends the round with the camera pulling back over the whole tower. A drop dead on is a **Perfect**: nothing is sliced, the thunk climbs a scale with each one in a row, the bonus multiplies up to x5, and every third in a row grows the block back. Gold blocks from floor 15 are worth more and grow it twice as much. The slide speeds up from floor 10, and the floors bring twists: blocks from either side that may turn back (20), lag spikes that freeze a block for a beat (30) and wind (40), then a rush through the middle (70) and everything faster (90). The tower goes from server racks to office floors, glass towers and rockets under a sky that turns from day to space, Planny rides the top block (and wobbles after a sloppy drop), and a dashed line marks the highest floor ever reached, which the start screen names with the next style to reach.
- **web console**: Activities has a seventh game, **Bumper Ring**, sumo in bumper cars on a platform over the void. Held arrows push your car that way and momentum carries it; cars bounce off each other and the one closing faster rams and wins the exchange, while two cars leaning in are a pushing match. Space dashes (two charges a heat, one back every six seconds, up to three). A car whose center goes past the edge falls, and the last car on the ring wins the heat: a win moves on, a fall costs one of three lives and runs the heat again. Rivals rev before they dash, so a quick sidestep can send one flying off on its own. Nine arenas, from the **Training Mat** to the **Grand Final** and then endless, sharper Finals, bring five rivals with their own ways (the Bully, the heavy Turtle, the Sniper, the Scrapper and the Mirror, who copies your moves), power pads (Heavy, Spring, Charge, Shield, Grow, Ghost and Slick), bumpers, ice, a turntable, holes in the floor, a magnet and a ring that turns square. After a while the ring shrinks a flashing band at a time, then goes to sudden death, so every heat ends. Knockouts go to the last car to touch the one that fell, quick ones build a combo up to x5 and two at once count double, and the start and end screens show the furthest arena you have reached.
- **web console**: Activities has an eighth game, **Rapids Run**, a fast vertical scroller on a winding river. Planny pilots a jet-skimmer up a river that scrolls down the board, its banks narrowing and splitting around islands: the arrows steer, held up speeds up for double points per distance, held down slows, and held space fires. The battery drains all the while (faster at speed), so run over charge buoys to top it up, or shoot them for points if you can spare the charge. A bank, an island, a foe, a bolt or a flat battery costs one of three lives and starts the stretch again from the last dam (from the basin's mouth once a mini-boss is reached). Each stretch ends at a dam you must blast open to pass, for a stretch bonus and a new stretch name: eight stretches from **Willow Run** to **Old Lock**, then endless, quicker Night Water. The river's foes arrive a kind at a time (patrol skiffs, bob mines, gull drones, bank sentries that shoot back, whirlpools that tug and darters that swerve into your lane), every fourth dam is guarded by a mini-boss (the Dredger, Ironclad and Old Leviathan), and crates hold Spread shot, a Shield, a Magnet and a Surge. Quick sinks build a combo up to x5, skimming a bank at speed scores, the score shows big at the end, and the start and end screens show the furthest dam blasted.
- **web console**: Activities has a ninth game, **Hot Potato**, arena tag with a fizzing bomb: a merge conflict with its `<<<<<<<` markers showing. Held arrows run, whoever holds the bomb runs a little faster and passes it by touching someone, and whoever holds it when the fuse runs out is blown out of the match in a cartoon cloud, then waddles off charred. The fuse ticks quicker as it burns, the bomb grows and glows redder, and the edges pulse in the last second; each fuse in a match is shorter than the one before. Someone just handed the bomb cannot pass it on for a moment, and nobody can hand it straight back while three or more are left (a white ring at their feet shows who is safe); handed it at the last moment, you still get time to pass it, since a pass tops the fuse up to 1.4 seconds, once a fuse for each runner. Space dashes: a lunge for a tag while you hold it, a dodge while you do not, and rivals crouch before they lunge, so a quick sidestep gets you clear. The last one standing wins the match and moves on through nine venues, from the **Break Room** to the **Finale** and then endless, sharper Finales, bringing five rivals with their own ways (the Sprinter, the Hider, the Trickster, who feints, the Pal and the Clingy), pickups (Freeze, Sneakers, Extra Fuse and Swap), long rows of server racks, a roof with no wall on one side, ice, conveyor belts, a blackout and two bombs at once; being blown up costs one of three lives and runs the match again. Hot passes with under a second left chain a streak up to x5, and the start and end screens show the furthest venue reached.
- **web console**: Activities has a tenth game, **Crossing Rush**, a lane-crossing race. Planny and two rival hoppers hop up a strip of lanes a cell at a time, one hop a press: roads of cars and trucks, rivers where you ride the logs and turtles, train tracks that flash red and ring a bell before the train, and grass with bushes and rocks in the way. A car, a train or the water sends a hopper spinning back to the last grass row rather than out, so every heat ends with someone at the top, and the view follows you with a race bar beside it showing everyone's height; a hopper sent back stands dazed for 2 seconds before it may hop again. Pickups stack as you land on them and space uses the oldest first: **Spring** leaps two cells the way you face, **Shield** lets cars and trains through for 3 seconds and **Horn** stops the nearest road, while a **Coin** scores at once; the stack empties every heat. First to the top wins the heat and moves on through nine zones, from **Side Street** to **Rush Hour** and then endless, quicker Rush Hours, bringing logs, trains, diving turtles, trucks and lanes that speed up, a dusk lit by headlights, rivers that turn round and icy lanes that slide you on, and four rivals with their own ways (the careful Hopper, the Daredevil, the pushy Bruiser and the Tagalong, who follows you up). Second or third costs one of three lives and runs the heat again, though the first two zones let second place through. Quick forward hops climb in pitch, clean wins in a row multiply the win up to x3, a car through the cell you just left is a close call, and the start and end screens show the furthest zone reached.
- **web console**: Activities has an eleventh game, **Bounce Road**, a fast scrolling road seen from above. Planny races a springy toy car up a road laid across a giant's house and yard: hold up to drive, the arrows to steer and press space to jump, a faster jump going further. Bump a rival toy car sideways off the road, or land on one to flatten it and bounce up again, and land on another before your wheels touch the road to build the bounce chain, up to x8; every stunt in quick succession (crushes, bump-offs, jumps over holes, trains, balls and barriers, a ramp's big air, close shaves, boost strips) steps a combo that multiplies the points up to x4. Ten stages, each bringing something new, from **Chalk Lane** on the patio through **Kitchen Floor**, **Toy Room**, **Garden Pond**, **Rooftop Gutter** and **Night Lights** (in the dark) to **Monster Mash**, where the Monster truck must be stomped five times, then round again, quicker and meaner. The road has cracks, broken bridges, drawbridges, swaying bridges, road that crumbles behind you, ramps, boost strips, oil slicks, cone and toy-block chicanes, a toy train crossing, rolling balls, sprinklers, gusts of wind and things that fall where you are heading, every hole jumpable at 80% of the top speed after a warning sign and a run-up. Ten rivals, all keener the further you go (they block your line, swerve from under your landings, hop the gaps and keep the pack close): the Zigzag, the Brick (who brake-checks you), the Frog, the Nudge, the Hauler, the Sneak (who drops cones), the Bruiser, the Racer to catch, the Cop (who chases and pushes you toward the edge) and the Monster truck. There are four power-ups (Spring, Bubble, Nitro and Mega wheels), and every car is drawn in full toy-car detail. A stage line pays a bonus for beating its par time, a stage crossed with no life lost gives a life back, and the start and end screens show the furthest stage reached.
- **web console**: Activities has a twelfth game, **Ghoul Rush**, a fast, dark run-and-gun through a haunted house. Planny sprints left to right through a mansion a room at a time, the view scrolling with him, lit only by his glow, his flashlight's cone, candles, moonlight and the odd flash of lightning, with eyes burning in the dark around him: hold left or right to run, up jumps (let go early for a short hop), down drops through a shelf, and held space fires his flashlight blaster ten times a second the way he faces. Grab each room's key, then reach its door, while a horde pours in from the edges of the view. **Zombies** sprint once you are close, **crawlers** drag themselves up through loose boards, **bats** swoop at your chest, **ghosts** can only be hit (or hurt you) while solid, **skeletons** throw bones you can shoot down, **hellhounds** crouch growling and lunge, **widows** drop from the ceiling as you pass under, **wraiths** shriek and dive at where you were, and **bloaters** lob acid that leaves burning puddles and burst when they die; a shot to the head or a stomp from above doubles a kill, and quick kills build a chain up to x10 that runs out in 1.2 seconds. Pits, one-way shelves, crumbling boards and falling chandeliers (which crush whatever is under them) fill eight rooms, from the **Foyer** to the **Crypt**, with a boss every fourth: the **Rotting Gourd**, a giant rotten pumpkin that hops to where you stood and shakes loose gourdlings, and **Old Rattlebones**, who throws volleys of bones and slams shockwaves you jump. Power-ups (Spread shot, Rapid fire, a Garlic shield and a 1UP), souls, a time bonus per room that sends zombies in from the edges once it runs out, a flawless bonus and a life back for each boss add up, a hit or a fall costs one of three lives and restarts the room, and the start and end screens show the most stages cleared in a run.
- **web console**: **Mini golf** now has six themed courses of eighteen holes each, picked from a **course dashboard** that opens from its card: a card per course with a picture of one of its holes, its line, its par and your best round on it, walked by the arrows like the game picker, with **All courses** to get back; once a round is over, space or a click goes back to the dashboard rather than replaying the same course. **Pirate Cove** and the **Caves of Doom** each grow from nine holes to a full eighteen, and four new courses join them: **Dino Valley** (a prehistoric jungle and volcano), **Candy Carnival** (a sweets land), **Cosmic Glow** (black-light glow golf in outer space, where black holes bend your putt) and **Frosty Peaks** (a winter wonderland where the ball glides on ice). Two new hazards came with them: ice, where the ball barely slows, and gravity wells that pull a putt in or push it away. Each course keeps its own best round (`activityBestGolfPirate` to `activityBestGolfFrost` in `looks.json`), and the Mini golf card on the picker counts the courses you have a best on.
- **web console**: the Activities window now opens on a **picker**, a card for each game with a little cover scene, a line about it, its best score and a **Last played** tag, in place of the old row of buttons above the board. A card opens its game, the arrows walk the cards, and **All games** goes back. One game plays at a time: leaving for the picker keeps the round paused on its card (and reopening the window goes straight back into it), and picking a different game ends it.
- **web console**: **User Preferences → Sounds & activities** has a **Play game sounds** switch under Activities, so the games can play silently while the page's own cues (a new question, a reply) still sound. It covers every game's sounds and the window's own (the 3, 2, 1 and the new-best burst), turning it off silences a game playing now, it is grayed out while **Play sounds** is off (and keeps its tick for when sound comes back), and **Back to default** turns it back on. Saved as `activitySounds` in `looks.json`.
- **web console**: Ghoul Rush's flashlight blaster now heats up, so holding (or hammering) space is no longer the whole game: about three seconds of fire go at the full ten bolts a second, then each bolt waits longer, down to one a second, with a **LIGHT** gauge always at the right of the HUD: a bar that fills as the blaster heats and empties as it cools, notched where the bolts start to slow, pale, then amber near the notch, then red (reading **HOT** and throbbing) past it, and in Rapid fire's pink while that runs. Let go of fire and it starts cooling after a fifth of a second, the hottest blaster in about two seconds, so firing in bursts keeps it quick. Rapid fire's bolts add no heat and ignore it.
- **web console**: Ghoul Rush has four more power-ups that are not about the blaster: a **Lantern** pulls the dark far back for 15 seconds, **Bat wings** give one flap in the air per jump for 12 seconds (a press just before landing still jumps on landing), a **Church bell** holds every monster but a boss still for 4 seconds and lets none in until it stops or you reach the door, and an **Hourglass** puts 20 seconds back on the clock. They lie in the Gallery, Library, Kitchen, Conservatory and Attic and drop from kills, and power-ups now drop twice as often, so the blaster ones turn up as often as before.
- **web console**: every Ghoul Rush room but a boss's now has a **TIME** clock in the HUD (70 to 80 seconds by the room's length), red with a tick a second in its last ten; at none it costs a life and the room starts over with a full clock.
- **web console**: Ghoul Rush has music: a track for each room (a haunted music box in the Foyer, a 9/8 synth in the Portrait Gallery, creeping pizzicato in the Library, a gothic organ for the Rotting Gourd, a cauldron swing in the Kitchen, a 5/4 synth in the Conservatory, a phonograph foxtrot in the Attic and a dark-synth fight with Bones in the Crypt). Each plays only its drone and bass in a quiet stretch and grows fuller as monsters close in and in the clock's last ten seconds, with all of it in a boss fight. It plays under **Play game music**, like Sunset Drive's songs.
- **web console**: a game with music has its own **Music** volume slider in the Activities window, beside **Full screen**, remembered per game. Sunset Drive starts at 70 and Ghoul Rush at 50, so its music sits under the house's sounds. The slider is dimmed, and says why, while **Play game music** is off.
- **web console**: Ghoul Rush hides treasure up high, over each room's key shelf (but a boss's): **crystals** worth 250 points each, and in three rooms **Silver bolts**, a power-up found nowhere else whose bolts go on through every monster they hit for 10 seconds. None of it is reachable with one jump; a jump and a **Bat wings** flap from the key shelf takes it, and each of those rooms now has Bat wings on the way.
- **web console**: in Ghoul Rush, a zombie, crawler, spitter or gourdling that reaches the edge of a pit or a drop now stops for a moment, a "?" over its head as it thinks about it, then leaps: across a pit up to 10 units wide to floor at its own height, further down to a lower floor (the Kitchen's 12-unit pit from the counter to the floor), and straight down off a ledge. Wider pits and floor higher than a step still stop it.
- **web console**: Ghoul Rush's house drone is softer, and softer still in the Portrait Gallery and the Attic, where it is pitched higher and carried most.
- **web console**: **R** starts an Activities game's round over, from the 3, 2, 1, whether it is running, paused or finished. In full screen, the panel beside the board now holds the game's **Music** slider too.
- **web console**: in Ghoul Rush, two or more zombies, runners, crawlers or gourdlings bunched under you while you wait on a shelf now climb over each other at once, arms up, to reach you, so camping over a crowd for a run of stomps no longer works; the pile comes back down once you move off. A climber's raised arms hurt you if you land on them; only a landing on its head, between them, is a stomp.
- **web console**: Ghoul Rush no longer rewards camping near the door to farm the endless stream of monsters: each kill of the room's horde (and of the dead that come once the bonus runs out) is worth 80% of the last one in that room, down to a tenth of its points, and never drops a soul or a power-up. The room's own monsters score and drop as before.
- **web console**: Ghoul Rush has three new monsters that sometimes come in place of the usual ones: the **Runner**, a skinny zombie that sprints and falls to one bolt, and gives a high shriek and a red "!" at the screen's edge as it comes into view, so one coming up behind you is heard first; the **Glutton**, a fat, slow zombie that takes five times a zombie's bolts (15), is only bruised by a stomp, and never leaps or climbs; and the rare **Huntsman**, a big spider on the floor that crouches, then springs at you as high as you are (up onto a shelf) and takes twice a widow's bolts.
- **web console**: Ghoul Rush's zombies, runners and crawlers now climb walls up to 8 high after the same moment's thought they give a pit, and walkers cross a crumbling board laid level with the floor over a pit while it is there (falling in if it gives way under them) instead of stopping at its edge.
- **web console**: the Rotting Gourd fight in Ghoul Rush is harder: the Gourd picks one of three moves at random, never one three times running: its hop onto where you stood, a spit of two acid globs (after a half-second shake) that leave burning puddles, or a quake that leaps straight up and sends a shockwave along the floor both ways when it lands (a glowing orange crest trailing green embers, lit in the dark, so it is easy to see coming). To keep that fair, the Ballroom's arena is now stacked with balconies in three tiers to move around on: up on one over the Gourd's head it only spits at you, never hops; each corner keeps a pocket its hop cannot land on; it shakes a little longer (0.85 s) before each move and has less health (65, down from 80); and its gourdlings jump up onto the balconies after you and run off their ends to follow you down.
- **web console**: every Ghoul Rush monster now has its own voice, a sound for each thing it does: coming in, climbing or hopping, growling, lunging, shrieking, diving, spitting, throwing, taking a hit and dying. That covers the zombie, runner, glutton, crawler, bat, ghost, wraith, skeleton, gourdling, hellhound, widow, huntsman and bloater, and both bosses, who also have their own wake-up, hop, slam, wind-up and death. A zombie's gurgle, a skeleton's hollow cackle and a hellhound's growl now tell you what is coming before you see it. Rapid fire on one monster plays its cry at most about seven times a second, and a Rattlebones volley plays once for its three bones.
- **web console**: Ghoul Rush is now played in **stages**, picked as you go, so no two runs go the same way. Every run starts in **the Long Hall**, a long, easy walk with only zombies. Out of it, and out of every boss's room, you choose the next stage from two you have not played that run (one, once a single stage is left). Each card shows the stage with its boss standing in it, its name and its boss; left and right pick one out, space or up goes in. A stage is three rooms and then a boss: **the Manor** (Foyer, Portrait Gallery, Library, then the Rotting Gourd in the Ballroom) and **the East Wing** (Kitchen, Conservatory, Attic, then Old Rattlebones in the Crypt). Clear every stage and you **escape**, a win with its own fanfare, instead of the rooms coming around again. Each stage cleared makes the next one's monsters quicker, tougher and let out sooner, and its boss stronger and worth more. A boss now always gives a life back, and you can hold up to **nine** lives (up from five); the 1UP also drops a little more often. The start and end screens show the most stages you have cleared in a run, with a dot per stage.
- **web console**: an Activities game can go **Full screen**: a button under the board (or `F`) gives the game the whole screen, with the browser's own full screen where it allows one. The board grows as big as its shape allows, and the room its shape leaves holds a panel with the game's name, the score line (score, the meter toward the best, the best) and **Exit full screen**: beside the board on a wide screen, along the bottom on a tall one, and where the shape leaves no room (Sunset Drive on a 16:9 screen) the board gives up a little width for it, so nothing is ever laid over the play. The pointer hides after two still seconds. `F`, `Esc` or **Exit full screen** puts it back. In the desktop app the window goes full screen too, with the console laid over the bar and the terminal. When Plan2Code needs you (a question, a sign-off or a finish) and pauses the game, the window goes back to its own size so the banner and the page show.
- **web console**: every Activities game now has a full soundscape, still made in the browser with no audio files. The sound engine gained noise, sweeping filters, layered sounds and held **hums** that follow the action, so engines rev and fall away with your speed (Sunset Drive's V8 shifts through five gears, with tire squeal, wind and traffic that passes with a Doppler drop), Rapids Run's outboard purrs over the river, Bounce Road's toy car buzzes ahead of a Monster truck's rumble, Bumper Ring's electric cars whine over a crowd, light cycles drone, fuses hiss louder as they burn down, and every Mini golf course and Ghoul Rush room has its own ambience. Crashes, splashes, explosions, landings, pickups, combos, bosses, new bests and game over each get a sound of their own in every game. A hum fades by itself the moment a game pauses or closes, and **Play sounds** still silences everything.
- **web console**: Activities games can play chiptune music, written as note data and played by a small sequencer in the page (pulse-wave leads and arpeggios, a triangle bass and a noise drum kit). A track builds with the action. Sunset Drive gives each road its own song (surf rock on Sunset Coast, flamenco on Canyon Road, a 70s funk chase through Maple Valley, uplifting trance on Snowcap Pass, darksynth in Neon City and retro sci-fi on Starlight Highway), each starting as a lone bass line at a standstill, bringing in drums, chords and the lead as you pick up speed, and playing quicker on nitro; reaching a new road crossfades into its song. It is off until you turn on **Play game music** in **User Preferences → Sounds & activities**, and it fades the moment a game pauses or closes.
- **web console**: every Activities game with lives shows them as a solid pink pill with a heart per life, readable at a glance, and the banners in Bug Hunt, Sunset Drive, Stack Deploy and Bounce Road now fade almost clear while you, or whatever is coming at you, are under them, as the other games' banners already did.
- `plan2code` opens the app automatically when a desktop is available; `plan2code --classic` (or no desktop, e.g. over SSH) keeps today's terminal-only flow unchanged, and the installer brings the app in alongside the skills and the command.
- **custom agents**: add your own agent CLIs in the web console under **User Preferences → Agents & models** (name, command, arguments with `{prompt}` and `{model}` tokens, start prompt, bypass arguments, models) with a **Test** button that shows where the command is found. They are saved in `~/.plan2code/agents.json`, listed after Claude Code, Devin and Codex by both the `plan2code` command (`--cli <id>` picks one) and the desktop app, and New Session reuses the same agent. A broken file or entry is skipped with a warning and never stops anything. `/plan2code` only works in an agent that loads the installed Plan2Code skills; a blank start prompt starts the agent with nothing typed.
- **desktop app**: when no agent CLI is installed, the first-run checklist and the launch card explain what to install, with each agent's install command, an **Install page** link, and a **Check again** button that finds a newly installed agent (or a custom one) without restarting the app.
- **desktop app**: the taskbar entry now shows when Plan2Code needs you, mirroring the console's tab icon. Windows: a green dot on your move (a finished screen too, while it still offers a button to press, such as back to the dashboard or a review), a red dot on needs attention (or a finished screen whose press was never collected), none while busy or once nothing is left to press, and one short burst of flashes when the window is not focused (the button stays lit until focused). macOS: a red `!` dock badge on needs attention and one bounce (the system badge cannot be green). Linux: a count badge where the desktop supports it, plus the urgency hint. The dot clears when the agent ends, the page reloads or the page stops answering. **User Preferences → System → Desktop app** (inside the app only) has the switch **Show on the taskbar when Plan2Code needs me**, on by default and saved in the app's own `app.json`.
- **web console**: a one-answer question (a pick-one list, or a menu) now has a **Clear** button under its options that takes the card back to how it arrived: no pick, and nothing in **Something else**. A radio pick cannot be unticked by clicking it again, so before this a stray pick could only be swapped for another. The button shows only while the answer has not been sent.
- **contributors**: `npm run play` opens the web console straight from `src/` with the server reading each page file fresh, so a change to an Activities game shows on the next page reload, without `npm run build:skills` or a reinstall.
- **first run**: when no agent CLI can be used (a fresh install, an agent installed but off PATH, the only agent gone after an uninstall, or `--cli` naming a missing agent), the `plan2code` command and the desktop app show one **setup page**: the web console running an agent-less `setup` workflow. It lists each built-in agent (Claude Code, Devin, Codex) as **found**, **found outside PATH** or **not found**, with install commands for your OS, an install page link and **Check again**, plus four starter templates (Pi, Gemini CLI, OpenCode, GitHub Copilot CLI). **Use it from here** makes an off-PATH agent usable without a restart; once an agent is found the run carries straight on, the same browser tab (or the app's launch card) picking up where it left off. With no window or no person, the command prints the install steps and exits 127. One shared agent list (`src/launcher/agents.json`, installed to `~/.plan2code/bin/`) and one lookup rule (`agent-lookup.mjs`, with a Rust twin in the app held to the same fixture cases) serve the launcher, the console and the app; the maintainer skill `plan2code-model-update` is now `plan2code-launcher-update` and re-checks the list's install data too.
### 💥 Breaking ### 💥 Breaking
- **the `plan2code-loop` CLI is no longer an install target, and the package is removed.** The `plan2code-loop/` directory is deleted, and with it the installer's `O. LOOP CLI` advanced option and the loop's install, update and uninstall wiring. Its docs (`.readme/autonomous-loop.md`, `.agents-docs/AGENTS-plan2code-loop.md`) are gone too, and every remaining mention across the docs, templates, metadata and comments is removed or reworded. The desktop app's **Implementation Loop**, which superseded the CLI, is a separate feature built into the app and is unchanged. - **the `plan2code-loop` CLI is no longer an install target, and the package is removed.** The `plan2code-loop/` directory and the installer's `O. LOOP CLI` option are gone; the desktop app's **Implementation Loop** supersedes it. Stale installs are still cleaned up: update and uninstall remove the old global `plan2code-loop` command and npm package when they are present.
**Stale installs are still cleaned up.** `install.js` keeps a small `removeLegacyLoopShims()` step that removes the old global artifacts (`plan2code-loop`, `plan2code-loop.cmd`, `plan2code-loop.ps1` and `node_modules/plan2code-loop` under the npm prefix) when they are present. `update()` runs it once before reinstalling and quietly skips a stale `"loop"` entry in `~/.plan2code/install.json`; uninstall runs it too.
### 🔧 Changed ### 🔧 Changed
- **web console**: **User Preferences** is now four tabs in a side list (a sideways strip on narrow screens) instead of one long column: **Appearance**, **Agents & models**, **System** and **Sounds & activities**. Look and sound settings still save as they change and now show a **Saved** mark; **Back to default** resets only its own tab (and is hidden on the two tabs it has nothing to reset), and **Done** reads **Close**. **Agents & models** is a summary table of Claude Code, Devin, Codex and your own agents, with each one's models and a **Found** / **Not found** on PATH badge, and **Edit** opens a full form per agent with **Save** and **Discard**, an **Unsaved** badge and a Save / Discard / Keep editing prompt before an unsaved edit is lost. The separate Models section is gone: each built-in agent's form lists the models that come with Plan2Code beside your own. Help shares the same tab handling, and its User Preferences topic now covers every tab. - **web console**: **User Preferences** is now four tabs (Appearance, Agents & models, System, Sounds & activities), **Agents & models** is a list beside a form for the picked agent, and **Highlight color** offers 38 colors.
- **docs**: all prose, help text, skill prompts and comments now use US English spelling (color, gray, behavior, canceled, -ize), and `npm test` checks it (`scripts/test-us-english.mjs`). - **web console**: reads right inside the desktop app. Advice that assumed a terminal (the session meter, the update banner, the finished-step guide, Help) points at the app's **New Session**, **Update skills** and **Reconnect the console** instead.
- **web console**: **User Preferences → Appearance → Highlight color** now offers 38 colors in two rows of nineteen, covering the range of a Paint-style picker: new **Maroon**, **Peach**, **Brown**, **Cream**, **Lemon**, **Forest**, **Mint**, **Aqua**, **Lavender**, **Pink** and **Mono** (near-black in light mode, near-white in dark). Five near twins were merged (Copper into Rust, Marigold into Gold, Mustard into Lemon, Jade into Emerald, Lilac into Violet); a saved choice of one of those keeps its twin instead of falling back to Ocean. - **launcher**: `plan2code` asks whether to turn the agent's permission prompts off (Yes by default; `--keep-permissions` keeps them), and with no agent installed it prints each agent's install command and page before it exits.
- **web console**: the **Subagents** dialog is wider and shorter, like the Notebook: Helpers and At most share a row, and the four Helper strength choices sit side by side, each wearing the Subagents tab's colored level badge (Thrifty light, Balanced standard, Best strongest, Match my session plain), now ordered from lightest to strongest. - **docs**: all prose, help text, skill prompts and comments use US English spelling, and `npm test` checks it.
- **launcher**: after you pick the agent, `plan2code` now asks whether to turn its permission prompts off (Yes by default, so pressing Enter starts it as before), and only for an agent that has a flag for it: every built-in does, a custom agent only when it has bypass arguments. `plan2code --keep-permissions` keeps the prompts without asking; with no terminal to ask on, prompts are off as before. The installer no longer prints its warning about the command starting agents with prompts off.
- **launcher**: when no agent CLI is installed, `plan2code` now prints each supported agent's install command and official page, and points at User Preferences → Agents & models for another CLI, before it exits.
- **desktop app**: a clean start is now one press. Pathfinder's **Start fresh** menu option reads **Start New Session** under the app, and sending it asks the app for its New Session (the resume command is copied first; declining the app's confirm leaves the usual finish). A finished step that names a skill to run next shows a **Start a New Session** button beside its command, also copying the command first. The plain web console keeps its wording and does neither. The app's console frame also now allows clipboard writes, so the copied command and every **Copy** button can reach the clipboard there.
- **desktop app**: the launch card's agent choice is built from the agents that are installed, so a machine with only Devin or Codex starts on it with Start enabled, instead of assuming Claude Code.
- **desktop app**: the window now opens maximized, filling the screen with the title bar and taskbar still showing; restoring it from maximized gives the old 1280x800 size.
- **launcher**: `plan2code` no longer treats an SSH or service session on macOS or Windows as having a desktop, and asks before opening a folder that looks like it is not a project (no `.git`, `AGENTS.md` or `specs/`).
- **desktop app**: the app's own bar no longer repeats the open page as a second "page: " label; the console's own bar, inside the window, already names it. The web console now knows when the agent driving it is the desktop app (the same signal that already routed `open` to the app's window) and, only there, drops advice that assumed a plain terminal: its session meter, the finished-step guide and the dashboard's red-session banner point at the app's own **New Session** button instead of a command to paste into a new conversation; its own "update available" banner, a copy-pasted shell command, never shows, since **Update skills** already covers it in one click with no shell involved; and a slash command still offered to continue a step says to paste it into the app's terminal panel, which runs the real agent CLI, rather than "a new conversation" that does not exist there. Running a plain terminal is unchanged.
- **desktop app**: dropped the bar's own context-window meter and its restart nudge, front and back: a second, separately-tuned gauge beside the console's own Session meter (how much plan2code work this session has done) read as a duplicate of it, so there is now just the one, and it already points at New Session under the app (see above). The `agent_context` command, the Claude/Codex transcript readers behind it, and the context-nudge setting it read are removed from the Rust side too, not just unwired in the page. Every button that reconnects the console (after it stops, or after Update skills) is now labeled **Reconnect the console**, replacing the earlier mix of "Restart the console" and "Start it again" for the same action, and only one shows at a time.
- **desktop app**: the launch card's permission-mode tick is now **on by default** (checks off), matching the terminal's own default; untick it for an agent that keeps its normal approval prompts.
- **web console**: Help's "When an update is out" line now knows when it is read inside the app too: there, it names **Update skills** in the bar instead of describing the dashboard's UPDATE AVAILABLE banner and a terminal command, since that banner never shows under the app and the command has no terminal to run in.
- **desktop app**: the top bar's **Restart** button is now **New Session**, and every place the console names it under the app (the session meter, the dashboard's red-session banner, the finished-step guide, the Welcome tip, Help's Ask and Finishing topics, the handoff copy button's description) says so too; the meter's own advice under the app is a single **Start a New Session** button in the user's highlight color. Its confirmation no longer claims "What it was doing is not saved" (not always true).
- **desktop app**: with nothing saved yet, the terminal panel now starts docked right at a width that keeps the console's own side panels (such as Notes) from stacking under the main content, instead of the bottom dock it always opened with before; a saved choice from before is still kept exactly as it was.
- **desktop app**: the collapsed terminal panel's **Expand** button now reads **View Agent Terminal**, and docked right it reads top to bottom instead of running off the edge of the narrow strip.
- **desktop app**: the agent no longer prints the console's web address in the terminal panel, since the page is already in the window beside it: `terminalLine` under the app points at the dashboard instead, and the agent contract says to give no link there.
- **desktop app**: the console's "Not running... type **continue**" line makes **continue** a button under the app, which types `continue` and Enter (and, under Claude Code, its send-now chord) into the agent's terminal panel for you; the session meter's **Start a New Session** button presses the bar's own New Session (its confirmation included), replacing a "Press New Session at the top of the window" sentence now that the press works from there.
- **desktop app**: **New Session** now starts the fresh agent on a new console session, so the session meter starts over at green. Before, the fresh agent joined the window's old session, and the meter stayed red after the very press it asks for. The brief of where you were is still written from the old session first, and the old console shuts itself down once the window moves on.
- **web console**: the **Wrapping up** dialog after **Stop session** no longer closes itself when the stop lands: it turns into **Done**, with every step ticked, and stays up until you close it, so someone who stepped away comes back to an answer. Its "you can close the window/tab if you need to" line is gone.
- **web console**: a plan's **Build order** card has a **Combine phases** button beside **No changes**. One click fills the box with a request to merge phases where possible while keeping each to a clear concern. It shows only in Plan and Revise plan, where the breakdown is phases.
- **web console**: Help now reads right in the desktop app throughout, not just in the topics fixed before: what this page is and how long it runs, the troubleshooting table and its diagram, scroll memory, drafts, the session meter's red advice, Ask's "no agent" line and Privacy's link and address notes all name the app's window, its terminal panel, **New Session** and **Reconnect the console** instead of a browser tab, a link or a new conversation. The status line's approval hint says "the terminal panel" there too. In a browser, Help is unchanged.
- **desktop app**: the top bar's buttons now look like the console's own: rounded, quiet until hovered, then in your highlight color from User Preferences (the app keeps it for the next launch), with **New Session** outlined in it as the likely next step.
- **desktop app**: the New Session confirmation shows Planny, drawn like the console's own (outlined shell, star eye, smile), holding a steaming cup of coffee, and its buttons use the console's style: **New Session** in your highlight color, **Cancel** a plain button. The same highlight applies to the panel's other one-button prompts, such as **Retry** and **Reconnect the console**.
- **desktop app**: the top bar is rebuilt around two menus and one next step. The project shows as its folder name, with the full path and **Change project** in its menu; **New Session** always sits just left of the agent's menu, which carries a state dot, an amber **checks off** badge in place of the "Permission checks are off for ..." sentence, and **Change agent** once the agent has ended. The console's and the skills' messages share one slot at the right end that shows the most pressing step with its button (**Reconnect the console**, **Update skills**) and "+N more" for the rest, so the bar no longer overflows when several things go wrong at once. The repeated "Plan2Code" label, the full path, the "agent:" prefix and the long "Nothing starts until you press New Session" line are gone.
- **web console**: **User Preferences → Agents & models** is rebuilt as a master-detail split: the agent list stays pinned on the left and picking a row opens that agent's form in the pane beside it, so moving between agents no longer goes through a summary-to-form round trip. The same split carries the agent-less setup page (pick list left, state and way forward right). Behind it `agents-view.js` is split into a `screens/agents/` component set (data, list editor, summary, form) behind the unchanged `mountAgentsView` API, and the agent styles live in their own `styles/agents.css`. The setup page's starter templates are offered on the tab too, under **Or start from a template**: **Use this template** opens the new-agent form prefilled. Every capability is kept: per-form Save and Discard, the Unsaved prompt, Test, Delete, the 409 Save anyway path, and the setup states and templates. The Preferences dialog itself now follows the Card width pick, never wider than the wide preset (1080px), instead of a fixed 880px.
### 🐛 Fixed ### 🐛 Fixed
- **custom agents**: on Windows, a custom agent whose installer added its folder to the user PATH is now offered by `plan2code` and the desktop app every time, not only from a terminal opened after the install. Both read the saved PATH as well as the one they inherited, and the agent starts with it too. - **custom agents**: on Windows, an agent whose installer added its folder to the user PATH is offered right away, not only from a terminal opened after the install.
- **web console**: on the dashboard, canceling one spec's Delete and quickly opening another's no longer leaves **Delete it** doing nothing; the first dialog's late close cleared the second dialog's spec. - **web console**: a finished screen's press that nothing picks up now says Plan2Code is not running and how to continue, a failed Send says why, and links that leave the console open in the default browser from the desktop app.
- **web console**: a handoff's **Copy** button keeps showing **Copied** (or **Copy was refused**) when the dashboard redraws while the clipboard answers, instead of the word landing on a button that was already replaced. - **desktop app**: a test console started during a build can no longer take over the window, and a console too busy to answer a health check is no longer swapped for an empty dashboard mid-build.
- **web console**: a finished screen's press (**Commit it now**, **Update CHANGELOG first**, **Back to the dashboard**, **Continue here**, a review) that nothing picks up, because the agent's turn ended while the screen waited, no longer says "Opening Changelog…" forever. After a minute of silence the line beside Planny says Plan2Code is not running and the choice is saved, with **continue** to type in the terminal (a button that types it there, under the app).
- **desktop app**: under Claude Code, the console's **continue** button also sends Claude Code's send-now chord (ctrl+x ctrl+s), so a `continue` it held as a queued message behind a stuck turn is delivered in one press instead of waiting in the terminal.
- **desktop app**: links that leave the console (**Open pull request**, links in documents, the feedback button) open in the default browser instead of doing nothing; when no browser can be started, the page shows the link with a **Copy** button to paste into one.
- **web console**: answers sent and not picked up bring up the "not running, type **continue**" help after a minute of the agent's silence (three when it said it was working), instead of after its quiet allowance, which a build can set to half an hour.
- **web console**: a failed Send says why: the lost-contact state and its reconnect help at once when the console is gone, the console's reason when it refuses the send, or that the console is still up and Send can be pressed again.
- **desktop app**: a test console started inside the app (for example by `cargo test` during a build) can no longer take over the window. Before, the window followed it, then fell back to an empty dashboard once the test shut it down, and the build's question sat on a page no one could see. The app now ignores any page whose session is not in its own console store.
- **desktop app**: a console too busy to answer a health check in time (a machine running a test suite) is given a second, longer look and then resumed on the same session. It is no longer swapped for a fresh, empty dashboard mid-build.
- **desktop app**: the Implementation Loop's end screen offers **Back to the dashboard** next to its other actions, on a finished loop and a stopped one, and it works with no agent running (it opens a fresh dashboard console session in the frame). The screen's status line also tells the truth now: it reads "Loop finished. Pick what happens next." (or "The loop stopped.") as your move instead of spinning "Starting Building + review…", so the taskbar dot goes green there instead of staying dark while the loop's finished page waits.
## v2.11.1 ## v2.11.1
+3 -1
View File
@@ -16,7 +16,7 @@ The web console is the main way in: a local page where questions, documents, bui
| From your project (shell) | `plan2code` | Opens Claude Code, Devin or Codex on the dashboard (`--cli claude` / `devin` / `codex` to choose) | | From your project (shell) | `plan2code` | Opens Claude Code, Devin or Codex on the dashboard (`--cli claude` / `devin` / `codex` to choose) |
| Inside any agent | `/plan2code` (`$plan2code` in Codex) | Opens the dashboard: a card for every skill, launched on the same page | | Inside any agent | `/plan2code` (`$plan2code` in Codex) | Opens the dashboard: a card for every skill, launched on the same page |
| Install | `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git` | Installs the skills and the `plan2code` command (re-run it to update without the `plan2code` command) | | Install | `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git` | Installs the skills and the `plan2code` command (re-run it to update without the `plan2code` command) |
| Update | `plan2code update` | Updates everything that was installed, with no menu; never uninstalls anything | | Update | `plan2code update` | Updates the skills, command, app and status line, with no menu (metrics and the bot only from a git checkout: `node install.js`); never uninstalls anything |
| Straight into a skill | `/plan2code-1-plan --web` (any step) | Skips the "web console or terminal?" question and opens the page | | Straight into a skill | `/plan2code-1-plan --web` (any step) | Skips the "web console or terminal?" question and opens the page |
The install command always opens a menu. Back at your prompt with no output at all? npm could not reach the repository and hid the reason: run `git ls-remote https://github.com/jparkerweb/plan2code.git` to see it (usually the network, a proxy or the VPN). The install command always opens a menu. Back at your prompt with no output at all? npm could not reach the repository and hid the reason: run `git ls-remote https://github.com/jparkerweb/plan2code.git` to see it (usually the network, a proxy or the VPN).
@@ -46,6 +46,8 @@ Every command below is what a dashboard card runs. Typed on its own, each one as
| handoff | /plan2code-handoff | Conversation | Self-contained handoff doc (OS temp dir by default, or a folder you pick such as `handoffs/`) | | handoff | /plan2code-handoff | Conversation | Self-contained handoff doc (OS temp dir by default, or a folder you pick such as `handoffs/`) |
| xray | /plan2code-xray | An area, or none | An explanation citing files and commits, or `ARCHITECTURE-BRIEF-<date>.md` with the rough spots you picked | | xray | /plan2code-xray | An area, or none | An explanation citing files and commits, or `ARCHITECTURE-BRIEF-<date>.md` with the rough spots you picked |
| diagnose | /plan2code-diagnose | A bug, or none | `DIAGNOSIS-<date>.md` with the cause and its evidence, then Quick Task (or Plan for a big fix) to fix it | | diagnose | /plan2code-diagnose | A bug, or none | `DIAGNOSIS-<date>.md` with the cause and its evidence, then Quick Task (or Plan for a big fix) to fix it |
| pr-prep | /plan2code-pr-prep | Your branch | A readiness verdict (Ready, Ready with notes, Not ready) and a PR description to copy; no commits, no push |
| test | /plan2code-test | An area, or none | New unit and integration tests in the project's style, run; a bug handed to Diagnose; no source changes |
| changelog | /plan2code-changelog | Your branch | `CHANGELOG.md` entries and the `package.json` version, from the default branch's latest version | | changelog | /plan2code-changelog | Your branch | `CHANGELOG.md` entries and the `package.json` version, from the default branch's latest version |
| git | /plan2code-git | Your repo | Commits (`<subject>` / `AI Assisted`), branches, pull with conflict help, push, publish | | git | /plan2code-git | Your repo | Commits (`<subject>` / `AI Assisted`), branches, pull with conflict help, push, publish |
+4
View File
@@ -250,6 +250,8 @@ The dashboard's cards, and when each one lights up for the spec you pick:
| Handoff | Pack this conversation into a document a fresh session can pick up cold. Any skill's **Stop with a handoff** writes one too, and the dashboard lists them to pick up. | Always | | Handoff | Pack this conversation into a document a fresh session can pick up cold. Any skill's **Stop with a handoff** writes one too, and the dashboard lists them to pick up. | Always |
| Codebase X-ray | Explain how and why an area works, or find the rough spots worth fixing. | Always | | Codebase X-ray | Explain how and why an area works, or find the rough spots worth fixing. | Always |
| Diagnose a bug | Find a bug's cause and write it up, without fixing it. | Always | | Diagnose a bug | Find a bug's cause and write it up, without fixing it. | Always |
| Get a PR ready | Runs the checks your branch needs, says if it is ready, and writes the PR description to copy. Never commits, pushes or opens the PR. | Always |
| Write missing tests | Finds code with no tests and writes unit and integration tests in your project's own style. Never changes source code. | Always |
| Changelog | Checks the CHANGELOG version against the main branch and suggests entries for what is new. | Always | | Changelog | Checks the CHANGELOG version against the main branch and suggests entries for what is new. | Always |
| Git | Branches, pull, push and commits on one board, asking before anything leaves your machine. | Always (offers to start a repository outside one) | | Git | Branches, pull, push and commits on one board, asking before anything leaves your machine. | Always (offers to start a repository outside one) |
@@ -420,6 +422,8 @@ console or the terminal; add `--web` to skip the question and go straight to the
| `/plan2code-handoff` | Compact this conversation into a doc the next one resumes from, saved in `~/.plan2code/handoffs/` and listed on the dashboard to pick up | | `/plan2code-handoff` | Compact this conversation into a doc the next one resumes from, saved in `~/.plan2code/handoffs/` and listed on the dashboard to pick up |
| `/plan2code-xray` | Explain how and why an area of the code works (citing files, commits and PRs), or rank the rough spots worth fixing into a brief for Pathfinder or Plan; never edits code | | `/plan2code-xray` | Explain how and why an area of the code works (citing files, commits and PRs), or rank the rough spots worth fixing into a brief for Pathfinder or Plan; never edits code |
| `/plan2code-diagnose` | Find a bug's cause and write it up as `specs/<bug-name>/DIAGNOSIS-<date>.md` without fixing it, then offer `/plan2code-quick-task` to fix it, or `/plan2code-1-plan` when the fix is big | | `/plan2code-diagnose` | Find a bug's cause and write it up as `specs/<bug-name>/DIAGNOSIS-<date>.md` without fixing it, then offer `/plan2code-quick-task` to fix it, or `/plan2code-1-plan` when the fix is big |
| `/plan2code-pr-prep` | Before you open a pull request. Picks the checks the branch's changes need from the project's `## Test map` (or its config files), runs the ones you keep, says Ready, Ready with notes or Not ready, and writes a PR description to copy with the create-a-PR link; never commits, pushes or opens the PR |
| `/plan2code-test` | Parts of the code have no tests. Asks where to look, finds the untested files (plus real coverage when the project already has a coverage tool), shows a plan in the project's own style, then writes and runs unit and integration tests; never changes source code, hands a real bug to `/plan2code-diagnose` |
| `/plan2code-changelog` | Check the CHANGELOG version against the default branch, suggest entries for new work you can edit, keep `package.json` aligned, then hand off to Git to commit | | `/plan2code-changelog` | Check the CHANGELOG version against the default branch, suggest entries for new work you can edit, keep `package.json` aligned, then hand off to Git to commit |
| `/plan2code-git` | Branches, pull, push and commits on one board (or plain instructions in the terminal); asks before every push, publish and delete | | `/plan2code-git` | Branches, pull, push and commits on one board (or plain instructions in the terminal); asks before every push, publish and delete |
+2 -1
View File
@@ -146,6 +146,7 @@ not), so your own edits never end up inside a phase's commit.
- **Fix findings**: **Smart pick** (the default) has a fresh agent read the findings and fix only the - **Fix findings**: **Smart pick** (the default) has a fresh agent read the findings and fix only the
ones worth fixing, recording every skip. A skipped Critical stops the phase. **By level** fixes the ones worth fixing, recording every skip. A skipped Critical stops the phase. **By level** fixes the
Critical, Warning and Suggestion findings you tick (all three start ticked). Critical, Warning and Suggestion findings you tick (all three start ticked).
- **Strength per phase** (off): turn on **Set strength per phase** to pick **Thrifty**, **Balanced**, **Best** or **Match my session** for each phase still to build (or **Set all to** one pick). A phase you leave untouched runs on the model the app was launched with, as before. A phase whose agent crashes or goes quiet gets its one retry (when the retry tick is on) one step up (Thrifty to Balanced, Balanced to Best; Best stays Best; **Match my session** runs on the launch model and its retry stays there), and the phase's helpers follow the same strength. Which model each word means for your agent is set in User Preferences, **Agents & models**, under **Strengths in the loop**; an agent with nothing mapped shows the toggle off with a link there. The picks are remembered per project and spec, and a pick for a phase that is done or gone is dropped.
- **When a phase asks something**: **Take the agent's best guess** (the default), which records the - **When a phase asks something**: **Take the agent's best guess** (the default), which records the
assumption as a `[?]` task, **Pause and wait for me**, or **Stop the loop**. assumption as a `[?]` task, **Pause and wait for me**, or **Stop the loop**.
- **After the last phase**: **Stop and offer Finalize** (the default) or **Run Finalize automatically**. - **After the last phase**: **Stop and offer Finalize** (the default) or **Run Finalize automatically**.
@@ -221,7 +222,7 @@ evidence, when:
- the Smart pick skipped a Critical finding. - the Smart pick skipped a Critical finding.
A crashed or silent agent gets exactly one retry per phase when the retry tick is on, and none when it is off. A crashed or silent agent gets exactly one retry per phase when the retry tick is on, and none when it is off.
It never retries a real failure. On a stop screen, **Resume the loop** carries on from the stopped It never retries a real failure. On a stop screen, **Ask a question** (first in the row, offered whenever Resume is) wakes an ordinary agent on the stopped phase on the same page, so the Ask tab answers; it starts no loop and changes nothing, and **Resume the loop** is still there afterwards. **Resume the loop** carries on from the stopped
phase and **Fix it by hand** opens an ordinary Implement session on it. phase and **Fix it by hand** opens an ordinary Implement session on it.
**The report.** One report follows the whole build, across stops and Resume. For every phase it says what **The report.** One report follows the whole build, across stops and Resume. For every phase it says what
+706 -125
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 110 KiB

After

Width:  |  Height:  |  Size: 119 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 114 KiB

After

Width:  |  Height:  |  Size: 122 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 109 KiB

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 119 KiB

After

Width:  |  Height:  |  Size: 123 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 115 KiB

After

Width:  |  Height:  |  Size: 117 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 122 KiB

After

Width:  |  Height:  |  Size: 122 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 103 KiB

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 106 KiB

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 117 KiB

After

Width:  |  Height:  |  Size: 119 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 96 KiB

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 104 KiB

After

Width:  |  Height:  |  Size: 105 KiB

+46 -6
View File
@@ -143,7 +143,7 @@ const SOURCE_PROMPTS = [
displayName: 'Init Mode', displayName: 'Init Mode',
description: 'Generate AGENTS.md file for project-specific guidance', description: 'Generate AGENTS.md file for project-specific guidance',
isUtility: true, isUtility: true,
scripts: ['agents-md.mjs', 'agent-files.mjs'], scripts: ['agents-md.mjs', 'agent-files.mjs', 'test-map.mjs', 'glob.mjs', 'test-commands.mjs'],
additionalReferences: [ additionalReferences: [
{ source: 'web-console', target: 'web-console' }, { source: 'web-console', target: 'web-console' },
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' } { source: 'shared-references/helper-strength.md', target: 'helper-strength.md' }
@@ -156,7 +156,7 @@ const SOURCE_PROMPTS = [
displayName: 'Init Update Mode', displayName: 'Init Update Mode',
description: 'Update existing AGENTS.md with new learnings', description: 'Update existing AGENTS.md with new learnings',
isUtility: true, isUtility: true,
scripts: ['agents-md.mjs', 'agent-files.mjs', 'commit-msg.mjs'], scripts: ['agents-md.mjs', 'agent-files.mjs', 'commit-msg.mjs', 'test-map.mjs', 'glob.mjs', 'test-commands.mjs'],
additionalReferences: [ additionalReferences: [
{ source: 'web-console', target: 'web-console' }, { source: 'web-console', target: 'web-console' },
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' } { source: 'shared-references/helper-strength.md', target: 'helper-strength.md' }
@@ -332,6 +332,35 @@ const SOURCE_PROMPTS = [
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' } { source: 'shared-references/helper-strength.md', target: 'helper-strength.md' }
] ]
}, },
{
source: 'plan2code-pr-prep.md',
stepNumber: 'pr-prep',
name: 'pr-prep',
displayName: 'PR Prep Mode',
description: 'Pick and run the checks a branch needs, give a readiness verdict and write the PR description',
isUtility: true,
scripts: ['review-scope.mjs', 'glob.mjs', 'test-map.mjs', 'test-match.mjs', 'test-commands.mjs', 'run-check.mjs'],
additionalReferences: [
{ source: 'web-console', target: 'web-console' },
{ source: 'shared-references/test-runs.md', target: 'test-runs.md' },
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' }
]
},
{
source: 'plan2code-test.md',
stepNumber: 'test',
name: 'test',
displayName: 'Test Mode',
description: 'Find untested code and write unit and integration tests in the project\'s own style',
isUtility: true,
scripts: ['review-scope.mjs', 'glob.mjs', 'test-map.mjs', 'test-match.mjs', 'test-commands.mjs', 'run-check.mjs'],
additionalReferences: [
{ source: 'web-console', target: 'web-console' },
{ source: 'shared-references/test-runs.md', target: 'test-runs.md' },
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' },
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' }
]
},
{ {
source: 'plan2code-changelog.md', source: 'plan2code-changelog.md',
stepNumber: 'changelog', stepNumber: 'changelog',
@@ -380,6 +409,8 @@ function generateStepLabel(prompt) {
if (prompt.stepNumber === 'git') return 'Git'; if (prompt.stepNumber === 'git') return 'Git';
if (prompt.stepNumber === 'xray') return 'X-ray'; if (prompt.stepNumber === 'xray') return 'X-ray';
if (prompt.stepNumber === 'diagnose') return 'Diagnose'; if (prompt.stepNumber === 'diagnose') return 'Diagnose';
if (prompt.stepNumber === 'pr-prep') return 'PR Prep';
if (prompt.stepNumber === 'test') return 'Test';
if (prompt.stepNumber === 'changelog') return 'Changelog'; if (prompt.stepNumber === 'changelog') return 'Changelog';
if (prompt.stepNumber === 'quick') return 'Quick Task'; if (prompt.stepNumber === 'quick') return 'Quick Task';
return `Step ${prompt.stepNumber}`; return `Step ${prompt.stepNumber}`;
@@ -2274,10 +2305,12 @@ function getLauncherShims(binDir, nodePath = process.execPath) {
'@echo off', '@echo off',
`rem ${LAUNCHER_MARKER}`, `rem ${LAUNCHER_MARKER}`,
`if not exist "${cmdNode}" goto p2c_path_node`, `if not exist "${cmdNode}" goto p2c_path_node`,
`"${cmdNode}" "${cmdDest}" %*`, // Each command ends its own line with `& exit /b`: cmd.exe reads a running .cmd by byte
'exit /b %ERRORLEVEL%', // offset, and `plan2code update` rewrites this file while it runs, so nothing may be read
// after the command returns. A bare `exit /b` keeps the command's exit code.
`"${cmdNode}" "${cmdDest}" %* & exit /b`,
':p2c_path_node', ':p2c_path_node',
`node "${cmdDest}" %*`, `node "${cmdDest}" %* & exit /b`,
'', '',
].join('\r\n'), ].join('\r\n'),
}, },
@@ -2566,7 +2599,7 @@ function uninstallLauncher() {
const shortcut = getShortcutFile(); const shortcut = getShortcutFile();
if (isOurShortcut(shortcut)) remove(shortcut); if (isOurShortcut(shortcut)) remove(shortcut);
forgetInstalled('launcher'); forgetInstalled('launcher');
for (const file of [LAUNCHER_DEST, MODELS_DEST, UPDATE_CHECK_DEST, LAUNCHER_VERSION_DEST, SHORTCUT_ICON_DEST, SHORTCUT_PNG_DEST, LAUNCHER_STATE, INSTALL_RECORD]) { for (const file of [LAUNCHER_DEST, MODELS_DEST, UPDATE_CHECK_DEST, LAUNCHER_VERSION_DEST, SHORTCUT_ICON_DEST, SHORTCUT_PNG_DEST, LAUNCHER_STATE, INSTALL_RECORD, AGENTS_DEST, AGENT_LOOKUP_DEST]) {
if (fs.existsSync(file)) remove(file); if (fs.existsSync(file)) remove(file);
} }
try { try {
@@ -2824,6 +2857,13 @@ async function update({ steps = UPDATE_STEPS, cleanShims = removeLegacyLoopShims
const results = {}; const results = {};
for (const piece of INSTALL_PIECES) { for (const piece of INSTALL_PIECES) {
if (!pieces.includes(piece) || piece in results) continue; if (!pieces.includes(piece) || piece in results) continue;
// The metrics and bot commands run from this folder: from npx's cache (which the launcher
// note above calls free to delete) they would break once it is cleared, so only a checkout updates them.
if ((piece === 'metrics' || piece === 'bot') && !fs.existsSync(path.join(__dirname, '.git'))) {
results[piece] = 'kept (update it from a git checkout: node install.js)';
console.log('');
continue;
}
const outcome = {}; const outcome = {};
try { try {
const code = await steps[piece]({ quiet: true, unattended: true, outcome }); const code = await steps[piece]({ quiet: true, unattended: true, outcome });
+1 -1
View File
@@ -11,7 +11,7 @@
"fix:eol": "node scripts/fix-line-endings.mjs", "fix:eol": "node scripts/fix-line-endings.mjs",
"play": "node scripts/play.mjs", "play": "node scripts/play.mjs",
"pretest": "node scripts/fix-line-endings.mjs", "pretest": "node scripts/fix-line-endings.mjs",
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-pointers.mjs scripts/test-console-wire-budgets.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-banister.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-tray.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-intro.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-story.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-skill-test-runs.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-agent-lookup.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-activities.mjs scripts/test-web-console-page-setup.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs" "test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-test-map.mjs scripts/test-script-test-match.mjs scripts/test-script-test-commands.mjs scripts/test-script-run-check.mjs scripts/test-script-pr-prep.mjs scripts/test-script-coverage.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-pointers.mjs scripts/test-console-wire-budgets.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities-flock.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-lantern.mjs scripts/test-web-console-activities-ghoul-marrow.mjs scripts/test-web-console-activities-ghoul-mat.mjs scripts/test-web-console-activities-ghoul-eye.mjs scripts/test-web-console-activities-ghoul-bonestair.mjs scripts/test-web-console-activities-ghoul-heart.mjs scripts/test-web-console-activities-ghoul-ending.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-banister.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-tray.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-intro.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-story.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-send-state.mjs scripts/test-web-console-strengths.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-skill-test-runs.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-agent-lookup.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-activities.mjs scripts/test-web-console-page-setup.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs"
}, },
"devDependencies": { "devDependencies": {
"gpt-tokenizer": "2.9.0", "gpt-tokenizer": "2.9.0",
+1
View File
@@ -10,6 +10,7 @@
//! REPORT <json> write <json> as `loopOutcome` into the session's state.json //! REPORT <json> write <json> as `loopOutcome` into the session's state.json
//! (PLAN2CODE_CONSOLE_HOME and PLAN2CODE_CONSOLE_SID name it), say //! (PLAN2CODE_CONSOLE_HOME and PLAN2CODE_CONSOLE_SID name it), say
//! `REPORT written` (`REPORT unavailable` when either is missing) //! `REPORT written` (`REPORT unavailable` when either is missing)
//! ENV <name> print the variable as `ENV <name>=<value>`
//! HANG say `HANGING`, then go silent for good (no more lines read) //! HANG say `HANGING`, then go silent for good (no more lines read)
//! <other> echoed back as `echo: <line>` //! <other> echoed back as `echo: <line>`
//! //!
+105 -8
View File
@@ -207,6 +207,8 @@ impl AgentManager {
}, },
brief, brief,
prompt, prompt,
None,
Vec::new(),
) )
} }
@@ -231,6 +233,42 @@ impl AgentManager {
}, },
None, None,
prompt, prompt,
None,
Vec::new(),
)
}
/// `start_transient` for a loop phase that runs on its own strength after
/// the agent was stopped: the stored launch choice is `kind`, `model`,
/// `effort` and `mode` (so a later New Session or phase runs on it), while
/// this one launch runs on `phase_model` and `phase_effort` with
/// `extra_env` added.
pub fn start_transient_on(
&self,
launch: (Agent, Option<String>, Option<String>, PermissionMode),
prompt: String,
phase_model: String,
phase_effort: Option<String>,
extra_env: Vec<(String, String)>,
) -> Result<(), String> {
let (kind, model, effort, mode) = launch;
let on = StartChoice {
kind: kind.clone(),
model: Some(phase_model),
effort: phase_effort,
mode,
};
self.begin(
StartChoice {
kind,
model,
effort,
mode,
},
None,
prompt,
Some(on),
extra_env,
) )
} }
@@ -242,6 +280,8 @@ impl AgentManager {
choice: StartChoice, choice: StartChoice,
restart_brief: Option<String>, restart_brief: Option<String>,
first_prompt: String, first_prompt: String,
launch_choice: Option<StartChoice>,
launch_env: Vec<(String, String)>,
) -> Result<(), String> { ) -> Result<(), String> {
let mut inner = lock(&self.shared.inner); let mut inner = lock(&self.shared.inner);
if inner.state == AgentState::Running { if inner.state == AgentState::Running {
@@ -249,7 +289,10 @@ impl AgentManager {
} }
inner.brief_note = None; inner.brief_note = None;
let previous = inner.last_start.replace((choice, restart_brief)); let previous = inner.last_start.replace((choice, restart_brief));
match self.shared.spawn(&mut inner, first_prompt) { match self
.shared
.spawn(&mut inner, first_prompt, launch_choice, launch_env)
{
Ok(()) => Ok(()), Ok(()) => Ok(()),
Err(e) => { Err(e) => {
// A start that never ran must not take away what Restart would // A start that never ran must not take away what Restart would
@@ -270,6 +313,42 @@ impl AgentManager {
/// was, so a later New Session still opens the dashboard, not this /// was, so a later New Session still opens the dashboard, not this
/// prompt again. /// prompt again.
pub fn start_fresh(&self, prompt: String) -> Result<(), String> { pub fn start_fresh(&self, prompt: String) -> Result<(), String> {
self.fresh(prompt, None, Vec::new())
}
/// Like `start_fresh`, but the agent runs on `model` and `effort` for this
/// launch alone, with `extra_env` added to its environment: the loop's way
/// to start a phase on its strength. The agent kind and permission mode
/// stay the stored launch choice's, and the stored choice itself is never
/// written, so a later `start_fresh`, New Session or Restart runs on the
/// original model and effort without `extra_env`.
pub fn start_phase_on(
&self,
prompt: String,
model: String,
effort: Option<String>,
extra_env: Vec<(String, String)>,
) -> Result<(), String> {
let stored = lock(&self.shared.inner)
.last_start
.as_ref()
.map(|(choice, _)| choice.clone())
.ok_or("no agent has been started")?;
let choice = StartChoice {
model: Some(model),
effort,
..stored
};
self.fresh(prompt, Some(choice), extra_env)
}
/// The kill-then-spawn body `start_fresh` and `start_phase_on` share.
fn fresh(
&self,
prompt: String,
choice: Option<StartChoice>,
extra_env: Vec<(String, String)>,
) -> Result<(), String> {
let mut inner = lock(&self.shared.inner); let mut inner = lock(&self.shared.inner);
if inner.last_start.is_none() { if inner.last_start.is_none() {
return Err("no agent has been started".to_string()); return Err("no agent has been started".to_string());
@@ -282,7 +361,7 @@ impl AgentManager {
let _ = old.host.kill(); let _ = old.host.kill();
} }
} }
match self.shared.spawn(&mut inner, prompt) { match self.shared.spawn(&mut inner, prompt, choice, extra_env) {
Ok(()) => Ok(()), Ok(()) => Ok(()),
Err(e) => { Err(e) => {
inner.state = AgentState::Ended { inner.state = AgentState::Ended {
@@ -427,11 +506,28 @@ impl Shared {
/// end. `prompt` is this launch's first prompt: the stored brief for a /// end. `prompt` is this launch's first prompt: the stored brief for a
/// start or a Restart, or a transient one (`start_fresh`, /// start or a Restart, or a transient one (`start_fresh`,
/// `start_transient`) that a Restart must not repeat. /// `start_transient`) that a Restart must not repeat.
fn spawn(self: &Arc<Self>, inner: &mut Inner, prompt: String) -> Result<(), String> { ///
let (choice, _) = inner /// `choice_override` runs this launch on another choice than the stored
.last_start /// one (which it never replaces), and `launch_env` is added to the
.clone() /// process env after the manager's own; both are empty for every caller
.ok_or("no agent has been started")?; /// but the loop's phase start.
fn spawn(
self: &Arc<Self>,
inner: &mut Inner,
prompt: String,
choice_override: Option<StartChoice>,
launch_env: Vec<(String, String)>,
) -> Result<(), String> {
let choice = match choice_override {
Some(choice) => choice,
None => {
inner
.last_start
.clone()
.ok_or("no agent has been started")?
.0
}
};
let mut spec = agent_launch_spec( let mut spec = agent_launch_spec(
&choice.kind, &choice.kind,
&self.folder, &self.folder,
@@ -443,6 +539,7 @@ impl Shared {
if let Ok(extra) = self.extra_env.lock() { if let Ok(extra) = self.extra_env.lock() {
spec.env.extend(extra.iter().cloned()); spec.env.extend(extra.iter().cloned());
} }
spec.env.extend(launch_env);
let generation = self.generation.fetch_add(1, Ordering::SeqCst) + 1; let generation = self.generation.fetch_add(1, Ordering::SeqCst) + 1;
let on_output = { let on_output = {
@@ -520,7 +617,7 @@ impl Shared {
.unwrap_or_else(|| choice.kind.default_prompt().to_string()) .unwrap_or_else(|| choice.kind.default_prompt().to_string())
}) })
.ok_or("no agent has been started")?; .ok_or("no agent has been started")?;
match self.spawn(inner, prompt) { match self.spawn(inner, prompt, None, Vec::new()) {
Ok(()) => Ok(()), Ok(()) => Ok(()),
Err(e) => { Err(e) => {
inner.state = AgentState::Ended { inner.state = AgentState::Ended {
+24 -2
View File
@@ -631,8 +631,30 @@ pub fn launch_spec(
spec.args, spec.args,
&std::env::var("PATH").unwrap_or_default(), &std::env::var("PATH").unwrap_or_default(),
); );
spec.program = program; if program == "cmd" && args.first().map(String::as_str) == Some("/c") {
spec.args = args; // A shim wrapped for cmd: quote the line, hand it over in a variable
// and keep cmd from trying the project folder before PATH, exactly as
// a custom .cmd agent does (a same-named file in a cloned repo must not
// run in the agent's place). Accepted trade-off: the variable reaches
// everything the agent starts, so a `cmd` it runs as a tool no longer
// finds `gradlew` or `setup.bat` in the project without `.\`; custom
// .cmd agents already behave this way.
let line: Vec<String> = args[1..].iter().map(|arg| quote_for_cmd(arg)).collect();
spec.env.push((CMD_LINE_ENV.to_string(), line.join(" ")));
spec.env.push((
"NoDefaultCurrentDirectoryInExePath".to_string(),
"1".to_string(),
));
spec.args = vec![
"/d".to_string(),
"/c".to_string(),
format!("%{CMD_LINE_ENV}%"),
];
spec.program = program;
} else {
spec.program = program;
spec.args = args;
}
} }
spec spec
} }
+7 -2
View File
@@ -366,8 +366,9 @@ pub fn commit(
/// Take what a failed commit left staged out of the index, so a commit the /// Take what a failed commit left staged out of the index, so a commit the
/// person makes by hand does not carry a mark the loop took back. /// person makes by hand does not carry a mark the loop took back.
pub fn unstage(project: &Path) { pub fn unstage(project: &Path) -> Option<String> {
let _ = loop_tools::git_unstage_all(project); let unstaged = loop_tools::git_unstage_all(project);
(!unstaged.ok).then(|| first_line(&unstaged.output))
} }
/// The phases the spec shows done (`done`) that the commit log does not hold: /// The phases the spec shows done (`done`) that the commit log does not hold:
@@ -793,6 +794,10 @@ mod tests {
#[test] #[test]
fn commit_stages_the_marked_files_but_leaves_an_ignored_spec_folder_alone() { fn commit_stages_the_marked_files_but_leaves_an_ignored_spec_folder_alone() {
if !git_ready() || !node_ready() { if !git_ready() || !node_ready() {
assert!(
std::env::var_os("CI").is_none(),
"git or node is not on PATH"
);
return; return;
} }
let repo = init_repo("commit-ignored"); let repo = init_repo("commit-ignored");
+656 -15
View File
@@ -11,6 +11,7 @@
//! retry; every other failure stops at once through `stop_loop`, the one place //! retry; every other failure stops at once through `stop_loop`, the one place
//! a stop goes, with its evidence on the page. //! a stop goes, with its evidence on the page.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard}; use std::sync::{Arc, Mutex, MutexGuard};
@@ -27,6 +28,7 @@ use crate::loop_commit;
use crate::loop_notify::{self, NotifyKind}; use crate::loop_notify::{self, NotifyKind};
use crate::loop_report::{self, EntryResult, LoopReport, ReportEntry}; use crate::loop_report::{self, EntryResult, LoopReport, ReportEntry};
use crate::loop_tools; use crate::loop_tools;
use crate::models::{self, StrengthRow};
use crate::session_reader::{self, ReadError}; use crate::session_reader::{self, ReadError};
// ---------------------------------------------------------------- the setup // ---------------------------------------------------------------- the setup
@@ -74,6 +76,57 @@ pub enum AfterLast {
RunFinalize, RunFinalize,
} }
/// A phase's strength word: what the person picked for one phase.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Strength {
Thrifty,
Balanced,
Best,
}
impl Strength {
/// The word the setup, the env var and the console use.
pub fn word(self) -> &'static str {
match self {
Strength::Thrifty => "thrifty",
Strength::Balanced => "balanced",
Strength::Best => "best",
}
}
/// The word for the report and the page.
pub fn label(self) -> &'static str {
match self {
Strength::Thrifty => "Thrifty",
Strength::Balanced => "Balanced",
Strength::Best => "Best",
}
}
pub fn from_word(word: &str) -> Option<Strength> {
match word {
"thrifty" => Some(Strength::Thrifty),
"balanced" => Some(Strength::Balanced),
"best" => Some(Strength::Best),
_ => None,
}
}
}
/// The env var a strength phase's agent gets; the console reads it so the
/// phase's helpers follow the phase.
pub const STRENGTH_ENV: &str = "PLAN2CODE_LOOP_STRENGTH";
/// One saved pick: the phase's number and name (a renamed phase drops the pick)
/// and the strength word chosen for it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PhasePick {
pub n: u32,
pub name: String,
pub strength: Strength,
}
/// One project's entry in `loop-setup.json`. /// One project's entry in `loop-setup.json`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)] #[serde(rename_all = "camelCase", default)]
@@ -97,6 +150,10 @@ pub struct LoopSetup {
/// The query parameter or JSON field that carries the message, for the /// The query parameter or JSON field that carries the message, for the
/// kinds that let the person name it. /// kinds that let the person name it.
pub notify_param: String, pub notify_param: String,
/// Whether each phase runs on its own strength (off: every phase runs as today).
pub phase_strength: bool,
/// The picks per spec folder (`specs/<name>`), only for phases not yet done.
pub strengths: BTreeMap<String, Vec<PhasePick>>,
} }
impl Default for LoopSetup { impl Default for LoopSetup {
@@ -114,6 +171,8 @@ impl Default for LoopSetup {
notify_kind: NotifyKind::Query, notify_kind: NotifyKind::Query,
notify_url: String::new(), notify_url: String::new(),
notify_param: loop_notify::DEFAULT_PARAM.to_string(), notify_param: loop_notify::DEFAULT_PARAM.to_string(),
phase_strength: false,
strengths: BTreeMap::new(),
} }
} }
} }
@@ -260,6 +319,9 @@ pub struct PhaseRecord {
pub commit: Option<String>, pub commit: Option<String>,
pub subject: Option<String>, pub subject: Option<String>,
pub retries: u32, pub retries: u32,
/// The strength this phase runs on now: its pick, stepped up by a retry.
/// `None` for Match my session and for a run with the toggle off.
pub strength: Option<Strength>,
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
@@ -321,6 +383,37 @@ pub struct RunningRecord {
/// How many looks in a row could not read the phase's session; reset by /// How many looks in a row could not read the phase's session; reset by
/// the next good read. While it is above zero a silence stop says why. /// the next good read. While it is above zero a silence stop says why.
pub read_failures: u32, pub read_failures: u32,
/// What each strength word maps to for the loop's agent, resolved once at
/// the start (empty with the toggle off), so no phase start rereads files.
pub strength_rows: BTreeMap<String, StrengthRow>,
/// The launch choice's model and effort, which a Match my session phase runs on.
pub launch_model: Option<String>,
pub launch_effort: Option<String>,
}
/// What one phase runs on, for its start, the strip and the report.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PhaseRun {
/// `None`: the phase runs on the launch choice.
pub strength: Option<Strength>,
pub model: Option<String>,
pub effort: Option<String>,
}
impl PhaseRun {
/// "sonnet, low", "opus", or "" when no model is known.
pub fn model_text(&self) -> String {
match (&self.model, &self.effort) {
(Some(m), Some(e)) => format!("{m}, {e}"),
(Some(m), None) => m.clone(),
_ => String::new(),
}
}
/// The report's word: "Thrifty", or "Match my session".
pub fn word_text(&self) -> &'static str {
self.strength.map_or("Match my session", Strength::label)
}
} }
fn report_time() -> String { fn report_time() -> String {
@@ -375,6 +468,48 @@ impl RunningRecord {
start_head: None, start_head: None,
own_dirty: Vec::new(), own_dirty: Vec::new(),
read_failures: 0, read_failures: 0,
strength_rows: BTreeMap::new(),
launch_model: None,
launch_effort: None,
}
}
/// What phase `index` runs on, or `None` with Set strength per phase off.
/// A phase whose word the agent does not map runs on the launch choice
/// (Start is held for such a pick, so this is only a guard).
pub fn phase_run(&self, index: usize) -> Option<PhaseRun> {
if !self.setup.phase_strength {
return None;
}
let word = self.phases.get(index)?.strength;
if let Some(word) = word {
if let Some(row) = self.strength_rows.get(word.word()) {
return Some(PhaseRun {
strength: Some(word),
model: Some(row.model.clone()),
effort: row.effort.clone(),
});
}
}
Some(PhaseRun {
strength: None,
model: self.launch_model.clone(),
effort: self.launch_effort.clone(),
})
}
/// Step phase `index` one strength up for its retry: Thrifty to Balanced,
/// Balanced to Best, Best stays; a partly mapped agent goes to the next
/// word it maps, or stays. A Match my session phase stays.
pub fn step_strength_up(&mut self, index: usize) {
let Some(phase) = self.phases.get_mut(index) else {
return;
};
let Some(word) = phase.strength else { return };
if let Some(next) = models::next_strength(&self.strength_rows, word.word())
.and_then(|w| Strength::from_word(&w))
{
phase.strength = Some(next);
} }
} }
} }
@@ -402,6 +537,11 @@ pub struct LoopStateEvent {
pub stopping: bool, pub stopping: bool,
/// Stop after this phase can be turned on (false on the run's last phase). /// Stop after this phase can be turned on (false on the run's last phase).
pub can_stop_after: bool, pub can_stop_after: bool,
/// The running phase's strength word, when it has one (not Match my session).
pub strength: Option<String>,
/// The model and effort the phase runs on, when known.
pub model: Option<String>,
pub effort: Option<String>,
} }
impl LoopStateEvent { impl LoopStateEvent {
@@ -422,6 +562,9 @@ impl LoopStateEvent {
stop_after_phase: false, stop_after_phase: false,
stopping: false, stopping: false,
can_stop_after: false, can_stop_after: false,
strength: None,
model: None,
effort: None,
} }
} }
} }
@@ -433,6 +576,7 @@ pub fn state_event(rec: &RunningRecord) -> LoopStateEvent {
.checked_sub(1) .checked_sub(1)
.and_then(|at| rec.phases.get(at)) .and_then(|at| rec.phases.get(at))
.filter(|p| p.status == PhaseStatus::Done); .filter(|p| p.status == PhaseStatus::Done);
let run = rec.phase_run(rec.current);
LoopStateEvent { LoopStateEvent {
running: true, running: true,
spec_name: rec spec_name: rec
@@ -452,6 +596,12 @@ pub fn state_event(rec: &RunningRecord) -> LoopStateEvent {
stop_after_phase: rec.stop_after_phase, stop_after_phase: rec.stop_after_phase,
stopping: rec.stop_now, stopping: rec.stop_now,
can_stop_after: rec.current + 1 < rec.phases.len(), can_stop_after: rec.current + 1 < rec.phases.len(),
strength: run
.as_ref()
.and_then(|r| r.strength)
.map(|w| w.word().to_string()),
model: run.as_ref().and_then(|r| r.model.clone()),
effort: run.as_ref().and_then(|r| r.effort.clone()),
} }
} }
@@ -964,6 +1114,7 @@ pub fn prepare_with(
commit: None, commit: None,
subject: None, subject: None,
retries: 0, retries: 0,
strength: phase_pick(&setup, spec, n, p["name"].as_str().unwrap_or("")),
}) })
}) })
.collect() .collect()
@@ -1020,6 +1171,33 @@ pub fn prepare_with(
Ok(rec) Ok(rec)
} }
/// The strength the person picked for phase `n` called `name` of `spec`, only
/// with the toggle on. A renamed phase drops its pick.
fn phase_pick(setup: &LoopSetup, spec: &str, n: u32, name: &str) -> Option<Strength> {
if !setup.phase_strength {
return None;
}
setup
.strengths
.get(spec)?
.iter()
.find(|p| p.n == n && p.name == name)
.map(|p| p.strength)
}
/// What each strength word maps to for `agent`, from the shipped and user
/// model files: read once, when the loop begins.
fn strength_rows_for(agent: &Agent) -> BTreeMap<String, StrengthRow> {
let models: Vec<String> = match agent {
Agent::Builtin(entry) => models::models_for_builtin(&entry.id),
Agent::Custom(custom) => custom.models.clone(),
}
.into_iter()
.map(|m| m.id)
.collect();
models::strengths_for(agent.id(), &models, agent.has_effort())
}
/// Open again the phases `prepare` found marked done with no commit behind /// Open again the phases `prepare` found marked done with no commit behind
/// them. Writes to the spec, so Start calls it only after the confirm. /// them. Writes to the spec, so Start calls it only after the confirm.
pub fn reopen_rebuilt(rec: &RunningRecord) -> Result<(), String> { pub fn reopen_rebuilt(rec: &RunningRecord) -> Result<(), String> {
@@ -1281,6 +1459,11 @@ pub fn begin_with_limits(
let home = session_reader::console_home().ok_or("no home folder found")?; let home = session_reader::console_home().ok_or("no home folder found")?;
// A build that stopped earlier carries on in the same report. // A build that stopped earlier carries on in the same report.
let mut rec = rec; let mut rec = rec;
if rec.setup.phase_strength {
rec.strength_rows = strength_rows_for(&launch.0);
}
rec.launch_model.clone_from(&launch.1);
rec.launch_effort.clone_from(&launch.2);
if let Some(report) = loop_report::load(&home, &rec.project, &rec.spec) { if let Some(report) = loop_report::load(&home, &rec.project, &rec.spec) {
rec.report = report; rec.report = report;
} }
@@ -1340,11 +1523,58 @@ pub fn start_with(agent: &AgentManager, launch: &Launch, prompt: String) -> Resu
} }
} }
/// Start a fresh agent on `prompt` for a phase that runs on `word`'s `row`: the
/// agent starts on that model and effort with `PLAN2CODE_LOOP_STRENGTH` set,
/// and the stored launch choice stays what it was (an agent the loop stopped
/// gets the launch choice stored, then the phase's own run on top).
pub fn start_phase_with(
agent: &AgentManager,
launch: &Launch,
prompt: String,
row: &StrengthRow,
word: Strength,
) -> Result<(), String> {
let env = vec![(STRENGTH_ENV.to_string(), word.word().to_string())];
if agent.launch_choice().is_some() {
agent.start_phase_on(prompt, row.model.clone(), row.effort.clone(), env)
} else {
agent.forget_session();
agent.start_transient_on(
launch.clone(),
prompt,
row.model.clone(),
row.effort.clone(),
env,
)
}
}
/// The prompt behind Fix it by hand: an ordinary Implement session. /// The prompt behind Fix it by hand: an ordinary Implement session.
pub fn fix_prompt(spec: &str) -> String { pub fn fix_prompt(spec: &str) -> String {
format!("/plan2code-3-implement {spec}/overview.md --web") format!("/plan2code-3-implement {spec}/overview.md --web")
} }
/// The prompt behind Ask a question: an ordinary agent on the stopped phase
/// that builds and fixes nothing. It opens the console with `--web`, which
/// joins the session already on screen, and answers through its Ask tab.
pub fn ask_prompt(spec: &str) -> String {
format!(
"The Implementation Loop for {spec} stopped. Change nothing: do not start the loop, \
do not edit files and do not run git. Read {spec}/overview.md and the report so far, \
then open the web console with --web (it joins the session already on screen) and \
answer the person's questions through its Ask tab until they press a button on the \
stopped screen."
)
}
/// Start the Ask agent: `start_with` without the forget step, so the agent's
/// `open` joins the session on screen and the stopped screen stays up. The
/// prompt is transient, as `start_with`'s is.
pub fn start_asking(agent: &AgentManager, launch: &Launch, prompt: String) -> Result<(), String> {
let (kind, model, effort, mode) = launch.clone();
agent.start_transient(kind, model, effort, mode, prompt)
}
pub fn finalize_prompt(spec: &str) -> String { pub fn finalize_prompt(spec: &str) -> String {
format!("/plan2code-4-finalize {spec}/overview.md --web") format!("/plan2code-4-finalize {spec}/overview.md --web")
} }
@@ -1376,12 +1606,21 @@ fn start_phase(ctx: &Ctx, index: usize) -> Result<(), String> {
rec.phase_started_at = Instant::now(); rec.phase_started_at = Instant::now();
rec.activity_checked = Instant::now(); rec.activity_checked = Instant::now();
rec.last_activity = SystemTime::now(); rec.last_activity = SystemTime::now();
phase_prompt(&rec.spec, rec.phases[index].n, &rec.setup) let prompt = phase_prompt(&rec.spec, rec.phases[index].n, &rec.setup);
let on = rec.phase_run(index).and_then(|run| {
let word = run.strength?;
Some((word, rec.strength_rows.get(word.word())?.clone()))
});
(prompt, on)
}; };
let (prompt, on) = prompt;
// Said before the agent starts: the banner is up from the moment of Start, // Said before the agent starts: the banner is up from the moment of Start,
// and says what is happening between phases. // and says what is happening between phases.
emit(ctx); emit(ctx);
start_with(&ctx.agent, &ctx.launch, prompt)?; match on {
Some((word, row)) => start_phase_with(&ctx.agent, &ctx.launch, prompt, &row, word)?,
None => start_with(&ctx.agent, &ctx.launch, prompt)?,
}
let generation = ctx.agent.snapshot().generation; let generation = ctx.agent.snapshot().generation;
if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) { if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) {
rec.generation = generation; rec.generation = generation;
@@ -1719,6 +1958,10 @@ fn fail(ctx: &Ctx, snap: &Snapshot, cause: StopCause, detail: String) -> bool {
return false; return false;
} }
if should_retry(&cause, &snap.setup, snap.phase_retries) { if should_retry(&cause, &snap.setup, snap.phase_retries) {
// The retry runs one strength up, and its entry says so.
if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) {
rec.step_strength_up(snap.current);
}
let why = stop_line(&cause, snap.phase_n, &detail, false); let why = stop_line(&cause, snap.phase_n, &detail, false);
let name = phase_name(ctx); let name = phase_name(ctx);
add_entry( add_entry(
@@ -1864,10 +2107,19 @@ fn handle_outcome(ctx: &Ctx, snap: &Snapshot, raw: &Value) -> bool {
Ok(()) => {} Ok(()) => {}
Err(loop_commit::StageError::Add(failure)) => { Err(loop_commit::StageError::Add(failure)) => {
keep_output(ctx, &failure.output); keep_output(ctx, &failure.output);
loop_commit::unstage(&snap.project); let left_staged = loop_commit::unstage(&snap.project);
let cause = StopCause::Commit; let cause = StopCause::Commit;
let detail = format!("git add failed: {}", failure.first_line); let detail = if failure.first_line == loop_tools::STAGED_TOO_LONG {
let line = stop_line(&cause, n, &detail, false); failure.first_line.clone()
} else {
format!("git add failed: {}", failure.first_line)
};
let mut line = stop_line(&cause, n, &detail, false);
if let Some(why) = left_staged {
line = format!(
"{line}. The files are still staged ({why}): run git reset before committing by hand"
);
}
return stop(cause, line); return stop(cause, line);
} }
Err(loop_commit::StageError::Problem(problem)) => { Err(loop_commit::StageError::Problem(problem)) => {
@@ -1902,11 +2154,18 @@ fn handle_outcome(ctx: &Ctx, snap: &Snapshot, raw: &Value) -> bool {
} }
Err(failure) => { Err(failure) => {
keep_output(ctx, &failure.message); keep_output(ctx, &failure.message);
if snap.setup.commit { let left_staged = if snap.setup.commit {
loop_commit::unstage(&snap.project); loop_commit::unstage(&snap.project)
} } else {
None
};
let staged_note = left_staged
.map(|why| {
format!("; the files are still staged ({why}): run git reset before committing by hand")
})
.unwrap_or_default();
return refused(format!( return refused(format!(
"the phase could not be marked done ({})", "the phase could not be marked done ({}){staged_note}",
one_line(&failure.message) one_line(&failure.message)
)); ));
} }
@@ -2027,13 +2286,18 @@ fn commit_failed(
keep_output(ctx, &failure.output); keep_output(ctx, &failure.output);
let (cause, line) = match loop_commit::undo(prepared, marked) { let (cause, line) = match loop_commit::undo(prepared, marked) {
Ok(()) => { Ok(()) => {
loop_commit::unstage(&snap.project); let left_staged = loop_commit::unstage(&snap.project);
let cause = StopCause::Commit; let cause = StopCause::Commit;
let detail = match failure.stage { let detail = match failure.stage {
loop_commit::Stage::Add => format!("git add failed: {}", failure.first_line), loop_commit::Stage::Add => format!("git add failed: {}", failure.first_line),
loop_commit::Stage::Commit => failure.first_line.clone(), loop_commit::Stage::Commit => failure.first_line.clone(),
}; };
let line = stop_line(&cause, n, &detail, false); let mut line = stop_line(&cause, n, &detail, false);
if let Some(why) = left_staged {
line = format!(
"{line}. The files are still staged ({why}): run git reset before committing by hand"
);
}
(cause, line) (cause, line)
} }
Err(why) => { Err(why) => {
@@ -2098,11 +2362,19 @@ fn phase_assumptions(
/// Add to the report and save it straight away, so a crash loses nothing. A save /// Add to the report and save it straight away, so a crash loses nothing. A save
/// that fails never stops the loop; the report stays in memory and the end says so. /// that fails never stops the loop; the report stays in memory and the end says so.
fn add_entry(ctx: &Ctx, entry: ReportEntry) { fn add_entry(ctx: &Ctx, entry: ReportEntry) {
let mut entry = entry;
let saved = { let saved = {
let mut guard = lock(&ctx.slot); let mut guard = lock(&ctx.slot);
let Some(rec) = guard.as_mut().filter(|r| r.run_id == ctx.run_id) else { let Some(rec) = guard.as_mut().filter(|r| r.run_id == ctx.run_id) else {
return; return;
}; };
// What the phase ran on, with Set strength per phase on.
if entry.strength.is_empty() {
if let Some(run) = rec.phase_run(rec.current) {
entry.strength = run.word_text().to_string();
entry.model = run.model_text();
}
}
rec.report.entries.push(entry); rec.report.entries.push(entry);
(rec.project.clone(), rec.report.clone()) (rec.project.clone(), rec.report.clone())
}; };
@@ -2522,6 +2794,19 @@ fn post_end(ctx: &Ctx, rec: &RunningRecord, patch: &Value) {
let _ = loop_tools::console_post(&ctx.console_dir, &sid, &plain); let _ = loop_tools::console_post(&ctx.console_dir, &sid, &plain);
} }
/// The buttons a stopped screen offers: `can`, with Ask a question first
/// whenever Resume is offered (the person can ask before choosing), and Back
/// to the dashboard last.
fn stop_can(can: &[&str]) -> Vec<String> {
let ask = can.contains(&"resume") && !can.contains(&"ask");
ask.then_some("ask")
.into_iter()
.chain(can.iter().copied())
.chain(["dashboard"])
.map(String::from)
.collect()
}
/// End the loop, the one place every stop goes through: stop the agent, mark /// End the loop, the one place every stop goes through: stop the agent, mark
/// the phase stopped, write the evidence and the end to the page, clear the /// the phase stopped, write the evidence and the end to the page, clear the
/// record and tell the strip. `can` names the buttons the stop screen offers. /// record and tell the strip. `can` names the buttons the stop screen offers.
@@ -2575,6 +2860,11 @@ fn stop_loop(ctx: &Ctx, cause: StopCause, line: String, can: &[&str]) {
entry = entry.with_outcome(outcome); entry = entry.with_outcome(outcome);
} }
} }
// What the phase ran on, as `add_entry` does for every other entry.
if let Some(run) = rec.phase_run(at) {
entry.strength = run.word_text().to_string();
entry.model = run.model_text();
}
rec.report.entries.push(entry); rec.report.entries.push(entry);
rec.report_failure = loop_report::save(&ctx.home, &rec.project, &rec.report).err(); rec.report_failure = loop_report::save(&ctx.home, &rec.project, &rec.report).err();
let mut evidence = evidence_with_report(&evidence_markdown(&cause, &line, &rec), &rec); let mut evidence = evidence_with_report(&evidence_markdown(&cause, &line, &rec), &rec);
@@ -2596,7 +2886,7 @@ fn stop_loop(ctx: &Ctx, cause: StopCause, line: String, can: &[&str]) {
"evidence": "evidence", "evidence": "evidence",
"phases": phase_rows(&rec), "phases": phase_rows(&rec),
"uncommitted": uncommitted, "uncommitted": uncommitted,
"can": can.iter().copied().chain(["dashboard"]).collect::<Vec<_>>(), "can": stop_can(can),
}, },
}); });
post_end(ctx, &rec, &patch); post_end(ctx, &rec, &patch);
@@ -3048,6 +3338,7 @@ mod tests {
commit: None, commit: None,
subject: None, subject: None,
retries: 0, retries: 0,
strength: None,
} }
} }
@@ -3545,6 +3836,43 @@ second line"
assert_eq!(s.silence_minutes, 30); assert_eq!(s.silence_minutes, 30);
} }
#[test]
fn an_older_entry_reads_without_phase_strengths() {
let s: LoopSetup =
serde_json::from_value(json!({ "review": true, "commit": false })).unwrap();
assert!(!s.phase_strength);
assert!(s.strengths.is_empty());
}
#[test]
fn a_full_entry_with_phase_strengths_round_trips() {
let entry = json!({
"phaseStrength": true,
"strengths": { "specs/lunch": [
{ "n": 2, "name": "The API", "strength": "thrifty" },
{ "n": 3, "name": "The page", "strength": "best" }
] }
});
let s: LoopSetup = serde_json::from_value(entry.clone()).unwrap();
assert!(s.phase_strength);
let picks = &s.strengths["specs/lunch"];
assert_eq!(picks.len(), 2);
assert_eq!(picks[0].strength, Strength::Thrifty);
assert_eq!(
picks[1],
PhasePick {
n: 3,
name: "The page".to_string(),
strength: Strength::Best
}
);
let back = serde_json::to_value(&s).unwrap();
assert_eq!(back["phaseStrength"], true);
assert_eq!(back["strengths"], entry["strengths"]);
let again: LoopSetup = serde_json::from_value(back).unwrap();
assert_eq!(again, s);
}
#[test] #[test]
fn the_setup_is_found_under_the_consoles_folded_key() { fn the_setup_is_found_under_the_consoles_folded_key() {
let dir = std::env::temp_dir().join(format!("plan2code-loop-setup-{}", std::process::id())); let dir = std::env::temp_dir().join(format!("plan2code-loop-setup-{}", std::process::id()));
@@ -4428,6 +4756,223 @@ second line"
assert!(entry.line.ends_with("after one retry"), "{}", entry.line); assert!(entry.line.ends_with("after one retry"), "{}", entry.line);
} }
fn strength_rows() -> BTreeMap<String, StrengthRow> {
let row = |model: &str, effort: Option<&str>| StrengthRow {
model: model.into(),
effort: effort.map(str::to_string),
};
BTreeMap::from([
("thrifty".to_string(), row("sonnet", Some("low"))),
("balanced".to_string(), row("opus", Some("medium"))),
("best".to_string(), row("opus", Some("high"))),
])
}
/// Turn Set strength per phase on for the harness loop: the phases'
/// words, the rows an agent maps and a launch model for Match my session.
fn with_strengths(ctx: &Ctx, words: &[Option<Strength>]) {
let mut guard = lock(&ctx.slot);
let rec = guard.as_mut().unwrap();
rec.setup.phase_strength = true;
rec.strength_rows = strength_rows();
rec.launch_model = Some("haiku".into());
for (phase, word) in rec.phases.iter_mut().zip(words) {
phase.strength = *word;
}
}
#[test]
fn a_thrifty_phase_starts_on_its_strength_and_a_retry_steps_it_up() {
if !git_ready("strength retry") {
return;
}
let repo = throwaway_repo("strength-retry");
let (ctx, home, seen) = running_loop_seen(&repo, Limits::default());
with_strengths(&ctx, &[Some(Strength::Thrifty), Some(Strength::Best)]);
let ready = |count: usize| {
wait_until("the fake agent ready", || {
lock(&seen).matches("FAKE-AGENT ready").count() >= count
})
};
start_phase(&ctx, 0).expect("start the fake agent");
ready(1);
ctx.agent.input(b"ENV PLAN2CODE_LOOP_STRENGTH\r").unwrap();
wait_until("the strength env", || {
lock(&seen).contains("ENV PLAN2CODE_LOOP_STRENGTH=thrifty")
});
// The strip says what the phase runs on.
let event = state_event(lock(&ctx.slot).as_ref().unwrap());
assert_eq!(event.strength.as_deref(), Some("thrifty"));
assert_eq!(event.model.as_deref(), Some("sonnet"));
assert_eq!(event.effort.as_deref(), Some("low"));
// The stored launch choice is the loop's own, not the phase's.
let (_, model, _, _) = ctx.agent.launch_choice().unwrap();
assert_eq!(model, None);
ctx.agent.input(b"EXIT 3\r").unwrap();
wait_until("the agent ended", || {
matches!(ctx.agent.snapshot().state, AgentState::Ended { .. })
});
assert!(tick(&ctx), "the crash is retried");
{
let guard = lock(&ctx.slot);
let rec = guard.as_ref().unwrap();
assert_eq!(rec.phases[0].strength, Some(Strength::Balanced));
let entry = rec.report.entries.last().unwrap();
assert_eq!(entry.result, EntryResult::Retried);
assert_eq!(entry.strength, "Balanced");
assert_eq!(entry.model, "opus, medium");
}
ready(2);
ctx.agent.input(b"ENV PLAN2CODE_LOOP_STRENGTH\r").unwrap();
wait_until("the stepped-up env", || {
lock(&seen).contains("ENV PLAN2CODE_LOOP_STRENGTH=balanced")
});
let saved = loop_report::load(&home, &repo, "specs/lunch").expect("a saved report");
assert_eq!(saved.entries.last().unwrap().strength, "Balanced");
end_the_test(&ctx);
}
#[test]
fn a_loop_with_the_toggle_off_starts_every_phase_without_the_strength_env() {
if !git_ready("strength off") {
return;
}
let repo = throwaway_repo("strength-off");
let (ctx, _home, seen) = running_loop_seen(&repo, Limits::default());
{
// The words are there, but the toggle is off: they are ignored.
let mut guard = lock(&ctx.slot);
let rec = guard.as_mut().unwrap();
rec.strength_rows = strength_rows();
rec.phases[0].strength = Some(Strength::Best);
assert!(rec.phase_run(0).is_none());
}
start_phase(&ctx, 0).expect("start the fake agent");
wait_until("the fake agent ready", || {
lock(&seen).contains("FAKE-AGENT ready")
});
ctx.agent.input(b"ENV PLAN2CODE_LOOP_STRENGTH\r").unwrap();
wait_until("the env line", || {
lock(&seen).contains("ENV PLAN2CODE_LOOP_STRENGTH=\r")
});
let event = state_event(lock(&ctx.slot).as_ref().unwrap());
assert_eq!(
(event.strength, event.model, event.effort),
(None, None, None)
);
end_the_test(&ctx);
}
#[test]
fn fix_it_by_hand_and_finalize_never_pass_the_strength_env() {
if !git_ready("strength fix") {
return;
}
let repo = throwaway_repo("strength-fix");
let (ctx, _home, seen) = running_loop_seen(&repo, Limits::default());
with_strengths(&ctx, &[Some(Strength::Thrifty), None]);
start_phase(&ctx, 0).expect("start the fake agent");
wait_until("the phase agent ready", || {
lock(&seen).matches("FAKE-AGENT ready").count() >= 1
});
for (round, prompt) in [fix_prompt("specs/lunch"), finalize_prompt("specs/lunch")]
.into_iter()
.enumerate()
{
start_with(&ctx.agent, &ctx.launch, prompt).unwrap();
wait_until("the next agent ready", || {
lock(&seen).matches("FAKE-AGENT ready").count() >= round + 2
});
ctx.agent.input(b"ENV PLAN2CODE_LOOP_STRENGTH\r").unwrap();
wait_until("the env line", || {
lock(&seen).matches("PLAN2CODE_LOOP_STRENGTH=\r").count() > round
});
}
assert!(!lock(&seen).contains("PLAN2CODE_LOOP_STRENGTH=thrifty"));
end_the_test(&ctx);
}
#[test]
fn a_retry_steps_best_stays_and_a_partly_mapped_agent_skips_to_its_next_word() {
let mut rec = record("specs/x", vec![phase(1), phase(2), phase(3), phase(4)]);
rec.strength_rows = strength_rows();
rec.phases[0].strength = Some(Strength::Thrifty);
rec.phases[1].strength = Some(Strength::Balanced);
rec.phases[2].strength = Some(Strength::Best);
for i in 0..4 {
rec.step_strength_up(i);
}
assert_eq!(rec.phases[0].strength, Some(Strength::Balanced));
assert_eq!(rec.phases[1].strength, Some(Strength::Best));
assert_eq!(rec.phases[2].strength, Some(Strength::Best), "Best stays");
assert_eq!(rec.phases[3].strength, None, "Match my session stays");
// An agent that maps only Thrifty and Best skips the gap, and stays
// when nothing above is mapped.
rec.strength_rows.remove("balanced");
rec.phases[0].strength = Some(Strength::Thrifty);
rec.step_strength_up(0);
assert_eq!(rec.phases[0].strength, Some(Strength::Best));
rec.strength_rows.remove("best");
rec.phases[1].strength = Some(Strength::Thrifty);
rec.step_strength_up(1);
assert_eq!(rec.phases[1].strength, Some(Strength::Thrifty));
}
#[test]
fn the_strip_says_a_match_my_session_phase_runs_on_the_launch_model() {
let mut rec = record("specs/x", vec![phase(1)]);
rec.setup.phase_strength = true;
rec.strength_rows = strength_rows();
rec.launch_model = Some("opus".into());
rec.launch_effort = Some("high".into());
let event = state_event(&rec);
assert_eq!(event.strength, None);
assert_eq!(event.model.as_deref(), Some("opus"));
assert_eq!(event.effort.as_deref(), Some("high"));
let json = serde_json::to_value(&event).unwrap();
assert_eq!(json["model"], "opus");
assert!(json["strength"].is_null());
// A pick the agent does not map runs on the launch choice too.
rec.strength_rows.clear();
rec.phases[0].strength = Some(Strength::Thrifty);
assert_eq!(rec.phase_run(0).unwrap().strength, None);
}
#[test]
fn a_stopped_phase_entry_says_what_it_ran_on() {
if !git_ready("stopped ran on") {
return;
}
let repo = throwaway_repo("stopped-ran-on");
let limits = Limits {
notice_wait: Duration::ZERO,
..Limits::default()
};
let (ctx, home) = running_loop(&repo, limits);
{
let mut guard = lock(&ctx.slot);
let rec = guard.as_mut().unwrap();
rec.sid = None;
rec.setup.retry_once = false;
rec.setup.phase_strength = true;
rec.phases[rec.current].strength = Some(Strength::Thrifty);
rec.strength_rows.insert(
"thrifty".to_string(),
StrengthRow {
model: "sonnet".to_string(),
effort: Some("low".to_string()),
},
);
}
assert!(!tick(&ctx), "the loop is over");
let entry = last_entry_saved(&home, &repo);
assert_eq!(entry.result, EntryResult::Stopped);
assert_eq!(entry.strength, "Thrifty");
assert_eq!(entry.model, "sonnet, low");
}
#[test] #[test]
fn a_refused_commit_stops_the_loop() { fn a_refused_commit_stops_the_loop() {
if !harness_ready("refused commit") { if !harness_ready("refused commit") {
@@ -5960,6 +6505,94 @@ second line"
); );
} }
#[test]
fn the_ask_prompt_names_the_spec_and_changes_nothing() {
let prompt = ask_prompt("specs/x");
assert!(prompt.contains("specs/x"), "{prompt}");
assert!(prompt.contains("--web"), "{prompt}");
assert!(!prompt.contains("--loop"), "{prompt}");
assert!(!prompt.contains("--phase"), "{prompt}");
assert!(prompt.to_lowercase().contains("change nothing"), "{prompt}");
assert!(!prompt.contains('\u{2014}'), "{prompt}");
}
#[test]
fn every_resumable_stop_offers_ask_first_and_a_finalize_only_stop_does_not() {
assert_eq!(
stop_can(&["resume", "fix"]),
["ask", "resume", "fix", "dashboard"]
);
assert_eq!(stop_can(&["resume"]), ["ask", "resume", "dashboard"]);
assert_eq!(stop_can(&["finalize"]), ["finalize", "dashboard"]);
// Never twice when a caller already named it.
assert_eq!(stop_can(&["ask", "resume"]), ["ask", "resume", "dashboard"]);
}
#[test]
fn asking_leaves_the_session_on_screen_and_fix_it_by_hand_still_forgets_it() {
let (agent, seen) = fake_agent_manager(Path::new("."));
let forgets = Arc::new(Mutex::new(0));
let counter = Arc::clone(&forgets);
agent.set_forget_session(Arc::new(move || *lock(&counter) += 1));
let launch = fake_agent_launch();
start_asking(&agent, &launch, ask_prompt("specs/x")).unwrap();
wait_until("the Ask agent ready", || {
lock(&seen).matches("FAKE-AGENT ready").count() >= 1
});
assert_eq!(*lock(&forgets), 0, "Ask must join the session on screen");
// The Ask agent is still running when the next button is pressed, as in
// the app: Fix it by hand replaces it and forgets the session.
start_with(&agent, &launch, fix_prompt("specs/x")).unwrap();
wait_until("the fix agent ready", || {
lock(&seen).matches("FAKE-AGENT ready").count() >= 2
});
assert_eq!(*lock(&forgets), 1, "Fix it by hand must forget the session");
let prompts = launched_prompts(&seen);
assert_eq!(
prompts,
vec![ask_prompt("specs/x"), fix_prompt("specs/x")],
"the fix prompt replaced the Ask agent's"
);
agent.stop();
}
#[test]
fn resuming_the_loop_after_asking_replaces_the_ask_agent_and_forgets_the_session() {
let (agent, seen) = fake_agent_manager(Path::new("."));
let forgets = Arc::new(Mutex::new(0));
let counter = Arc::clone(&forgets);
agent.set_forget_session(Arc::new(move || *lock(&counter) += 1));
let launch = fake_agent_launch();
start_asking(&agent, &launch, ask_prompt("specs/x")).unwrap();
wait_until("the Ask agent ready", || {
lock(&seen).matches("FAKE-AGENT ready").count() >= 1
});
assert_eq!(*lock(&forgets), 0, "Ask must join the session on screen");
let row = strength_rows()["balanced"].clone();
start_phase_with(
&agent,
&launch,
"resume prompt".into(),
&row,
Strength::Balanced,
)
.unwrap();
wait_until("the resumed agent ready", || {
lock(&seen).matches("FAKE-AGENT ready").count() >= 2
});
assert_eq!(*lock(&forgets), 1, "Resume must forget the session");
assert_eq!(
launched_prompts(&seen),
vec![ask_prompt("specs/x"), "resume prompt".to_string()],
"the resumed phase replaced the Ask agent's"
);
agent.stop();
}
/// The `ARGS` lines the fake agent has printed, one per generation, in the /// The `ARGS` lines the fake agent has printed, one per generation, in the
/// order they started: the prompts each launch ran with. /// order they started: the prompts each launch ran with.
fn launched_prompts(seen: &Arc<Mutex<String>>) -> Vec<String> { fn launched_prompts(seen: &Arc<Mutex<String>>) -> Vec<String> {
@@ -5984,9 +6617,17 @@ second line"
} }
fn wait_for_generations(seen: &Arc<Mutex<String>>, count: usize) { fn wait_for_generations(seen: &Arc<Mutex<String>>, count: usize) {
wait_until("the agent generations", || { let deadline = Instant::now() + Duration::from_secs(30);
launched_prompts(seen).len() >= count while Instant::now() < deadline {
}); if launched_prompts(seen).len() >= count {
return;
}
thread::sleep(Duration::from_millis(20));
}
panic!(
"never saw {count} agent generations; the fake agent printed {:?}. No ARGS line means target/debug/fake-agent is older than its source: touch fake-agent/src/main.rs",
lock(seen).as_str()
);
} }
#[test] #[test]
@@ -59,6 +59,12 @@ pub struct ReportEntry {
/// Things the app noticed that did not stop the phase (leftover Suggestions). /// Things the app noticed that did not stop the phase (leftover Suggestions).
pub warnings: Vec<String>, pub warnings: Vec<String>,
pub retries: u32, pub retries: u32,
/// What the phase ran on, with Set strength per phase on: "Thrifty",
/// "Balanced", "Best" or "Match my session" (the word a retry stepped up
/// to, for a retry); empty with the toggle off.
pub strength: String,
/// The model it ran on, with the effort folded in ("sonnet, low").
pub model: String,
} }
impl ReportEntry { impl ReportEntry {
@@ -281,6 +287,14 @@ fn entry_markdown(md: &mut String, e: &ReportEntry) {
} else if e.result == EntryResult::Passed { } else if e.result == EntryResult::Passed {
md.push_str("- Commit: not committed\n"); md.push_str("- Commit: not committed\n");
} }
if !e.strength.is_empty() {
let on = if e.model.is_empty() {
e.strength.clone()
} else {
format!("{} ({})", e.strength, e.model)
};
md.push_str(&format!("- Ran on: {}\n", cell(&on)));
}
if e.retries > 0 { if e.retries > 0 {
md.push_str(&format!("- Retries: {}\n", e.retries)); md.push_str(&format!("- Retries: {}\n", e.retries));
} }
@@ -565,4 +579,31 @@ mod tests {
let old: ReportEntry = serde_json::from_str(r#"{"phase":4,"name":"P4"}"#).unwrap(); let old: ReportEntry = serde_json::from_str(r#"{"phase":4,"name":"P4"}"#).unwrap();
assert!(old.warnings.is_empty()); assert!(old.warnings.is_empty());
} }
#[test]
fn a_phase_line_says_what_it_ran_on_and_an_old_store_says_nothing() {
let mut thrifty = entry(2, EntryResult::Passed);
thrifty.strength = "Thrifty".into();
thrifty.model = "sonnet, low".into();
let mut matched = entry(3, EntryResult::Passed);
matched.strength = "Match my session".into();
matched.model = "opus".into();
let mut bare = entry(4, EntryResult::Passed);
bare.strength = "Best".into();
let mut report = LoopReport::new("specs/x", "2026-11-01 10:00");
report.entries = vec![thrifty, matched, bare, entry(5, EntryResult::Passed)];
let md = body_markdown(&report);
assert!(md.contains("- Ran on: Thrifty (sonnet, low)"), "{md}");
assert!(md.contains("- Ran on: Match my session (opus)"), "{md}");
assert!(
md.contains(
"- Ran on: Best
"
),
"{md}"
);
assert_eq!(md.matches("Ran on").count(), 3, "toggle off adds nothing");
let old: ReportEntry = serde_json::from_str(r#"{"phase":4,"name":"P4"}"#).unwrap();
assert!(old.strength.is_empty() && old.model.is_empty());
}
} }
+149 -20
View File
@@ -6,6 +6,7 @@
use std::io::{Read, Write}; use std::io::{Read, Write};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::{Command, Stdio}; use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::thread; use std::thread;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
@@ -23,6 +24,13 @@ pub struct ToolRun {
/// Output kept per call: the tail, which is where a failure says why. /// Output kept per call: the tail, which is where a failure says why.
const OUTPUT_LIMIT: usize = 200 * 1024; const OUTPUT_LIMIT: usize = 200 * 1024;
/// What a stop says when too many files are staged to check.
pub const STAGED_TOO_LONG: &str =
"too many changed files to check: add generated folders to .gitignore, then Resume";
/// Output kept for the staged-file list the commit gate checks (far above any real list).
const STAGED_LIST_LIMIT: usize = 64 * 1024 * 1024;
/// The limit for node and git calls. /// The limit for node and git calls.
pub const QUICK_LIMIT: Duration = Duration::from_secs(60); pub const QUICK_LIMIT: Duration = Duration::from_secs(60);
/// The limit for the person's quick check. /// The limit for the person's quick check.
@@ -42,6 +50,8 @@ fn append_tail(buf: &mut Vec<u8>, bytes: &[u8], limit: usize) {
fn pump<R: Read + Send + 'static>( fn pump<R: Read + Send + 'static>(
mut source: R, mut source: R,
sink: Arc<Mutex<Vec<u8>>>, sink: Arc<Mutex<Vec<u8>>>,
keep: Keep,
cut: Arc<AtomicBool>,
) -> thread::JoinHandle<()> { ) -> thread::JoinHandle<()> {
thread::spawn(move || { thread::spawn(move || {
let mut chunk = [0u8; 8192]; let mut chunk = [0u8; 8192];
@@ -50,7 +60,16 @@ fn pump<R: Read + Send + 'static>(
Ok(0) | Err(_) => break, Ok(0) | Err(_) => break,
Ok(n) => { Ok(n) => {
if let Ok(mut buf) = sink.lock() { if let Ok(mut buf) = sink.lock() {
append_tail(&mut buf, &chunk[..n], OUTPUT_LIMIT); match keep {
Keep::Tail(cap) => append_tail(&mut buf, &chunk[..n], cap),
Keep::Head(cap) => {
let room = cap.saturating_sub(buf.len()).min(n);
buf.extend_from_slice(&chunk[..room]);
if room < n {
cut.store(true, Ordering::Relaxed);
}
}
}
} }
} }
} }
@@ -67,17 +86,45 @@ fn run_limited(cmd: Command, stdin: Option<&str>, limit: Duration) -> ToolRun {
/// `run_limited`, with stderr dropped when `keep_stderr` is false: a list read /// `run_limited`, with stderr dropped when `keep_stderr` is false: a list read
/// from stdout must not be mixed with a warning git printed beside it. /// from stdout must not be mixed with a warning git printed beside it.
fn run_limited_with( fn run_limited_with(
mut cmd: Command, cmd: Command,
stdin: Option<&str>, stdin: Option<&str>,
limit: Duration, limit: Duration,
keep_stderr: bool, keep_stderr: bool,
) -> ToolRun { ) -> ToolRun {
run_capped(cmd, stdin, limit, keep_stderr, Keep::Tail(OUTPUT_LIMIT)).0
}
/// Which part of a long output a call keeps.
#[derive(Clone, Copy)]
enum Keep {
/// The last `n` bytes, where a failure says why.
Tail(usize),
/// The first `n` bytes; anything after is read and dropped, and the call
/// reports it was cut. For a list a safety check must read whole.
Head(usize),
}
/// `run_limited_with` with the part kept chosen, and whether output was dropped.
fn run_capped(
mut cmd: Command,
stdin: Option<&str>,
limit: Duration,
keep_stderr: bool,
keep: Keep,
) -> (ToolRun, bool) {
let cut = Arc::new(AtomicBool::new(false));
cmd.env("PATH", crate::node_check::resolved_path()); cmd.env("PATH", crate::node_check::resolved_path());
#[cfg(windows)] #[cfg(windows)]
{ {
use std::os::windows::process::CommandExt; use std::os::windows::process::CommandExt;
cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW
} }
#[cfg(unix)]
{
// Its own process group, so a timeout can end every descendant at once.
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
cmd.stdin(if stdin.is_some() { cmd.stdin(if stdin.is_some() {
Stdio::piped() Stdio::piped()
} else { } else {
@@ -92,17 +139,26 @@ fn run_limited_with(
let mut child = match cmd.spawn() { let mut child = match cmd.spawn() {
Ok(child) => child, Ok(child) => child,
Err(e) => { Err(e) => {
return ToolRun { return (
ok: false, ToolRun {
code: None, ok: false,
output: format!("could not start: {e}"), code: None,
} output: format!("could not start: {e}"),
},
false,
);
} }
}; };
let sink = Arc::new(Mutex::new(Vec::new())); let sink = Arc::new(Mutex::new(Vec::new()));
let readers = [ let readers = [
child.stdout.take().map(|s| pump(s, Arc::clone(&sink))), child
child.stderr.take().map(|s| pump(s, Arc::clone(&sink))), .stdout
.take()
.map(|s| pump(s, Arc::clone(&sink), keep, Arc::clone(&cut))),
child
.stderr
.take()
.map(|s| pump(s, Arc::clone(&sink), keep, Arc::clone(&cut))),
]; ];
if let (Some(text), Some(mut pipe)) = (stdin, child.stdin.take()) { if let (Some(text), Some(mut pipe)) = (stdin, child.stdin.take()) {
// A child that exits before reading closes the pipe: not an error here. // A child that exits before reading closes the pipe: not an error here.
@@ -148,11 +204,14 @@ fn run_limited_with(
} }
output.push_str(&format!("(stopped after {})", describe_limit(limit))); output.push_str(&format!("(stopped after {})", describe_limit(limit)));
} }
ToolRun { (
ok: status.is_some_and(|s| s.success()), ToolRun {
code: status.and_then(|s| s.code()), ok: status.is_some_and(|s| s.success()),
output, code: status.and_then(|s| s.code()),
} output,
},
cut.load(Ordering::Relaxed),
)
} }
/// "1 minute", "15 minutes", "2 seconds". /// "1 minute", "15 minutes", "2 seconds".
@@ -180,11 +239,14 @@ fn kill_tree(pid: u32) {
} }
#[cfg(not(windows))] #[cfg(not(windows))]
{ {
let _ = Command::new("pkill") // The child leads its own process group (see run_limited): a negative
.args(["-KILL", "-P", &pid.to_string()]) // pid ends the whole group, grandchildren included.
.stdout(Stdio::null()) if let Ok(pgid) = i32::try_from(pid) {
.stderr(Stdio::null()) // SAFETY: kill(2) takes plain integers and touches no memory.
.status(); unsafe {
libc::kill(-pgid, libc::SIGKILL);
}
}
} }
} }
@@ -347,15 +409,26 @@ pub fn git_add_paths(project: &Path, paths: &[&Path]) -> ToolRun {
/// The names of the staged files, as `git diff --cached --name-only -z` prints /// The names of the staged files, as `git diff --cached --name-only -z` prints
/// them: NUL-separated, so no path is quoted. /// them: NUL-separated, so no path is quoted.
pub fn git_staged(project: &Path) -> Result<Vec<String>, String> { pub fn git_staged(project: &Path) -> Result<Vec<String>, String> {
let run = run_limited_with( git_staged_capped(project, STAGED_LIST_LIMIT)
}
/// `git_staged` with the size the list may reach. The secret and size gate
/// reads every staged name, so a list over the cap fails closed rather than
/// being checked in part.
fn git_staged_capped(project: &Path, cap: usize) -> Result<Vec<String>, String> {
let (run, cut) = run_capped(
git(project, &["diff", "--cached", "--name-only", "-z"]), git(project, &["diff", "--cached", "--name-only", "-z"]),
None, None,
QUICK_LIMIT, QUICK_LIMIT,
false, false,
Keep::Head(cap),
); );
if !run.ok { if !run.ok {
return Err(run.output.trim().to_string()); return Err(run.output.trim().to_string());
} }
if cut {
return Err(STAGED_TOO_LONG.to_string());
}
Ok(split_nul(&run.output)) Ok(split_nul(&run.output))
} }
@@ -558,6 +631,62 @@ fn parse_json_object(run: &ToolRun) -> Result<serde_json::Value, String> {
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn a_capped_run_keeps_the_part_asked_for_and_says_when_output_was_cut() {
if Command::new("node").arg("--version").output().is_err() {
assert!(std::env::var_os("CI").is_none(), "node is not on PATH");
return;
}
fn run(keep: Keep, text: &str) -> (ToolRun, bool) {
let mut cmd = Command::new("node");
cmd.args(["-e", &format!("process.stdout.write('{text}')")]);
run_capped(cmd, None, QUICK_LIMIT, false, keep)
}
let (tail, tail_cut) = run(Keep::Tail(4), "aaaabbbb");
assert!(tail.ok);
assert_eq!(tail.output, "bbbb");
assert!(!tail_cut, "a tail keeper never reports a cut");
let (head, head_cut) = run(Keep::Head(4), "aaaabbbb");
assert_eq!(head.output, "aaaa");
assert!(head_cut);
let (whole, whole_cut) = run(Keep::Head(8), "aaaabbbb");
assert_eq!(whole.output, "aaaabbbb");
assert!(!whole_cut);
}
#[test]
fn a_staged_list_over_the_cap_is_refused_not_checked_in_part() {
if Command::new("git").arg("--version").output().is_err() {
assert!(std::env::var_os("CI").is_none(), "git is not on PATH");
return;
}
let repo =
std::env::temp_dir().join(format!("plan2code-staged-cap-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&repo);
std::fs::create_dir_all(&repo).unwrap();
let git_in = |args: &[&str]| {
let status = Command::new("git")
.args(args)
.current_dir(&repo)
.status()
.unwrap();
assert!(status.success(), "git {args:?}");
};
git_in(&["init", "-q"]);
for name in [".env", "a.txt", "b.txt"] {
std::fs::write(repo.join(name), "x").unwrap();
}
git_in(&["add", "-A"]);
// A cap below the list's size: refused, never a list missing its first names.
assert_eq!(
git_staged_capped(&repo, 8),
Err(STAGED_TOO_LONG.to_string())
);
let all = git_staged_capped(&repo, 1024).unwrap();
assert_eq!(all, [".env", "a.txt", "b.txt"]);
let _ = std::fs::remove_dir_all(&repo);
}
#[test] #[test]
fn the_commit_message_is_read_from_the_scripts_output_without_a_shell() { fn the_commit_message_is_read_from_the_scripts_output_without_a_shell() {
let ok = r#"{"ok":true,"subject":"Add it","message":"Add it\n\nAI Assisted"}"#; let ok = r#"{"ok":true,"subject":"Add it","message":"Add it\n\nAI Assisted"}"#;
+22 -6
View File
@@ -798,7 +798,7 @@ async fn update_skills(
/// The OS folder picker, shown when no folder is known; a choice becomes the /// The OS folder picker, shown when no folder is known; a choice becomes the
/// launcher's remembered folder. /// launcher's remembered folder.
#[tauri::command] #[tauri::command(async)]
fn pick_project_folder( fn pick_project_folder(
app: tauri::AppHandle, app: tauri::AppHandle,
state: State<'_, AppState>, state: State<'_, AppState>,
@@ -847,7 +847,7 @@ fn teardown_project(state: &AppState) -> Result<(), String> {
/// fresh for it rather than reusing anything from the one just left. Picking /// fresh for it rather than reusing anything from the one just left. Picking
/// nothing (canceled) leaves the current project untouched. One project per /// nothing (canceled) leaves the current project untouched. One project per
/// window stays; this replaces it, it does not add a second. /// window stays; this replaces it, it does not add a second.
#[tauri::command] #[tauri::command(async)]
fn change_project( fn change_project(
app: tauri::AppHandle, app: tauri::AppHandle,
state: State<'_, AppState>, state: State<'_, AppState>,
@@ -876,7 +876,7 @@ fn change_project(
/// is `console_setup_start` below: the agent-less `setup` page, which is no /// is `console_setup_start` below: the agent-less `setup` page, which is no
/// dashboard and has no agent to announce it, so the app opens it itself. /// dashboard and has no agent to announce it, so the app opens it itself.
/// Nothing to show yet is an error the page words for the person. /// Nothing to show yet is an error the page words for the person.
#[tauri::command] #[tauri::command(async)]
fn console_start(state: State<'_, AppState>) -> Result<serde_json::Value, String> { fn console_start(state: State<'_, AppState>) -> Result<serde_json::Value, String> {
console_start_impl(&state) console_start_impl(&state)
} }
@@ -894,7 +894,7 @@ fn console_start_impl(state: &AppState) -> Result<serde_json::Value, String> {
/// The bar's poll: none (never started or stopped on purpose), running, or /// The bar's poll: none (never started or stopped on purpose), running, or
/// dead (started but not answering). /// dead (started but not answering).
#[tauri::command] #[tauri::command(async)]
fn console_status(state: State<'_, AppState>) -> serde_json::Value { fn console_status(state: State<'_, AppState>) -> serde_json::Value {
let Ok(guard) = state.console.lock() else { let Ok(guard) = state.console.lock() else {
return serde_json::json!({ "state": "none", "url": null }); return serde_json::json!({ "state": "none", "url": null });
@@ -927,7 +927,7 @@ fn console_stop(state: State<'_, AppState>) -> Result<(), String> {
/// on its own), and the URL comes back for the page to frame. When /// on its own), and the URL comes back for the page to frame. When
/// `console.mjs` cannot be found the error names it, and the page shows its /// `console.mjs` cannot be found the error names it, and the page shows its
/// plain "skills are missing" checklist row. /// plain "skills are missing" checklist row.
#[tauri::command] #[tauri::command(async)]
fn console_setup_start( fn console_setup_start(
app: tauri::AppHandle, app: tauri::AppHandle,
state: State<'_, AppState>, state: State<'_, AppState>,
@@ -1229,6 +1229,16 @@ fn loop_fix(state: State<'_, AppState>) -> Result<(), String> {
loop_driver::start_with(&agent, &last.launch, loop_driver::fix_prompt(&last.spec)) loop_driver::start_with(&agent, &last.launch, loop_driver::fix_prompt(&last.spec))
} }
// Ask a question: an ordinary agent on the stopped phase that changes nothing.
// It starts without the forget step, so its `open` joins the stopped screen's
// session and the Ask tab comes online beside the buttons.
#[tauri::command]
fn loop_ask(state: State<'_, AppState>) -> Result<(), String> {
let last = last_loop(&state)?;
let agent = current_agent(&state).ok_or("No agent is available")?;
loop_driver::start_asking(&agent, &last.launch, loop_driver::ask_prompt(&last.spec))
}
#[tauri::command] #[tauri::command]
fn loop_finalize(state: State<'_, AppState>) -> Result<(), String> { fn loop_finalize(state: State<'_, AppState>) -> Result<(), String> {
let last = last_loop(&state)?; let last = last_loop(&state)?;
@@ -1244,7 +1254,7 @@ fn loop_finalize(state: State<'_, AppState>) -> Result<(), String> {
/// fresh dashboard console in its place. Needs no agent: a dashboard session /// fresh dashboard console in its place. Needs no agent: a dashboard session
/// is only `console.mjs open --workflow dashboard`, which the supervisor runs /// is only `console.mjs open --workflow dashboard`, which the supervisor runs
/// itself. /// itself.
#[tauri::command] #[tauri::command(async)]
fn loop_dashboard(state: State<'_, AppState>) -> Result<serde_json::Value, String> { fn loop_dashboard(state: State<'_, AppState>) -> Result<serde_json::Value, String> {
let app = state.app.get().cloned().ok_or("no window yet")?; let app = state.app.get().cloned().ok_or("no window yet")?;
let origin = window_origin(&app); let origin = window_origin(&app);
@@ -1254,6 +1264,11 @@ fn loop_dashboard(state: State<'_, AppState>) -> Result<serde_json::Value, Strin
.ok() .ok()
.and_then(|p| p.as_ref().map(|p| p.dir.clone())) .and_then(|p| p.as_ref().map(|p| p.dir.clone()))
.ok_or("no project yet")?; .ok_or("no project yet")?;
// An Ask or Fix agent started from the stopped screen would go on answering
// a session that is about to end: stop it first.
if let Some(agent) = current_agent(&state) {
agent.stop();
}
let mut guard = state.console.lock().map_err(|e| e.to_string())?; let mut guard = state.console.lock().map_err(|e| e.to_string())?;
if let Some(mut sup) = guard.take() { if let Some(mut sup) = guard.take() {
let _ = sup.stop(); let _ = sup.stop();
@@ -1319,6 +1334,7 @@ fn main() {
loop_state, loop_state,
loop_resume, loop_resume,
loop_fix, loop_fix,
loop_ask,
loop_finalize, loop_finalize,
loop_dashboard, loop_dashboard,
set_attention, set_attention,
+276 -2
View File
@@ -7,8 +7,9 @@
//! agents never come through here: their menu is their own `models` in //! agents never come through here: their menu is their own `models` in
//! agents.json. //! agents.json.
use serde::{Deserialize, Serialize};
use serde_json::Value; use serde_json::Value;
use std::collections::HashSet; use std::collections::{BTreeMap, HashSet};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use crate::agents::CustomModel; use crate::agents::CustomModel;
@@ -108,6 +109,126 @@ pub fn models_for_builtin(cli_id: &str) -> Vec<CustomModel> {
) )
} }
/// The loop's strength words, lightest first (`STRENGTH_ORDER` in
/// src/web-console/strengths.mjs).
pub const STRENGTH_ORDER: [&str; 3] = ["thrifty", "balanced", "best"];
/// One strength's model, and the effort when the agent takes one.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StrengthRow {
pub model: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub effort: Option<String>,
}
/// A row as the resolver keeps it, or None when it is not usable: the model
/// must be a string in `models`; an effort survives only when the agent takes
/// one and it is low, medium or high (`validRow` in strengths.mjs).
fn valid_strength_row(
row: Option<&Value>,
models: &[String],
has_effort: bool,
) -> Option<StrengthRow> {
let row = row?.as_object()?;
let model = row.get("model")?.as_str()?;
if !models.iter().any(|m| m == model) {
return None;
}
let effort = row
.get("effort")
.and_then(Value::as_str)
.filter(|e| has_effort && matches!(*e, "low" | "medium" | "high"))
.map(str::to_string);
Some(StrengthRow {
model: model.to_string(),
effort,
})
}
/// `{ thrifty?, balanced?, best? }` for one agent from the shipped and the
/// user's `strengths` objects (each keyed by agent id): per word the user's row
/// if it is valid, else the shipped row if it is valid; a word with neither is
/// left out. The twin of `resolveStrengths` in strengths.mjs, held to
/// scripts/fixtures/strength-cases.json.
pub fn resolve_strengths(
shipped: &Value,
user: &Value,
agent: &str,
models: &[String],
has_effort: bool,
) -> BTreeMap<String, StrengthRow> {
let mut resolved = BTreeMap::new();
for word in STRENGTH_ORDER {
let row = valid_strength_row(
user.get(agent).and_then(|a| a.get(word)),
models,
has_effort,
)
.or_else(|| {
valid_strength_row(
shipped.get(agent).and_then(|a| a.get(word)),
models,
has_effort,
)
});
if let Some(row) = row {
resolved.insert(word.to_string(), row);
}
}
resolved
}
/// The first mapped word after `word` in `STRENGTH_ORDER`, else None
/// (`nextStrength` in strengths.mjs).
pub fn next_strength(resolved: &BTreeMap<String, StrengthRow>, word: &str) -> Option<String> {
let at = STRENGTH_ORDER.iter().position(|w| *w == word)?;
STRENGTH_ORDER[at + 1..]
.iter()
.find(|w| resolved.contains_key(**w))
.map(|w| w.to_string())
}
/// `strengths_for` from explicit file paths, so tests never touch the real
/// home. The shipped file falls back to the baked list, like `models_for`.
fn strengths_from(
agent: &str,
models: &[String],
has_effort: bool,
shipped_file: Option<&Path>,
user_file: Option<&Path>,
) -> BTreeMap<String, StrengthRow> {
let shipped = shipped_file
.and_then(read_json)
.or_else(|| serde_json::from_str(BAKED_MODELS).ok())
.unwrap_or(Value::Null);
let user = user_file.and_then(read_json).unwrap_or(Value::Null);
resolve_strengths(
shipped.get("strengths").unwrap_or(&Value::Null),
user.get("strengths").unwrap_or(&Value::Null),
agent,
models,
has_effort,
)
}
/// What each strength word maps to for the built-in `agent`, from the same
/// shipped and user files as `models_for_builtin`. `models` is the ids of the
/// agent's menu; a row naming a model outside it reads unmapped.
pub fn strengths_for(
agent: &str,
models: &[String],
has_effort: bool,
) -> BTreeMap<String, StrengthRow> {
strengths_from(
agent,
models,
has_effort,
shipped_models_file().as_deref(),
user_models_file().as_deref(),
)
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -211,7 +332,7 @@ mod tests {
assert!(baked.len() > 1); assert!(baked.len() > 1);
std::fs::write(&missing, "{ nope").unwrap(); std::fs::write(&missing, "{ nope").unwrap();
assert!(models_for("claude", Some(&missing), Some(&missing)).len() > 1); assert!(models_for("claude", Some(&missing), Some(&missing)).len() > 1);
assert!(models_for("codex", Some(&missing), Some(&missing)).is_empty()); assert!(models_for("nonesuch", Some(&missing), Some(&missing)).is_empty());
} }
#[test] #[test]
@@ -234,4 +355,157 @@ mod tests {
vec![model("sonnet", Some("S"))] vec![model("sonnet", Some("S"))]
); );
} }
/// Every case in the shared strength fixture: the same file drives
/// scripts/test-web-console-strengths.mjs, so the console's resolver and
/// this one stay the one rule.
#[test]
fn the_shared_strength_cases_all_resolve_the_same() {
let cases: Value = serde_json::from_str(include_str!(
"../../../scripts/fixtures/strength-cases.json"
))
.unwrap();
assert_eq!(cases["schema"], 1);
let list = cases["cases"].as_array().unwrap();
assert!(list.len() >= 10);
for case in list {
let name = case["name"].as_str().unwrap();
let agent = case["agent"].as_str().unwrap();
let models: Vec<String> = case["models"]
.as_array()
.unwrap()
.iter()
.map(|m| m.as_str().unwrap().to_string())
.collect();
// The fixture holds one agent's rows; the resolver reads them by agent id.
let wrap = |rows: &Value| json!({ agent: rows.clone() });
let resolved = resolve_strengths(
&wrap(&case["shipped"]),
&wrap(&case["user"]),
agent,
&models,
case["hasEffort"].as_bool().unwrap(),
);
let got = serde_json::to_value(&resolved).unwrap();
assert_eq!(got, case["expect"]["resolved"], "{name}: resolved");
for word in STRENGTH_ORDER {
let want = case["expect"]["next"][word].as_str().map(str::to_string);
assert_eq!(
next_strength(&resolved, word),
want,
"{name}: next after {word}"
);
}
}
}
#[test]
fn next_strength_of_an_unknown_word_is_none() {
let mut resolved = BTreeMap::new();
resolved.insert(
"best".to_string(),
StrengthRow {
model: "x".to_string(),
effort: None,
},
);
assert_eq!(next_strength(&resolved, "cheap"), None);
assert_eq!(
next_strength(&resolved, "thrifty"),
Some("best".to_string())
);
}
#[test]
fn strengths_for_reads_the_shipped_and_user_files() {
let dir = temp_dir("strengths");
let shipped = dir.join("bin").join("models.json");
let user = dir.join("models.json");
std::fs::write(
&shipped,
r#"{ "claude": [{ "id": "sonnet", "label": "S" }, { "id": "opus", "label": "O" }],
"strengths": { "claude": {
"thrifty": { "model": "sonnet", "effort": "low" },
"best": { "model": "opus", "effort": "medium" } } } }"#,
)
.unwrap();
std::fs::write(
&user,
r#"{ "strengths": { "claude": { "best": { "model": "sonnet", "effort": "high" } } } }"#,
)
.unwrap();
let models = vec!["sonnet".to_string(), "opus".to_string()];
let got = strengths_from("claude", &models, true, Some(&shipped), Some(&user));
assert_eq!(got["thrifty"].model, "sonnet");
assert_eq!(got["best"].model, "sonnet");
assert_eq!(got["best"].effort.as_deref(), Some("high"));
assert!(!got.contains_key("balanced"));
// No user file: the shipped rows alone.
let got = strengths_from("claude", &models, true, Some(&shipped), None);
assert_eq!(got["best"].model, "opus");
// An agent with no rows anywhere has none.
assert!(strengths_from("codex", &models, false, Some(&shipped), Some(&user)).is_empty());
}
#[test]
fn the_baked_copy_ships_the_claude_and_devin_strengths() {
let dir = temp_dir("baked-strengths");
let missing = dir.join("bin").join("models.json");
let ids = |agent: &str| -> Vec<String> {
models_for(agent, Some(&missing), Some(&missing))
.into_iter()
.map(|m| m.id)
.collect()
};
let claude = strengths_from(
"claude",
&ids("claude"),
true,
Some(&missing),
Some(&missing),
);
assert_eq!(claude.len(), 3);
let devin = strengths_from(
"devin",
&ids("devin"),
false,
Some(&missing),
Some(&missing),
);
assert_eq!(devin.len(), 3);
assert!(strengths_from(
"codex",
&ids("codex"),
false,
Some(&missing),
Some(&missing)
)
.is_empty());
}
/// A `strengths` key beside the agents' lists is never read as a model
/// list: the menus come out as they did without it.
#[test]
fn a_strengths_key_leaves_the_model_menus_unchanged() {
let dir = temp_dir("strengths-menu");
let shipped = dir.join("bin").join("models.json");
let user = dir.join("models.json");
std::fs::write(
&shipped,
r#"{ "claude": [{ "id": "sonnet", "label": "S" }],
"strengths": { "claude": { "best": { "model": "sonnet" } } } }"#,
)
.unwrap();
std::fs::write(
&user,
r#"{ "claude": [{ "id": "mine", "label": "M" }],
"strengths": { "claude": { "best": { "model": "mine" } } } }"#,
)
.unwrap();
assert_eq!(
models_for("claude", Some(&shipped), Some(&user)),
vec![model("sonnet", Some("S")), model("mine", Some("M"))]
);
assert!(models_for("strengths", Some(&shipped), Some(&user)).is_empty());
}
} }
+1 -1
View File
@@ -155,7 +155,7 @@ pub fn remember_folder(dir: &Path) -> Result<ProjectDir, String> {
std::fs::create_dir_all(parent).map_err(err)?; std::fs::create_dir_all(parent).map_err(err)?;
} }
let json = serde_json::to_string_pretty(&serde_json::Value::Object(state)).map_err(err)?; let json = serde_json::to_string_pretty(&serde_json::Value::Object(state)).map_err(err)?;
std::fs::write(file, json).map_err(err)?; crate::loop_driver::write_atomic(&file, &json)?;
Ok(ProjectDir { Ok(ProjectDir {
dir: dir.to_path_buf(), dir: dir.to_path_buf(),
source: ProjectSource::Picked, source: ProjectSource::Picked,
+1 -1
View File
@@ -153,7 +153,7 @@ fn write(file: &Path, settings: serde_json::Map<String, serde_json::Value>) -> R
} }
let json = serde_json::to_string_pretty(&serde_json::Value::Object(settings)) let json = serde_json::to_string_pretty(&serde_json::Value::Object(settings))
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
std::fs::write(file, json).map_err(|e| e.to_string()) crate::loop_driver::write_atomic(file, &json)
} }
#[cfg(test)] #[cfg(test)]
+4 -4
View File
@@ -257,7 +257,7 @@ mod tests {
let lines = std::sync::Mutex::new(Vec::<String>::new()); let lines = std::sync::Mutex::new(Vec::<String>::new());
let result = let result =
with_fake_launcher("ok", "console.log('line1'); console.log('line2');", || { with_fake_launcher("ok", "console.log('line1'); console.log('line2');", || {
run_update_within("9.9.9", Duration::from_secs(10), |line| { run_update_within("9.9.9", Duration::from_secs(60), |line| {
lines.lock().unwrap().push(line.to_string()) lines.lock().unwrap().push(line.to_string())
}) })
}); });
@@ -273,7 +273,7 @@ mod tests {
let result = with_fake_launcher( let result = with_fake_launcher(
"tag", "tag",
"console.log(process.argv.slice(2).join(' '));", "console.log(process.argv.slice(2).join(' '));",
|| run_update_within("9.9.9", Duration::from_secs(10), |_| {}), || run_update_within("9.9.9", Duration::from_secs(60), |_| {}),
); );
assert_eq!(result, Ok("update --tag v9.9.9".to_string())); assert_eq!(result, Ok("update --tag v9.9.9".to_string()));
} }
@@ -281,7 +281,7 @@ mod tests {
#[test] #[test]
fn run_update_fails_with_the_installer_s_own_last_line() { fn run_update_fails_with_the_installer_s_own_last_line() {
let result = with_fake_launcher("fail", "console.log('oops'); process.exit(1);", || { let result = with_fake_launcher("fail", "console.log('oops'); process.exit(1);", || {
run_update_within("9.9.9", Duration::from_secs(10), |_| {}) run_update_within("9.9.9", Duration::from_secs(60), |_| {})
}); });
assert_eq!(result, Err("the update did not finish: oops".to_string())); assert_eq!(result, Err("the update did not finish: oops".to_string()));
} }
@@ -298,7 +298,7 @@ mod tests {
fn a_missing_launcher_is_an_error_not_a_panic() { fn a_missing_launcher_is_an_error_not_a_panic() {
let result = with_fake_launcher("missing", "", || { let result = with_fake_launcher("missing", "", || {
std::fs::remove_file(launcher_dir().unwrap().join("plan2code.js")).unwrap(); std::fs::remove_file(launcher_dir().unwrap().join("plan2code.js")).unwrap();
run_update_within("9.9.9", Duration::from_secs(10), |_| {}) run_update_within("9.9.9", Duration::from_secs(60), |_| {})
}); });
assert!(result.unwrap_err().contains("is missing")); assert!(result.unwrap_err().contains("is missing"));
} }
@@ -432,3 +432,57 @@ fn a_custom_agent_runs_the_override_too_and_restart_keeps_its_id() {
); );
h.manager.stop(); h.manager.stop();
} }
#[test]
fn a_phase_start_runs_on_its_model_and_env_and_leaves_the_launch_choice_alone() {
let mut h = Harness::new();
h.manager
.start(
Agent::Builtin(builtin_entry("claude").unwrap()),
Some("opus".to_string()),
Some("high".to_string()),
PermissionMode::Checked,
None,
)
.expect("start the fake agent");
h.wait_for_output(READY, 1);
h.manager
.start_phase_on(
"/plan2code phase".to_string(),
"sonnet".to_string(),
Some("low".to_string()),
vec![("PLAN2CODE_LOOP_STRENGTH".to_string(), "thrifty".to_string())],
)
.expect("start the phase on its strength");
h.wait_for_output(READY, 2);
// The agent-bin override drops every argument, so the fake agent sees the
// env only; the model is checked through the stored choice below.
h.type_line("ENV PLAN2CODE_LOOP_STRENGTH");
h.wait_for_output("ENV PLAN2CODE_LOOP_STRENGTH=thrifty", 1);
// The stored choice, kind and mode are what they were.
let (kind, model, effort, mode) = h.manager.launch_choice().unwrap();
assert_eq!(kind.id(), "claude");
assert_eq!(model.as_deref(), Some("opus"));
assert_eq!(effort.as_deref(), Some("high"));
assert_eq!(mode, PermissionMode::Checked);
// The next plain start runs on the original choice, with no strength.
h.manager
.start_fresh("/plan2code next".to_string())
.unwrap();
h.wait_for_output(READY, 3);
h.type_line("ENV PLAN2CODE_LOOP_STRENGTH");
h.wait_for_output("ENV PLAN2CODE_LOOP_STRENGTH=\r", 1);
h.manager.stop();
}
#[test]
fn a_phase_start_with_no_launch_choice_is_refused() {
let h = Harness::new();
let refused = h
.manager
.start_phase_on("p".to_string(), "sonnet".to_string(), None, Vec::new());
assert!(refused.is_err());
}
+2 -2
View File
@@ -795,10 +795,10 @@ window.addEventListener('message', (event) => {
invoke('loop_facts') invoke('loop_facts')
.then((facts) => source.postMessage({ plan2code: 'loop-facts', facts }, '*')) .then((facts) => source.postMessage({ plan2code: 'loop-facts', facts }, '*'))
.catch(() => {}); .catch(() => {});
} else if (kind === 'loop-resume' || kind === 'loop-fix' || kind === 'loop-finalize') { } else if (kind === 'loop-resume' || kind === 'loop-ask' || kind === 'loop-fix' || kind === 'loop-finalize') {
// Fixed requests, no free text: the page answers with ok or the error. // Fixed requests, no free text: the page answers with ok or the error.
const source = event.source; const source = event.source;
const command = { 'loop-resume': 'loop_resume', 'loop-fix': 'loop_fix', 'loop-finalize': 'loop_finalize' }[kind]; const command = { 'loop-resume': 'loop_resume', 'loop-ask': 'loop_ask', 'loop-fix': 'loop_fix', 'loop-finalize': 'loop_finalize' }[kind];
invoke(command) invoke(command)
.then(() => source.postMessage({ plan2code: `${kind}-result`, ok: true, error: null }, '*')) .then(() => source.postMessage({ plan2code: `${kind}-result`, ok: true, error: null }, '*'))
.catch((error) => source.postMessage({ plan2code: `${kind}-result`, ok: false, error: String(error) }, '*')); .catch((error) => source.postMessage({ plan2code: `${kind}-result`, ok: false, error: String(error) }, '*'));
+16 -1
View File
@@ -181,7 +181,22 @@ export function loopBanner(state) {
} }
return { ...base, title: "Starting the loop", detail: `Opening a fresh agent for ${named}.` }; return { ...base, title: "Starting the loop", detail: `Opening a fresh agent for ${named}.` };
} }
return { ...base, title: "Implementation loop running", detail: step ? `${named} \u00b7 ${step}` : named }; const ran = loopRunText(state);
const where = step ? `${named} \u00b7 ${step}` : named;
return { ...base, title: "Implementation loop running", detail: ran ? `${where} \u00b7 ${ran}` : where };
}
/**
* What the running phase runs on, from the app's `loop-state`: "Thrifty (sonnet,
* low)" for a phase on a strength, "(opus, high)" for a Match my session phase
* with a known model, and "" when the loop runs as it always did.
*/
export function loopRunText(state) {
const model = state && typeof state.model === "string" ? state.model : "";
const effort = model && state.effort ? `, ${state.effort}` : "";
const word = state && typeof state.strength === "string" && state.strength ? state.strength[0].toUpperCase() + state.strength.slice(1) : "";
if (word) return model ? `${word} (${model}${effort})` : word;
return model ? `(${model}${effort})` : "";
} }
/** /**
+14 -1
View File
@@ -2,7 +2,7 @@ import fs from 'fs';
import os from 'os'; import os from 'os';
import path from 'path'; import path from 'path';
import { describe, it, expect, afterEach } from 'vitest'; import { describe, it, expect, afterEach } from 'vitest';
import { avg, rate, buildCohortKey, backfillPromptVersions, cohortKeyForRun, aggregate } from './aggregator.js'; import { avg, rate, buildCohortKey, backfillPromptVersions, cohortKeyForRun, aggregate, writeRunFile } from './aggregator.js';
import type { PromptVersions, RunMetrics } from './types.js'; import type { PromptVersions, RunMetrics } from './types.js';
// ── avg() ───────────────────────────────────────────────────────────────────── // ── avg() ─────────────────────────────────────────────────────────────────────
@@ -251,3 +251,16 @@ describe('aggregate', () => {
expect(result.current_cohort_key).toBe(buildCohortKey(local.prompt_versions)); expect(result.current_cohort_key).toBe(buildCohortKey(local.prompt_versions));
}); });
}); });
describe('writeRunFile', () => {
it('refuses a run_id that is not a run-<id> name, so it cannot leave the runs folder', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'p2c-runs-'));
try {
const run = { ...makeRun({}), run_id: '../../escape' };
expect(() => writeRunFile(run, path.join(dir, 'runs'))).toThrow(/run-<id>/);
expect(fs.existsSync(path.join(dir, 'escape.json'))).toBe(false);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
});
+4
View File
@@ -230,6 +230,10 @@ export function loadAggregated(outputPath: string): AggregatedMetrics | null {
* Returns true if written, false if a file for that run_id already existed. * Returns true if written, false if a file for that run_id already existed.
*/ */
export function writeRunFile(run: RunMetrics, runsDir: string): boolean { export function writeRunFile(run: RunMetrics, runsDir: string): boolean {
// The id becomes a file name: only the collector's own shape may reach a path.
if (!/^run-[A-Za-z0-9-]{1,64}$/.test(run.run_id)) {
throw new Error(`Refusing run_id "${String(run.run_id).slice(0, 80)}": it is not a run-<id> name.`);
}
const destPath = path.join(runsDir, `${run.run_id}.json`); const destPath = path.join(runsDir, `${run.run_id}.json`);
if (fs.existsSync(destPath)) { if (fs.existsSync(destPath)) {
+3 -3
View File
@@ -5,11 +5,11 @@
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import { fileURLToPath } from 'url';
import type { AggregatedMetrics } from './types.js'; import type { AggregatedMetrics } from './types.js';
import { invokeLLM, type AgentType } from './invoke-llm.js'; import { invokeLLM, type AgentType } from './invoke-llm.js';
const ANALYZE_PROMPT_PATH = new URL('../src/prompts/analyze.md', import.meta.url).pathname const ANALYZE_PROMPT_PATH = fileURLToPath(new URL('../src/prompts/analyze.md', import.meta.url));
.replace(/^\/([A-Za-z]:)/, '$1'); // Fix Windows path
// ── Helpers ─────────────────────────────────────────────────────────────────── // ── Helpers ───────────────────────────────────────────────────────────────────
@@ -40,7 +40,7 @@ function readPromptFiles(plan2codeRoot: string): Record<string, string> {
function interpolate(template: string, vars: Record<string, string>): string { function interpolate(template: string, vars: Record<string, string>): string {
let result = template; let result = template;
for (const [key, value] of Object.entries(vars)) { for (const [key, value] of Object.entries(vars)) {
result = result.replaceAll(`{{${key}}}`, value); result = result.replaceAll(`{{${key}}}`, () => value);
} }
return result; return result;
} }
+2 -2
View File
@@ -67,7 +67,7 @@ function applyEdit(edit: PromptEdit, plan2codeRoot: string): boolean {
console.error(chalk.red(`✗ Cannot apply: old_text not found in ${edit.file} (may have been modified by a previous edit)`)); console.error(chalk.red(`✗ Cannot apply: old_text not found in ${edit.file} (may have been modified by a previous edit)`));
return false; return false;
} }
content = content.replace(edit.old_text, edit.new_text); content = content.replace(edit.old_text, () => edit.new_text);
// Post-apply char count check // Post-apply char count check
if (content.length > CHAR_LIMIT) { if (content.length > CHAR_LIMIT) {
@@ -173,7 +173,7 @@ export async function reviewAndApply(opts: ApplierOptions): Promise<ApplierResul
if (success) { if (success) {
applied++; applied++;
// Update in-memory content to reflect the edit // Update in-memory content to reflect the edit
promptContents[edit.file] = promptContents[edit.file].replace(edit.old_text, edit.new_text); promptContents[edit.file] = promptContents[edit.file].replace(edit.old_text, () => edit.new_text);
} else { } else {
failed++; failed++;
} }
+6
View File
@@ -87,6 +87,12 @@ describe('parseSubmissionPayload', () => {
expect(result).toBeNull(); expect(result).toBeNull();
}); });
it('returns null when run_id is not a run-<id> name (it becomes a file name)', () => {
for (const run_id of ['../../x', 'run-../x', 'x', 'run-' + 'a'.repeat(65), 'run-a/b']) {
expect(parseSubmissionPayload(issueBody({ ...VALID_PAYLOAD, run_id }))).toBeNull();
}
});
it('returns null when user_feedback.overall_rating is a string instead of a number', () => { it('returns null when user_feedback.overall_rating is a string instead of a number', () => {
const badPayload = { const badPayload = {
...VALID_PAYLOAD, ...VALID_PAYLOAD,
+2 -1
View File
@@ -242,7 +242,8 @@ export function parseSubmissionPayload(body: string): RunMetrics | null {
if (!parsed) return null; if (!parsed) return null;
if (parsed['schema_version'] !== '1.0') return null; if (parsed['schema_version'] !== '1.0') return null;
if (!isString(parsed['run_id'])) return null; // The id becomes a file name in the runs folder: only the collector's own shape.
if (!isString(parsed['run_id']) || !/^run-[A-Za-z0-9-]{1,64}$/.test(parsed['run_id'])) return null;
if (!isString(parsed['plan2code_version'])) return null; if (!isString(parsed['plan2code_version'])) return null;
const feedbackRaw = parsed['user_feedback']; const feedbackRaw = parsed['user_feedback'];
+1 -1
View File
@@ -128,7 +128,7 @@ describe('parseProposalFromResponse', () => {
}); });
it('returns null for malformed JSON', () => { it('returns null for malformed JSON', () => {
const result = parseProposalFromResponse('```json\n{broken json]\n```'); const result = parseProposalFromResponse('```json\n[{"old_text": broken]\n```');
expect(result).toBeNull(); expect(result).toBeNull();
}); });
+5 -5
View File
@@ -6,19 +6,19 @@
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import { fileURLToPath } from 'url';
import type { PromptEdit, PromptProposal } from './types.js'; import type { PromptEdit, PromptProposal } from './types.js';
import { invokeLLM, type AgentType } from './invoke-llm.js'; import { invokeLLM, type AgentType } from './invoke-llm.js';
const CHAR_LIMIT = 20_000; const CHAR_LIMIT = 20_000;
const IMPROVE_PROMPT_PATH = new URL('../src/prompts/improve.md', import.meta.url).pathname const IMPROVE_PROMPT_PATH = fileURLToPath(new URL('../src/prompts/improve.md', import.meta.url));
.replace(/^\/([A-Za-z]:)/, '$1'); // Fix Windows path
// ── Helpers ─────────────────────────────────────────────────────────────────── // ── Helpers ───────────────────────────────────────────────────────────────────
function interpolate(template: string, vars: Record<string, string>): string { function interpolate(template: string, vars: Record<string, string>): string {
let result = template; let result = template;
for (const [key, value] of Object.entries(vars)) { for (const [key, value] of Object.entries(vars)) {
result = result.replaceAll(`{{${key}}}`, value); result = result.replaceAll(`{{${key}}}`, () => value);
} }
return result; return result;
} }
@@ -93,7 +93,7 @@ export function validateEdit(
} }
// Check char count after edit // Check char count after edit
const afterContent = fileContent.replace(edit.old_text, edit.new_text); const afterContent = fileContent.replace(edit.old_text, () => edit.new_text);
if (afterContent.length > CHAR_LIMIT) { if (afterContent.length > CHAR_LIMIT) {
errors.push(`Edit would cause "${edit.file}" to exceed ${CHAR_LIMIT} char limit (would be ${afterContent.length} chars).`); errors.push(`Edit would cause "${edit.file}" to exceed ${CHAR_LIMIT} char limit (would be ${afterContent.length} chars).`);
} }
@@ -232,7 +232,7 @@ export async function generateImprovement(opts: ImproverOptions): Promise<Improv
if (result.valid) { if (result.valid) {
// Compute accurate char counts // Compute accurate char counts
const fileContent = promptContents[edit.file] ?? ''; const fileContent = promptContents[edit.file] ?? '';
const afterContent = fileContent.replace(edit.old_text, edit.new_text); const afterContent = fileContent.replace(edit.old_text, () => edit.new_text);
edit.char_count_before = fileContent.length; edit.char_count_before = fileContent.length;
edit.char_count_after = afterContent.length; edit.char_count_after = afterContent.length;
edit.char_count_delta = afterContent.length - fileContent.length; edit.char_count_delta = afterContent.length - fileContent.length;
+1 -1
View File
@@ -81,7 +81,7 @@
{ {
"name": "an install folder with %NAME% expands against vars", "name": "an install folder with %NAME% expands against vars",
"platform": "win", "platform": "win",
"entry": { "command": "goose", "installDirs": { "win": ["%TOOLS%\\bin"] } }, "entry": { "command": "goose", "installDirs": { "win": ["%TOOLS%/bin"] } },
"dirs": { "tools": ["bin/goose.exe"] }, "dirs": { "tools": ["bin/goose.exe"] },
"env": { "path": "", "savedPath": "", "npmBin": "", "pathext": ".EXE;.CMD", "vars": { "TOOLS": "{tools}" } }, "env": { "path": "", "savedPath": "", "npmBin": "", "pathext": ".EXE;.CMD", "vars": { "TOOLS": "{tools}" } },
"state": "outside", "state": "outside",
+163
View File
@@ -1891,6 +1891,169 @@
"args": [ "args": [
"a $HOME & \"b\"" "a $HOME & \"b\""
] ]
},
{
"name": "OpenCode's shape: a chosen model goes ahead of the prompt",
"entry": {
"id": "opencode",
"name": "OpenCode",
"command": "opencode",
"args": [
"{model}",
"--prompt",
"{prompt}"
],
"prompt": "Use the plan2code skill",
"bypassArgs": [
"--auto"
],
"modelArgs": [
"--model",
"{model}"
]
},
"options": {
"model": "anthropic/sonnet",
"bypass": false
},
"args": [
"--model",
"anthropic/sonnet",
"--prompt",
"Use the plan2code skill"
]
},
{
"name": "OpenCode's shape: no model, no model argument",
"entry": {
"id": "opencode",
"name": "OpenCode",
"command": "opencode",
"args": [
"{model}",
"--prompt",
"{prompt}"
],
"prompt": "Use the plan2code skill",
"bypassArgs": [
"--auto"
],
"modelArgs": [
"--model",
"{model}"
]
},
"options": {
"bypass": false
},
"args": [
"--prompt",
"Use the plan2code skill"
]
},
{
"name": "Gemini CLI's shape: a chosen model goes ahead of the prompt",
"entry": {
"id": "gemini",
"name": "Gemini CLI",
"command": "gemini",
"args": [
"{model}",
"{prompt}"
],
"prompt": "Use the plan2code skill",
"bypassArgs": [
"--approval-mode=yolo"
],
"modelArgs": [
"--model",
"{model}"
]
},
"options": {
"model": "flash",
"bypass": false
},
"args": [
"--model",
"flash",
"Use the plan2code skill"
]
},
{
"name": "Gemini CLI's shape: no model, no model argument",
"entry": {
"id": "gemini",
"name": "Gemini CLI",
"command": "gemini",
"args": [
"{model}",
"{prompt}"
],
"prompt": "Use the plan2code skill",
"bypassArgs": [
"--approval-mode=yolo"
],
"modelArgs": [
"--model",
"{model}"
]
},
"options": {
"bypass": false
},
"args": [
"Use the plan2code skill"
]
},
{
"name": "Pi's shape: a chosen model goes ahead of the prompt",
"entry": {
"id": "pi",
"name": "Pi",
"command": "pi",
"args": [
"{model}",
"{prompt}"
],
"prompt": "/skill:plan2code",
"modelArgs": [
"--model",
"{model}"
]
},
"options": {
"model": "sonnet:high",
"bypass": false
},
"args": [
"--model",
"sonnet:high",
"/skill:plan2code"
]
},
{
"name": "Pi's shape: no model, no model argument",
"entry": {
"id": "pi",
"name": "Pi",
"command": "pi",
"args": [
"{model}",
"{prompt}"
],
"prompt": "/skill:plan2code",
"modelArgs": [
"--model",
"{model}"
]
},
"options": {
"bypass": false
},
"args": [
"/skill:plan2code"
]
} }
], ],
"ids": [ "ids": [
+478
View File
@@ -0,0 +1,478 @@
{
"schema": 1,
"cases": [
{
"name": "claude shipped only",
"agent": "claude",
"shipped": {
"thrifty": {
"model": "sonnet",
"effort": "low"
},
"balanced": {
"model": "sonnet",
"effort": "medium"
},
"best": {
"model": "opus",
"effort": "medium"
}
},
"user": null,
"models": [
"default",
"sonnet",
"opus",
"haiku"
],
"hasEffort": true,
"expect": {
"resolved": {
"thrifty": {
"model": "sonnet",
"effort": "low"
},
"balanced": {
"model": "sonnet",
"effort": "medium"
},
"best": {
"model": "opus",
"effort": "medium"
}
},
"next": {
"thrifty": "balanced",
"balanced": "best",
"best": null
}
}
},
{
"name": "devin shipped only",
"agent": "devin",
"shipped": {
"thrifty": {
"model": "swe-2-medium"
},
"balanced": {
"model": "swe-2-high"
},
"best": {
"model": "claude-opus-5-5-medium"
}
},
"user": null,
"models": [
"adaptive",
"swe-2-medium",
"swe-2-high",
"claude-opus-5-5-medium"
],
"hasEffort": false,
"expect": {
"resolved": {
"thrifty": {
"model": "swe-2-medium"
},
"balanced": {
"model": "swe-2-high"
},
"best": {
"model": "claude-opus-5-5-medium"
}
},
"next": {
"thrifty": "balanced",
"balanced": "best",
"best": null
}
}
},
{
"name": "a user row overrides one shipped row, the others follow shipped",
"agent": "claude",
"shipped": {
"thrifty": {
"model": "sonnet",
"effort": "low"
},
"balanced": {
"model": "sonnet",
"effort": "medium"
},
"best": {
"model": "opus",
"effort": "medium"
}
},
"user": {
"balanced": {
"model": "opus",
"effort": "low"
}
},
"models": [
"default",
"sonnet",
"opus",
"haiku"
],
"hasEffort": true,
"expect": {
"resolved": {
"thrifty": {
"model": "sonnet",
"effort": "low"
},
"balanced": {
"model": "opus",
"effort": "low"
},
"best": {
"model": "opus",
"effort": "medium"
}
},
"next": {
"thrifty": "balanced",
"balanced": "best",
"best": null
}
}
},
{
"name": "user-only mapping for an agent with nothing shipped",
"agent": "codex",
"shipped": null,
"user": {
"thrifty": {
"model": "gpt-a"
},
"balanced": {
"model": "gpt-b"
},
"best": {
"model": "gpt-c"
}
},
"models": [
"gpt-a",
"gpt-b",
"gpt-c"
],
"hasEffort": false,
"expect": {
"resolved": {
"thrifty": {
"model": "gpt-a"
},
"balanced": {
"model": "gpt-b"
},
"best": {
"model": "gpt-c"
}
},
"next": {
"thrifty": "balanced",
"balanced": "best",
"best": null
}
}
},
{
"name": "partly mapped: Balanced only",
"agent": "opencode",
"shipped": null,
"user": {
"balanced": {
"model": "m1"
}
},
"models": [
"m1",
"m2"
],
"hasEffort": false,
"expect": {
"resolved": {
"balanced": {
"model": "m1"
}
},
"next": {
"thrifty": "balanced",
"balanced": null,
"best": null
}
}
},
{
"name": "partly mapped: Thrifty and Best only",
"agent": "opencode",
"shipped": null,
"user": {
"thrifty": {
"model": "m1"
},
"best": {
"model": "m2"
}
},
"models": [
"m1",
"m2"
],
"hasEffort": false,
"expect": {
"resolved": {
"thrifty": {
"model": "m1"
},
"best": {
"model": "m2"
}
},
"next": {
"thrifty": "best",
"balanced": "best",
"best": null
}
}
},
{
"name": "a user row whose model left the list falls back to the shipped row",
"agent": "claude",
"shipped": {
"thrifty": {
"model": "sonnet",
"effort": "low"
},
"balanced": {
"model": "sonnet",
"effort": "medium"
},
"best": {
"model": "opus",
"effort": "medium"
}
},
"user": {
"best": {
"model": "gone",
"effort": "high"
}
},
"models": [
"default",
"sonnet",
"opus",
"haiku"
],
"hasEffort": true,
"expect": {
"resolved": {
"thrifty": {
"model": "sonnet",
"effort": "low"
},
"balanced": {
"model": "sonnet",
"effort": "medium"
},
"best": {
"model": "opus",
"effort": "medium"
}
},
"next": {
"thrifty": "balanced",
"balanced": "best",
"best": null
}
}
},
{
"name": "a shipped row whose model left the list reads unmapped",
"agent": "claude",
"shipped": {
"thrifty": {
"model": "sonnet",
"effort": "low"
},
"balanced": {
"model": "sonnet",
"effort": "medium"
},
"best": {
"model": "opus",
"effort": "medium"
}
},
"user": null,
"models": [
"default",
"opus"
],
"hasEffort": true,
"expect": {
"resolved": {
"best": {
"model": "opus",
"effort": "medium"
}
},
"next": {
"thrifty": "best",
"balanced": "best",
"best": null
}
}
},
{
"name": "an effort on an agent without one is dropped",
"agent": "devin",
"shipped": null,
"user": {
"thrifty": {
"model": "swe-2-medium",
"effort": "low"
},
"best": {
"model": "swe-2-high",
"effort": "high"
}
},
"models": [
"adaptive",
"swe-2-medium",
"swe-2-high",
"claude-opus-5-5-medium"
],
"hasEffort": false,
"expect": {
"resolved": {
"thrifty": {
"model": "swe-2-medium"
},
"best": {
"model": "swe-2-high"
}
},
"next": {
"thrifty": "best",
"balanced": "best",
"best": null
}
}
},
{
"name": "an effort outside low, medium and high is dropped, the row stays",
"agent": "claude",
"shipped": null,
"user": {
"thrifty": {
"model": "haiku",
"effort": "max"
},
"balanced": {
"model": "sonnet",
"effort": "medium"
}
},
"models": [
"default",
"sonnet",
"opus",
"haiku"
],
"hasEffort": true,
"expect": {
"resolved": {
"thrifty": {
"model": "haiku"
},
"balanced": {
"model": "sonnet",
"effort": "medium"
}
},
"next": {
"thrifty": "balanced",
"balanced": null,
"best": null
}
}
},
{
"name": "a bad word or a row that is not an object is ignored",
"agent": "claude",
"shipped": null,
"user": {
"cheap": {
"model": "haiku"
},
"thrifty": "haiku",
"balanced": [
"sonnet"
],
"best": {
"model": 7
},
"extra": null
},
"models": [
"default",
"sonnet",
"opus",
"haiku"
],
"hasEffort": true,
"expect": {
"resolved": {},
"next": {
"thrifty": null,
"balanced": null,
"best": null
}
}
},
{
"name": "nothing anywhere",
"agent": "pi",
"shipped": null,
"user": null,
"models": [],
"hasEffort": false,
"expect": {
"resolved": {},
"next": {
"thrifty": null,
"balanced": null,
"best": null
}
}
},
{
"name": "mappings that are not objects",
"agent": "pi",
"shipped": [
"x"
],
"user": "y",
"models": [
"x"
],
"hasEffort": false,
"expect": {
"resolved": {},
"next": {
"thrifty": null,
"balanced": null,
"best": null
}
}
}
]
}
+79
View File
@@ -116,9 +116,38 @@ export async function openSession(browser, { t, workflow, payload: first, projec
s.page.on("pageerror", (e) => s.errors.push(e.message)); s.page.on("pageerror", (e) => s.errors.push(e.message));
await s.page.goto(s.url, { waitUntil: "domcontentloaded" }); await s.page.goto(s.url, { waitUntil: "domcontentloaded" });
await drawn(s.page); await drawn(s.page);
// Redraws that follow the first one (the workspace frame, a scan, the update check) land a
// moment later, and on a busy runner a test that has already scrolled, typed or opened
// something loses it to them. Hand the test a page that has gone quiet. A fake clock freezes
// the page's own timers, so those sessions are left as they are.
if (!clock) await quiet(s.page);
return s; return s;
} }
// Waits until the document has not changed for `quietMs`, or `maxMs` at most (a page that never
// goes quiet must not block a test). Counts mutations in the page and polls the count from
// here, so it needs no timer in the page.
export async function quiet(page, { quietMs = 300, maxMs = 4000 } = {}) {
await page
.evaluate(() => {
if (window.__quiet) return;
window.__quiet = { n: 0 };
new MutationObserver(() => window.__quiet.n++).observe(document.body, { subtree: true, childList: true, attributes: true, characterData: true });
})
.catch(() => {});
const end = Date.now() + maxMs;
let last = -1;
let since = Date.now();
while (Date.now() < end) {
const n = await page.evaluate(() => (window.__quiet ? window.__quiet.n : -1)).catch(() => -1);
if (n !== last) {
last = n;
since = Date.now();
} else if (Date.now() - since >= quietMs) return;
await new Promise((r) => setTimeout(r, 50));
}
}
// The page has adopted a state frame: app.js has replaced the boot pane the // The page has adopted a state frame: app.js has replaced the boot pane the
// markup ships with. // markup ships with.
export async function drawn(page) { export async function drawn(page) {
@@ -186,12 +215,62 @@ export async function fillBox(locator, text) {
const box = locator.first(); const box = locator.first();
const isField = await box.evaluate((n) => Boolean(n.field)).catch(() => false); const isField = await box.evaluate((n) => Boolean(n.field)).catch(() => false);
if (!isField) return box.fill(text); if (!isField) return box.fill(text);
// A field is drawn disabled until the page knows the agent's state (the Ask box, for one),
// and a disabled field drops what is typed into it, leaving Send off for good: give it a
// moment to open, on whichever element the box is by then.
for (let i = 0; i < 200; i++) {
const open = await box.evaluate((n) => n.isConnected && !n.classList.contains("is-disabled")).catch(() => false);
if (open) break;
await new Promise((r) => setTimeout(r, 50));
}
await box.evaluate((n, t) => { await box.evaluate((n, t) => {
n.field.value = t; n.field.value = t;
n.field.emitInput(); n.field.emitInput();
}, text); }, text);
} }
// Waits until nothing inside the element has changed for `quietMs`. A late redraw (state that
// rides an event, a scan that lands after the page is drawn) replaces what a test has just
// scrolled or opened, and the test then fails on a slow runner: let the page go quiet first.
export async function settled(page, selector, quietMs = 500) {
await page.locator(selector).first().evaluate(
(n, ms) =>
new Promise((resolve) => {
let timer;
const done = () => {
observer.disconnect();
resolve();
};
const observer = new MutationObserver(() => {
clearTimeout(timer);
timer = setTimeout(done, ms);
});
observer.observe(n, { subtree: true, childList: true, attributes: true, characterData: true });
timer = setTimeout(done, ms);
}),
quietMs
);
}
// Types a message in the Ask box and presses Send. The composer is rebuilt whenever the page's
// view of the agent changes, and a box filled just before a rebuild can come back empty with Send
// off: fill again until Send is on, and when it never is, fail with the composer's own reason
// (its disabled note) instead of a minute-long click timeout.
export async function sendAsk(page, text) {
const send = page.locator(".ask-composer").getByRole("button", { name: "Send", exact: true });
let on = false;
for (let attempt = 0; attempt < 6 && !on; attempt++) {
await fillBox(page.locator("#ask-input"), text);
on = await send.isEnabled().catch(() => false);
if (!on) await page.waitForTimeout(500);
}
if (!on) {
const note = await page.locator(".ask-composer .ask-disabled-note").innerText().catch(() => "no disabled note");
throw new Error(`Send in the Ask box stayed off after typing ${text.length} characters: ${note}`);
}
await send.click();
}
// The text a box holds: a Markdown field through its facade, a real input // The text a box holds: a Markdown field through its facade, a real input
// through its value. // through its value.
export const boxValue = (locator) => locator.first().evaluate((n) => (n.field ? n.field.value : n.value)); export const boxValue = (locator) => locator.first().evaluate((n) => (n.field ? n.field.value : n.value));
+17
View File
@@ -0,0 +1,17 @@
// Pins Math.random to a seeded generator for a test file that drives an Activities game, so the
// game's own dice (a road with a crack where a test wanted plain road, a spawn that lands out of
// reach) give the same layout on every run and a rare roll can never fail a test at random.
// Import it FIRST in the file: a game module may roll at load time.
//
// A seed that fails a test is a real finding, not a flake: set PLAN2CODE_TEST_SEED to reproduce
// another roll, for example to hunt a bug the fixed seed hides.
let state = Number(process.env.PLAN2CODE_TEST_SEED || 20261105) >>> 0;
// mulberry32: small, fast and good enough for game dice.
Math.random = () => {
state = (state + 0x6d2b79f5) | 0;
let t = Math.imul(state ^ (state >>> 15), 1 | state);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
+2 -1
View File
@@ -64,10 +64,11 @@ export function scrubbedEnv(extra = {}) {
for (const k of AMBIENT_GIT_ENV) delete process.env[k]; for (const k of AMBIENT_GIT_ENV) delete process.env[k];
Object.assign(process.env, { GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: EMPTY_GITCONFIG }); Object.assign(process.env, { GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: EMPTY_GITCONFIG });
export function runScript(skill, script, args, { cwd, env } = {}) { export function runScript(skill, script, args, { cwd, env, input } = {}) {
const r = spawnSync(process.execPath, [path.join(SKILLS, skill, "scripts", script), ...args], { const r = spawnSync(process.execPath, [path.join(SKILLS, skill, "scripts", script), ...args], {
cwd: cwd || ROOT, cwd: cwd || ROOT,
encoding: "utf8", encoding: "utf8",
input,
env: scrubbedEnv({ PLAN2CODE_NOW: NOW, ...env }), env: scrubbedEnv({ PLAN2CODE_NOW: NOW, ...env }),
}); });
let json = null; let json = null;
+13 -1
View File
@@ -11,7 +11,7 @@ import assert from "node:assert/strict";
import fs from "node:fs"; import fs from "node:fs";
import path from "node:path"; import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url"; import { fileURLToPath, pathToFileURL } from "node:url";
import { attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopLocks, loopStopLabels, loopWindowTitle, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS } from "../plan2code-app/ui/meter.js"; import { attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopRunText, loopLocks, loopStopLabels, loopWindowTitle, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS } from "../plan2code-app/ui/meter.js";
import { findBrowser, launchBrowser } from "./browser.mjs"; import { findBrowser, launchBrowser } from "./browser.mjs";
const HERE = path.dirname(fileURLToPath(import.meta.url)); const HERE = path.dirname(fileURLToPath(import.meta.url));
@@ -339,6 +339,18 @@ test("the loop banner says what the loop is doing at every moment", () => {
assert.deepEqual(said({ phase: 0, phases: 0 }).pips, []); assert.deepEqual(said({ phase: 0, phases: 0 }).pips, []);
}); });
test("the loop banner names the strength and model a phase runs on, and nothing when the toggle is off", () => {
const base = { phase: 3, phases: 5, phaseName: "API", step: "Build" };
const said = (extra) => loopBanner({ ...base, ...extra }).detail;
assert.equal(said({ strength: "thrifty", model: "sonnet", effort: "low" }), "Phase 3 of 5: API \u00b7 Build \u00b7 Thrifty (sonnet, low)");
assert.equal(said({ strength: "best", model: "opus" }), "Phase 3 of 5: API \u00b7 Build \u00b7 Best (opus)");
assert.equal(said({ strength: "balanced" }), "Phase 3 of 5: API \u00b7 Build \u00b7 Balanced");
assert.equal(said({ strength: null, model: "opus", effort: "high" }), "Phase 3 of 5: API \u00b7 Build \u00b7 (opus, high)", "Match my session shows the launch model");
assert.equal(said({ strength: null, model: null, effort: null }), "Phase 3 of 5: API \u00b7 Build", "toggle off or no model known: unchanged");
assert.equal(said({}), "Phase 3 of 5: API \u00b7 Build");
assert.equal(loopRunText({}), "");
});
test("Stop now turns the banner to Stopping, ahead of a question or a stop on its way", () => { test("Stop now turns the banner to Stopping, ahead of a question or a stop on its way", () => {
const base = { phase: 2, phases: 4, phaseName: "API", step: "Build", stopAfterPhase: false, stopping: true }; const base = { phase: 2, phases: 4, phaseName: "API", step: "Build", stopAfterPhase: false, stopping: true };
for (const extra of [{}, { step: "Waiting on you" }, { stopAfterPhase: true }, { step: "Starting" }]) { for (const extra of [{}, { step: "Waiting on you" }, { stopAfterPhase: true }, { step: "Starting" }]) {
+3 -1
View File
@@ -36,12 +36,14 @@ export const BUDGETS = {
"handoff.md": 300, "handoff.md": 300,
"implement.md": 5700, "implement.md": 5700,
"init.md": 300, "init.md": 300,
"loop.md": 11100, "loop.md": 11600,
"pathfinder.md": 2400, "pathfinder.md": 2400,
"plan.md": 700, "plan.md": 700,
"pr-prep.md": 4500,
"quick-task.md": 4000, "quick-task.md": 4000,
"review.md": 1000, "review.md": 1000,
"revise-plan.md": 1200, "revise-plan.md": 1200,
"test.md": 5400,
"xray.md": 2500, "xray.md": 2500,
}, },
// One printed line each, for a session with one choice card. // One printed line each, for a session with one choice card.
+20
View File
@@ -334,6 +334,26 @@ test("launcher: mergeModels keeps the shipped list first and drops user duplicat
assert.deepEqual(modelEntries({ devin: [{ id: 1 }, null, { id: "ok", label: "Ok" }] }, "devin"), [{ id: "ok", label: "Ok" }]); assert.deepEqual(modelEntries({ devin: [{ id: 1 }, null, { id: "ok", label: "Ok" }] }, "devin"), [{ id: "ok", label: "Ok" }]);
}); });
test("launcher: a strengths key in the models files is never read as a model list, and every shipped strength names a listed model", () => {
const { modelEntries, mergeModels } = require(LAUNCHER);
const shipped = JSON.parse(fs.readFileSync(path.join(path.dirname(LAUNCHER), "models.json"), "utf8"));
assert.ok(shipped.strengths && typeof shipped.strengths === "object");
assert.deepEqual(modelEntries(shipped, "strengths"), []);
const claude = modelEntries(shipped, "claude");
assert.ok(claude.length > 0);
const user = { claude: [{ id: "mine", label: "Mine" }], strengths: { claude: { best: { model: "mine" } } } };
assert.deepEqual(modelEntries(user, "strengths"), []);
assert.deepEqual(mergeModels(claude, modelEntries(user, "claude")), [...claude, { id: "mine", label: "Mine" }]);
assert.deepEqual(mergeModels(claude, modelEntries({ claude: user.claude }, "claude")), mergeModels(claude, modelEntries(user, "claude")));
// Only Claude Code and Devin ship a mapping, and every row names a model in that agent's list.
assert.deepEqual(Object.keys(shipped.strengths).sort(), ["claude", "devin"]);
for (const [agent, rows] of Object.entries(shipped.strengths)) {
assert.deepEqual(Object.keys(rows), ["thrifty", "balanced", "best"], agent);
const ids = new Set(shipped[agent].map((m) => m.id));
for (const row of Object.values(rows)) assert.ok(ids.has(row.model), `${agent}: ${row.model}`);
}
});
test("launcher: the shipped models.json is curated Devin at low/medium/high only", () => { test("launcher: the shipped models.json is curated Devin at low/medium/high only", () => {
const shipped = JSON.parse(fs.readFileSync(path.join(path.dirname(LAUNCHER), "models.json"), "utf8")); const shipped = JSON.parse(fs.readFileSync(path.join(path.dirname(LAUNCHER), "models.json"), "utf8"));
assert.ok(shipped.claude.length > 0); assert.ok(shipped.claude.length > 0);
+181
View File
@@ -0,0 +1,181 @@
// Tests for plan2code-test's scripts/coverage.mjs: lcov and go tool cover -func
// output read into per-file numbers. See skill-script-helpers.mjs for how these
// run.
import { test, after } from "node:test";
import assert from "node:assert/strict";
import { runScript, tmp, write, fixtureCleanup } from "./skill-script-helpers.mjs";
after(fixtureCleanup);
const C = (cwd, ...a) => runScript("plan2code-test", "coverage.mjs", a, { cwd });
// What `node --test --experimental-test-coverage --test-reporter=lcov` writes:
// FN/FNDA/BRDA lines around the DA lines, relative paths, one file never run.
const NODE_LCOV = `TN:
SF:src/math.js
FN:1,add
FNDA:3,add
FNF:1
FNH:1
BRDA:2,0,0,1
BRF:1
BRH:1
DA:1,1
DA:2,3
DA:3,3
DA:4,1
LH:4
LF:4
end_of_record
TN:
SF:src/unused.js
FN:1,never
FNDA:0,never
FNF:1
FNH:0
DA:1,0
DA:2,0
DA:3,0
LH:0
LF:3
end_of_record
`;
test("coverage read --lcov: Node's lcov reporter, two files, one at 0 hits", () => {
const dir = tmp("cov-node");
write(dir, "lcov.info", NODE_LCOV);
const r = C(dir, "read", "--lcov", "lcov.info");
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json, {
ok: true,
format: "lcov",
files: [
{ file: "src/math.js", lines: 4, hit: 4, pct: 100 },
{ file: "src/unused.js", lines: 3, hit: 0, pct: 0 },
],
total: { lines: 7, hit: 4, pct: 57.1 },
});
});
test("coverage read --lcov: Jest's absolute Windows paths under the root become relative", () => {
const dir = tmp("cov-jest");
const lcov = [
"TN:",
"SF:C:\\work\\app\\src\\b\\view.ts",
"DA:1,1",
"DA:2,0",
"DA:3,1",
"LF:3",
"LH:2",
"end_of_record",
"TN:",
"SF:c:\\work\\app\\src\\a.ts",
"DA:1,1",
"LF:1",
"LH:1",
"end_of_record",
"TN:",
"SF:D:\\other\\lib.ts",
"DA:1,0",
"LF:1",
"LH:0",
"end_of_record",
"",
].join("\r\n");
write(dir, "coverage/lcov.info", lcov);
const r = C(dir, "read", "--lcov", "coverage/lcov.info", "--root", "C:\\work\\app");
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(
r.json.files.map((f) => [f.file, f.pct]),
[
["D:\\other\\lib.ts", 0],
["src/a.ts", 100],
["src/b/view.ts", 66.7],
]
);
});
test("coverage read --lcov: a record without LF or LH counts its DA lines", () => {
const dir = tmp("cov-nolf");
write(dir, "lcov.info", "SF:lib/x.py\nDA:1,2\nDA:2,0\nDA:5,1\nend_of_record\nSF:lib/empty.py\nend_of_record\n");
const r = C(dir, "read", "--lcov", "lcov.info");
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json.files, [
{ file: "lib/empty.py", lines: 0, hit: 0, pct: null },
{ file: "lib/x.py", lines: 3, hit: 2, pct: 66.7 },
]);
assert.deepEqual(r.json.total, { lines: 3, hit: 2, pct: 66.7 });
});
test("coverage read --go-func: functions grouped by file, the module path dropped, total reported", () => {
const dir = tmp("cov-go");
write(dir, "go.mod", "module example.com/shop\n\ngo 1.22\n");
write(
dir,
"cover.txt",
[
"example.com/shop/cart/cart.go:12:\t\tAdd\t\t100.0%",
"example.com/shop/cart/cart.go:30:\t\tRemove\t\t33.4%",
"example.com/shop/pay/pay.go:8:\t\tCharge\t\t0.0%",
"total:\t\t\t\t(statements)\t\t52.6%",
"",
].join("\n")
);
const r = C(dir, "read", "--go-func", "cover.txt");
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json, {
ok: true,
format: "go-func",
files: [
{ file: "cart/cart.go", lines: null, hit: null, pct: 66.7 },
{ file: "pay/pay.go", lines: null, hit: null, pct: 0 },
],
total: { lines: null, hit: null, pct: 52.6 },
});
});
test("coverage read --go-func: a nested module's files read from its own folder", () => {
const dir = tmp("cov-go-nested");
write(dir, "go.mod", "module example.com/shop\n\ngo 1.22\n");
write(dir, "tools/go.mod", "module example.com/shop/tools\n\ngo 1.22\n");
write(dir, "cover.txt", "example.com/shop/tools/gen/gen.go:5:\t\tRun\t\t50.0%\nexample.com/shop/cart/cart.go:3:\t\tAdd\t\t100.0%\n");
const r = C(dir, "read", "--go-func", "cover.txt");
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json.files.map((f) => f.file), ["cart/cart.go", "tools/gen/gen.go"]);
});
test("coverage read: a missing file is exit 3", () => {
const dir = tmp("cov-missing");
const r = C(dir, "read", "--lcov", "nope.info");
assert.equal(r.code, 3);
assert.equal(r.json.error, "no-file");
});
test("coverage read: a file in neither format is exit 4", () => {
const dir = tmp("cov-garbage");
write(dir, "junk.txt", "PASS src/a.test.js\nAll files | 80 | 70 |\n");
for (const flag of ["--lcov", "--go-func"]) {
const r = C(dir, "read", flag, "junk.txt");
assert.equal(r.code, 4, flag);
assert.equal(r.json.error, "unreadable-format", flag);
}
});
test("coverage read: exactly one format flag is required", () => {
const dir = tmp("cov-usage");
assert.equal(C(dir, "read").code, 2);
assert.equal(C(dir, "read", "--lcov", "a", "--go-func", "b").code, 2);
assert.equal(C(dir).code, 2);
});
test("coverage read --lcov --cwd: a runner's relative paths get its folder in front", () => {
const dir = tmp("cov-cwd");
write(dir, "lcov.info", "SF:src/x.ts\nDA:1,1\nLF:1\nLH:1\nend_of_record\nSF:D:/elsewhere/y.ts\nDA:1,0\nLF:1\nLH:0\nend_of_record\n");
const r = C(dir, "read", "--lcov", "lcov.info", "--cwd", "./packages/api/");
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(
r.json.files.map((f) => f.file),
["D:/elsewhere/y.ts", "packages/api/src/x.ts"]
);
});
+24 -1
View File
@@ -1,4 +1,5 @@
// Tests for plan2code-4-finalize's scripts/feedback-payload.mjs. // Tests for plan2code-4-finalize's scripts/feedback-payload.mjs and Step 5's
// opening question.
// //
// See skill-script-helpers.mjs for how these run. // See skill-script-helpers.mjs for how these run.
@@ -172,3 +173,25 @@ test("feedback-payload: submit refuses an oversize URL when gh fails, and dry-ru
assert.match(j.next, /--truncate/); assert.match(j.next, /--truncate/);
assert.match(j.next, /gh/); assert.match(j.next, /gh/);
}); });
/* ===================================================== Step 5's opening question */
// What a person sees break: Finalize posts the rating and reason cards straight
// away, and opting out takes a scroll to Skip on every one of them.
test("Step 5 asks one question first, with a No thank you, on the page and in the terminal", () => {
const notes = fs.readFileSync(path.join(ROOT, "src/web-console/notes/finalize.md"), "utf8");
const row = notes.split("\n").find((line) => line.startsWith("| 5, Feedback"));
assert.ok(row, "the notes have a row for Step 5");
const opening = row.indexOf('`confirm` "Rate this run"');
assert.ok(opening !== -1, "the row opens on the Rate this run card");
assert.match(row, /`noLabel` "No thank you"/);
assert.ok(opening < row.indexOf("rating as `choice`"), "the opening card comes before the rating card");
assert.ok(row.indexOf("No thank you") < row.indexOf("rating as `choice`"), "the way out comes before the rating card");
assert.match(row, /No: Step 6, no more cards/, "No thank you ends the questions on the page");
const prompt = fs.readFileSync(path.join(ROOT, "src/plan2code-4-finalize.md"), "utf8");
const step = prompt.slice(prompt.indexOf("### STEP 5:"), prompt.indexOf("### STEP 6:"));
assert.match(step, /on its own/, "the prompt asks the opening question alone");
assert.ok(step.indexOf("on its own") < step.indexOf("**Rating**"), "the opening question comes before the rating");
assert.match(step, /On no, skip to Step 6 and ask nothing more/, "no ends the questions in the terminal");
});
+266
View File
@@ -0,0 +1,266 @@
// Tests for plan2code-pr-prep's scripts/pr-prep.mjs: the template lookup, the
// pull-request link and the branch's spec folder. See skill-script-helpers.mjs
// for how these run.
import { test, after } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { runScript, tmp, write, gitInit, gitIn, slashed, fixtureCleanup } from "./skill-script-helpers.mjs";
after(fixtureCleanup);
// The console home holds pr-hosts.json; keep the real one out of every run.
const HOME = tmp("pr-prep-console-home");
const P = (cwd, ...a) => runScript("plan2code-pr-prep", "pr-prep.mjs", a, { cwd, env: { PLAN2CODE_CONSOLE_HOME: HOME } });
/* --------------------------------------------------------------- template */
const LOOKUP = [
".github/pull_request_template.md",
".github/PULL_REQUEST_TEMPLATE.md",
"PULL_REQUEST_TEMPLATE.md",
"docs/pull_request_template.md",
".github/PULL_REQUEST_TEMPLATE/feature.md",
"docs/PULL_REQUEST_TEMPLATE/feature.md",
".gitlab/merge_request_templates/Default.md",
];
test("pr-prep template: each place in the lookup order is found on its own", () => {
for (const rel of LOOKUP) {
const dir = tmp("pr-tpl");
write(dir, rel, "## Summary\n");
const r = P(dir, "template");
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json, { ok: true, found: true, path: rel, headings: ["Summary"], hasTesting: false, others: [] }, rel);
}
});
test("pr-prep template: the first in order wins and the rest are others", () => {
const dir = tmp("pr-tpl-order");
write(dir, "PULL_REQUEST_TEMPLATE.md", "## Root\n");
write(dir, "docs/pull_request_template.md", "## Docs\n");
write(dir, ".github/PULL_REQUEST_TEMPLATE/feature.md", "## Feature\n");
write(dir, ".github/PULL_REQUEST_TEMPLATE/bug.md", "## Bug\n");
write(dir, ".github/PULL_REQUEST_TEMPLATE/notes.txt", "not a template\n");
write(dir, ".gitlab/merge_request_templates/Default.md", "## GitLab\n");
const r = P(dir, "template");
assert.equal(r.code, 0, r.stderr);
assert.equal(r.json.path, "PULL_REQUEST_TEMPLATE.md");
assert.deepEqual(r.json.headings, ["Root"]);
assert.deepEqual(r.json.others, [
"docs/pull_request_template.md",
".github/PULL_REQUEST_TEMPLATE/bug.md",
".github/PULL_REQUEST_TEMPLATE/feature.md",
".gitlab/merge_request_templates/Default.md",
]);
});
test("pr-prep template: names are compared case-insensitively", () => {
const dir = tmp("pr-tpl-case");
write(dir, ".GitHub/Pull_Request_Template.MD", "## What\n");
const r = P(dir, "template");
assert.equal(r.code, 0, r.stderr);
assert.equal(r.json.found, true);
assert.equal(r.json.path, ".GitHub/Pull_Request_Template.MD");
});
test("pr-prep template: headings outside code fences only, # to ###, and hasTesting", () => {
const dir = tmp("pr-tpl-headings");
write(
dir,
".github/pull_request_template.md",
"# Title\n\n<!-- describe it -->\n## Summary ##\n\n```markdown\n## Not a heading\n```\n\n~~~\n# Also not\n~~~\n\n### How was this tested?\n#### Too deep\n ## indented code\n#No space\n"
);
const r = P(dir, "template");
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json.headings, ["Title", "Summary", "How was this tested?"]);
assert.equal(r.json.hasTesting, true);
for (const [heading, expected] of [["## Verification", true], ["## QA notes", true], ["## How it was checked", true], ["## Summary\n## Risks", false]]) {
write(dir, ".github/pull_request_template.md", `${heading}\n`);
assert.equal(P(dir, "template").json.hasTesting, expected, heading);
}
});
test("pr-prep template: none found", () => {
const dir = tmp("pr-tpl-none");
write(dir, "README.md", "# Project\n");
write(dir, ".github/workflows/ci.yml", "on: push\n");
const r = P(dir, "template");
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json, { ok: true, found: false, path: null, headings: [], hasTesting: false, others: [] });
});
/* ----------------------------------------------------------------- pr-url */
function repoOnMain(name) {
const repo = tmp(name);
const g = gitInit(repo);
write(repo, "a.txt", "a\n");
g("add", "a.txt");
g("commit", "-q", "-m", "init");
return { repo, g };
}
test("pr-prep pr-url: a pushed branch gives the link, an unpushed one pushed: false with exit 0", () => {
const { repo, g } = repoOnMain("pr-url");
const bare = tmp("pr-url-origin");
execFileSync("git", ["init", "-q", "--bare", "-b", "main", bare], { stdio: "pipe" });
g("remote", "add", "origin", slashed(bare));
g("push", "-q", "-u", "origin", "main");
g("switch", "-q", "-c", "feature/x");
write(repo, "b.txt", "b\n");
g("add", "b.txt");
g("commit", "-q", "-m", "b");
const unpushed = P(repo, "pr-url");
assert.equal(unpushed.code, 0, unpushed.stderr);
assert.equal(unpushed.json.ok, true);
assert.equal(unpushed.json.pushed, false);
assert.equal(unpushed.json.branch, "feature/x");
assert.match(unpushed.json.next, /plan2code-git/);
g("push", "-q", "-u", "origin", "feature/x");
// The pushed copy lives in the local bare repo; the link comes from the
// remote's address, so point it at a forge host once the push is done.
g("remote", "set-url", "origin", "git@github.com:owner/repo.git");
write(repo, "c.txt", "c\n");
g("add", "c.txt");
g("commit", "-q", "-m", "c");
const pushed = P(repo, "pr-url");
assert.equal(pushed.code, 0, pushed.stderr);
assert.deepEqual(pushed.json, {
ok: true,
pushed: true,
url: "https://github.com/owner/repo/compare/main...feature/x?quick_pull=1",
host: "github.com",
kind: "github",
needsKind: false,
branch: "feature/x",
base: "main",
ahead: 1,
});
});
test("pr-prep pr-url: a detached HEAD fails as git.mjs does; outside a repo is exit 3", () => {
const { repo, g } = repoOnMain("pr-url-detached");
g("checkout", "-q", "--detach");
const mine = P(repo, "pr-url");
const git = runScript("plan2code-git", "git.mjs", ["pr-url"], { cwd: repo, env: { PLAN2CODE_CONSOLE_HOME: HOME } });
assert.equal(mine.code, 5);
assert.equal(mine.code, git.code);
assert.deepEqual(mine.json, git.json);
assert.equal(mine.json.error, "detached");
const plain = tmp("pr-url-plain");
const r = P(plain, "pr-url");
assert.equal(r.code, 3);
assert.equal(r.json.error, "not-a-repo");
});
/* ------------------------------------------------------------------- spec */
const EARLY = new Date("2026-06-01T12:00:00Z");
const LATE = new Date("2026-07-15T12:00:00Z");
/** Every file under `dir` stamped with `when`. */
function stamp(dir, when) {
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, e.name);
if (e.isDirectory()) stamp(p, when);
else fs.utimesSync(p, when, when);
}
}
/** A repo whose main commit is dated 2026-07-01, on `branch` from it, with the given spec folders (each stamped EARLY). */
function specRepo(name, branch, folders) {
const repo = tmp(name);
const g = gitInit(repo);
write(repo, "a.txt", "a\n");
g("add", "a.txt");
const env = { ...process.env, GIT_AUTHOR_DATE: "2026-07-01T12:00:00Z", GIT_COMMITTER_DATE: "2026-07-01T12:00:00Z" };
execFileSync("git", ["commit", "-q", "-m", "init"], { cwd: repo, env, stdio: "pipe" });
if (branch !== "main") g("switch", "-q", "-c", branch);
for (const f of folders) write(repo, `${f}/overview.md`, "# Spec\n");
for (const d of ["specs", "specs--completed"]) if (fs.existsSync(path.join(repo, d))) stamp(path.join(repo, d), EARLY);
return repo;
}
test("pr-prep spec: the branch name matches a folder in specs/", () => {
const repo = specRepo("spec-branch", "feature/pr-prep-and-test-skills", ["specs/pr-prep-and-test-skills", "specs/other-thing", "specs--completed/pr-prep-and-test-skills"]);
const r = P(repo, "spec");
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json, { ok: true, branch: "feature/pr-prep-and-test-skills", match: "specs/pr-prep-and-test-skills", candidates: [], how: "branch" });
});
test("pr-prep spec: a match only in specs--completed/, a user segment, and --branch", () => {
const repo = specRepo("spec-completed", "jane/Lunch_Vote", ["specs--completed/lunch-vote", "specs/unrelated"]);
const r = P(repo, "spec");
assert.equal(r.code, 0, r.stderr);
assert.equal(r.json.match, "specs--completed/lunch-vote");
assert.equal(r.json.how, "branch");
assert.equal(P(repo, "spec", "--branch", "fix/unrelated-crash").json.match, "specs/unrelated");
});
test("pr-prep spec: two names in the branch is ask", () => {
const repo = specRepo("spec-ask", "feature/auth-and-billing", ["specs/auth", "specs/billing", "specs/search"]);
const r = P(repo, "spec");
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json, { ok: true, branch: "feature/auth-and-billing", match: null, candidates: ["specs/auth", "specs/billing"], how: "ask" });
});
test("pr-prep spec: no name match, one folder touched since the branch began, is recent; several is ask", () => {
const repo = specRepo("spec-recent", "feature/something-else", ["specs/old-work", "specs/new-work", "specs--completed/done-work"]);
stamp(path.join(repo, "specs", "new-work"), LATE);
const r = P(repo, "spec");
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json, { ok: true, branch: "feature/something-else", match: "specs/new-work", candidates: [], how: "recent" });
write(repo, "specs--completed/done-work/deep/a/b/c/notes.md", "x\n");
stamp(path.join(repo, "specs--completed", "done-work"), EARLY);
fs.utimesSync(path.join(repo, "specs--completed/done-work/deep/a/b/c/notes.md"), LATE, LATE);
assert.equal(P(repo, "spec").json.how, "recent", "a file five levels down is past the walk");
fs.utimesSync(path.join(repo, "specs--completed/done-work/overview.md"), LATE, LATE);
const two = P(repo, "spec").json;
assert.equal(two.how, "ask");
assert.deepEqual(two.candidates, ["specs/new-work", "specs--completed/done-work"]);
});
test("pr-prep spec: --branch measures the recent rule from that branch's start, not HEAD's", () => {
const repo = specRepo("spec-branch-start", "feature/side-work", ["specs/tracker"]);
const g = gitIn(repo);
g("switch", "-q", "main");
write(repo, "b.txt", "b\n");
g("add", "b.txt");
const env = { ...process.env, GIT_AUTHOR_DATE: "2026-08-01T12:00:00Z", GIT_COMMITTER_DATE: "2026-08-01T12:00:00Z" };
execFileSync("git", ["commit", "-q", "-m", "later on main"], { cwd: repo, env, stdio: "pipe" });
stamp(path.join(repo, "specs", "tracker"), LATE);
assert.equal(P(repo, "spec").json.how, "none", "on main the start is main's own tip, after the folder changed");
const r = P(repo, "spec", "--branch", "feature/side-work");
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json, { ok: true, branch: "feature/side-work", match: "specs/tracker", candidates: [], how: "recent" });
});
test("pr-prep spec: nothing fits is none; outside a repo is exit 3", () => {
const repo = specRepo("spec-none", "feature/something-else", ["specs/old-work"]);
const r = P(repo, "spec");
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json, { ok: true, branch: "feature/something-else", match: null, candidates: [], how: "none" });
const bare = specRepo("spec-empty", "main", []);
assert.equal(P(bare, "spec").json.how, "none");
const plain = tmp("spec-plain");
const out = P(plain, "spec");
assert.equal(out.code, 3);
assert.equal(out.json.error, "not-a-repo");
});
test("pr-prep: bad arguments exit 2", () => {
const dir = tmp("pr-args");
assert.equal(P(dir).code, 2);
assert.equal(P(dir, "nope").code, 2);
assert.equal(P(dir, "template", "extra").code, 2);
assert.equal(P(dir, "spec", "--bogus").code, 2);
});
+107
View File
@@ -0,0 +1,107 @@
// run-check.mjs: the four outcomes, the process-tree kill on timeout, the log
// and the tail cap, run from the built plan2code-pr-prep skill, which ships
// it. See skill-script-helpers.mjs for the fixtures.
import { test } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { ROOT, runScript, scrubbedEnv, tmp, write } from "./skill-script-helpers.mjs";
const NODE = `"${process.execPath}"`;
const alive = (pid) => {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
};
test("run-check: passed on exit 0", () => {
const r = runScript("plan2code-pr-prep", "run-check.mjs", ["--cmd", `${NODE} -e "process.exit(0)"`]);
assert.equal(r.code, 0, r.stderr);
assert.equal(r.json.outcome, "passed");
assert.equal(r.json.exit, 0);
assert.equal(r.json.cwd, ".");
assert.equal(typeof r.json.seconds, "number");
assert.equal(r.json.log, null);
});
test("run-check: failed on exit 1, with the printed lines in the tail", () => {
const dir = tmp("check-fail");
write(dir, "fail.js", "console.log('first line');\nconsole.error('second line');\nprocess.exit(1);\n");
const r = runScript("plan2code-pr-prep", "run-check.mjs", ["--cmd", `${NODE} fail.js`, "--cwd", dir]);
assert.equal(r.code, 0, r.stderr);
assert.equal(r.json.outcome, "failed");
assert.equal(r.json.exit, 1);
assert.ok(r.json.tail.includes("first line"), JSON.stringify(r.json.tail));
assert.ok(r.json.tail.includes("second line"), JSON.stringify(r.json.tail));
});
test("run-check: not-started for a made-up command and for a missing --cwd", () => {
const r = runScript("plan2code-pr-prep", "run-check.mjs", ["--cmd", "p2c-no-such-command-xyz --flag"]);
assert.equal(r.code, 0, r.stderr);
assert.equal(r.json.outcome, "not-started");
assert.equal(r.json.reason, "command-not-found");
const c = runScript("plan2code-pr-prep", "run-check.mjs", ["--cmd", `${NODE} -e "process.exit(0)"`, "--cwd", path.join(tmp("check-cwd"), "missing")]);
assert.equal(c.code, 0, c.stderr);
assert.equal(c.json.outcome, "not-started");
assert.equal(c.json.reason, "cwd-missing");
const folder = tmp("check-log-dir");
const l = runScript("plan2code-pr-prep", "run-check.mjs", ["--cmd", `${NODE} -e "process.exit(0)"`, "--log", folder]);
assert.equal(l.code, 0, l.stderr);
assert.equal(l.json.outcome, "not-started", "a --log that is a folder stops the check with JSON, not a crash");
assert.equal(l.json.reason, "log-unwritable");
});
test("run-check: timeout kills the whole process tree", async () => {
const dir = tmp("check-timeout");
write(dir, "grandchild.js", "require('fs').writeFileSync(require('path').join(__dirname, 'pid.txt'), String(process.pid));\nsetInterval(() => {}, 1000);\n");
write(dir, "parent.js", "require('child_process').spawn(process.execPath, [require('path').join(__dirname, 'grandchild.js')], { stdio: 'inherit' });\nsetInterval(() => {}, 1000);\n");
const r = runScript("plan2code-pr-prep", "run-check.mjs", ["--cmd", `${NODE} parent.js`, "--cwd", dir, "--timeout", "2"]);
assert.equal(r.code, 0, r.stderr);
assert.equal(r.json.outcome, "timeout");
const pidFile = path.join(dir, "pid.txt");
assert.ok(fs.existsSync(pidFile), "the grandchild started");
const pid = Number(fs.readFileSync(pidFile, "utf8"));
const until = Date.now() + 5000;
while (alive(pid) && Date.now() < until) await new Promise((res) => setTimeout(res, 100));
assert.equal(alive(pid), false, `grandchild ${pid} is gone`);
});
test("run-check: --log holds the full output and the tail keeps 60 lines of at most 400 characters", () => {
const dir = tmp("check-log");
write(dir, "many.js", "for (let i = 1; i <= 100; i++) console.log('line ' + i);\nconsole.log('x'.repeat(500));\n");
const log = path.join(dir, "logs", "deep", "run.log");
const r = runScript("plan2code-pr-prep", "run-check.mjs", ["--cmd", `${NODE} many.js`, "--cwd", dir, "--log", log]);
assert.equal(r.code, 0, r.stderr);
assert.equal(r.json.outcome, "passed");
assert.equal(r.json.log, log);
const full = fs.readFileSync(log, "utf8").split(/\r?\n/).filter(Boolean);
assert.equal(full.length, 101);
assert.equal(full[0], "line 1");
assert.equal(r.json.tail.length, 60);
assert.equal(r.json.tail[0], "line 42");
assert.equal(r.json.tail[59].length, 400);
assert.deepEqual(fs.readdirSync(dir).sort(), ["logs", "many.js"], "nothing written outside --log");
});
test("run-check: bad arguments exit 2", () => {
assert.equal(runScript("plan2code-pr-prep", "run-check.mjs", []).code, 2);
assert.equal(runScript("plan2code-pr-prep", "run-check.mjs", ["--cmd", "x", "--timeout", "soon"]).code, 2);
assert.equal(runScript("plan2code-pr-prep", "run-check.mjs", ["--cmd", "x", "--timeout", "0"]).code, 2);
assert.equal(runScript("plan2code-pr-prep", "run-check.mjs", ["--cmd", "x", "--timeout", "86401"]).code, 2, "past one day the timer would overflow");
assert.equal(runScript("plan2code-pr-prep", "run-check.mjs", ["--cmd", "x", "extra"]).code, 2);
});
test("run-check and test-commands do nothing when imported", () => {
for (const file of ["run-check.mjs", "test-commands.mjs"]) {
const url = new URL(`file:///${path.join(ROOT, "src", "skill-scripts", file).replace(/\\/g, "/")}`).href;
const r = spawnSync(process.execPath, ["--input-type=module", "-e", `await import(${JSON.stringify(url)});`], { encoding: "utf8", env: scrubbedEnv() });
assert.equal(r.status, 0, `${file}: ${r.stderr}`);
assert.equal(r.stdout, "", `${file} printed nothing on import`);
}
});
+162
View File
@@ -0,0 +1,162 @@
// test-commands.mjs discover: one fixture per ecosystem, run from the built
// plan2code-init skill. See skill-script-helpers.mjs for how these run.
import { test } from "node:test";
import assert from "node:assert/strict";
import { runScript, tmp, write } from "./skill-script-helpers.mjs";
function discover(files) {
const dir = tmp("cmds");
for (const [rel, content] of Object.entries(files)) write(dir, rel, typeof content === "string" ? content : JSON.stringify(content));
const r = runScript("plan2code-init", "test-commands.mjs", ["discover"], { cwd: dir });
assert.equal(r.code, 0, r.stderr);
assert.equal(r.json.ok, true);
return r.json;
}
test("npm project: suite, lint, types and build checks", () => {
const r = discover({ "package.json": { scripts: { test: "node --test", lint: "eslint .", typecheck: "tsc --noEmit", build: "tsc" } } });
assert.deepEqual(r.suite, { cmd: "npm test", why: "package.json scripts.test" });
assert.deepEqual(r.runners, [{ cmd: "npm test", cwd: ".", covers: ["**"] }]);
assert.deepEqual(r.checks, [
{ kind: "lint", cmd: "npm run lint" },
{ kind: "types", cmd: "npm run typecheck" },
{ kind: "build", cmd: "npm run build" },
]);
assert.deepEqual(r.coverage, [{ runner: "node", cmd: "node --test --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=\"<out>\"", cwd: ".", reads: "lcov" }]);
assert.equal(r.builtin, null);
});
test("the lockfile picks the package manager; tsconfig gives npx tsc", () => {
const r = discover({ "package.json": { scripts: { test: "jest", lint: "eslint ." } }, "pnpm-lock.yaml": "", "tsconfig.json": "{}" });
assert.equal(r.suite.cmd, "pnpm test");
assert.deepEqual(r.checks, [
{ kind: "lint", cmd: "pnpm run lint" },
{ kind: "types", cmd: "npx tsc --noEmit" },
]);
assert.equal(discover({ "package.json": { scripts: { test: "x" } }, "yarn.lock": "" }).suite.cmd, "yarn test");
assert.equal(discover({ "package.json": { scripts: { test: "x" } }, "bun.lock": "" }).suite.cmd, "bun test");
});
test("npm's placeholder test script is no suite", () => {
const r = discover({ "package.json": { scripts: { test: 'echo "Error: no test specified" && exit 1' } } });
assert.equal(r.suite, null);
assert.deepEqual(r.runners, []);
assert.deepEqual(r.builtin, { language: "node", cmd: "node --test" });
});
test("npm workspaces array: one runner per package with a test script", () => {
const r = discover({
"package.json": { workspaces: ["packages/*"], scripts: { test: "npm test --workspaces" } },
"packages/a/package.json": { scripts: { test: "node --test" } },
"packages/b/package.json": { scripts: { test: "vitest" }, devDependencies: { vitest: "1", "@vitest/coverage-v8": "1" } },
"packages/c/package.json": { scripts: {} },
});
assert.deepEqual(r.runners, [
{ cmd: "npm test", cwd: ".", covers: ["**"] },
{ cmd: "npm test", cwd: "packages/a", covers: ["packages/a/**"] },
{ cmd: "npm test", cwd: "packages/b", covers: ["packages/b/**"] },
]);
assert.deepEqual(r.coverage.map((c) => [c.runner, c.cwd]), [["node", "packages/a"], ["vitest", "packages/b"]]);
});
test("pnpm workspace: packages lines and the { packages } form", () => {
const r = discover({
"package.json": { name: "root" },
"pnpm-lock.yaml": "",
"pnpm-workspace.yaml": "packages:\n - 'apps/*'\n - \"libs/core\"\n - '!apps/skip'\n",
"apps/web/package.json": { scripts: { test: "vitest" } },
"apps/skip/package.json": { scripts: { test: "vitest" } },
"libs/core/package.json": { scripts: { test: "jest" } },
});
assert.equal(r.suite, null);
assert.deepEqual(r.runners, [
{ cmd: "pnpm test", cwd: "apps/web", covers: ["apps/web/**"] },
{ cmd: "pnpm test", cwd: "libs/core", covers: ["libs/core/**"] },
], "a ! line excludes its folders");
assert.deepEqual(r.coverage, [{ runner: "jest", cmd: "npx jest --coverage --coverageReporters=lcov", cwd: "libs/core", reads: "lcov" }]);
const inline = discover({
"package.json": { name: "root" },
"pnpm-lock.yaml": "",
"pnpm-workspace.yaml": "packages: ['apps/*', \"!apps/skip\"]\n",
"apps/web/package.json": { scripts: { test: "vitest" } },
"apps/skip/package.json": { scripts: { test: "vitest" } },
});
assert.deepEqual(inline.runners, [{ cmd: "pnpm test", cwd: "apps/web", covers: ["apps/web/**"] }], "an inline packages list works too");
const obj = discover({ "package.json": { workspaces: { packages: ["pkgs/*"] } }, "pkgs/x/package.json": { scripts: { test: "t" } } });
assert.deepEqual(obj.runners, [{ cmd: "npm test", cwd: "pkgs/x", covers: ["pkgs/x/**"] }]);
});
test("Go module with a nested second module", () => {
const r = discover({ "go.mod": "module example.com/a\n", "main.go": "package main\n", "tools/go.mod": "module example.com/tools\n" });
assert.deepEqual(r.runners, [
{ cmd: "go test ./...", cwd: ".", covers: ["**"] },
{ cmd: "go test ./...", cwd: "tools", covers: ["tools/**"] },
]);
assert.deepEqual(r.coverage[0], { runner: "go", cmd: "go test -coverprofile=\"<out>\" ./... && go tool cover -func=\"<out>\"", cwd: ".", reads: "go-func" });
assert.equal(r.builtin, null);
});
test("Cargo workspace: one runner at the root, members run from it", () => {
const r = discover({
"Cargo.toml": '[workspace]\nmembers = ["crates/a"]\n',
"crates/a/Cargo.toml": '[package]\nname = "a"\n',
"crates/a/src/lib.rs": "",
});
assert.deepEqual(r.runners, [{ cmd: "cargo test", cwd: ".", covers: ["**"] }]);
});
test("pytest project and plain Python project", () => {
const py = discover({ "pyproject.toml": "[tool.pytest.ini_options]\naddopts = \"-q\"\n", "pkg/a.py": "" });
assert.deepEqual(py.runners, [{ cmd: "python -m pytest", cwd: ".", covers: ["**"] }]);
assert.deepEqual(py.coverage, [], "no pytest-cov, no coverage");
const plain = discover({ "setup.cfg": "[metadata]\nname = x\n", "x/a.py": "" });
assert.deepEqual(plain.runners, [{ cmd: "python -m unittest", cwd: ".", covers: ["**"] }]);
const req = discover({ "tox.ini": "[tox]\n", "requirements-dev.txt": "pytest==8\n" });
assert.equal(req.runners[0].cmd, "python -m pytest");
});
test(".NET project", () => {
const r = discover({ "App.sln": "", "src/App/App.csproj": "<Project />", "tests/App.Tests/App.Tests.csproj": "<Project />" });
assert.deepEqual(r.runners, [{ cmd: "dotnet test", cwd: ".", covers: ["**"] }]);
assert.deepEqual(r.coverage, []);
});
test("Makefile-only project: make test is the suite and the root runner", () => {
const r = discover({ Makefile: "build:\n\tcc a.c\n\ntest: build\n\t./run-tests\n" });
assert.deepEqual(r.suite, { cmd: "make test", why: "Makefile test target" });
assert.deepEqual(r.runners, [{ cmd: "make test", cwd: ".", covers: ["**"] }]);
assert.equal(discover({ Makefile: "build:\n\tcc a.c\n" }).suite, null);
});
test("coverage is listed only with its add-on present", () => {
const vitest = (extra) => discover({ "package.json": { scripts: { test: "vitest" }, devDependencies: { vitest: "1", ...extra } } });
assert.deepEqual(vitest({ "@vitest/coverage-v8": "1" }).coverage, [{ runner: "vitest", cmd: "npx vitest run --coverage --coverage.reporter=lcov", cwd: ".", reads: "lcov" }]);
assert.deepEqual(vitest({}).coverage, []);
const pytest = (deps) => discover({ "pyproject.toml": `[project]\ndependencies = [${deps}]\n` });
assert.deepEqual(pytest('"pytest", "pytest-cov"').coverage, [{ runner: "pytest", cmd: "python -m pytest --cov --cov-report=lcov:\"<out>\"", cwd: ".", reads: "lcov" }]);
assert.deepEqual(pytest('"pytest"').coverage, []);
const nested = discover({ "requirements-dev.txt": "pytest-cov\n", "svc/setup.cfg": "[tool:pytest]\n" });
assert.deepEqual(nested.coverage, [{ runner: "pytest", cmd: "python -m pytest --cov --cov-report=lcov:\"<out>\"", cwd: "svc", reads: "lcov" }], "pytest-cov listed in a folder above the runner");
const dotnet = (ref) => discover({ "App.Tests/App.Tests.csproj": `<Project><ItemGroup>${ref}</ItemGroup></Project>` });
assert.deepEqual(dotnet('<PackageReference Include="coverlet.collector" Version="6" />').coverage, [{ runner: "dotnet", cmd: 'dotnet test --collect:"XPlat Code Coverage"', cwd: "App.Tests", reads: "lcov" }]);
assert.deepEqual(dotnet("").coverage, []);
});
test("builtin: an empty Node project, a Python-only folder, and others in a mixed folder", () => {
assert.deepEqual(discover({ "package.json": { name: "x" } }).builtin, { language: "node", cmd: "node --test" });
assert.deepEqual(discover({ "a.py": "", "lib/b.py": "" }).builtin, { language: "python", cmd: "python -m unittest" });
const mixed = discover({ "package.json": { name: "x" }, "index.js": "", "a.py": "", "b.py": "", "c.py": "" });
assert.deepEqual(mixed.builtin, { language: "python", cmd: "python -m unittest", others: [{ language: "node", cmd: "node --test" }] });
assert.equal(discover({ "README.md": "hi" }).builtin, null);
});
test("skipped folders are never walked; bad input is a usage error", () => {
const r = discover({ "node_modules/x/go.mod": "module x\n", "vendor/y/Cargo.toml": "[package]\n", "a.txt": "" });
assert.deepEqual(r.runners, []);
const dir = tmp("cmds-bad");
assert.equal(runScript("plan2code-init", "test-commands.mjs", ["list"], { cwd: dir }).code, 2);
assert.equal(runScript("plan2code-init", "test-commands.mjs", ["discover", "--root", "nope"], { cwd: dir }).code, 3);
});
+322
View File
@@ -0,0 +1,322 @@
// Tests for the shared test-map.mjs (shipped in plan2code-init) and glob.mjs.
//
// See skill-script-helpers.mjs for how these run.
import { test } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { runScript, tmp, write, read } from "./skill-script-helpers.mjs";
import { toPosix, globToRegExp, matchGlob, unsupported } from "../src/skill-scripts/glob.mjs";
const T = (cwd, args) => runScript("plan2code-init", "test-map.mjs", args, { cwd });
const TABLE = "| Area | Paths | Run | Shared |\n|---|---|---|---|\n| Launcher | `src/launcher/**` | `node --test scripts/test-launcher.mjs` | no |\n";
function project(agents, files = {}) {
const dir = tmp("test-map");
if (agents !== null) write(dir, "AGENTS.md", agents);
for (const [rel, content] of Object.entries(files)) write(dir, rel, content);
return dir;
}
function rowsFile(dir, rows) {
return write(dir, "rows.json", JSON.stringify(rows));
}
const NEW_TABLE =
"| Area | Paths | Run | Shared |\n|---|---|---|---|\n| Console | `src/web-console/**`, `scripts/test-web-console-*.mjs` | `node --test scripts/test-web-console-logic.mjs` | no |\n| Helpers | `scripts/*-helpers.mjs` | `npm test` | yes |\n";
const ROWS = [
{ area: "Console", paths: ["src/web-console/**", "scripts/test-web-console-*.mjs"], run: "node --test scripts/test-web-console-logic.mjs", shared: false },
{ area: "Helpers", paths: ["scripts/*-helpers.mjs"], run: "npm test", shared: true },
];
/* ------------------------------------------------------------------ read */
test("test-map read: a table in AGENTS.md", () => {
const dir = project(`# Project\n\n## Test map\n\nWhich checks cover what.\n\n${TABLE}\n## Next\n\nMore.\n`);
const r = T(dir, ["read"]);
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json, {
ok: true,
found: true,
source: "AGENTS.md",
rows: [{ area: "Launcher", paths: ["src/launcher/**"], run: "node --test scripts/test-launcher.mjs", shared: false }],
problems: [],
});
});
test("test-map read: a section linking to .agents-docs/AGENTS-test-map.md reads that file", () => {
const dir = project("# P\n\n## Test map\n\nDetails: [Test map](./.agents-docs/AGENTS-test-map.md)\n", {
".agents-docs/AGENTS-test-map.md": `# Test map\n\n> Part of [AGENTS.md](../AGENTS.md).\n\nSee [other](./AGENTS-other.md).\n\n${TABLE}`,
".agents-docs/AGENTS-other.md": `# Other\n\n${TABLE.replace("Launcher", "Wrong")}`,
});
const r = T(dir, ["read"]);
assert.equal(r.code, 0, r.stderr);
assert.equal(r.json.source, ".agents-docs/AGENTS-test-map.md");
assert.equal(r.json.rows.length, 1);
assert.equal(r.json.rows[0].area, "Launcher", "follows exactly one link, never a link from the linked file");
const bare = project("## Test map\n\nSee [map](.agents-docs/AGENTS-test-map.md).\n", { ".agents-docs/AGENTS-test-map.md": TABLE });
assert.equal(T(bare, ["read"]).json.source, ".agents-docs/AGENTS-test-map.md", "the ](.agents-docs/...) form works too");
const nested = project("## Test map\n\nSee [map](./.agents-docs/testing/map.md).\n", { ".agents-docs/testing/map.md": TABLE });
const n = T(nested, ["read"]);
assert.equal(n.json.source, ".agents-docs/testing/map.md", "a link into a subfolder of .agents-docs/ is inside it");
assert.deepEqual(n.json.problems, []);
const escape = project("## Test map\n\nSee [map](./.agents-docs/../docs/map.md).\n", { "docs/map.md": TABLE });
assert.match(T(escape, ["read"]).json.problems[0], /outside \.agents-docs\//, "a link that climbs out is still outside");
const prose = project("## Test map\n\nSee [contributing](./CONTRIBUTING.md), then [map](./.agents-docs/AGENTS-test-map.md).\n", { ".agents-docs/AGENTS-test-map.md": TABLE });
const p = T(prose, ["read"]);
assert.equal(p.json.source, ".agents-docs/AGENTS-test-map.md", "a prose link before the docs link does not hide it");
assert.deepEqual(p.json.problems, []);
});
test("test-map write: a new nested linked file links back to AGENTS.md from its own depth", () => {
const dir = project("## Test map\n\nSee [map](./.agents-docs/testing/map.md).\n");
rowsFile(dir, ROWS);
const w = T(dir, ["write", "--rows", "rows.json"]);
assert.equal(w.code, 0, w.stderr);
assert.match(read(dir, ".agents-docs/testing/map.md"), /\[AGENTS\.md\]\(\.\.\/\.\.\/AGENTS\.md\)/);
});
test("test-map read and write: a link outside .agents-docs/ is a problem, and write refuses", () => {
const dir = project("## Test map\n\nSee [map](./docs/test-map.md).\n", { "docs/test-map.md": TABLE });
const r = T(dir, ["read"]);
assert.equal(r.code, 0, r.stderr);
assert.equal(r.json.found, true);
assert.deepEqual(r.json.rows, []);
assert.match(r.json.problems[0], /outside \.agents-docs\//);
rowsFile(dir, ROWS);
const w = T(dir, ["write", "--rows", "rows.json"]);
assert.equal(w.code, 5);
assert.equal(w.json.error, "link-outside");
});
test("test-map read: headers in any order and case, extra columns ignored", () => {
const dir = project("## Test Map\n\n| run | SHARED | Notes | paths | area |\n|:---|---|---|---|---:|\n| `npm t` | Yes | x | `a/**`, b/*.js , `c/{d,e}.ts` | Core |\n");
const r = T(dir, ["read"]);
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json.rows, [{ area: "Core", paths: ["a/**", "b/*.js", "c/{d,e}.ts"], run: "npm t", shared: true }]);
assert.deepEqual(r.json.problems, []);
});
test("test-map read: a missing Run column is a problem and no rows are returned", () => {
const dir = project("## Test map\n\n| Area | Paths | Shared |\n|---|---|---|\n| A | `a/**` | no |\n");
const r = T(dir, ["read"]);
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json.rows, []);
assert.match(r.json.problems[0], /no Run column/);
});
test("test-map read: Shared values, unsupported globs and escaped pipes", () => {
const dir = project(
"## Test map\n\n| Area | Paths | Run | Shared |\n|---|---|---|---|\n| One | `a/**` | `x \\| y` | Yes |\n| Two | b/** | y | no |\n| Three | c/** | z | maybe |\n| Four | `src/[ab]/*.js`, `ok/**` | w | NO |\n| Five | `src/[ab]/*.js` | v | no |\n"
);
const r = T(dir, ["read"]);
assert.equal(r.code, 0, r.stderr);
const [one, two, three, four, five] = r.json.rows;
assert.equal(one.shared, true);
assert.equal(one.run, "x | y", "an escaped pipe stays inside its cell");
assert.equal(two.shared, false);
assert.equal(three.shared, false);
assert.deepEqual(four.paths, ["ok/**"], "the unsupported glob is dropped from the row");
assert.equal(four.shared, false);
assert.deepEqual(five.paths, [], "a row left with no paths");
assert.equal(r.json.problems.length, 3);
assert.ok(r.json.problems.some((p) => /Row 3 \(Three\).*"maybe"/.test(p)));
assert.ok(r.json.problems.some((p) => /Row 4 \(Four\).*src\/\[ab\]\/\*\.js/.test(p)));
});
test("test-map read: a table inside a code fence is ignored, and so is a heading there", () => {
const fenced = project("# P\n\n```md\n## Test map\n\n" + TABLE + "```\n");
assert.equal(T(fenced, ["read"]).json.found, false, "a heading inside a fence is not the section");
const dir = project("## Test map\n\n```\n" + TABLE + "```\n\n" + TABLE.replace("Launcher", "Real"));
const r = T(dir, ["read"]);
assert.equal(r.code, 0, r.stderr);
assert.equal(r.json.rows.length, 1);
assert.equal(r.json.rows[0].area, "Real");
});
test("test-map read: no heading is found: false; no AGENTS.md is exit 3", () => {
const r = T(project("# P\n\n## Commands\n\nnpm test\n"), ["read"]);
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json, { ok: true, found: false, source: null, rows: [], problems: [] });
const none = T(project(null), ["read"]);
assert.equal(none.code, 3);
assert.equal(none.json.error, "no-agents-md");
});
/* ----------------------------------------------------------------- write */
// Every line of `before` outside the table is in `after`, in order and unchanged.
function outsideTableUnchanged(before, after) {
const strip = (t) => t.split("\n").filter((l) => !/^\|/.test(l));
const b = strip(before);
const a = strip(after);
let i = 0;
for (const line of a) if (line === b[i]) i++;
assert.equal(i, b.length, "every line outside the table is kept");
}
function roundTrip(dir) {
const r = T(dir, ["read"]);
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json.rows, ROWS);
assert.deepEqual(r.json.problems, []);
}
test("test-map write: no heading appends a Test map section", () => {
const before = "# P\n\n## Commands\n\nnpm test\n";
const dir = project(before);
rowsFile(dir, ROWS);
const w = T(dir, ["write", "--rows", "rows.json"]);
assert.equal(w.code, 0, w.stderr);
assert.deepEqual(w.json, { ok: true, written: true, source: "AGENTS.md", dryRun: false });
const after = read(dir, "AGENTS.md");
assert.ok(after.startsWith(before), "the old text is untouched");
assert.equal(
after.slice(before.length),
"\n## Test map\n\n| Area | Paths | Run | Shared |\n|---|---|---|---|\n| Console | `src/web-console/**`, `scripts/test-web-console-*.mjs` | `node --test scripts/test-web-console-logic.mjs` | no |\n| Helpers | `scripts/*-helpers.mjs` | `npm test` | yes |\n"
);
roundTrip(dir);
});
test("test-map write: a heading with no table gets one after its first paragraph", () => {
const before = "# P\n\n## Test map\n\nWhich checks cover\nwhich files.\n\nA second paragraph.\n\n## Next\n\nMore.\n";
const dir = project(before);
rowsFile(dir, ROWS);
assert.equal(T(dir, ["write", "--rows", "rows.json"]).code, 0);
const after = read(dir, "AGENTS.md");
assert.match(after, /which files\.\n\n\| Area \| Paths \| Run \| Shared \|\n[\s\S]*\| yes \|\n\nA second paragraph\./);
outsideTableUnchanged(before, after);
roundTrip(dir);
const bare = project("## Test map\n\n## Next\n");
rowsFile(bare, ROWS);
assert.equal(T(bare, ["write", "--rows", "rows.json"]).code, 0);
assert.match(read(bare, "AGENTS.md"), /^## Test map\n\n\| Area [\s\S]*\| yes \|\n\n## Next\n$/, "directly under a heading with no paragraph");
const tag = project("## Test map\n\n#123 tracks this.\n\n## Next\n");
rowsFile(tag, ROWS);
assert.equal(T(tag, ["write", "--rows", "rows.json"]).code, 0);
assert.match(read(tag, "AGENTS.md"), /^## Test map\n\n#123 tracks this\.\n\n\| Area /, "a line like #123 is a paragraph, not a heading");
});
test("test-map write: an existing table is replaced in place, every other line byte-identical", () => {
const before = `# P\n\nIntro.\n\n## Test map\n\nWhich checks.\n\n${TABLE}| Old | \`old/**\` | \`x\` | no |\n\nAfter the table.\n\n## Next\n\nMore.\n`;
const dir = project(before);
rowsFile(dir, ROWS);
assert.equal(T(dir, ["write", "--rows", "rows.json"]).code, 0);
const after = read(dir, "AGENTS.md");
assert.equal(after, before.replace(`${TABLE}| Old | \`old/**\` | \`x\` | no |\n`, NEW_TABLE), "only the table changed");
roundTrip(dir);
const again = T(dir, ["write", "--rows", "rows.json"]);
assert.equal(again.json.written, false, "unchanged rows write nothing");
});
test("test-map write: a CRLF AGENTS.md keeps its line endings", () => {
const before = `# P\r\n\r\n## Test map\r\n\r\nWhich checks.\r\n\r\n${TABLE.replace(/\n/g, "\r\n")}\r\n## Next\r\n\r\nMore.\r\n`;
const dir = project(before);
rowsFile(dir, ROWS);
assert.equal(T(dir, ["write", "--rows", "rows.json"]).code, 0);
const after = read(dir, "AGENTS.md");
assert.ok(!/[^\r]\n/.test(after), "every line ends in CRLF");
assert.equal(after, before.replace(TABLE.replace(/\n/g, "\r\n"), NEW_TABLE.replace(/\n/g, "\r\n")), "only the table changed");
roundTrip(dir);
});
test("test-map write: a linked file's table is replaced there, AGENTS.md untouched", () => {
const agents = "# P\n\n## Test map\n\nDetails: [Test map](./.agents-docs/AGENTS-test-map.md)\n";
const linked = `# Test map\n\n> Part of [AGENTS.md](../AGENTS.md).\n\n${TABLE}\nTrailing note.\n`;
const dir = project(agents, { ".agents-docs/AGENTS-test-map.md": linked });
rowsFile(dir, ROWS);
const w = T(dir, ["write", "--rows", "rows.json"]);
assert.equal(w.code, 0, w.stderr);
assert.equal(w.json.source, ".agents-docs/AGENTS-test-map.md");
assert.equal(read(dir, "AGENTS.md"), agents);
outsideTableUnchanged(linked, read(dir, ".agents-docs/AGENTS-test-map.md"));
roundTrip(dir);
});
test("test-map write: --dry-run writes nothing", () => {
const before = "# P\n";
const dir = project(before);
rowsFile(dir, ROWS);
const w = T(dir, ["write", "--rows", "rows.json", "--dry-run"]);
assert.equal(w.code, 0, w.stderr);
assert.deepEqual(w.json, { ok: true, written: false, source: "AGENTS.md", dryRun: true });
assert.equal(read(dir, "AGENTS.md"), before);
});
test("test-map write: invalid rows are exit 4 with the row index; no AGENTS.md is exit 3", () => {
const dir = project("# P\n");
rowsFile(dir, [ROWS[0], { area: "B", paths: [], run: "x" }]);
const w = T(dir, ["write", "--rows", "rows.json"]);
assert.equal(w.code, 4);
assert.equal(w.json.row, 1);
assert.equal(read(dir, "AGENTS.md"), "# P\n");
const none = project(null);
rowsFile(none, ROWS);
assert.equal(T(none, ["write", "--rows", "rows.json"]).code, 3);
assert.ok(!fs.existsSync(path.join(none, "AGENTS.md")));
assert.equal(T(dir, ["write"]).code, 2, "--rows is required");
for (const [row, why] of [
[{ area: "A", paths: ["src/[ab]/**"], run: "x", shared: false }, /unsupported glob/],
[{ area: "A", paths: ["src/**"], run: "npm `t`", shared: false }, /backtick or line break/],
[{ area: "A\nB", paths: ["src/**"], run: "x", shared: false }, /backtick or line break/],
]) {
rowsFile(dir, [row]);
const w = T(dir, ["write", "--rows", "rows.json"]);
assert.equal(w.code, 4);
assert.match(w.json.message, why);
}
});
/* ------------------------------------------------------------------ glob */
test("glob: ** at the start, middle and end", () => {
assert.ok(matchGlob("**/test/**", "test/a.js"));
assert.ok(matchGlob("**/test/**", "a/b/test/c/d.js"));
assert.ok(matchGlob("**/*.md", "README.md"));
assert.ok(matchGlob("**/*.md", "docs/x/y.md"));
assert.ok(matchGlob("src/**/a.js", "src/a.js"));
assert.ok(matchGlob("src/**/a.js", "src/x/y/a.js"));
assert.ok(!matchGlob("src/**/a.js", "src/xa.js"));
assert.ok(matchGlob("src/**", "src/a.js"));
assert.ok(matchGlob("src/**", "src/x/y/a.js"));
assert.ok(!matchGlob("src/**", "srcx/a.js"));
assert.ok(matchGlob("**", "any/thing.js"));
});
test("glob: * and ? stay inside one folder; a bare name matches only at the root", () => {
assert.ok(matchGlob("src/*.js", "src/a.js"));
assert.ok(!matchGlob("src/*.js", "src/x/a.js"));
assert.ok(matchGlob("src/?.js", "src/a.js"));
assert.ok(!matchGlob("src/?.js", "src/ab.js"));
assert.ok(!matchGlob("src/?.js", "src//.js"));
assert.ok(matchGlob("package.json", "package.json"));
assert.ok(!matchGlob("package.json", "a/package.json"));
assert.ok(matchGlob("**/package.json", "a/package.json"));
});
test("glob: {a,b} alternation, literal dots and parentheses", () => {
assert.ok(matchGlob("src/*.{js,ts}", "src/a.ts"));
assert.ok(matchGlob("{lib,src}/**", "lib/x.js"));
assert.ok(!matchGlob("src/*.{js,ts}", "src/a.tsx"));
assert.ok(!matchGlob("a.js", "axjs"), "a dot is literal");
assert.ok(matchGlob("docs/(old)/a+b.md", "docs/(old)/a+b.md"), "parentheses and + are literal");
assert.ok(!matchGlob("docs/(old)/a+b.md", "docs/old/aab.md"));
assert.ok(globToRegExp("a.js") instanceof RegExp);
});
test("glob: Windows backslash input and unsupported syntax", () => {
assert.equal(toPosix("src\\a\\b.js"), "src/a/b.js");
assert.equal(toPosix("./src/a.js"), "src/a.js");
assert.ok(matchGlob("src/**", "src\\a\\b.js"));
assert.ok(matchGlob("src\\*.js", "src/a.js"));
assert.match(unsupported("src/[ab]/*.js"), /character classes/);
assert.match(unsupported("!src/**"), /negation/);
assert.match(unsupported("{a,{b,c}}"), /nested/);
assert.match(unsupported("src/***"), /\*\*\*/);
assert.equal(unsupported("src/**/*.{js,ts}"), null);
assert.ok(!matchGlob("src/[ab].js", "src/a.js"), "an unsupported glob matches nothing");
assert.throws(() => globToRegExp("src/[ab].js"));
});
+296
View File
@@ -0,0 +1,296 @@
// Tests for the shared test-match.mjs, run from the built plan2code-pr-prep
// skill, which ships it beside common.mjs, glob.mjs, test-map.mjs and
// review-scope.mjs. See skill-script-helpers.mjs for the fixtures and the
// scrubbed git config.
import { test, after } from "node:test";
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { runScript, tmp, write, gitInit, gitIn, copyFixture, fixtureCleanup } from "./skill-script-helpers.mjs";
after(fixtureCleanup);
// A commit with pinned author and committer dates.
function commitAt(dir, date, msg, files = {}) {
for (const [rel, content] of Object.entries(files)) write(dir, rel, content);
const env = { ...process.env, GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date };
execFileSync("git", ["add", "-A"], { cwd: dir, env, stdio: "pipe" });
execFileSync("git", ["commit", "-q", "-m", msg], { cwd: dir, env, stdio: "pipe" });
}
const MAP = `# Project
## Test map
| Area | Paths | Run | Shared |
|---|---|---|---|
| Launcher | \`src/launcher/**\` | \`node --test scripts/test-launcher.mjs\` | no |
| Console | \`src/web-console/**\`, \`src/launcher/shared.js\` | \`node --test tests/console\` | yes |
`;
// One repo for covers and nearest: a test map, and tests found by name,
// by mirrored folder and by imports (JS, Python, Go).
function matchRepo() {
return copyFixture("match", "match", (dir) => {
gitInit(dir);
commitAt(dir, "2026-07-01T12:00:00Z", "Start", {
"AGENTS.md": MAP,
"package.json": "{}\n",
"src/launcher/a.js": "a\n",
"src/launcher/shared.js": "s\n",
"src/web-console/x.js": "x\n",
"tests/console/server.test.js": "t\n",
"tests/console/page.test.js": "t\n",
"src/app/util.js": "u\n",
"src/app/util.test.js": "t\n",
"src/app/other.test.js": "t\n",
"tests/app/mirror.test.js": "t\n",
"tests/app/second.test.js": "t\n",
"src/widget/button.js": "b\n",
"src/widget/__tests__/button.js": "t\n",
"src/lib/math.js": "m\n",
"src/lib/alias.js": "al\n",
"src/pkgdir/index.js": "i\n",
"tests/calc.test.js": 'import { add } from "../src/lib/math";\nconst p = require("../src/pkgdir");\nimport x from "@/lib/alias";\nimport fs from "node:fs";\n',
"pkg/__init__.py": "",
"pkg/mod.py": "def thing(): pass\n",
"tests/test_calc.py": "from pkg.mod import thing\n",
"go.mod": "module example.com/m\n\ngo 1.21\n",
"gosrc/util/u.go": "package util\n",
"gotests/check_test.go": 'package gotests\n\nimport (\n\t"testing"\n\tu "example.com/m/gosrc/util"\n)\n',
"fixtures/sample.json": "{}\n",
"test/helpers/setup.js": "h\n",
});
});
}
/* ---------------------------------------------------------------- covers */
test("test-match covers: map rows, shared hits, hints and the fallback rules", () => {
const dir = matchRepo();
const files = ["src/launcher/a.js", "src/launcher/shared.js", "src/web-console/x.js", "src/app/util.js", "src/widget/button.js", "src/lib/math.js", "src/pkgdir/index.js", "src/lib/alias.js", "pkg/mod.py", "gosrc/util/u.go", "package.json", "fixtures/sample.json", "test/helpers/setup.js"];
const r = runScript("plan2code-pr-prep", "test-match.mjs", ["covers", "--files", files.join(",")], { cwd: dir });
assert.equal(r.code, 0, r.stderr);
assert.equal(r.json.mapFound, true);
assert.deepEqual(r.json.matched, [
{ area: "Launcher", run: "node --test scripts/test-launcher.mjs", shared: false, files: ["src/launcher/a.js", "src/launcher/shared.js"] },
{ area: "Console", run: "node --test tests/console", shared: true, files: ["src/launcher/shared.js", "src/web-console/x.js"] },
]);
const un = Object.fromEntries(r.json.unmatched.map((u) => [u.file, u]));
assert.deepEqual(Object.keys(un).sort(), files.slice(3).sort(), "every file no row covers is unmatched");
assert.deepEqual(un["src/app/util.js"], { file: "src/app/util.js", tests: ["src/app/util.test.js"], method: "name" });
assert.deepEqual(un["src/widget/button.js"], { file: "src/widget/button.js", tests: ["src/widget/__tests__/button.js"], method: "folder" });
assert.deepEqual(un["src/lib/math.js"], { file: "src/lib/math.js", tests: ["tests/calc.test.js"], method: "imports" }, "an extensionless relative import");
assert.deepEqual(un["src/pkgdir/index.js"], { file: "src/pkgdir/index.js", tests: ["tests/calc.test.js"], method: "imports" }, "a folder import resolves to its index");
assert.deepEqual(un["src/lib/alias.js"], { file: "src/lib/alias.js", tests: [], method: null }, "an @/ alias is never guessed");
assert.deepEqual(un["pkg/mod.py"], { file: "pkg/mod.py", tests: ["tests/test_calc.py"], method: "imports" });
assert.deepEqual(un["gosrc/util/u.go"], { file: "gosrc/util/u.go", tests: ["gotests/check_test.go"], method: "imports" }, "a Go import through go.mod");
assert.deepEqual(r.json.sharedHits, [
{ file: "src/launcher/shared.js", why: "row" },
{ file: "src/web-console/x.js", why: "row" },
{ file: "package.json", why: "config" },
{ file: "fixtures/sample.json", why: "fixture" },
{ file: "test/helpers/setup.js", why: "test-helper" },
]);
});
test("test-match covers: Windows-style --files input", () => {
const dir = matchRepo();
const r = runScript("plan2code-pr-prep", "test-match.mjs", ["covers", "--files", "src\\launcher\\a.js"], { cwd: dir });
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json.matched[0].files, ["src/launcher/a.js"]);
});
test("test-match covers --stdin: real review-scope.mjs output", () => {
const dir = matchRepo();
gitIn(dir)("checkout", "-q", "-b", "feature");
commitAt(dir, "2026-07-02T12:00:00Z", "Change", { "src/launcher/a.js": "a2\n" });
write(dir, "src/app/util.js", "u2\n");
const scope = runScript("plan2code-pr-prep", "review-scope.mjs", [], { cwd: dir });
assert.equal(scope.code, 0, scope.stderr);
const r = runScript("plan2code-pr-prep", "test-match.mjs", ["covers", "--stdin"], { cwd: dir, input: scope.stdout });
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json.matched.map((m) => m.area), ["Launcher"]);
assert.deepEqual(r.json.unmatched, [{ file: "src/app/util.js", tests: ["src/app/util.test.js"], method: "name" }]);
assert.equal(runScript("plan2code-pr-prep", "test-match.mjs", ["covers", "--stdin"], { cwd: dir, input: "not json" }).code, 2);
const odd = runScript("plan2code-pr-prep", "test-match.mjs", ["covers", "--stdin"], { cwd: dir, input: JSON.stringify({ files: [{}, null, { path: "src/launcher/a.js" }] }) });
assert.equal(odd.code, 0, odd.stderr);
assert.deepEqual(odd.json.unmatched, [], "an entry with no path is dropped, never read as a file named undefined");
assert.deepEqual(odd.json.matched[0].files, ["src/launcher/a.js"]);
assert.equal(runScript("plan2code-pr-prep", "test-match.mjs", ["covers"], { cwd: dir }).code, 2);
});
test("test-match covers: no test map leaves every file unmatched, still exit 0", () => {
const dir = tmp("match-nomap");
write(dir, "a.js", "a\n");
write(dir, "a.test.js", "t\n");
const r = runScript("plan2code-pr-prep", "test-match.mjs", ["covers", "--files", "a.js,b.js"], { cwd: dir });
assert.equal(r.code, 0, r.stderr);
assert.equal(r.json.mapFound, false);
assert.deepEqual(r.json.matched, []);
assert.deepEqual(r.json.unmatched, [
{ file: "a.js", tests: ["a.test.js"], method: "name" },
{ file: "b.js", tests: [], method: null },
]);
});
/* ------------------------------------------------------------------ gaps */
// Untested files changed on pinned dates: c newest, then a (two commits) and
// b (one) on the same day, then old (outside the 90-day window).
function gapsRepo() {
return copyFixture("gaps", "gaps", (dir) => {
gitInit(dir);
commitAt(dir, "2026-01-01T12:00:00Z", "Old", { "src/old.js": "o\n", "src/d.js": "d\n", "src/d.test.js": "t\n", "src/types.d.ts": "x\n", "specs/x/a.js": "s\n", "vendor/v.js": "v\n", "README.md": "r\n" });
commitAt(dir, "2026-07-01T12:00:00Z", "A", { "src/a.js": "a1\n" });
commitAt(dir, "2026-07-20T12:00:00Z", "A and B", { "src/a.js": "a2\n", "src/b.js": "b1\n" });
commitAt(dir, "2026-07-25T12:00:00Z", "C", { "src/sub/c.js": "c1\n" });
});
}
test("test-match gaps --scope all: untested source files ranked by last change, then churn", () => {
const dir = gapsRepo();
const r = runScript("plan2code-pr-prep", "test-match.mjs", ["gaps", "--scope", "all"], { cwd: dir });
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json.gaps, [
{ file: "src/sub/c.js", area: null, runner: null, commits90d: 1, lastTouched: "2026-07-25" },
{ file: "src/a.js", area: null, runner: null, commits90d: 2, lastTouched: "2026-07-20" },
{ file: "src/b.js", area: null, runner: null, commits90d: 1, lastTouched: "2026-07-20" },
{ file: "src/old.js", area: null, runner: null, commits90d: 0, lastTouched: null },
]);
assert.equal(r.json.scope, "all");
assert.equal(r.json.scanned, 5, "tests, .d.ts, specs/, vendor/ and docs are not source files");
assert.equal(r.json.covered, 1);
assert.equal(r.json.capped, false);
});
test("test-match gaps --scope path and --scope branch", () => {
const dir = gapsRepo();
const p = runScript("plan2code-pr-prep", "test-match.mjs", ["gaps", "--scope", "path", "--path", "src/sub"], { cwd: dir });
assert.equal(p.code, 0, p.stderr);
assert.deepEqual(p.json.gaps.map((x) => x.file), ["src/sub/c.js"]);
const all = runScript("plan2code-pr-prep", "test-match.mjs", ["gaps", "--scope", "all"], { cwd: dir });
const dot = runScript("plan2code-pr-prep", "test-match.mjs", ["gaps", "--scope", "path", "--path", "."], { cwd: dir });
assert.equal(dot.code, 0, dot.stderr);
assert.deepEqual(dot.json.gaps, all.json.gaps, "--path . is the whole project");
assert.equal(runScript("plan2code-pr-prep", "test-match.mjs", ["gaps", "--scope", "path"], { cwd: dir }).code, 2, "--scope path needs --path");
gitIn(dir)("checkout", "-q", "-b", "feature");
commitAt(dir, "2026-07-30T12:00:00Z", "Feature", { "src/feat.js": "f\n", "src/feat2.js": "g\n" });
write(dir, "src/new.js", "n\n");
const b = runScript("plan2code-pr-prep", "test-match.mjs", ["gaps", "--scope", "branch"], { cwd: dir });
assert.equal(b.code, 0, b.stderr);
assert.deepEqual(b.json.gaps, [
{ file: "src/feat.js", area: null, runner: null, commits90d: 1, lastTouched: "2026-07-30" },
{ file: "src/feat2.js", area: null, runner: null, commits90d: 1, lastTouched: "2026-07-30" },
{ file: "src/new.js", area: null, runner: null, commits90d: 0, lastTouched: null },
]);
});
test("test-match gaps: a non-git folder walks the tree; --scope branch is exit 3", () => {
const dir = tmp("match-nogit");
write(dir, "src/a.js", "a\n");
write(dir, "node_modules/x/i.js", "x\n");
const r = runScript("plan2code-pr-prep", "test-match.mjs", ["gaps", "--scope", "all"], { cwd: dir });
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json.gaps, [{ file: "src/a.js", area: null, runner: null, commits90d: null, lastTouched: null }]);
const b = runScript("plan2code-pr-prep", "test-match.mjs", ["gaps", "--scope", "branch"], { cwd: dir });
assert.equal(b.code, 3);
assert.equal(b.json.error, "not-a-repo");
assert.equal(runScript("plan2code-pr-prep", "test-match.mjs", ["gaps"], { cwd: dir }).code, 2);
});
test("test-match gaps: any matching row with a run covers a file; a row without one only names its area", () => {
const dir = tmp("match-rows");
write(dir, "AGENTS.md", "## Test map\n\n| Area | Paths | Run | Shared |\n|---|---|---|---|\n| Source | `src/**` | | no |\n| X | `src/x.js` | `npm t` | no |\n");
write(dir, "src/x.js", "x\n");
write(dir, "src/y.js", "y\n");
write(dir, "src/m.ts", "m\n");
write(dir, "src/m.test.mts", "t\n");
const r = runScript("plan2code-pr-prep", "test-match.mjs", ["gaps", "--scope", "all"], { cwd: dir });
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json.gaps, [{ file: "src/y.js", area: "Source", runner: null, commits90d: null, lastTouched: null }]);
assert.equal(r.json.covered, 2, "x.js by the second row, m.ts by its .mts test");
});
test("test-match gaps: a test in another language never covers a file by name", () => {
const dir = tmp("match-lang");
write(dir, "src/foo.js", "f\n");
write(dir, "src/foo.test.py", "t\n");
write(dir, "src/bar.ts", "b\n");
write(dir, "src/bar.test.js", "t\n");
const r = runScript("plan2code-pr-prep", "test-match.mjs", ["gaps", "--scope", "all"], { cwd: dir });
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json.gaps.map((g) => g.file), ["src/foo.js"], "foo.test.py does not cover foo.js; a JS test still covers a TS file");
});
test("test-match gaps: capped at 2,000 source files", () => {
const dir = tmp("match-cap");
for (let i = 0; i < 2005; i++) write(dir, `src/f${String(i).padStart(4, "0")}.js`, "x\n");
const r = runScript("plan2code-pr-prep", "test-match.mjs", ["gaps", "--scope", "all"], { cwd: dir });
assert.equal(r.code, 0, r.stderr);
assert.equal(r.json.capped, true);
assert.equal(r.json.scanned, 2000);
assert.equal(r.json.gaps.length, 2000);
assert.equal(r.json.gaps.at(-1).file, "src/f1999.js", "the first 2,000 by path");
});
/* --------------------------------------------------------------- nearest */
test("test-match nearest: own tests, then the same folder, then the mirrored folder, at most 3", () => {
const dir = matchRepo();
const r = runScript("plan2code-pr-prep", "test-match.mjs", ["nearest", "--file", "src/app/util.js"], { cwd: dir });
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json, { ok: true, file: "src/app/util.js", tests: ["src/app/util.test.js", "src/app/other.test.js", "tests/app/mirror.test.js"] });
const m = runScript("plan2code-pr-prep", "test-match.mjs", ["nearest", "--file", "src/app/new.js"], { cwd: dir });
assert.deepEqual(m.json.tests, ["src/app/other.test.js", "src/app/util.test.js", "tests/app/mirror.test.js"]);
assert.equal(runScript("plan2code-pr-prep", "test-match.mjs", ["nearest"], { cwd: dir }).code, 2);
});
test("test-match nearest: the area's run path, then the nearest by shared folders", () => {
const dir = matchRepo();
const r = runScript("plan2code-pr-prep", "test-match.mjs", ["nearest", "--file", "src/web-console/x.js"], { cwd: dir });
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json.tests.slice(0, 2), ["tests/console/page.test.js", "tests/console/server.test.js"], "the Console row's run names tests/console");
assert.equal(r.json.tests.length, 3);
const deep = runScript("plan2code-pr-prep", "test-match.mjs", ["nearest", "--file", "src/widget/deep/z.js"], { cwd: dir });
assert.equal(deep.json.tests[0], "src/widget/__tests__/button.js", "the test file sharing the most folders");
});
/* ------------------------------------------------- the project's own map */
test("test-match covers: AGENTS.md's Targeted tests first table, saved as a test map", () => {
const dir = tmp("match-targeted");
write(
dir,
"AGENTS.md",
`## Test map
| Area | Paths | Run | Shared |
|---|---|---|---|
| Activities | \`src/web-console/public/activities/**\`, \`src/web-console/public/tones.js\`, \`src/web-console/public/music.js\` | \`node --test scripts/test-web-console-tones.mjs scripts/test-web-console-activities.mjs\` | no |
| Music prototype | \`prototypes/music/**\` | \`node prototypes/music/check.cjs\` | no |
| Web console area | \`src/web-console/**\` | \`node --test scripts/test-web-console-logic.mjs\` | no |
| Launcher | \`src/launcher/**\` | \`node --test scripts/test-launcher.mjs\` | no |
| Skill script | \`src/skill-scripts/**\`, \`src/plan2code-*-scripts/**\` | \`node --test scripts/test-skill-scripts.mjs\` | no |
| Workflow prompt | \`src/plan2code-*.md\` | \`node scripts/validate-char-count.js\` | no |
| Docs | \`**/*.md\` | \`node --test scripts/test-us-english.mjs scripts/test-line-endings.mjs\` | no |
`
);
const samples = {
Activities: "src/web-console/public/activities/snake.js",
"Music prototype": "prototypes/music/ghoul/index.html",
"Web console area": "src/web-console/routes.mjs",
Launcher: "src/launcher/plan2code.js",
"Skill script": "src/plan2code-git-scripts/git.mjs",
"Workflow prompt": "src/plan2code-3-implement.md",
Docs: ".readme/web-console.md",
};
const r = runScript("plan2code-pr-prep", "test-match.mjs", ["covers", "--files", Object.values(samples).join(",")], { cwd: dir });
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(r.json.unmatched, []);
for (const [area, file] of Object.entries(samples)) {
const row = r.json.matched.find((m) => m.area === area);
assert.ok(row && row.files.includes(file), `${area} covers ${file}`);
}
});
+30 -1
View File
@@ -70,11 +70,23 @@ test("scripts are self-contained: built-ins and siblings only", () => {
for (const f of fs.readdirSync(dir).filter((n) => n.endsWith(".mjs"))) { for (const f of fs.readdirSync(dir).filter((n) => n.endsWith(".mjs"))) {
const t = fs.readFileSync(path.join(dir, f), "utf8"); const t = fs.readFileSync(path.join(dir, f), "utf8");
for (const m of t.matchAll(/^import .* from "([^"]+)";$/gm)) { for (const m of t.matchAll(/^import .* from "([^"]+)";$/gm)) {
assert.ok(m[1].startsWith("node:") || m[1] === "./common.mjs", `${f} imports ${m[1]}`); const sibling = /^\.\/[\w-]+\.mjs$/.test(m[1]) && fs.existsSync(path.join(dir, m[1]));
assert.ok(m[1].startsWith("node:") || m[1] === "./common.mjs" || sibling, `${f} imports ${m[1]}`);
} }
assert.ok(!/[\u0000-\u0008]/.test(t), `${f} contains a control character (an escape lost in an edit?)`); assert.ok(!/[\u0000-\u0008]/.test(t), `${f} contains a control character (an escape lost in an edit?)`);
} }
} }
// A sibling import ships with its importer: every skill that carries a
// script also carries each ./x.mjs it imports.
for (const skill of fs.readdirSync(SKILLS)) {
const dir = path.join(SKILLS, skill, "scripts");
if (!fs.existsSync(dir)) continue;
for (const f of fs.readdirSync(dir).filter((n) => n.endsWith(".mjs"))) {
for (const m of fs.readFileSync(path.join(dir, f), "utf8").matchAll(/^import .* from "(\.\/[^"]+)";$/gm)) {
assert.ok(fs.existsSync(path.join(dir, m[1])), `${skill}/scripts/${f} imports ${m[1]}, which the skill does not ship`);
}
}
}
}); });
/* ================================================================ specs.mjs */ /* ================================================================ specs.mjs */
@@ -707,6 +719,23 @@ test("specs check-draft: a pathfinder draft at Resume at Phase 4 is checked ligh
assert.deepEqual(bad.json.problems.map((p) => p.code).sort(), ["loop-token", "metric-word"]); assert.deepEqual(bad.json.problems.map((p) => p.code).sort(), ["loop-token", "metric-word"]);
}); });
test("specs check-draft: a Test escalation draft passes like a Quick Task one", () => {
const root = specFixture();
for (const from of ["Quick Task", "Test"]) {
write(root, "specs/idea-only/PLAN-DRAFT-20260801.md", `# PLAN-DRAFT: Tests\n\n**Status:** Escalated from ${from} - Resume at Phase 2\n**Source:** ${from} escalation\n\n## 1. Executive Summary\n\nWrite the tests.\n`);
const r = runScript("plan2code-1-plan", "specs.mjs", ["check-draft", "idea-only", "--root", root]);
assert.equal(r.code, 0, r.stdout);
assert.equal(r.json.status, `Escalated from ${from} - Resume at Phase 2`);
}
});
test("the skills that run test-match.mjs ship glob.mjs and test-map.mjs beside it", () => {
for (const s of ["plan2code-pr-prep", "plan2code-test"]) {
for (const f of ["test-match.mjs", "glob.mjs", "test-map.mjs"]) assert.ok(fs.existsSync(path.join(SKILLS, s, "scripts", f)), `${s}/scripts/${f}`);
}
assert.ok(fs.existsSync(path.join(SKILLS, "plan2code-test", "scripts", "coverage.mjs")), "plan2code-test ships its own coverage.mjs");
});
test("common.mjs exports the shared loop-token and scrape patterns", async () => { test("common.mjs exports the shared loop-token and scrape patterns", async () => {
const common = await import(new URL(`file:///${path.join(SKILLS, "plan2code-2-document", "scripts", "common.mjs").replace(/\\/g, "/")}`).href); const common = await import(new URL(`file:///${path.join(SKILLS, "plan2code-2-document", "scripts", "common.mjs").replace(/\\/g, "/")}`).href);
assert.ok(common.LOOP_TOKENS instanceof RegExp); assert.ok(common.LOOP_TOKENS instanceof RegExp);
+17 -5
View File
@@ -47,7 +47,7 @@ test("Document writes Targeted, Quick checks and Full suite lines and reads test
assert.match(doc, /no Full Suite row: ask/); assert.match(doc, /no Full Suite row: ask/);
}); });
test("test-runs.md ships in the six skills that run, write or offer tests, and in no other", () => { test("test-runs.md ships in the eight skills that run, write or offer tests, and in no other", () => {
// npm test has just built skills/; a direct run builds it so the check never reads a stale tree. // npm test has just built skills/; a direct run builds it so the check never reads a stale tree.
if (process.env.npm_lifecycle_event !== "test") { if (process.env.npm_lifecycle_event !== "test") {
execFileSync(process.execPath, [path.join(ROOT, "install.js"), "--build-skills"], { stdio: "ignore" }); execFileSync(process.execPath, [path.join(ROOT, "install.js"), "--build-skills"], { stdio: "ignore" });
@@ -59,8 +59,10 @@ test("test-runs.md ships in the six skills that run, write or offer tests, and i
"plan2code-3-implement", "plan2code-3-implement",
"plan2code-3-implement-review", "plan2code-3-implement-review",
"plan2code-4-finalize", "plan2code-4-finalize",
"plan2code-pr-prep",
"plan2code-quick-task", "plan2code-quick-task",
"plan2code-review", "plan2code-review",
"plan2code-test",
]); ]);
}); });
@@ -123,9 +125,19 @@ test("test-runs.md says to ask when a check or its tests are unclear", () => {
test("Init and Init-update keep a test map beside the single-test command", () => { test("Init and Init-update keep a test map beside the single-test command", () => {
const init = src("plan2code-init.md"); const init = src("plan2code-init.md");
assert.match(init, /run single test \(and beside it a short \*\*Test map\*\*: `area -> tests or command`/); assert.match(init, /run single test \(and beside it a note of which checks are quick\)/);
assert.match(init, /which checks are quick/); assert.ok(init.includes("## Test map"), "Init names the ## Test map section");
assert.match(init, /test-commands\.mjs" discover/);
assert.match(init, /write it only on a yes with `test-map\.mjs write --rows <file>`/);
assert.doesNotMatch(init, /area -> tests or command/, "the old line format is gone");
const upd = src("plan2code-init-update.md"); const upd = src("plan2code-init-update.md");
assert.match(upd, /\*\*4\. Testing\*\* - .*the test map and quick checks/); assert.match(upd, /\*\*4\. Testing\*\* - .*the `## Test map` table and quick checks/);
assert.match(upd, /\| Testing \| Commands\? Test map and quick checks stale\?/); assert.match(upd, /\| Testing \| Commands\? Test map `Paths` still match real files and `Run` commands still exist \(`test-map\.mjs read` problems, `test-commands\.mjs discover`\)\?/);
assert.match(upd, /written only on a yes through `test-map\.mjs write`/);
});
test("test-runs.md reads the ## Test map table and treats Shared rows as shared ground", () => {
const rule = src("shared-references", "test-runs.md");
assert.ok(rule.includes("`## Test map`"), "names the ## Test map table");
assert.ok(rule.includes("`Shared: yes`"), "a Shared: yes row is shared ground");
}); });
@@ -5,6 +5,7 @@
// and records every point it draws through, as in // and records every point it draws through, as in
// scripts/test-web-console-activities-rapids.mjs. // scripts/test-web-console-activities-rapids.mjs.
import "./seed-random.mjs";
import test from "node:test"; import test from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { CAR_STYLES, MARGINS, STYLE_NAMES, carLength, carReach, drawCarBody, drawCarShadow, rgbOf, shade, styleOf } from "../src/web-console/public/activities/bounce-cars.js"; import { CAR_STYLES, MARGINS, STYLE_NAMES, carLength, carReach, drawCarBody, drawCarShadow, rgbOf, shade, styleOf } from "../src/web-console/public/activities/bounce-cars.js";
@@ -6,6 +6,7 @@
// handed, so a stub canvas stands in for the page, as in // handed, so a stub canvas stands in for the page, as in
// scripts/test-web-console-activities.mjs, whose helpers this file copies. // scripts/test-web-console-activities.mjs, whose helpers this file copies.
import "./seed-random.mjs";
import test from "node:test"; import test from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import * as bounce from "../src/web-console/public/activities/bounce.js"; import * as bounce from "../src/web-console/public/activities/bounce.js";
@@ -193,7 +194,10 @@ const eventsOf = (round, type) => round.events.filter((e) => e.type === type);
// A rival of `kind` put at (x, d), still and on the ground, going nowhere on // A rival of `kind` put at (x, d), still and on the ground, going nowhere on
// its own. // its own.
function bounceRival(round, kind, x, d, over = {}) { function bounceRival(round, kind, x, d, over = {}) {
const car = bounce.spawnRival(round, kind, steady, round.cars[0].d + 300); // A rival only spawns on plain road, and the road is generated at random: a crack or a bridge can
// sit at the first spot tried, so try further along until one takes. The rival is moved anyway.
let car = null;
for (let at = round.cars[0].d + 300; !car && at < round.cars[0].d + 3000; at += 40) car = bounce.spawnRival(round, kind, steady, at);
assert.ok(car, `a ${kind} spawns`); assert.ok(car, `a ${kind} spawns`);
Object.assign(car, { x, d, v: 0, tv: 0, vx: 0, kx: 0, air: 0, tx: x, lane: x, hopIn: 1e9, dropIn: 1e9, mode: "calm", ...over }); Object.assign(car, { x, d, v: 0, tv: 0, vx: 0, kx: 0, air: 0, tx: x, lane: x, hopIn: 1e9, dropIn: 1e9, mode: "calm", ...over });
return car; return car;
@@ -5,6 +5,7 @@
// handed, so a stub canvas stands in for the page, as in // handed, so a stub canvas stands in for the page, as in
// scripts/test-web-console-activities.mjs, whose helpers this file copies. // scripts/test-web-console-activities.mjs, whose helpers this file copies.
import "./seed-random.mjs";
import test from "node:test"; import test from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import * as bounce from "../src/web-console/public/activities/bounce.js"; import * as bounce from "../src/web-console/public/activities/bounce.js";
File diff suppressed because it is too large. Load diff
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's secondary weapons: the double tap that uses one (hammering spends one at most, a hold carries on as bolts), the bag and its HUD pill, what each weapon does, what they may do to a boss, where they are placed and how they drop, and that all of it draws and sounds. // Web console tests, Ghoul Rush's secondary weapons: the double tap that uses one (hammering spends one at most, a hold carries on as bolts), the bag and its HUD pill, what each weapon does, what they may do to a boss, where they are placed and how they drop, and that all of it draws and sounds.
import "./seed-random.mjs";
import { test } from "node:test"; import { test } from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js"; import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,5 +1,6 @@
// Web console tests, Ghoul Rush's Grand Banister (the Manor's bonus round, between the Library and the Ballroom): its shape (every break clears with a jump and swallows a rider that does not jump, the brass under-rails, every low can be ducked, spacing, checkpoints, the clock), the ride's speed on slopes and its lean and brake, its jump, ducking and diving, a vase, a candlestick, a hanging frame, a chandelier on its pendulum, a ghostly butler, the cobwebs, a fall off the rail, the checkpoint, the jump off the end and the door, the bonus round's hearts and dice (3 to 9), endless lives for every new cause, a voice for every event, the drawing, and bots that ride the whole stair (one that rides well, one that never dodges). // Web console tests, Ghoul Rush's Grand Banister (the Manor's bonus round, between the Library and the Ballroom): its shape (every break clears with a jump and swallows a rider that does not jump, the brass under-rails, every low can be ducked, spacing, checkpoints, the clock), the ride's speed on slopes and its lean and brake, its jump, ducking and diving, a vase, a candlestick, a hanging frame, a chandelier on its pendulum, a ghostly butler, the cobwebs, a fall off the rail, the checkpoint, the jump off the end and the door, the bonus round's hearts and dice (3 to 9), endless lives for every new cause, a voice for every event, the drawing, and bots that ride the whole stair (one that rides well, one that never dodges).
// Run with: node --test scripts/test-web-console-activities-ghoul-banister.mjs // Run with: node --test scripts/test-web-console-activities-ghoul-banister.mjs
import "./seed-random.mjs";
import { test } from "node:test"; import { test } from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js"; import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -4,6 +4,7 @@
// mud spans that slow and sink you, the Bog Runner's stub and the Drowning // mud spans that slow and sink you, the Bog Runner's stub and the Drowning
// Pool's boss spec. The monsters' rules, the fight and the ride land in // Pool's boss spec. The monsters' rules, the fight and the ride land in
// later phases. // later phases.
import "./seed-random.mjs";
import { test } from "node:test"; import { test } from "node:test";
import { readFileSync } from "node:fs"; import { readFileSync } from "node:fs";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's Old Rattlebones: his volley and slam, the skull he throws like a boomerang (and is headless without), the bone rain and the skeletons he raises once his rage begins, the double slam, and what each move looks and sounds like. // Web console tests, Ghoul Rush's Old Rattlebones: his volley and slam, the skull he throws like a boomerang (and is headless without), the bone rain and the skeletons he raises once his rage begins, the double slam, and what each move looks and sounds like.
import "./seed-random.mjs";
import { test } from "node:test"; import { test } from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js"; import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -0,0 +1,766 @@
// Web console tests, Ghoul Rush's Bone Stair (the finale's second ride, between Kill II and the Pit): its shape (the spiral's flights and seams, every gap of missing treads clears with a jump and swallows YOU without one, every ribcage can be ducked, spacing, checkpoints, the last step over the Pit's floor), the run's speed (DOWN and LEFT slow YOU), every obstacle's cost and cause (missing treads, treads giving way, ribcages, skeletons, hands, masonry, the rubble), the telegraphs (shadows, creaks and cracks, fingers over the edge, skeletons rising), shooting skeletons down, the pursuit meter (the gap that clean running opens and hits, ducks and holds close), the catch, three hearts of its own, the grade and the dice, endless lives, the finish, no random numbers, its sounds and its drawing on a fake canvas, and bots that play it well and badly.
// Run with: node --test scripts/test-web-console-activities-ghoul-bonestair.mjs
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
import * as bs from "../src/web-console/public/activities/ghoul-rush/rides/bonestair/ghoul-bonestair.js";
import { BONESTAIR_ROOM } from "../src/web-console/public/activities/ghoul-rush/rides/bonestair/ghoul-bonestair-room.js";
import { ANSWERS, EVENT_VOICE, LOSE_SOUNDS, LOSE_WORDS, LOOKS as STAIR_LOOKS, VOICES as STAIR_VOICES, telegraphMarks, telegraphs } from "../src/web-console/public/activities/ghoul-rush/rides/bonestair/ghoul-bonestair-draw.js";
import * as ghoulSfx from "../src/web-console/public/activities/ghoul-rush/sfx/ghoul-sfx.js";
import { LOOKS, VOICES, bonusTick, react } from "../src/web-console/public/activities/ghoul-rush/draw/ghoul-draw.js";
import { BONUS_FLOOR, diceFor, endBonus, makeBonus } from "../src/web-console/public/activities/ghoul-rush/core/ghoul-bonus.js";
const steady = () => 0.5;
// The pack draws no random number: a run on this fails on the first draw.
const never = () => {
throw new Error("the stair drew a random number");
};
const events = (round, type) => round.events.filter((e) => e.type === type);
function through(round) {
round.phase = "clear";
round.phaseMs = 1;
ghoul.advance(round, 4, steady);
}
// A round on The Bone Stair reached the way a run reaches it: six stages behind it, on
// through the finale's rooms before it; the clocks long, the bonus round on (three hearts).
function stairRound(seed = 5) {
const round = ghoul.newRound(seed);
round.lives = 3;
round.dice = 0;
through(round);
round.cleared = ghoul.STAGES.slice(0, ghoul.RUN_STAGES).map((st) => st.id);
round.offer = null;
for (let n = 0; n < 14 && round.spec.id !== "bonestair"; n++) through(round);
assert.equal(round.spec.id, "bonestair");
round.phase = "play";
round.timeMs = 1e9;
round.bonus = 1e9;
round.events.length = 0;
return round;
}
const ROOM = ghoul.roomById("bonestair");
const R = ROOM.ride;
const F = R.flights;
const floorOf = (x) => ghoul.groundAt(ROOM, x);
const K = { HIT_W: ghoul.HIT_W, HIT_H: ghoul.HIT_H, DUCK_H: ghoul.DUCK_H };
const NONE = { runner: "bonestair", hearts: 3, time: 1e9, finish: 6020, top: [0, 20, 36], flights: [[20, 6020, 36, -600]], gaps: [], rot: [], ribs: [], skels: [], hands: [], stones: [], surge: [], checks: [] };
// The same round over a stair of its own: one long flight to measure the run on (or `ride`'s).
function synth(ride) {
const round = stairRound();
round.spec = { ...round.spec, start: 30, length: 7000, ground: [[0, 20, 36]], ride: { ...NONE, ...ride } };
bs.BONESTAIR.place[0](round, {});
return round;
}
// A gentle stair for the obstacle tests: one flight dropping a unit every ten.
const GENTLE = [[20, 4020, 36, -364]];
// YOU on the stair at x, at speed v.
function stairAt(round, x, { v = bs.RUN_V, safe = false } = {}) {
const y = bs.stairY(round.spec.ride, x);
assert.ok(y !== null, `the stair runs under ${x}`);
Object.assign(round.you, { x, y, vy: 0, state: "run", shelf: -1, face: 1, out: 0, safeMs: safe ? 1e9 : 0, ducking: false });
Object.assign(round.runner, { v, coyote: 0, heldMs: 0 });
round.camX = Math.max(0, Math.min(round.spec.length - ghoul.FIELD_W, x - 24));
}
function run(round, ms, keys = {}, random = steady) {
Object.assign(round.input, keys);
for (let t = 0; t < ms; t += 4) ghoul.advance(round, 4, random);
for (const k of Object.keys(keys)) round.input[k] = typeof keys[k] === "number" ? 0 : false;
}
function until(round, done, ms = 6000, random = steady) {
let t = 0;
for (; t < ms && !done(); t += 4) ghoul.advance(round, 4, random);
return t;
}
const press = (round) => {
round.input.jump = ghoul.JUMP_BUFFER_MS;
round.input.up = true;
};
const heard = (e, extra = {}) => {
const played = [];
const noop = () => {};
const kit = { tone: (name) => played.push(name), burst: noop, float: noop, ring: noop, banner: () => null, shake: noop, flash: noop, glow: noop, splat: noop, fx: { clock: 1e6 }, monsters: ghoul.MONSTERS, powers: ghoul.POWERS, bosses: ghoul.BOSSES, ...extra };
react({ x: 10, y: 6, tx: 20, ty: 6, ...e }, kit);
return { played };
};
// Where YOU, in the air at (x, y) going up at vy and across at v, come down: { x, y } on the
// stair, or null for a fall through (the room's own geometry, gaps and the seams' lift).
function flight(x, y, vy, v) {
const dt = 0.004;
for (let t = 0; t < 4; t += dt) {
const px = x;
let py = y;
vy = Math.max(-ghoul.FALL_MAX, vy - bs.STAIR_G * dt);
x += v * dt;
y += vy * dt;
for (const s of bs.seams(R)) if (px < s.x && x >= s.x) {
y += s.rise;
py += s.rise;
}
const line = bs.stairY(R, x);
if (line === null) return null;
const inGap = R.gaps.some(([a, b]) => x > a && x < b);
if (vy <= 0 && !inGap && py >= line - bs.LAND_TOL && y <= line) return { x, y: line };
if (y < line - bs.FALL_DEPTH) return null;
}
return null;
}
/* -------------------------------------------------------------- the room */
test("Ghoul Rush's Bone Stair is the finale's second ride, between Kill II and the Pit: ready, lit, no key, no boss, no pickups, a bonus round of three hearts and about 30 seconds", () => {
assert.equal(BONESTAIR_ROOM.ready, true);
const rooms = ghoul.FINALE.rooms;
assert.ok(rooms.includes("bonestair"));
assert.ok(rooms.indexOf("bonestair") > rooms.indexOf("lawn"));
if (rooms.includes("dollhouse")) assert.equal(rooms.indexOf("bonestair"), rooms.indexOf("dollhouse") + 1, "just after Kill II");
if (rooms.includes("pit")) assert.equal(rooms.indexOf("pit"), rooms.indexOf("bonestair") + 1, "just before the Pit");
assert.deepEqual([ROOM.title, ROOM.sub], ["The Bone Stair", "Every step down is someone"]);
assert.equal(ROOM.dark, false);
assert.equal(ROOM.key, null);
assert.equal(ROOM.boss, null);
assert.equal(ROOM.bonus, true);
assert.equal(R.runner, "bonestair");
assert.equal(R.hearts, 3, "three hearts, not five");
assert.equal(typeof ghoul.ROOM_MUSIC.bonestair, "string", "a track (borrowed until its own is voted)");
assert.deepEqual(Object.keys(bs.BONESTAIR.monsters), []);
assert.equal(LOOKS.bonestair, STAIR_LOOKS.bonestair);
assert.equal(LOOKS.bonestair.pack, "bonestair");
assert.ok(Object.isFrozen(R) && Object.isFrozen(R.flights) && Object.isFrozen(R.flights[0]) && Object.isFrozen(R.ribs[0]), "frozen all the way down");
assert.ok(ROOM.horde.length === 0 && ROOM.spawns.length === 0, "no monsters: the stair's things are the pack's own");
assert.deepEqual([ROOM.candy.length, ROOM.items.length], [0, 0], "no pickups");
// The ground: the cellar landing at the start and the Pit's floor at the end only.
assert.equal(ROOM.ground.length, 2);
assert.deepEqual([...ROOM.ground[0]], [...R.top]);
assert.equal(ROOM.ground[1][0], R.finish, "the Pit's floor starts under the last step");
assert.ok(ROOM.ground[1][2] < F.at(-1)[3] - 8, "a real drop off the last step");
assert.ok(ROOM.door > R.finish + 20 && ROOM.door > ROOM.length - 14, "the door at the room's end, out on the Pit's floor");
assert.ok(floorOf(ROOM.door - 2) > -Infinity);
// About 30 seconds at a clean run, on a clock that holds it comfortably (the game's ride rule: 70 to 120 s).
const secs = (R.finish - ROOM.start) / bs.RUN_V;
assert.ok(secs >= 26 && secs <= 34, `${secs.toFixed(1)} s at RUN_V`);
assert.equal(ghoul.timeFor(ghoul.roomFor("bonestair")), R.time);
assert.ok(R.time >= 70000 && R.time <= 120000);
assert.deepEqual([R.gaps.length, R.rot.length, R.ribs.length, R.skels.length, R.hands.length, R.stones.length], [4, 3, 3, 4, 3, 3], "gaps, give-ways, ribcages, skeletons, hands, masonry");
});
test("Ghoul Rush's Bone Stair: the spiral is a run of flights, each starting where the last ended, high again; crossing a seam lifts YOU by the flight's height and the field never runs out going down", () => {
assert.equal(F[0][0], R.top[1], "the first flight starts at the landing's end");
assert.equal(F[0][2], R.top[2], "level with it");
for (let i = 0; i < F.length; i++) {
const [x0, x1, y0, y1] = F[i];
assert.ok(x1 > x0 && y1 < y0, `flight ${i} goes down`);
assert.ok(y0 < ghoul.FIELD_H - 12 && y1 > 10, `flight ${i} stays on the field (${y0} to ${y1})`);
const slope = (y1 - y0) / (x1 - x0);
assert.ok(slope > -0.2 && slope < -0.1, `flight ${i}'s slope ${slope.toFixed(3)}`);
if (i) assert.equal(x0, F[i - 1][1], "no hole at a seam");
}
assert.equal(F.at(-1)[1], R.finish);
const seams = bs.seams(R);
assert.equal(seams.length, F.length - 1);
for (const s of seams) assert.ok(s.rise > 15, "high again");
// Running across a seam on the treads.
const round = stairRound();
const sx = F[0][1];
stairAt(round, sx - 6, { safe: true });
run(round, 300);
assert.ok(round.you.x > sx);
assert.ok(Math.abs(round.you.y - bs.stairY(R, round.you.x)) < 1e-6, "on the next flight's treads");
assert.ok(round.you.y > F[1][2] - 3, "high again");
assert.equal(events(round, "stairTurn").length, 1);
assert.equal(round.runner.flight, 1);
// And in the air: a jump just before a seam lands on the next flight.
const air = stairRound();
stairAt(air, sx - 8, { safe: true });
press(air);
until(air, () => air.you.state === "air", 200);
until(air, () => air.you.state === "run", 2000);
assert.ok(air.you.x > sx && Math.abs(air.you.y - bs.stairY(R, air.you.x)) < 1e-6, "landed round the column");
// A bolt winds round with YOU.
const shot = stairRound();
stairAt(shot, sx - 14, { safe: true });
shot.input.fire = true;
run(shot, 30);
shot.input.fire = false;
const s = shot.shots[0];
assert.ok(s, "a bolt");
until(shot, () => s.x > sx + 10, 600);
assert.ok(Math.abs(s.y - (bs.stairY(R, s.x) + ghoul.SHOT_Y)) < 1.2, `the bolt flies along the next flight (${s.y.toFixed(1)} over ${bs.stairY(R, s.x).toFixed(1)})`);
});
test("Ghoul Rush's Bone Stair: every stretch of missing treads clears with a jump at its edge or a few units early (at a run or a duck's speed), and running off it without one is a fall", () => {
for (const [x0, x1] of R.gaps) {
const w = x1 - x0;
assert.ok(w >= 6 && w <= 9, `a gap at ${x0} is ${w} wide`);
assert.equal(bs.flightAt(R, x0), bs.flightAt(R, x1), "inside one flight");
// Off the edge with no jump.
assert.equal(flight(x0, bs.stairY(R, x0), bs.slopeAt(R, x0) * bs.RUN_V, bs.RUN_V), null, `no jump at ${x0}`);
for (const v of [bs.DUCK_V, bs.RUN_V]) {
for (const early of [0, 3, 6]) {
const x = x0 - early;
const land = flight(x, bs.stairY(R, x), bs.STAIR_JUMP_V, v);
assert.ok(land && land.x > x1, `a jump ${early} early at ${v} clears the gap at ${x0}`);
}
}
}
// In play: a fall costs a heart (cause "stairGap") and puts YOU back on the treads past it.
const round = stairRound();
const [x0, x1] = R.gaps[0];
stairAt(round, x0 - 6);
until(round, () => events(round, "lose").length > 0, 2000);
assert.equal(events(round, "lose")[0].cause, "stairGap");
assert.equal(round.bonusRound.hearts, 2);
assert.equal(round.phase, "play", "the run goes on");
assert.ok(round.you.x > x1 && round.you.state === "run", "back on the treads past it");
assert.equal(events(round, "stairDrop").length, 1);
// A jump clears it in play.
const ok = stairRound();
stairAt(ok, x0 - 4);
press(ok);
until(ok, () => ok.you.x > x1 + 4, 2000);
assert.equal(events(ok, "lose").length, 0);
});
test("Ghoul Rush's Bone Stair: every ribcage's underside sits between a ducked box and a standing one along its width; ducking passes, standing is a heart (cause \"stairRib\"); ducking slows YOU", () => {
for (const [x, under] of R.ribs) {
const hi = bs.stairY(R, x - bs.RIB_W / 2 - K.HIT_W / 2);
const lo = bs.stairY(R, x + bs.RIB_W / 2 + K.HIT_W / 2);
assert.ok(hi + K.DUCK_H < under, `a ducked box clears the ribcage at ${x}`);
assert.ok(lo + K.HIT_H > under, `a standing box hits the ribcage at ${x}`);
}
const [x] = R.ribs[0];
const stand = stairRound();
stairAt(stand, x - 10);
until(stand, () => events(stand, "lose").length > 0, 1000);
assert.equal(events(stand, "lose")[0].cause, "stairRib");
const duck = stairRound();
stairAt(duck, x - 8);
duck.input.down = true;
until(duck, () => duck.you.x > x + 6, 2000);
duck.input.down = false;
assert.equal(events(duck, "lose").length, 0);
assert.ok(duck.runner.v < bs.RUN_V - 4, "a duck slows YOU");
// And the speeds.
const s = synth({ flights: GENTLE });
run(s, 1500, { down: true });
assert.ok(Math.abs(s.runner.v - bs.DUCK_V) < 1);
run(s, 1500, { left: true });
assert.ok(Math.abs(s.runner.v - bs.HOLD_V) < 1, "LEFT holds back");
run(s, 2500);
assert.ok(Math.abs(s.runner.v - bs.RUN_V) < 1, "back up to a run");
});
test("Ghoul Rush's Bone Stair: masonry warns first (a shadow, a creak at once, a crack halfway, more than a second in all), lands ahead of a runner, and lies as a pile to jump; under it, or into the pile, is a heart (cause \"stairStone\")", () => {
assert.ok(bs.STONE_MS >= 1200, "a long, clear warning");
const round = synth({ flights: GENTLE, stones: [[300]] });
stairAt(round, 200, { safe: true });
until(round, () => events(round, "stairCreak").length > 0, 2000);
const at = round.you.x;
assert.ok(300 - at <= bs.STONE_NEAR && 300 - at > bs.STONE_NEAR - 2);
assert.equal(round.runner.stones[0].state, "warn");
until(round, () => events(round, "stairCrack").length > 0, 2000);
assert.ok(Math.abs(round.runner.stones[0].t - bs.STONE_MS / 2) < 20, "the crack halfway");
until(round, () => events(round, "stairThud").length > 0, 2000);
assert.equal(round.runner.stones[0].state, "pile");
assert.ok(300 - round.you.x > 10, `it lands ahead of a runner (${(300 - round.you.x).toFixed(1)} short)`);
// Into the pile: a heart.
round.you.safeMs = 0;
until(round, () => events(round, "lose").length > 0, 1000);
assert.equal(events(round, "lose")[0].cause, "stairStone");
// Jumped: clean.
const ok = synth({ flights: GENTLE, stones: [[300]] });
stairAt(ok, 200);
until(ok, () => ok.runner.stones[0].state === "pile", 3000);
until(ok, () => 300 - ok.you.x < 8, 1000);
press(ok);
until(ok, () => ok.you.x > 306, 1000);
assert.equal(events(ok, "lose").length, 0);
// Under it as it lands: a heart.
const under = synth({ flights: GENTLE, stones: [[300]] });
stairAt(under, 200);
until(under, () => under.runner.stones[0].state === "warn" && under.runner.stones[0].t < 200, 3000);
stairAt(under, 299.5, { v: 0 });
under.runner.heldMs = 1e9;
until(under, () => events(under, "lose").length > 0, 2000);
assert.equal(events(under, "lose")[0].cause, "stairStone");
});
test("Ghoul Rush's Bone Stair: a bone hand's fingers creep over the edge first (HAND_WARN_MS), then it grabs; a jump clears it, a grab is a heart (cause \"stairHand\") and holds YOU still a moment", () => {
assert.ok(bs.HAND_WARN_MS >= 700);
const round = synth({ flights: GENTLE, hands: [[300]] });
stairAt(round, 220);
until(round, () => events(round, "stairReach").length > 0, 3000);
assert.ok(300 - round.you.x <= bs.HAND_NEAR);
until(round, () => events(round, "stairGrab").length > 0, 2000);
assert.ok(300 - round.you.x > 10, "it grabs ahead of YOU, in plain sight");
until(round, () => events(round, "lose").length > 0, 1000);
assert.equal(events(round, "lose")[0].cause, "stairHand");
assert.equal(round.runner.heldMs > 0 || round.runner.v < 1, true, "held");
const x = round.you.x;
run(round, bs.HELD_MS - 40);
assert.ok(Math.abs(round.you.x - x) < 0.01, "still while held");
run(round, 400);
assert.ok(round.you.x > x + 2, "and off again");
// Jumped.
const ok = synth({ flights: GENTLE, hands: [[300]] });
stairAt(ok, 220);
until(ok, () => 300 - ok.you.x < 7, 3000);
press(ok);
until(ok, () => ok.you.x > 306, 1000);
assert.equal(events(ok, "lose").length, 0);
});
test("Ghoul Rush's Bone Stair: a skeleton rises over the treads first, then climbs up at YOU; SKEL_HP bolts knock it down (an act, points, a little ground back), and running into it is a heart (cause \"stairSkel\")", () => {
const round = synth({ flights: GENTLE, skels: [[300]] });
stairAt(round, 200);
until(round, () => events(round, "stairRise").length > 0, 3000);
assert.ok(300 - round.you.x <= bs.SKEL_NEAR);
assert.equal(round.runner.skels[0].state, "rise");
until(round, () => round.runner.skels[0].state === "climb", 2000);
const x0 = round.runner.skels[0].x;
run(round, 200);
assert.ok(round.runner.skels[0].x < x0, "climbing up the stair at YOU");
until(round, () => events(round, "lose").length > 0, 2000);
assert.equal(events(round, "lose")[0].cause, "stairSkel");
assert.equal(round.runner.skels[0].state, "smashed");
// Shot down.
const shot = synth({ flights: GENTLE, skels: [[300]] });
stairAt(shot, 200);
shot.input.fire = true;
until(shot, () => shot.runner.skels[0].state === "down" || events(shot, "lose").length > 0, 3000);
assert.equal(shot.runner.skels[0].state, "down");
assert.equal(events(shot, "stairSkelHit").length, bs.SKEL_HP - 1);
assert.equal(events(shot, "stairSkelDown").length, 1);
assert.equal(shot.bonusRound.perf.acts, 1);
assert.ok(shot.score >= bs.SKEL_POINTS);
until(shot, () => shot.you.x > 310, 2000);
assert.equal(events(shot, "lose").length, 0);
// A waiting skeleton takes no bolt.
const early = synth({ flights: GENTLE, skels: [[300]] });
assert.equal(bs.BONESTAIR.target(early, { x: 300, y: bs.stairY(early.spec.ride, 300) + 2 }), false);
});
test("Ghoul Rush's Bone Stair: treads that give way start crumbling once YOU are in, at a speed between a duck and a run: a runner outruns it, a ducker drops through (cause \"stairGive\") and is put back past the stretch", () => {
assert.ok(bs.ROT_V > bs.DUCK_V && bs.ROT_V > bs.HOLD_V && bs.ROT_V < bs.RUN_V);
for (const [x0, x1] of R.rot) {
assert.ok(x1 - x0 >= 30, "long enough to matter");
assert.equal(bs.flightAt(R, x0), bs.flightAt(R, x1), "inside one flight");
for (const [a, b] of R.gaps) if (a > x0 && b < x1) assert.ok(a - x0 > 15 && x1 - b > 15, "a gap inside one is well clear of its ends");
}
const runner = synth({ flights: GENTLE, rot: [[200, 260]] });
stairAt(runner, 180);
until(runner, () => runner.you.x > 270, 3000);
assert.equal(events(runner, "stairRot").length, 1);
assert.equal(events(runner, "lose").length, 0, "outrun");
const ducker = synth({ flights: GENTLE, rot: [[200, 260]] });
stairAt(ducker, 180);
ducker.input.down = true;
until(ducker, () => events(ducker, "lose").length > 0, 4000);
ducker.input.down = false;
assert.equal(events(ducker, "lose")[0].cause, "stairGive");
assert.ok(ducker.you.x > 260 && ducker.you.state === "run", "back on the treads past it");
// Blinking safe after a heart, it waits behind YOU.
const safe = synth({ flights: GENTLE, rot: [[200, 260]] });
stairAt(safe, 180, { safe: true });
safe.input.down = true;
until(safe, () => safe.you.x > 262, 6000);
safe.input.down = false;
assert.equal(events(safe, "lose").length, 0);
});
test("Ghoul Rush's Bone Stair: the rubble behind gains on a duck or a hold and loses to a clean run; at CATCH_GAP it has YOU (a heart, cause \"stairRubble\") and falls back; a hit shoves it closer", () => {
const s = synth({ flights: GENTLE });
assert.equal(s.runner.gap, bs.GAP_START);
run(s, 3000);
assert.ok(s.runner.gap > bs.GAP_START, "a clean run wins ground");
assert.ok(s.runner.gap <= bs.GAP_MAX);
const d = synth({ flights: GENTLE });
const g0 = d.runner.gap;
run(d, 1000, { down: true });
assert.ok(d.runner.gap < g0, "a duck loses ground");
const caught = synth({ flights: GENTLE });
caught.input.left = true;
until(caught, () => events(caught, "lose").length > 0, 10000);
caught.input.left = false;
assert.equal(events(caught, "lose")[0].cause, "stairRubble");
assert.equal(events(caught, "stairCatch").length, 1);
assert.equal(caught.runner.gap, bs.GAP_RESET);
assert.ok(events(caught, "stairClose").length >= 1, "a warning before it");
const hit = synth({ flights: GENTLE, ribs: [[200, bs.stairY({ ...NONE, flights: GENTLE }, 197) + 3]] });
stairAt(hit, 190);
const before = hit.runner.gap;
until(hit, () => events(hit, "lose").length > 0, 1000);
assert.ok(hit.runner.gap < before - bs.HIT_CLOSE + 1, "the hit lets it closer");
assert.ok(hit.runner.v <= bs.STUMBLE_V, "and YOU stumble");
});
test("Ghoul Rush's Bone Stair: checkpoints are passed, and running off the last step drops YOU onto the Pit's floor: the run is over, the way out open, and YOU walk to the door", () => {
const round = stairRound();
stairAt(round, R.checks[0] - 4, { safe: true });
run(round, 300);
assert.equal(round.runner.check, 0);
assert.equal(events(round, "stairCheck").length, 1);
const end = stairRound();
stairAt(end, R.finish - 6, { safe: true });
until(end, () => end.runner.done, 3000);
assert.equal(events(end, "stairEdge").length, 1);
assert.equal(events(end, "stairFinish").length, 1);
assert.equal(end.hasKey, true);
assert.equal(end.you.y, floorOf(end.you.x));
assert.ok(end.you.x > R.finish && end.you.x < ROOM.door);
end.input.right = true;
until(end, () => end.phase !== "play", 4000);
assert.equal(end.phase, "clear");
assert.equal(end.bonusRound.won, true);
assert.ok(end.bonusRound.dice >= BONUS_FLOOR);
});
test("Ghoul Rush's Bone Stair: no random number is drawn in the room (20 seconds of running, jumping, ducking and shooting, on a draw that throws)", () => {
const r = stairRound();
for (let t = 0; t < 20000; t += 16) {
r.input.fire = t % 4000 < 1500;
r.input.down = t % 3000 < 300;
if (t % 1700 < 20) press(r);
r.you.safeMs = 1e9;
ghoul.advance(r, 16, never);
r.events.length = 0;
}
assert.ok(r.you.x > 500);
assert.equal(r.runner.id, "bonestair");
});
test("Ghoul Rush's Bone Stair's grade: three hearts pay at most one die for hearts, every skeleton shot is the acts die, the rubble kept far is the steady die", () => {
const full = stairRound();
const b = full.bonusRound;
assert.equal(b.max, 3);
assert.equal(b.hearts, 3);
assert.equal(b.perf.goal, R.skels.length);
assert.equal(b.perf.total, R.gaps.length + R.rot.length + R.ribs.length + R.skels.length + R.hands.length + R.stones.length);
const mk = (hearts, hits, acts, steadyDie) => {
const bb = makeBonus({ stats: { kills: 0 }, spec: { ride: R } });
bb.hearts = hearts;
bb.perf = { total: 20, hits: Array.from({ length: hits }, (_, i) => `x${i}`), acts, goal: R.skels.length, steady: steadyDie, kills0: 0 };
return diceFor(bb, 0);
};
assert.equal(mk(3, 0, R.skels.length, true), 8, "a perfect run");
assert.equal(mk(3, 0, R.skels.length - 1, true), 7, "a skeleton missed");
assert.equal(mk(1, 3, 0, false), 5);
const s = synth({ flights: GENTLE });
s.runner.gap = 8;
s.runner.gapMs = 20000;
s.runner.gapSum = 8 * 20000;
run(s, 100);
assert.equal(s.bonusRound.perf.steady, false, "the rubble stayed close");
const t = synth({ flights: GENTLE });
run(t, 3000);
assert.equal(t.bonusRound.perf.steady, true);
});
test("Ghoul Rush's Bone Stair: endless lives (round.infinite) spare the hearts for every cause, the Garlic shield takes a hit instead of a heart", () => {
const r = stairRound();
r.infinite = true;
stairAt(r, R.gaps[0][0] - 6);
until(r, () => events(r, "lose").length > 0, 2000);
assert.equal(r.bonusRound.hearts, 3);
assert.equal(events(r, "lose")[0].cause, "stairGap");
assert.equal(r.phase, "play");
const m = synth({ flights: GENTLE });
m.infinite = true;
m.input.left = true;
until(m, () => m.runner.catches > 0, 10000);
assert.equal(m.bonusRound.hearts, 3);
const g = synth({ flights: GENTLE, ribs: [[200, bs.stairY({ ...NONE, flights: GENTLE }, 197) + 3]] });
g.you.garlic = true;
stairAt(g, 190);
until(g, () => !g.you.garlic, 1000);
assert.equal(g.bonusRound.hearts, 3);
});
/* ----------------------------------------------------------- sound, names */
test("Ghoul Rush's Bone Stair: every event has a voice that plays, every cause has words and a sound, every tone exists and is short", () => {
assert.deepEqual(Object.keys(EVENT_VOICE).sort(), [...bs.EVENTS].sort(), "a voice for every event and no more");
const tones = ghoulSfx.default.tones;
for (const [event, [kind, act]] of Object.entries(EVENT_VOICE)) {
const name = STAIR_VOICES[kind] && STAIR_VOICES[kind][act];
assert.ok(name, `${event} has a ${kind}.${act} voice`);
assert.ok(tones[name], `${name} exists`);
assert.equal(VOICES[kind][act], name, "joined to the game's voices");
assert.ok(heard({ type: event, n: 0, points: 50, cause: "stairGap" }).played.includes(name), `${event} plays ${name}`);
}
for (const cause of bs.CAUSES) {
assert.ok(LOSE_WORDS[cause], `${cause} has words`);
assert.ok(LOSE_SOUNDS[cause] && LOSE_SOUNDS[cause].length === 3, `${cause} has a sound`);
assert.ok(tones[LOSE_SOUNDS[cause][0]] || ["thud", "crunch"].includes(LOSE_SOUNDS[cause][0]), `${cause}'s sound is a tone`);
assert.ok(heard({ type: "lose", cause, hearts: 2 }).played.length > 0, `${cause} sounds`);
}
for (const name of Object.keys(tones).filter((n) => n.startsWith("ghoulStair"))) {
const layers = tones[name].layers;
assert.ok(Math.max(...layers.map((l) => (l.delay || 0) + l.seconds)) <= 1.2, `${name} is short`);
for (const l of layers) assert.ok(l.gain > 0 && l.gain <= 1);
}
});
test("Ghoul Rush's Bone Stair: its names are its own (every event, cause and tone starts with its prefix), and it keeps to the shared ride slot", () => {
for (const e of bs.EVENTS) assert.ok(e.startsWith("stair"), e);
for (const c of bs.CAUSES) assert.ok(c.startsWith("stair"), c);
for (const kind of Object.keys(STAIR_VOICES)) for (const name of Object.values(STAIR_VOICES[kind])) assert.ok(name.startsWith("ghoulStair"), name);
assert.deepEqual(Object.keys(bs.BONESTAIR).filter((key) => ["hazards", "bosses", "boss"].includes(key)), []);
const r = stairRound();
assert.equal(r.runner.id, "bonestair");
assert.ok(!("bonestair" in r));
});
/* ------------------------------------------------------------ telegraphs */
test("Ghoul Rush's Bone Stair telegraphs: JUMP over gaps, hands and masonry, DUCK over ribcages, SHOOT over skeletons, RUN where the treads will give way, words on the first three of each kind, seen from afar, the same every time", () => {
const marks = telegraphMarks(R);
assert.equal(marks.length, R.gaps.length + R.rot.length + R.ribs.length + R.skels.length + R.hands.length + R.stones.length, "one per thing");
for (const m of marks) assert.equal(m.answer, ANSWERS[m.kind], m.kind);
assert.deepEqual(ANSWERS, { gap: "JUMP", hand: "JUMP", stone: "JUMP", rib: "DUCK", skel: "SHOOT", rot: "RUN" });
const m = marks.find((q) => q.kind === "rib");
const alphaOf = (x) => (telegraphs(R, x).find((t) => t.kind === "rib" && t.lead === m.lead) || { alpha: 0 }).alpha;
assert.equal(alphaOf(m.lead - 45), 0, "not yet");
assert.ok(alphaOf(m.lead - 36) > 0 && alphaOf(m.lead - 36) < 1, "fading in");
assert.equal(alphaOf(m.lead - 20), 1);
assert.equal(alphaOf(m.lead + 7), 0, "gone once passed");
const sk = marks.find((q) => q.kind === "skel");
assert.ok(telegraphs(R, sk.lead - 55).some((q) => q.lead === sk.lead && q.alpha > 0.5), "a skeleton seen from further");
assert.deepEqual(telegraphs(R, m.lead - 33), telegraphs(R, m.lead - 33), "deterministic");
for (const kind of Object.keys(ANSWERS)) {
const of = marks.filter((q) => q.kind === kind).sort((p, q) => p.lead - q.lead);
of.forEach((q, i) => {
assert.equal(q.n, i);
const shown = telegraphs(R, q.lead - 30).find((s) => s.lead === q.lead);
assert.equal(shown.words, i < 3, `${kind} ${i}`);
});
}
});
test("Ghoul Rush's Bone Stair: every thing sits on the treads, clear of the seams (none within 14 before one or 20 after), and spaced for a player", () => {
const seams = bs.seams(R).map((s) => s.x);
const things = [...R.gaps.map(([a, b]) => [a, b]), ...R.ribs.map(([x]) => [x - bs.RIB_W / 2, x + bs.RIB_W / 2]), ...R.hands.map(([x]) => [x, x]), ...R.stones.map(([x]) => [x, x]), ...R.rot.map(([a, b]) => [a, b])];
for (const [a, b] of things) {
assert.ok(bs.stairY(R, a) !== null && bs.stairY(R, b) !== null && a > F[0][0] && b < R.finish - 8);
for (const s of seams) assert.ok(b < s - 14 || a > s + 20, `${a} to ${b} is clear of the seam at ${s}`);
}
for (const [x] of R.skels) for (const s of seams) assert.ok(x < s - 14 || x > s + 30, `a skeleton at ${x} has room to climb from the seam at ${s}`);
const xs = [...R.gaps.map(([a]) => a), ...R.ribs.map(([x]) => x), ...R.hands.map(([x]) => x), ...R.stones.map(([x]) => x), ...R.skels.map(([x]) => x)].sort((p, q) => p - q);
for (let i = 0; i + 1 < xs.length; i++) assert.ok(xs[i + 1] - xs[i] >= 22, `${xs[i]} and ${xs[i + 1]} are ${xs[i + 1] - xs[i]} apart`);
for (const x of R.checks) for (const [a, b] of things) assert.ok(x < a - 10 || x > b + 10, `a checkpoint at ${x} is clear`);
});
test("Ghoul Rush's Bone Stair's intro banner says the controls plainly", () => {
assert.match(R.how, /UP jump, DOWN duck/);
assert.match(R.how, /SPACE to shoot/);
assert.match(R.how, /YOU/);
});
/* --------------------------------------------------------------- drawing */
test("Ghoul Rush's Bone Stair draws: the stair, each thing in each state, a seam, the rubble far and close, a crash, the last step and the floor, the result card, and the stage select straight into it", () => {
const ctx = new Proxy({}, { get: (t, name) => (name in t ? t[name] : () => {}), set: (t, name, value) => ((t[name] = value), true) });
const g = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } });
g.resize(900, 900);
g.key("action");
g.tick(16);
const r = g.round;
through(r);
r.cleared = ghoul.STAGES.slice(0, ghoul.RUN_STAGES).map((st) => st.id);
r.offer = null;
for (let n = 0; n < 14 && r.spec.id !== "bonestair"; n++) through(r);
r.lives = 99;
const spots = [ROOM.start + 4, R.gaps[0][0] - 8, R.ribs[0][0] - 6, R.hands[0][0] - 20, R.stones[0][0] - 30, R.skels[0][0] - 30, R.rot[0][0] + 10, F[0][1] - 1, F[0][1] + 6, R.checks[0], R.finish - 10];
for (const dark of [true, false]) {
for (const x of spots) {
r.dark = dark;
r.phase = "play";
stairAt(r, x, { safe: true });
r.runner.hands = r.runner.hands.map((h, i) => ({ state: ["reach", "grab", "hold", "wait"][i % 4], t: 300 }));
r.runner.stones = r.runner.stones.map((s, i) => ({ state: ["warn", "pile", "warn"][i % 3], t: i === 2 ? 100 : 700, cracked: true }));
r.runner.skels = r.runner.skels.map((s, i) => ({ state: ["rise", "climb", "down", "wait"][i % 4], t: 300, x: R.skels[i][0] - 3, hp: 2 }));
r.runner.rot = r.runner.rot.map((q, i) => (i === 0 ? { state: "go", front: R.rot[0][0] + 6 } : q));
for (const gap of [24, 6]) {
r.runner.gap = gap;
r.runner.close = gap < bs.CLOSE_ON;
r.shots.push({ x: x + 6, y: r.you.y + 2.4, vx: 130, vy: -10, gone: 0 });
for (let k = 0; k < 3; k++) g.tick(16);
stairAt(r, x, { safe: true });
}
r.you.ducking = true;
g.tick(16);
Object.assign(r.you, { state: "air", vy: 10, y: r.you.y + 3, ducking: false });
g.tick(16);
}
}
assert.equal(r.spec.id, "bonestair");
// A crash.
r.you.safeMs = 0;
r.runner.hands = r.runner.hands.map(() => ({ state: "wait", t: 0 }));
stairAt(r, R.ribs[0][0] - 8);
for (let k = 0; k < 60; k++) g.tick(16);
assert.ok(r.bonusRound.hearts < r.bonusRound.max || r.phase !== "play", "the crash draws too");
// Down on the Pit's floor, and the card.
const done = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } });
done.resize(900, 900);
done.key("action");
done.tick(16);
const d = done.round;
through(d);
d.cleared = ghoul.STAGES.slice(0, ghoul.RUN_STAGES).map((st) => st.id);
d.offer = null;
for (let n = 0; n < 14 && d.spec.id !== "bonestair"; n++) through(d);
d.phase = "play";
d.runner.done = true;
Object.assign(d.you, { x: R.finish + 16, y: floorOf(R.finish + 16), state: "run" });
d.camX = R.finish - 40;
for (let k = 0; k < 10; k++) done.tick(16);
for (const won of [true, false]) {
endBonus(d, won, { ROOM_POINTS: 300, award: (rd, pts) => (rd.score += pts) });
d.bonusRound.over = true;
for (let k = 0; k < 10; k++) {
done.tick(16);
bonusTick(d, { tone() {}, fx: {} });
}
d.bonusRound.over = false;
}
// The stage select goes straight into it.
const pick = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx } });
pick.resize(900, 900);
pick.stageSelect();
const p = pick.round;
for (let i = 0; i < ghoul.SELECTABLE.length; i++) ghoul.steerSelect(p, 1, 0);
const at = ghoul.FINALE.rooms.indexOf("bonestair");
for (let i = 0; i < at; i++) ghoul.steerSelect(p, 0, 1);
assert.equal(p.select.room, at);
pick.tick(16);
ghoul.takeSelect(p);
assert.equal(p.spec.id, "bonestair");
assert.equal(p.runner.id, "bonestair");
assert.equal(p.you.y, R.top[2]);
assert.equal(p.bonusRound.max, 3);
pick.tick(16);
});
/* ----------------------------------------------------------- the bots */
// A bot that plays well: it jumps at the edge of missing treads, over a grabbing hand and a pile of
// masonry, ducks every ribcage, and fires only while a skeleton is up ahead (a held blaster runs
// hot). `miss` is the share of things it fails to dodge (by a hash).
const mix = (a, b) => {
let h = Math.imul(a + 0x9e37, 0x85ebca6b) ^ Math.imul(b + 0x7f4a, 0xc2b2ae35);
h ^= h >>> 13;
h = Math.imul(h, 0x5bd1e995);
h ^= h >>> 15;
return (h >>> 0) / 4294967296;
};
function goodBot(round, seed, miss = 0) {
const { you, runner: c, input: inp } = round;
inp.left = inp.right = inp.down = false;
inp.fire = false;
if (round.phase !== "play" || !c || c.done) {
inp.up = false;
return;
}
const ok = (x) => mix(seed, Math.round(x)) >= miss;
const look = seed % 4;
inp.fire = c.skels.some((s) => (s.state === "rise" || s.state === "climb") && s.x > you.x && s.x - you.x < 75);
let jump = false;
if (you.state === "run") {
for (const [x0] of R.gaps) if (x0 - you.x > 0 && x0 - you.x < 1.5 + look * 0.5 && ok(x0)) jump = true;
R.hands.forEach(([x], i) => {
const h = c.hands[i];
if ((h.state === "grab" || h.state === "reach") && x - you.x > 4 && x - you.x < 7 + look && ok(x)) jump = true;
});
R.stones.forEach(([x], i) => {
if (c.stones[i].state === "pile" && x - you.x > 7 && x - you.x < 9 + look && ok(x)) jump = true;
});
for (const [x] of R.ribs) if (you.x > x - bs.RIB_W / 2 - 3 && you.x < x + bs.RIB_W / 2 + 2 && ok(x)) inp.down = true;
}
if (jump && !inp.down) press(round);
else inp.up = false;
}
function idleBot(round) {
const inp = round.input;
inp.left = inp.right = inp.down = inp.up = inp.fire = false;
}
function rideWith(seed, bot, limit = 80000) {
const round = stairRound(seed);
const lost = [];
let t = 0;
for (; t < limit && round.phase !== "clear" && !round.over; t += 16) {
bot(round);
if (round.runner && round.runner.done && round.phase === "play") round.input.right = true;
ghoul.advance(round, 16, steady);
for (const e of round.events) if (e.type === "lose") lost.push(e.cause);
if (round.runner && !round.runner.done) {
const off = round.you.x - round.camX;
assert.ok(off > 4 && off < 70, `YOU stay in view (${off.toFixed(1)} from the left edge at ${round.you.x.toFixed(0)})`);
}
round.events.length = 0;
}
return { round, lost, ms: t };
}
test("Ghoul Rush's Bone Stair: a bot that dodges well runs the whole stair in about 30 seconds, every skeleton shot, all three hearts kept, 8 dice, past every checkpoint", () => {
for (let seed = 1; seed <= 4; seed++) {
const { round, lost, ms } = rideWith(seed, (r) => goodBot(r, seed));
const b = round.bonusRound;
assert.equal(b.won, true, `seed ${seed} finished (lost ${lost.join(",")})`);
assert.ok(ms > 26000 && ms < 36000, `${ms} ms`);
assert.equal(b.hearts, 3, lost.join(","));
assert.equal(b.dice, 8);
assert.equal(round.lives, 3, "never a run life");
assert.equal(round.runner.done, true);
assert.equal(round.runner.check, R.checks.length - 1);
}
});
test("Ghoul Rush's Bone Stair: a bot that misses some things still mostly finishes, never with a run life lost", () => {
let won = 0;
for (let seed = 1; seed <= 8; seed++) {
const { round } = rideWith(seed, (r) => goodBot(r, seed, 0.12));
if (round.bonusRound.won) won++;
assert.equal(round.lives, 3);
assert.equal(round.over, false);
}
assert.ok(won >= 4, `${won} of 8 finished`);
});
test("Ghoul Rush's Bone Stair: a bot that never dodges loses all three hearts in the first half, ends with 0 dice, BONUS LOST, and the run goes on with no game over", () => {
for (let seed = 1; seed <= 3; seed++) {
const { round, lost } = rideWith(seed, idleBot);
const b = round.bonusRound;
assert.equal(b.won, false, "never finishes");
assert.equal(b.dice, 0);
assert.equal(b.hearts, 0);
assert.equal(lost.length, 3);
assert.ok(round.you.x < R.finish * 0.5, `out at ${round.you.x}`);
assert.equal(round.lives, 3, "never a run life");
assert.equal(round.over, false, "no game over");
// On into the next room.
until(round, () => round.spec.id !== "bonestair", 12000);
assert.notEqual(round.spec.id, "bonestair");
assert.equal(round.over, false);
}
});
test("Ghoul Rush's Bone Stair: a bot that ducks or holds back the whole way is caught by the rubble again and again", () => {
for (const key of ["down", "left"]) {
const { lost } = rideWith(3, (r) => {
goodBot(r, 3);
if (r.runner && !r.runner.done) r.input[key] = true;
}, 30000);
assert.ok(lost.filter((c) => c === "stairRubble").length >= 2, `${key}: ${lost.join(",")}`);
}
});
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's boss intro cards: every boss room has an entry (the boss's exact name, an epithet, no em dash, never the hero's name), the card shows when a boss room is entered (after the bonus ride too) and in no other room, not again on a retry, any fresh move key, fire or click moves it on after the lockout (repeats and early presses never do), it never moves on by itself, a pause holds it, and it draws for every boss on a fake canvas (through the boss's own art, with a fallback when the art throws or is missing). // Web console tests, Ghoul Rush's boss intro cards: every boss room has an entry (the boss's exact name, an epithet, no em dash, never the hero's name), the card shows when a boss room is entered (after the bonus ride too) and in no other room, not again on a retry, any fresh move key, fire or click moves it on after the lockout (repeats and early presses never do), it never moves on by itself, a pause holds it, and it draws for every boss on a fake canvas (through the boss's own art, with a fallback when the art throws or is missing).
import "./seed-random.mjs";
import { test } from "node:test"; import { test } from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js"; import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -34,6 +35,11 @@ function selectInto(at, room, texts = [], opts = {}) {
g.round.select = { at, room }; g.round.select = { at, room };
g.round.practice = true; g.round.practice = true;
g.key("action"); g.key("action");
// A stage that opens on its boss's room (the finale) shows its own card first.
if (g.round.phase === "intro") {
g.round.introMs = ghoul.INTRO_MIN_MS;
g.key("action");
}
return g; return g;
} }
@@ -244,7 +250,8 @@ test("Ghoul Rush boss intros: the card draws for every boss at many moments, thr
const sizes = { W: 96, H: 54 }; const sizes = { W: 96, H: 54 };
for (const room of bossRooms) { for (const room of bossRooms) {
const id = room.boss; const id = room.boss;
const st = ghoul.STAGES.find((s) => s.boss === id); // The stage that holds this boss's room (the finale holds three).
const st = ghoul.SELECTABLE.find((s) => s.rooms.includes(room.id));
const calls = []; const calls = [];
const BOSS_ART = new Proxy({}, { get: (t, k) => (k === id ? (ctx, pic, b) => calls.push([pic, b]) : undefined) }); const BOSS_ART = new Proxy({}, { get: (t, k) => (k === id ? (ctx, pic, b) => calls.push([pic, b]) : undefined) });
const texts = []; const texts = [];
@@ -261,7 +268,7 @@ test("Ghoul Rush boss intros: the card draws for every boss at many moments, thr
assert.ok(texts.includes(bossIntroFor(id).epithet), `${id}: the epithet`); assert.ok(texts.includes(bossIntroFor(id).epithet), `${id}: the epithet`);
// The same through the game's own drawing, with the real art. // The same through the game's own drawing, with the real art.
const g2texts = []; const g2texts = [];
const g = selectInto(ghoul.STAGES.findIndex((s) => s.boss === id), ghoul.STAGES.find((s) => s.boss === id).rooms.length - 1, g2texts); const g = selectInto(ghoul.SELECTABLE.indexOf(st), st.rooms.indexOf(room.id), g2texts);
assert.equal(g.round.phase, "bossintro", id); assert.equal(g.round.phase, "bossintro", id);
for (let ms = 0; ms < 5000; ms += 80) { for (let ms = 0; ms < 5000; ms += 80) {
g.round.introMs = ms; g.round.introMs = ms;
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's Midnight Carnival stage: its four rooms (the Midway, the Hall of Mirrors, the Funhouse with its conveyor floors, the Big Top), grinners that honk out acid balloons, marionettes that drop on their strings, Mirror You that copies your moves and shots half a second late, strongmen that lob barbells, circus hounds that leap through hoops of fire, Cotton Candy and the Custard Pie (found only here), and the Ringmaster, whose puppet hangs on three strings: cut them all and he is open for four seconds. // Web console tests, Ghoul Rush's Midnight Carnival stage: its four rooms (the Midway, the Hall of Mirrors, the Funhouse with its conveyor floors, the Big Top), grinners that honk out acid balloons, marionettes that drop on their strings, Mirror You that copies your moves and shots half a second late, strongmen that lob barbells, circus hounds that leap through hoops of fire, Cotton Candy and the Custard Pie (found only here), and the Ringmaster, whose puppet hangs on three strings: cut them all and he is open for four seconds.
import "./seed-random.mjs";
import { test } from "node:test"; import { test } from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js"; import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,5 +1,6 @@
// Web console tests, Ghoul Rush's Runaway Cart (the Deep Seam Mine's ride room): its shape (between the Collapse and the Seam, every gap clears at the cart's speed with a jump, every beam can be ducked, checkpoints spaced, the clock covers the ride), the cart's speed on slopes, leaning and braking, its jump and its steering in the air, a ramp's launch, landing on the upper or the lower line of a split, a fall into the chasm and the respawn at the last checkpoint, ducking under a beam, rubble, crates (two shots break one), the boulder behind, the buffer stop and the door, the ledge imp, a canary's slide of rubble, endless lives for every new cause, a voice for every event, the drawing, and a bot that rides the whole room. // Web console tests, Ghoul Rush's Runaway Cart (the Deep Seam Mine's ride room): its shape (between the Collapse and the Seam, every gap clears at the cart's speed with a jump, every beam can be ducked, checkpoints spaced, the clock covers the ride), the cart's speed on slopes, leaning and braking, its jump and its steering in the air, a ramp's launch, landing on the upper or the lower line of a split, a fall into the chasm and the respawn at the last checkpoint, ducking under a beam, rubble, crates (two shots break one), the boulder behind, the buffer stop and the door, the ledge imp, a canary's slide of rubble, endless lives for every new cause, a voice for every event, the drawing, and a bot that rides the whole room.
// Run with: node --test scripts/test-web-console-activities-ghoul-cart.mjs // Run with: node --test scripts/test-web-console-activities-ghoul-cart.mjs
import "./seed-random.mjs";
import { test } from "node:test"; import { test } from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js"; import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's Chapel stage: its four rooms, gargoyles that are stone on their perch and dive when you pass under, choir ghosts whose song quickens the monsters near them, censer monks and their smoke, bats in the bells, the bell toll that freezes everything for a second, Holy Water (found only here), and the Choirmaster, whose organ pipes guard him and whose columns of notes have one gap each. // Web console tests, Ghoul Rush's Chapel stage: its four rooms, gargoyles that are stone on their perch and dive when you pass under, choir ghosts whose song quickens the monsters near them, censer monks and their smoke, bats in the bells, the bell toll that freezes everything for a second, Holy Water (found only here), and the Choirmaster, whose organ pipes guard him and whose columns of notes have one gap each.
import "./seed-random.mjs";
import { test } from "node:test"; import { test } from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js"; import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's Lucky die: it comes only from a kill, stacks to nine and lasts the run; when a life would be lost one rolls: a 4 to 6 brings Planny back (the monsters in view blown apart in an ordinary room, a boss's room untouched; a 5 adds a heart, a 6 a heart and a Garlic shield), a 3 or 2 costs the life and leaves a gift for the respawn, a 1 only laughs. // Web console tests, Ghoul Rush's Lucky die: it comes only from a kill, stacks to nine and lasts the run; when a life would be lost one rolls: a 4 to 6 brings Planny back (the monsters in view blown apart in an ordinary room, a boss's room untouched; a 5 adds a heart, a 6 a heart and a Garlic shield), a 3 or 2 costs the life and leaves a gift for the respawn, a 1 only laughs.
import "./seed-random.mjs";
import { test } from "node:test"; import { test } from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js"; import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -102,7 +103,7 @@ test("Ghoul Rush: a Lucky die is as common as a 1UP, comes only as a drop, and i
assert.equal(dark.drops.length, 1, "a kill drops a power-up on a low roll"); assert.equal(dark.drops.length, 1, "a kill drops a power-up on a low roll");
}); });
test("Ghoul Rush: picking up Lucky dice stacks them to nine, then pays points like a 1UP at its cap, and the dice show in a pill", () => { test("Ghoul Rush: picking up Lucky dice stacks them to MAX_HELD_DICE (13), then pays points like a 1UP at its cap, and the dice show in a pill", () => {
const round = hall(); const round = hall();
const drop = { id: 1, kind: "die", x: round.you.x, y: round.you.y + 1, vx: 0, vy: 0, life: 9000, rest: true }; const drop = { id: 1, kind: "die", x: round.you.x, y: round.you.y + 1, vx: 0, vy: 0, life: 9000, rest: true };
round.drops.push(drop); round.drops.push(drop);
@@ -110,12 +111,13 @@ test("Ghoul Rush: picking up Lucky dice stacks them to nine, then pays points li
assert.equal(round.dice, 1); assert.equal(round.dice, 1);
assert.equal(round.drops.length, 0); assert.equal(round.drops.length, 0);
assert.equal(events(round, "power")[0].kind, "die"); assert.equal(events(round, "power")[0].kind, "die");
for (let k = 0; k < 8; k++) ghoul.applyPower(round, "die"); assert.equal(ghoul.MAX_HELD_DICE, 13);
assert.equal(round.dice, 9); for (let k = 0; k < 20; k++) ghoul.applyPower(round, "die");
assert.equal(round.dice, ghoul.MAX_HELD_DICE, "stacks to the cap");
const score = round.score; const score = round.score;
ghoul.applyPower(round, "die"); ghoul.applyPower(round, "die");
assert.equal(round.dice, 10, "no cap"); assert.equal(round.dice, ghoul.MAX_HELD_DICE, "no more past it");
assert.equal(round.score, score, "no points instead"); assert.equal(round.score, score + ghoul.POWER_POINTS, "points instead");
const canvas = { getContext: () => null }; const canvas = { getContext: () => null };
const game = ghoul.default.create({ canvas }); const game = ghoul.default.create({ canvas });
game.start(); game.start();
@@ -239,13 +241,18 @@ test("Ghoul Rush: a 5 saves him with a heart and no shield, a 4 just saves him,
lose(held, "pit"); lose(held, "pit");
ghoul.advance(held, ghoul.ROLL_MS + 8, rolls(FOUR)); ghoul.advance(held, ghoul.ROLL_MS + 8, rolls(FOUR));
assert.equal(held.you.garlic, true, "a shield he already held stays"); assert.equal(held.you.garlic, true, "a shield he already held stays");
const some = hall(1);
some.lives = 9;
lose(some, "zombie");
ghoul.advance(some, ghoul.ROLL_MS + 8, rolls(FIVE));
assert.equal(some.lives, 10, "a heart under the cap");
const full = hall(1); const full = hall(1);
full.lives = 9; full.lives = ghoul.MAX_LIVES;
const score = full.score; const score = full.score;
lose(full, "zombie"); lose(full, "zombie");
ghoul.advance(full, ghoul.ROLL_MS + 8, rolls(FIVE)); ghoul.advance(full, ghoul.ROLL_MS + 8, rolls(FIVE));
assert.equal(full.lives, 10, "no cap"); assert.equal(full.lives, ghoul.MAX_LIVES, "never past MAX_LIVES (13)");
assert.equal(full.score, score, "no points instead"); assert.equal(full.score, score + ghoul.POWER_POINTS, "points instead");
}); });
test("Ghoul Rush: a 3 costs the life and he comes back with Rapid fire and a Garlic shield, a 2 with Bottle Rockets and a Garlic shield", () => { test("Ghoul Rush: a 3 costs the life and he comes back with Rapid fire and a Garlic shield, a 2 with Bottle Rockets and a Garlic shield", () => {
@@ -0,0 +1,381 @@
// Web console tests, Ghoul Rush's ending: four pages that obey the story's rules (2 to 4 short lines, no digits, no em dash, YOU on each, the gag's FINAL NOTICE); the House's last room opens it instead of the win; a press turns pages only after the lockout and finishes the typing first; holding fire skips it, a tap never does; the last page wins the run once, with n = round.winN; the window's keys, a click, a pause, its track and its sounds; every scene draws on a fake canvas at many moments; every event it raises has a react; every tone it names exists.
// Run with: node --test scripts/test-web-console-activities-ghoul-ending.mjs
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
import ghoulSfx from "../src/web-console/public/activities/ghoul-rush/sfx/ghoul-sfx.js";
import { react } from "../src/web-console/public/activities/ghoul-rush/draw/ghoul-draw.js";
import { PAGES as STORY_PAGES } from "../src/web-console/public/activities/ghoul-rush/story/ghoul-story.js";
import {
CLICK_OFF_MS,
ENDING_HINT,
ENDING_LOCK_MS,
ENDING_TRACK,
FLAG_MS,
LAST_HINT,
LIGHTS_OUT,
MAX_LINE,
PAGES,
RELOCK_MS,
SKIP_HINT,
SKIP_HOLD_MS,
SLIDE_MS,
STAMP_MS,
UNFOLD_MS,
beginEnding,
pressEnding,
releaseEnding,
revealEnd,
skipEnding,
stepEnding,
takeEnding,
} from "../src/web-console/public/activities/ghoul-rush/story/ghoul-ending.js";
import { SCENE_H, TEXT_SIZE, endingArt, roadFlat, windowLit } from "../src/web-console/public/activities/ghoul-rush/story/ghoul-ending-draw.js";
import { compileTrack } from "../src/web-console/public/music.js";
import { toneNames } from "../src/web-console/public/tones.js";
const steady = () => 0.5;
const DASH = String.fromCharCode(0x2014);
const events = (round, type) => round.events.filter((e) => e.type === type);
const isTone = (name) => toneNames().includes(name) || Object.hasOwn(ghoulSfx.tones, name);
function fakeCtx(texts) {
return new Proxy({}, {
get: (t, name) => (name in t ? t[name] : name === "fillText" ? (s) => texts.push(String(s)) : () => {}),
set: (t, name, value) => ((t[name] = value), true),
});
}
function through(round) {
round.phase = "clear";
round.phaseMs = 1;
ghoul.advance(round, 4, steady);
}
// A round walked through the hall and every stage to the House, then through each of the finale's rooms until the ending opens.
function toEnding(seed = 4) {
const round = ghoul.newRound(seed);
round.dice = 0;
through(round);
round.cleared = ghoul.STAGES.slice(0, ghoul.RUN_STAGES).map((st) => st.id);
round.offer = null;
through(round);
assert.equal(round.stage, ghoul.FINALE.id, "the House");
for (let k = 0; k < 20 && round.phase !== "ending"; k++) through(round);
assert.equal(round.phase, "ending", "the House's last room opens the ending");
return round;
}
// A window game in the ending, from the stage select's last entry (the House), and its sounds.
function openGame() {
const texts = [];
const sounds = [];
const tracks = [];
const ctx = fakeCtx(texts);
const g = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => ctx }, tone: (name) => sounds.push(name), music: (name) => tracks.push(name) });
g.resize(900, 900);
g.stageSelect();
for (let i = 0; i < ghoul.SELECTABLE.length; i++) g.key("down");
g.key("action");
assert.equal(g.round.stage, ghoul.FINALE.id);
for (let k = 0; k < 20 && g.round.phase !== "ending"; k++) through(g.round);
assert.equal(g.round.phase, "ending");
g.tick(16);
return { g, texts, sounds, tracks };
}
const tick = (g, ms) => {
for (let t = 0; t < ms; t += 16) g.tick(16);
};
const lock = (g) => tick(g, ENDING_LOCK_MS + 20);
// To the point the page can turn: its typing done and its scene played out.
const playedOut = (pg) => Math.max(revealEnd(pg), pg.wait);
const typedOut = (g) => tick(g, playedOut(PAGES[g.round.ending.page]) - g.round.ending.ms + 40);
test("Ghoul Rush ending: four pages, 2 to 4 short lines each that fit the field, no digits, no em dash, never the hero's name, YOU on every page", () => {
assert.equal(PAGES.length, 4);
assert.deepEqual(PAGES.map((p) => p.chapter), ["LIGHTS OUT", "THE ROAD", "MORNING", "FINAL NOTICE"]);
assert.equal(new Set(PAGES.map((p) => p.id)).size, PAGES.length, "unique ids");
for (const p of PAGES) {
assert.ok(p.chapter && p.scene && p.pal.sky && p.pal.ground && p.pal.a && p.pal.glow, `${p.id} has a heading, a scene and colors`);
assert.ok(p.lines.length >= 2 && p.lines.length <= 4, `${p.id} has 2 to 4 lines`);
const text = [p.chapter, ...p.lines].join("\n");
assert.ok(!text.includes(DASH), `${p.id} has no em dash`);
assert.ok(!/\d/.test(text), `${p.id} has no digit`);
assert.ok(!/planny|the player|the hero|\bhero\b/i.test(text), `${p.id} never names the hero`);
assert.ok(/\bYOU\b/.test(p.lines.join(" ")), `${p.id} speaks to YOU`);
for (const line of p.lines) {
assert.ok(line.length <= MAX_LINE, `${p.id}: "${line}" is ${line.length} characters`);
assert.ok(line.length * TEXT_SIZE * 0.62 <= ghoul.FIELD_W - 1, `${p.id}: "${line}" fits the field`);
}
for (const [at, name, vol, rate] of p.cues) {
assert.ok(at >= 0 && at < 9000 && vol > 0 && vol <= 1 && rate > 0, `${p.id}: a cue is timed and audible`);
assert.ok(isTone(name), `${p.id}: ${name} is a tone`);
}
assert.ok(p.cues.every((c, i) => i === 0 || c[0] >= p.cues[i - 1][0]), `${p.id}: its cues are in order`);
}
const lines = PAGES.flatMap((p) => p.lines);
assert.equal(new Set(lines).size, lines.length, "no line used twice");
const story = new Set(STORY_PAGES.flatMap((p) => p.lines));
assert.ok(lines.every((l) => !story.has(l)), "no line copied from the intro story");
const all = lines.join("\n");
assert.ok(all.includes("FINAL NOTICE") && /unpaid bills/.test(all), "the mailbox gag lands");
assert.ok(/unfolds/.test(all) && /cottage/.test(all), "the road and the cottage it was once");
assert.equal(ENDING_TRACK, "ghoulMarrowEnding");
});
test("Ghoul Rush ending: the scene timings agree with the cues (a falling tone per window, the click, the flag, the slide, the stamp)", () => {
const lights = PAGES[0].cues.filter(([, n]) => n === "ghoulEndingWindow" || n === "ghoulEndingLast");
assert.deepEqual(lights.map(([ms]) => ms), LIGHTS_OUT.map(([, ms]) => ms), "a tone as each window goes out");
assert.equal(lights.at(-1)[1], "ghoulEndingLast", "the last window has its own tone");
const rates = lights.slice(0, -1).map((c) => c[3]);
assert.ok(rates.every((r, i) => i === 0 || r < rates[i - 1]), "each window's tone a little lower");
assert.equal(new Set(LIGHTS_OUT.map(([i]) => i)).size, 10, "every one of the house's ten windows goes out");
assert.ok(LIGHTS_OUT.at(-1)[1] - LIGHTS_OUT.at(-2)[1] >= 1000, "a long breath before the last");
for (const [i, ms] of LIGHTS_OUT) {
assert.equal(windowLit(i, ms - 1), 1);
assert.equal(windowLit(i, ms + 2000), 0);
}
assert.equal(roadFlat(0, 0), 0, "the road starts folded");
assert.equal(roadFlat(0, 20000), 1, "and ends flat");
assert.ok(roadFlat(10, UNFOLD_MS + 600) > roadFlat(0, UNFOLD_MS + 600), "it unfolds from the far end toward YOU");
const cue = (pg, name) => PAGES[pg].cues.find(([, n]) => n === name)?.[0];
assert.equal(cue(1, "ghoulEndingClickOff"), CLICK_OFF_MS);
assert.equal(cue(1, "ghoulEndingFold"), UNFOLD_MS);
assert.equal(cue(3, "ghoulEndingFlag"), FLAG_MS);
assert.equal(cue(3, "ghoulEndingPaper"), SLIDE_MS);
assert.equal(cue(3, "ghoulEndingStamp"), STAMP_MS);
});
test("Ghoul Rush ending: the House's end opens it instead of the win, and nothing else moves while it is up", () => {
const round = toEnding();
assert.equal(round.won, false, "not won yet");
assert.equal(round.over, false);
assert.equal(round.winN, ghoul.RUN_STAGES + 1);
assert.equal(events(round, "won").length, 0);
assert.deepEqual(events(round, "endingPage").map((e) => e.page), [0]);
assert.equal(round.ending.page, 0);
round.input.right = true;
const x = round.you.x;
const clock = round.clock;
ghoul.advance(round, 2000, steady);
assert.equal(round.you.x, x, "YOU stay put");
assert.equal(round.clock, clock, "the room's clock holds");
assert.equal(round.phase, "ending");
assert.ok(round.ending.ms >= 2000);
assert.equal(beginEnding({ ...round, events: [], input: {} }), true, "beginEnding says there is an ending");
});
test("Ghoul Rush ending: a press turns a page only after the lockout, typing finishes first, and the last page wins the run once with n = winN", () => {
const round = toEnding();
round.events.length = 0;
assert.equal(takeEnding(round), false, "not at once");
ghoul.advance(round, ENDING_LOCK_MS - 40, steady);
assert.equal(takeEnding(round), false, "not before the lockout");
ghoul.advance(round, 60, steady);
assert.ok(round.ending.ms < revealEnd(PAGES[0]));
assert.equal(takeEnding(round), true);
assert.equal(round.ending.page, 0, "the first press finishes the typing");
assert.equal(round.ending.full, true);
assert.equal(takeEnding(round), false, "a press right on top of it does not count");
ghoul.advance(round, RELOCK_MS + 20, steady);
assert.equal(takeEnding(round), false, "the page waits for its scene to play out (the last window)");
assert.equal(round.ending.page, 0);
ghoul.advance(round, PAGES[0].wait - round.ending.ms + 10, steady);
assert.ok(round.ending.ms >= LIGHTS_OUT.at(-1)[1], "every window is out by then");
assert.equal(takeEnding(round), true);
assert.equal(round.ending.page, 1, "now the page turns");
assert.equal(round.ending.ms, 0);
assert.equal(takeEnding(round), false, "each page has its own lockout");
for (let at = 1; at < PAGES.length; at++) {
assert.equal(round.ending.page, at);
assert.equal(round.won, false, `not won on page ${at + 1}`);
ghoul.advance(round, playedOut(PAGES[at]) + 20, steady);
assert.equal(takeEnding(round), true);
}
assert.deepEqual(events(round, "endingPage").map((e) => e.page), [1, 2, 3]);
assert.equal(round.won, true, "the last page's press wins");
assert.equal(round.over, true);
assert.equal(round.ending, null);
assert.notEqual(round.phase, "ending");
assert.deepEqual(events(round, "won"), [{ type: "won", stages: round.cleared.length, n: ghoul.RUN_STAGES + 1 }]);
assert.equal(takeEnding(round), false, "nothing to take after");
assert.equal(skipEnding(round), false, "nothing to skip after");
ghoul.advance(round, 2000, steady);
assert.equal(events(round, "won").length, 1, "the won event fires once");
});
test("Ghoul Rush ending: holding fire for a second skips it all on any page, a tap or a short hold does not, and a skip always works", () => {
const r = toEnding();
assert.equal(pressEnding(r, true), false, "a repeat is nothing");
assert.equal(r.ending.hold, -1);
assert.equal(pressEnding(r, false), true);
assert.equal(r.ending.hold, 0, "a fresh press starts the clock");
stepEnding(r, SKIP_HOLD_MS - 50);
assert.equal(r.phase, "ending");
releaseEnding(r);
assert.equal(r.ending.hold, -1, "let go stops the clock");
stepEnding(r, 3000);
assert.equal(r.phase, "ending");
pressEnding(r, false);
stepEnding(r, SKIP_HOLD_MS + 10);
assert.equal(r.won, true, "the hold skipped it all");
assert.equal(r.over, true);
assert.equal(events(r, "won").length, 1);
// A skip from any page.
for (let at = 0; at < PAGES.length; at++) {
const s = toEnding(at + 7);
s.ending.page = at;
assert.equal(skipEnding(s), true);
assert.equal(s.won, true);
assert.equal(events(s, "won")[0].n, s.winN);
}
assert.equal(skipEnding(ghoul.newRound(1)), false, "no ending, nothing to skip");
});
test("Ghoul Rush ending: the window's keys, any move and fire alike, turn pages; repeats and early presses never do; a click does; a pause holds it", () => {
for (const name of ["left", "right", "up", "down", "action"]) {
const { g } = openGame();
g.key(name);
assert.equal(g.round.ending.full, false, `${name}: early press ignored`);
g.release(name);
lock(g);
g.key(name, true);
assert.equal(g.round.ending.full, false, `${name}: a repeat is ignored`);
g.key(name);
assert.equal(g.round.ending.full, true, `${name}: a fresh press finishes the typing first`);
g.release(name);
typedOut(g);
g.key(name);
assert.equal(g.round.ending.page, 1, `${name}: the next press turns it`);
g.release(name);
assert.equal(g.round.input.fire || g.round.input.left || g.round.input.right || g.round.input.up || g.round.input.down, false, `${name}: nothing is kept held`);
}
const { g } = openGame();
lock(g);
g.pointer("down", 10, 10);
assert.equal(g.round.ending.full, true, "a click finishes the typing");
typedOut(g);
g.pointer("down", 10, 10);
assert.equal(g.round.ending.page, 1, "and the next click turns the page");
g.pause();
const held = g.round.ending.ms;
tick(g, 2000);
assert.equal(g.round.ending.ms, held, "a pause holds the page's clock");
g.key("action");
assert.equal(g.round.ending.hold, -1, "no key counts while paused");
g.resume();
tick(g, 100);
assert.ok(g.round.ending.ms > held);
});
test("Ghoul Rush ending: through every page on a real clock to the end screen, with its track, its tones, page turns and the escape", () => {
const { g, texts, sounds, tracks } = openGame();
tick(g, 1300);
assert.ok(tracks.length && tracks.every((t) => t === ENDING_TRACK), "only the ending's track plays under it");
assert.ok(sounds.includes("ghoulEndingHush") && sounds.includes("ghoulEndingWindow"), "the first page's tones play");
let guard = 0;
while (g.state === "running" && guard++ < 20) {
typedOut(g);
tick(g, RELOCK_MS + 40);
g.key("right");
g.release("right");
tick(g, 16);
}
assert.equal(g.state, "over");
assert.equal(g.round.won, true);
assert.ok(sounds.includes("ghoulStoryPage"), "a page turn rustles");
for (const n of ["ghoulEndingFold", "ghoulEndingClickOff", "ghoulEndingBird", "ghoulEndingFlag", "ghoulEndingStamp"]) assert.ok(sounds.includes(n), `${n} played`);
texts.length = 0;
g.resize(900, 900);
assert.ok(texts.some((t) => t.startsWith("You escaped! Marrow starves")), "the end screen follows");
// Held fire skips it in the window too.
const { g: h } = openGame();
for (let k = 0; k < 20; k++) h.key("action", true);
tick(h, 2000);
assert.equal(h.round.phase, "ending", "a held key from before never skips");
h.key("action");
h.key("action", true);
tick(h, SKIP_HOLD_MS + 100);
assert.equal(h.state, "over");
assert.equal(h.round.won, true);
});
test("Ghoul Rush ending: every scene draws on a fake canvas at many moments, with its heading, hints and lines, without throwing", () => {
const { g, texts } = openGame();
for (let at = 0; at < PAGES.length; at++) {
for (const ms of [0, 1, 120, 600, 900, 1100, 1500, 2300, 2900, 3100, 4000, 4600, 5200, 6200, 6500, 8000, 12000, 40000]) {
for (const full of [false, true]) {
for (const hold of [-1, 500]) {
g.round.ending = { page: at, ms, full, arm: 0, hold, cue: 99, shown: 0, back: "clear" };
g.tick(1);
}
}
}
g.round.ending = { page: at, ms: 100, full: false, arm: 0, hold: -1, cue: 99, shown: 0, back: "clear" };
texts.length = 0;
g.tick(1);
assert.ok(texts.includes(SKIP_HINT.toUpperCase()), `page ${at + 1} shows how to skip`);
assert.equal(texts.includes(ENDING_HINT) || texts.includes(LAST_HINT), false, "no continue hint inside the lockout");
if (PAGES[at].wait) {
g.round.ending.ms = PAGES[at].wait - 100;
g.round.ending.full = true;
texts.length = 0;
g.tick(1);
assert.equal(texts.includes(ENDING_HINT) || texts.includes(LAST_HINT), false, `page ${at + 1}: no continue hint while its scene plays out`);
}
g.round.ending.ms = 60000;
g.round.ending.full = true;
texts.length = 0;
g.tick(1);
assert.ok(texts.includes(PAGES[at].chapter), `page ${at + 1} draws its heading`);
assert.ok(texts.includes(at === PAGES.length - 1 ? LAST_HINT : ENDING_HINT), `page ${at + 1} shows the continue hint`);
for (const line of PAGES[at].lines) assert.ok(texts.includes(line), `page ${at + 1}: "${line}" is drawn in full`);
}
assert.ok(texts.includes("FINAL NOTICE"), "the stamp reads FINAL NOTICE");
assert.ok(SCENE_H > 20 && SCENE_H < 40, "the scene keeps to the top of the field");
// The art alone, with no ending: draws nothing and does not throw.
const art = endingArt({ label() {}, GOLD: "#fc0", BONE: "#eee" });
art.card(fakeCtx([]), { round: { ending: null } });
});
test("Ghoul Rush ending: every event it raises has a react, its own react answers only its own events, and every tone it owns is a real, prefixed sound", () => {
const round = toEnding();
const s = round.ending;
for (let at = 0; at < PAGES.length; at++) {
s.page = at;
s.ms = 0;
s.cue = 0;
s.full = false;
stepEnding(round, 10000);
s.arm = 0;
takeEnding(round);
}
skipEnding(round);
const kinds = new Set(round.events.map((e) => e.type));
for (const kind of ["endingPage", "storyTone", "won"]) assert.ok(kinds.has(kind), `${kind} is raised`);
const played = [];
const marks = [];
const fx = { tone: (n) => played.push(n), burst() {}, float() {}, ring() {}, banner: () => ({}), shake() {}, flash() {}, glow() {}, splat() {}, fx: { clock: 0, banners: [] }, markFurthest: (n) => marks.push(n), roomBanner() {}, monsters: {}, powers: {}, bosses: {}, g: ghoul };
for (const e of round.events) {
if (!["endingPage", "storyTone", "won"].includes(e.type)) continue;
react(e, fx);
}
assert.ok(played.includes("ghoulStoryPage"), "a page turn plays its rustle");
assert.ok(played.includes("ghoulEndingWindow") && played.includes("ghoulEndingGag"), "the timed tones play through the story's own event");
assert.deepEqual(marks, [ghoul.RUN_STAGES + 1], "the win marks the House beaten");
const art = endingArt({ label() {}, GOLD: "#fc0", BONE: "#eee" });
const k = { tone() {} };
assert.equal(art.react({ type: "endingPage", page: 1 }, k), true);
for (const type of ["won", "storyTone", "storyPage", "kill", "hit", "room"]) assert.equal(art.react({ type }, k), false, `${type} is not its own`);
const own = Object.keys(ghoulSfx.tones).filter((n) => n.startsWith("ghoulEnding"));
assert.ok(own.length >= 10, "a handful of the ending's own tones");
for (const p of PAGES) for (const [, name] of p.cues) assert.ok(isTone(name), `${name} exists`);
const track = ghoulSfx.music[ENDING_TRACK];
assert.ok(track, "the ending's track is in the game's music");
const song = compileTrack(track);
assert.ok(song.length >= 64, "it runs a few bars");
// The user's pick (eighties horror end credits): a steady middle tempo, never a race.
assert.ok(track.bpm >= 84 && track.bpm <= 120, "a middle tempo");
assert.equal(track.rush || 0, 0, "it never races");
});
@@ -0,0 +1,705 @@
// Web console tests, Ghoul Rush's finale, Kill II, Every Room at Once (the dollhouse): the room
// agrees with the rules' house, the boss's box out of reach and always guarded, the Eye (a lamp
// flares first, it opens, never twice running in one room, hit only through its open box from its
// own floor, a clank while it flares or shuts, two lamps and one true in its last phase), the
// shades (the keepers beaten this run, a fixed three in practice, every stage's boss with a move,
// a door first, at most SHADE_CAP, each move telegraphed, costing a life with its own cause and
// dodged), the lurch (a creak first, YOU slid and stopped at the end walls, a dresser to jump or
// shoot apart), the kill and its retreat in order with the door kept until it has gone, a bot's
// fight length, the voices, words and drawing.
// Run with: node --test scripts/test-web-console-activities-ghoul-eye.mjs
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
import * as ey from "../src/web-console/public/activities/ghoul-rush/stages/marrow/ghoul-marrow-eye.js";
import { LOOKS, LOSE_SOUNDS, LOSE_WORDS, VOICES } from "../src/web-console/public/activities/ghoul-rush/stages/marrow/ghoul-marrow-eye-draw.js";
import { react } from "../src/web-console/public/activities/ghoul-rush/draw/ghoul-draw.js";
import { bossIntroFor } from "../src/web-console/public/activities/ghoul-rush/story/ghoul-boss-intros.js";
import { toneNames } from "../src/web-console/public/tones.js";
const steady = () => 0.5;
const events = (round, type) => round.events.filter((e) => e.type === type);
const seededRandom = (seed) => {
let s = seed;
return () => (s = (s * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;
};
function stubCanvas() {
const calls = { count: 0 };
const ctx = new Proxy({}, {
get: (target, name) => (name in target ? target[name] : () => { calls.count += 1; }),
set: (target, name, value) => { target[name] = value; return true; },
});
return { canvas: { width: 0, height: 0, getContext: () => ctx }, calls, ctx };
}
function through(round) {
round.phase = "clear";
round.phaseMs = 1;
ghoul.advance(round, 4, steady);
}
function skipCard(round) {
round.introMs = ghoul.INTRO_MIN_MS;
return ghoul.takeIntro(round);
}
// YOU standing on the floor `row` (0 to 2) at x, or on a shelf by index.
function standAt(round, x, row = 0) {
const y = ey.EYE_FLOORS[row];
const shelf = row ? round.spec.shelves.findIndex(([a, b, top]) => top === y && b - a > 20) : -1;
Object.assign(round.you, { x, y, vx: 0, vy: 0, state: "run", shelf, coyote: 0, drop: -1, cuttable: false, out: 0, safeMs: 0, face: 1, ducking: false });
}
function run(round, ms, keys = {}, random = steady) {
Object.assign(round.input, keys);
for (let t = 0; t < ms; t += 4) ghoul.advance(round, 4, random);
for (const k of Object.keys(keys)) round.input[k] = false;
}
// A run's way to the dollhouse: the finale entered at `depth` stages, on through its rooms to
// this one, its boss's card passed, nothing else woken.
function eyeRound(depth = ghoul.RUN_STAGES) {
const round = ghoul.newRound(5);
round.dice = 0;
through(round);
round.cleared = ghoul.STAGES.slice(0, depth).map((st) => st.id);
round.offer = null;
through(round);
for (let n = 0; round.spec.id !== "dollhouse"; n++) {
assert.ok(n < 10, "the dollhouse is in the finale");
skipCard(round);
skipCard(round);
through(round);
}
skipCard(round);
round.phase = "play";
round.items.fill(true);
round.candy.fill(true);
round.events.length = 0;
return round;
}
// Nothing coming: the Eye shut a long while, no lurch, no door, no shade.
function calm(round) {
const b = round.boss;
Object.assign(b.eye, { state: "shut", ms: 1e9, room: -1, decoy: -1 });
Object.assign(b.lurch, { state: "wait", ms: 1e9 });
b.shadeMs = 1e9;
round.hazards.length = 0;
round.monsters.length = 0;
}
// The fight under way: YOU in the arena, the boss awake, everything calm.
function eyeFight(depth = ghoul.RUN_STAGES) {
const round = eyeRound(depth);
standAt(round, round.spec.arena + 14);
run(round, ghoul.BOSS_INTRO_MS + 100);
assert.equal(round.boss.state, "fight");
calm(round);
round.events.length = 0;
return round;
}
// The Eye opened now in room `i`.
function openIn(round, i) {
Object.assign(round.boss.eye, { state: "open", ms: 1e9, full: 4000, room: i, decoy: -1 });
}
/* --------------------------------------------------------------- the house */
test("Ghoul Rush's dollhouse: the room agrees with the rules' house, comes after the lawn and the mat in the finale, and its boss is the Eye, named on its card", () => {
const base = ghoul.roomById("dollhouse");
assert.equal(base.boss, "marroweye");
const rooms = ghoul.FINALE.rooms;
assert.ok(rooms.indexOf("dollhouse") > rooms.indexOf("lawn"), "after the lawn");
if (rooms.includes("mat")) assert.ok(rooms.indexOf("dollhouse") > rooms.indexOf("mat"), "after the mat");
const spec = ghoul.roomFor("dollhouse");
assert.equal(spec.arena + ey.EYE_COLS * ey.EYE_ROOM_W, spec.length, "the rooms fill the arena");
assert.equal(ghoul.groundAt(spec, spec.arena + 1), ey.EYE_FLOORS[0]);
for (const f of ey.EYE_FLOORS.slice(1)) assert.ok(spec.shelves.some(([a, b, y]) => y === f && a === spec.arena && b === spec.length), `a floor right across at ${f}`);
// A landing between each floor at each end, a jump from each to the next.
for (const [lo, hi] of [[ey.EYE_FLOORS[0], ey.EYE_FLOORS[1]], [ey.EYE_FLOORS[1], ey.EYE_FLOORS[2]]]) {
const landings = spec.shelves.filter(([a, b, y]) => b - a < 20 && y > lo && y < hi);
assert.equal(landings.length, 2, `two landings between ${lo} and ${hi}`);
for (const [, , y] of landings) assert.ok(y - lo <= ghoul.JUMP_TOP - 1 && hi - y <= ghoul.JUMP_TOP - 1, "a jump up to it and on");
}
assert.equal(ghoul.BOSSES.marroweye.name, bossIntroFor("marroweye").name);
assert.ok(LOOKS.dollhouse, "a look");
});
test("Ghoul Rush's dollhouse: the Eye's box is out of everything's reach and always guarded, a lost life keeps its hp, and the fight never costs a life by its box's touch", () => {
const round = eyeFight();
const b = round.boss;
assert.equal(ghoul.guarded(b), true);
assert.ok(b.y > ghoul.FIELD_H, "its box above the field");
assert.equal(b.max, round.spec.bossHp);
b.hp -= 10;
round.lives = 5;
ghoul.lose(round, "eyeRock");
run(round, ghoul.CRASH_MS + ghoul.READY_MS + 100);
assert.notEqual(round.boss, b, "a new boss object after the life lost");
assert.equal(round.boss.hp, b.hp, "the same hp");
// A climb to the top floor and back, under the box's x: no touch.
const r = eyeFight();
for (const row of [0, 1, 2]) {
standAt(r, r.spec.length - 2, row);
jumpUp(r);
run(r, 900);
}
assert.deepEqual(events(r, "lose"), []);
});
/* ----------------------------------------------------------------- the Eye */
test("Ghoul Rush's dollhouse: a lamp flares before the Eye opens (a second step heard), it opens in that room, shuts, and never opens in the same room twice running; its open time shrinks with its phase", () => {
const round = eyeFight();
const b = round.boss;
Object.assign(b.eye, { state: "shut", ms: 1 });
const order = [];
const random = ghoul.seeded(17);
for (let t = 0; t < 420000; t += 4) {
round.you.safeMs = 1e9;
b.shadeMs = 1e9;
b.lurch.ms = 1e9;
ghoul.advance(round, 4, random);
for (const e of round.events) if (e.type.startsWith("eye")) order.push([e.type, e.room, t]);
round.events.length = 0;
round.hazards.length = 0;
round.monsters.length = 0;
}
const flares = order.filter(([type]) => type === "eyeFlare");
const opens = order.filter(([type]) => type === "eyeOpen");
assert.ok(opens.length >= 10, `it opened many times (${opens.length})`);
for (let i = 0; i < opens.length; i++) {
const f = flares[i];
assert.equal(f[1], opens[i][1], "it opens where its lamp flared");
assert.ok(opens[i][2] - f[2] >= ey.EYE_FLARE_MS - 8, "after the whole flare");
if (i) assert.notEqual(opens[i][1], opens[i - 1][1], "never the same room twice running");
}
const steps = order.filter(([type]) => type === "eyeFlareStep").length;
assert.ok(steps >= opens.length && steps <= flares.length, "one step heard each flare");
assert.ok(ey.EYE_OPEN_MS[0] > ey.EYE_OPEN_MS[1] && ey.EYE_OPEN_MS[1] > ey.EYE_OPEN_MS[2], "shorter open each phase");
assert.equal(new Set(opens.map(([, room]) => room)).size, ey.EYE_ROOMS, "every room gets its turn");
});
test("Ghoul Rush's dollhouse: in its last phase two lamps flare and only one is true; the other pops out as the Eye opens", () => {
const round = eyeFight();
const b = round.boss;
b.hp = Math.floor(b.max * ey.PHASE_HP[1]) - 1;
assert.equal(ey.phaseOf(b), 2);
Object.assign(b.eye, { state: "shut", ms: 1 });
run(round, 8);
const flares = events(round, "eyeFlare");
assert.equal(flares.length, 2);
assert.equal(flares.filter((e) => e.decoy).length, 1);
assert.notEqual(flares[0].room, flares[1].room);
round.events.length = 0;
run(round, ey.EYE_FLARE_MS + 20);
assert.equal(events(round, "eyeOpen")[0].room, flares.find((e) => !e.decoy).room, "the true one opens");
assert.equal(events(round, "eyeDud")[0].room, flares.find((e) => e.decoy).room, "the false one pops out");
});
test("Ghoul Rush's dollhouse: the open Eye is hurt from its own floor by a bolt standing or ducked, from either side, never from another floor; flaring or shutting it clanks; shut, bolts pass", () => {
for (let i = 0; i < ey.EYE_ROOMS; i++) {
const r = ey.roomBox(eyeFight().spec, i);
for (const [side, duck] of [[-1, false], [1, true]]) {
const round = eyeFight();
openIn(round, i);
const x = Math.min(round.spec.length - 2, Math.max(round.spec.arena + 2, r.cx + side * 12));
standAt(round, x, r.row);
round.you.face = -side;
const hp = round.boss.hp;
run(round, 500, { fire: true, down: duck });
assert.ok(round.boss.hp < hp, `room ${i} from the ${side < 0 ? "left" : "right"}${duck ? ", ducked" : ""}`);
assert.ok(events(round, "bossHit").every((e) => e.how === "eye" && Math.abs(e.x - r.cx) < 0.01), "the hit shows at the Eye");
// From the floor over it, nothing.
const other = eyeFight();
openIn(other, i);
standAt(other, x, (r.row + 1) % 3);
other.you.face = -side;
run(other, 500, { fire: true });
assert.equal(other.boss.hp, other.boss.max, `room ${i}: not from another floor`);
}
}
for (const state of ["flare", "closing"]) {
const round = eyeFight();
Object.assign(round.boss.eye, { state, ms: 1e9, full: 1e9, room: 1 });
standAt(round, ey.roomBox(round.spec, 1).cx - 12);
run(round, 400, { fire: true });
assert.equal(round.boss.hp, round.boss.max, `${state}: no harm`);
assert.ok(events(round, "bossBlock").length > 0, `${state}: a clank`);
}
const shut = eyeFight();
standAt(shut, ey.roomBox(shut.spec, 1).cx - 12);
run(shut, 400, { fire: true });
assert.deepEqual([shut.boss.hp, events(shut, "bossBlock").length], [shut.boss.max, 0], "shut: bolts fly on");
});
/* -------------------------------------------------------------- the shades */
test("Ghoul Rush's dollhouse: every boss of every stage has a shade's move, a run's shades are the keepers it beat, and practice meets a fixed three", () => {
for (const st of ghoul.STAGES) assert.ok(ey.SHADE_MOVES[st.boss], `${st.boss} (${st.id}) has a shade move`);
for (const of of Object.keys(ey.SHADE_MOVES)) assert.ok(ghoul.BOSSES[of], `${of} is a boss`);
const round = eyeRound();
assert.deepEqual(ey.shadesOf(round, { stageById: ghoul.stageById }), round.cleared.map((id) => ghoul.stageById(id).boss));
assert.deepEqual(ey.shadesOf({ cleared: [] }, { stageById: ghoul.stageById }), [...ey.PRACTICE_SHADES]);
assert.equal(ey.PRACTICE_SHADES.length, 3);
});
test("Ghoul Rush's dollhouse: a door creaks open before its shade steps out, the shade fades in harmless and unhittable, never more than SHADE_CAP, and it fades away at the end of its life", () => {
const round = eyeFight();
const b = round.boss;
round.you.safeMs = 1e9;
b.shadeMs = 0;
run(round, 8);
assert.equal(events(round, "eyeDoor").length, 1, "the door first");
assert.equal(round.monsters.length, 0, "no shade yet");
const door = round.hazards.find((h) => h.kind === "eyeDoorway");
assert.ok(door && round.boss.lastShade === door.of && ey.shadesOf(round, { stageById: ghoul.stageById }).includes(door.of));
run(round, ey.EYE_DOOR_MS);
const m = round.monsters.find((q) => q.kind === "eyeShade");
assert.ok(m, "out steps a shade");
assert.equal(ghoul.solid(m), false, "fading in");
assert.ok(Math.abs(m.x - round.you.x) >= ey.SHADE_CLEAR / 2 || m.y !== round.you.y, "not on top of YOU");
run(round, ey.SHADE_IN_MS + 20);
assert.equal(ghoul.solid(m), true, "then solid");
for (let t = 0; t < 20000; t += 4) {
round.you.safeMs = 1e9;
ghoul.advance(round, 4, steady);
const alive = round.monsters.filter((q) => q.kind === "eyeShade").length + round.hazards.filter((h) => h.kind === "eyeDoorway").length;
assert.ok(alive <= ey.SHADE_CAP[ey.phaseOf(round.boss)], "never past the cap");
}
assert.ok(!round.monsters.includes(m), "gone at the end of its life");
const g = eyeFight();
g.you.safeMs = 1e9;
g.boss.shadeMs = 0;
run(g, 8);
g.boss.shadeMs = 1e9;
run(g, ey.EYE_DOOR_MS + ey.SHADE_LIFE_MS + 100);
assert.equal(g.monsters.length, 0, "a shade left alone fades by itself");
assert.equal(events(g, "eyeShadeOut").length, 1);
});
// A shade of `of` put in at x on YOUR floor, out and ready to move at once.
function shadeAt(round, of, x, row = 0) {
const y = ey.EYE_FLOORS[row];
round.hazards.push({ kind: "eyeDoorway", x, y, w: 3, h: 5, warn: 1, full: 1, live: 0, of, cause: "marroweye" });
run(round, 4);
const m = round.monsters.find((q) => q.kind === "eyeShade" && q.of === of);
Object.assign(m, { act: "idle", wait: 0, life: 1e9 });
round.events.length = 0;
return m;
}
// A full jump: the press, and up held (it stays held: holding it does nothing else) so it is not cut short.
const jumpUp = (r) => {
r.input.jump = ghoul.JUMP_BUFFER_MS;
r.input.up = true;
};
// How YOU dodge each move, called each slice: the shade `m`.
const floorThings = new Set(["eyeRipple", "eyeNote", "eyeHoop", "eyeMud"]);
const DODGE = {
hop: (r) => {
if (r.hazards.some((h) => floorThings.has(h.kind) && Math.abs(h.x - r.you.x) < 2 + h.speed * r.spec.pace * 0.1 && Math.sign(r.you.x - h.x) === h.dir)) jumpUp(r);
},
skull: (r) => {
r.input.down = r.hazards.some((h) => h.kind === "eyeSkull" && Math.abs(h.x - r.you.x) < 6);
},
creep: (r, m) => {
r.you.face = Math.sign(m.x - r.you.x) || 1;
},
scythe: (r) => {
if (r.hazards.some((h) => h.kind === "eyeScythe" && h.warn > 0 && h.warn < 100)) jumpUp(r);
},
dash: (r, m) => {
if (m.going && Math.abs(m.x - r.you.x) < 8 && Math.sign(r.you.x - m.x) === m.dir) jumpUp(r);
},
// Off its mark, away from it, each time it marks YOU.
leap: (r, m) => {
if (m.act === "wind" && Math.abs(m.tx - r.you.x) < 4) {
const away = Math.sign(r.you.x - m.x) || 1;
const x = r.you.x + away * 8;
standAt(r, x > r.spec.arena + 3 && x < r.spec.length - 3 ? x : r.you.x - away * 8);
}
},
// Away from the knocker, out from under each rock marked at YOU.
knock: (r, m) => {
if (!r.hazards.some((q) => q.kind === "eyeRock" && q.warn > 0 && Math.abs(q.x - r.you.x) < 3)) return;
const away = Math.sign(r.you.x - m.x) || 1;
const x = r.you.x + away * 7;
standAt(r, x > r.spec.arena + 3 && x < r.spec.length - 3 ? x : r.you.x - away * 14);
},
// Back the way YOU came: the second icicle falls a step ahead.
icicles: (r) => {
if (!r.hazards.some((q) => q.kind === "eyeIcicle" && q.warn > 0 && Math.abs(q.x - r.you.x) < 2.5)) return;
const x = r.you.x - (r.you.face || 1) * 9;
standAt(r, x > r.spec.arena + 3 && x < r.spec.length - 3 ? x : r.you.x + (r.you.face || 1) * 15);
},
};
DODGE.note = DODGE.hop;
DODGE.hoop = DODGE.hop;
DODGE.mud = DODGE.hop;
const CAUSE = { hop: "eyeRipple", skull: "eyeSkull", creep: "eyeShade", scythe: "eyeScythe", note: "eyeNote", dash: "eyeShade", leap: ["eyePounce", "eyeShade"], knock: "eyeRock", hoop: "eyeHoop", icicles: "eyeIcicle", mud: "eyeMud" };
test("Ghoul Rush's dollhouse: each keeper's shade telegraphs its move before it can hurt, hurts standing YOU with its own cause, and is dodged", () => {
for (const st of ghoul.STAGES) {
const of = st.boss;
const move = ey.SHADE_MOVES[of];
const near = move === "scythe" ? 7 : move === "dash" || move === "leap" || move === "creep" ? 12 : 16;
const hit = eyeFight();
standAt(hit, 70);
const m = shadeAt(hit, of, 70 + near);
// The angel comes on only while YOU look away.
if (move === "creep") hit.you.face = -1;
const losses = [];
let told = Infinity;
for (let t = 0; t < 6000 && !losses.length; t += 4) {
ghoul.advance(hit, 4, steady);
if (events(hit, "eyeShadeWind").length && told === Infinity) told = t;
losses.push(...events(hit, "lose").map((e) => [e.cause, t]));
hit.events.length = 0;
}
assert.equal(losses.length, 1, `${of} (${move}): it hurts`);
assert.ok([CAUSE[move]].flat().includes(losses[0][0]), `${of} (${move}): as ${CAUSE[move]} (${losses[0][0]})`);
if (move !== "creep") assert.ok(losses[0][1] - told >= 600, `${of} (${move}): telegraphed well before (${losses[0][1] - told} ms)`);
const safe = eyeFight();
standAt(safe, 70);
const s = shadeAt(safe, of, 70 + near);
const lost = [];
for (let t = 0; t < 6000; t += 4) {
safe.input.down = false;
DODGE[move](safe, s);
ghoul.advance(safe, 4, steady);
lost.push(...events(safe, "lose").map((e) => e.cause));
safe.events.length = 0;
}
assert.deepEqual(lost, [], `${of} (${move}): dodged`);
assert.ok(m.hp > 0, "its hp");
}
});
test("Ghoul Rush's dollhouse: a shade takes bolts and dies for points, and endless lives spare every hit", () => {
const round = eyeFight();
standAt(round, 60);
const m = shadeAt(round, "gourd", 75);
m.wait = 1e9;
const score = round.score;
run(round, 2000, { fire: true });
assert.ok(!round.monsters.includes(m), "shot down");
assert.ok(events(round, "kill").some((e) => e.kind === "eyeShade"));
assert.ok(round.score > score);
const r = eyeFight();
r.infinite = true;
standAt(r, 70);
shadeAt(r, "keeper", 77);
const lives = r.lives;
run(r, 3000);
assert.ok(events(r, "lose").length >= 1, "hit");
assert.equal(r.lives, lives, "no life spent");
});
/* --------------------------------------------------------------- the lurch */
test("Ghoul Rush's dollhouse: the house creaks before it lurches, slides YOU while YOU stand (never in the air) and stops YOU at its end walls; a dresser comes down YOUR floor: jump it, or shoot it apart", () => {
const round = eyeFight();
const b = round.boss;
standAt(round, 70);
round.you.safeMs = 1e9;
Object.assign(b.lurch, { ms: 0 });
b.planLurch = 1;
run(round, 8);
assert.equal(events(round, "eyeCreak").length, 1, "a creak first");
assert.equal(round.you.x, 70, "nothing slides yet");
const dresser = round.hazards.find((h) => h.kind === "eyeDresser");
assert.ok(dresser && dresser.y === round.you.y && dresser.x < round.you.x, "a dresser uphill on YOUR floor");
run(round, ey.EYE_CREAK_MS);
assert.equal(events(round, "eyeLurch").length, 1);
const x = round.you.x;
run(round, 500);
assert.ok(round.you.x > x + 4, `slid (${(round.you.x - x).toFixed(1)})`);
standAt(round, round.spec.length - 2);
run(round, 800);
assert.ok(round.you.x <= round.spec.length - ey.WALL_PAD + 0.01, "held at the end wall");
// In the air, nothing pushes.
const air = eyeFight();
Object.assign(air.boss.lurch, { state: "go", ms: 1e9, dir: 1 });
standAt(air, 70);
Object.assign(air.you, { state: "air", vy: 0, y: 30, shelf: -1 });
const ax = air.you.x;
ghoul.advance(air, 4, steady);
assert.equal(air.you.x, ax);
// The dresser: it costs a life, a jump clears it, three bolts break it.
const go = () => {
const r = eyeFight();
standAt(r, 64);
r.boss.lurch.ms = 0;
r.boss.planLurch = 1;
run(r, 8);
return r;
};
const hit = go();
let lost = [];
for (let t = 0; t < 5000 && !lost.length; t += 4) {
ghoul.advance(hit, 4, steady);
lost = events(hit, "lose").map((e) => e.cause);
hit.events.length = 0;
}
assert.deepEqual(lost, ["eyeDresser"]);
const jump = go();
for (let t = 0; t < 5000; t += 4) {
const d = jump.hazards.find((h) => h.kind === "eyeDresser" && h.live > 0);
if (d && jump.you.x - d.x < 8 && jump.you.x > d.x) jumpUp(jump);
ghoul.advance(jump, 4, steady);
assert.deepEqual(events(jump, "lose"), [], "jumped");
jump.events.length = 0;
}
const shoot = go();
shoot.you.face = -1;
run(shoot, 2500, { fire: true });
assert.equal(events(shoot, "eyeDresserSmash").length, 1, "shot apart");
assert.deepEqual(events(shoot, "lose"), []);
});
/* ---------------------------------------------------------------- the kill */
test("Ghoul Rush's dollhouse: the last bolt in the Eye is a boss kill; its retreat plays once and in order; the door is kept from YOU until it has gone, then leads on", () => {
const round = eyeFight();
const b = round.boss;
b.hp = 1;
openIn(round, 1);
standAt(round, ey.roomBox(round.spec, 1).cx - 12);
const lives = round.lives;
run(round, 400, { fire: true });
assert.equal(b.state, "down");
assert.equal(round.lives, lives + 1, "a life, as every boss gives");
assert.equal(round.hasKey, true);
const order = [];
for (let t = 0; t < ey.GONE_AT + 1500 && round.phase !== "clear"; t += 4) {
standAt(round, round.spec.door);
round.input.right = true;
ghoul.advance(round, 4, steady);
for (const e of round.events) if (e.type.startsWith("eye")) order.push([e.type, Math.round(b.t)]);
round.events.length = 0;
if (!b.gone) assert.ok(round.you.x <= round.spec.door - ey.DOOR_KEEP + 0.2, "no door until it has gone");
}
assert.deepEqual(order.map(([t]) => t), ["eyeBurst", "eyePeel", "eyeCrack", "eyeCrack", "eyeCrack", "eyeGasp", "eyeSink", "eyeGone"]);
assert.ok(order[1][1] >= ey.PEEL_AT && order.at(-1)[1] >= ey.GONE_AT, "on the retreat's clock");
assert.equal(b.gone, true);
assert.equal(round.phase, "clear", "down its stairway of bones");
const next = ghoul.FINALE.rooms[ghoul.FINALE.rooms.indexOf("dollhouse") + 1];
run(round, ghoul.CLEAR_MS + 50);
if (next) assert.equal(round.spec.id, next, "on to the next room");
else assert.equal(round.won, true, "or the win while it is the last");
});
/* --------------------------------------------------------------- the fight */
// A steady player: when a lamp flares it goes to that room's floor (CLIMB_MS a floor, firing nothing
// on the way: the bot is put there after), stands a way off the Eye facing it and fires while it is
// open; jumps what runs along its floor, the dresser, a dashing shade; ducks a skull; steps out from
// under a rock, an icicle or a beast's mark; and shoots what shade is on its floor while the Eye is shut.
const CLIMB_MS = 1500;
function fight(seed, skilled = true) {
const round = eyeFight();
const random = seededRandom(seed);
Object.assign(round.boss.eye, { state: "shut", ms: 600 });
round.boss.lurch.ms = ey.EYE_LURCH_FIRST_MS;
round.boss.shadeMs = ey.SHADE_FIRST_DOOR_MS;
let at = 0;
let travel = 0;
let t = 0;
const causes = [];
const spec = round.spec;
for (; t < 300000 && round.boss.state !== "down" && !round.over; t += 4) {
const you = round.you;
const inp = round.input;
const b = round.boss;
inp.left = inp.right = inp.fire = inp.down = false;
if (round.phase === "ask") ghoul.answerDie(round, false);
if (skilled && round.phase === "play" && you.out <= 0 && you.state === "run") {
const row = ey.rowOf(you.y);
const level = (h) => Math.abs(h.y - ey.EYE_FLOORS[row]) < 0.5;
const runner = round.hazards.find((h) => (floorThings.has(h.kind) || h.kind === "eyeDresser") && h.live > 0 && level(h) && Math.abs(h.x - you.x) < 3 + (h.speed || ey.DRESSER_SPEED) * 0.13 && Math.sign(you.x - h.x) === (h.dir || 1));
const scythe = round.hazards.find((h) => h.kind === "eyeScythe" && level(h) && h.warn > 0 && h.warn < 100 && Math.abs(h.x - you.x) < h.w / 2 + 2);
const dasher = round.monsters.find((m) => m.kind === "eyeShade" && m.going && m.move === "dash" && Math.abs(m.floor - you.y) < 0.5 && Math.abs(m.x - you.x) < 7);
const skull = round.hazards.find((h) => h.kind === "eyeSkull" && Math.abs(h.y - ey.SKULL_UP - you.y) < 0.5 && Math.abs(h.x - you.x) < 6);
const above = round.hazards.find((h) => (h.kind === "eyeRock" || h.kind === "eyeIcicle") && h.warn > 0 && Math.abs(h.floor - you.y) < 0.5 && Math.abs(h.x - you.x) < 3);
const mark = round.monsters.find((m) => m.kind === "eyeShade" && m.move === "leap" && (m.act === "wind" || m.going) && Math.abs(m.floor - you.y) < 0.5 && Math.abs(m.tx - you.x) < 4);
const e = b.eye;
if (runner || scythe || dasher) jumpUp(round);
else if (skull) inp.down = true;
else if (above || mark) {
const from = above ? above.x : mark.tx;
const dir = from >= you.x ? -1 : 1;
inp[you.x + dir * 4 < spec.arena + 2 || you.x + dir * 4 > spec.length - 2 ? (dir < 0 ? "right" : "left") : dir < 0 ? "left" : "right"] = true;
} else if (travel > 0) travel -= 4;
else if (e && e.room >= 0 && e.state !== "shut") {
const r = ey.roomBox(spec, e.room);
if (r.row !== at) {
travel = CLIMB_MS * Math.abs(r.row - at);
at = r.row;
} else {
const side = r.cx - 13 > spec.arena + 2 ? -1 : 1;
const x = r.cx + side * 13;
if (row !== r.row || Math.abs(you.x - x) > 5) standAt(round, x, r.row);
you.face = -side;
inp.fire = e.state === "open";
}
} else {
const m = round.monsters.find((q) => q.kind === "eyeShade" && ghoul.solid(q) && Math.abs(q.floor - you.y) < 0.5 && Math.abs(q.x - you.x) < 40);
if (m) {
you.face = Math.sign(m.x - you.x) || you.face;
inp.fire = true;
}
}
}
ghoul.advance(round, 4, random);
causes.push(...events(round, "lose").map((e) => e.cause));
round.events.length = 0;
}
return { won: round.boss.state === "down", secs: t / 1000, causes, round };
}
test("Ghoul Rush's dollhouse takes a steady player a real fight at full depth: 60 to 120 seconds on most seeds, with lives to spare; a player who stands still dies", () => {
const times = [];
const lives = [];
let good = 0;
for (const seed of [3, 7, 19, 41]) {
const f = fight(seed);
assert.ok(f.won, `seed ${seed}: it fell (${f.causes}; ${f.secs.toFixed(1)} s, hp ${f.round.boss.hp})`);
assert.ok(f.round.lives > 0, `seed ${seed}: lives to spare (${f.causes})`);
for (const c of f.causes) assert.ok(LOSE_WORDS[c] || ghoul.MONSTERS[c], `${c} is the House's or one of the dead`);
if (process.env.EYE_DEBUG) console.log(`seed ${seed}: ${f.won ? "won" : "lost"} in ${f.secs.toFixed(1)} s, lives ${f.round.lives}, ${f.causes}`);
if (f.secs >= 60 && f.secs <= 120) good++;
times.push(f.secs);
lives.push(f.round.lives);
}
assert.ok(good >= 3, `most seeds in 60 to 120 s (${times.map((x) => x.toFixed(1))}; lives ${lives})`);
const idle = fight(7, false);
assert.equal(idle.won, false);
assert.ok(idle.round.over, `game over (${idle.causes})`);
assert.equal(idle.round.boss.hp, idle.round.boss.max, "and not a scratch on it");
});
/* ------------------------------------------------- voices, words, drawing */
const heard = (e) => {
const played = [];
const noop = () => {};
const kit = { tone: (name) => played.push(name), burst: noop, float: noop, ring: noop, banner: () => null, shake: noop, flash: noop, glow: noop, splat: noop, fx: { clock: 1e6, splats: [] }, monsters: ghoul.MONSTERS, powers: ghoul.POWERS, bosses: ghoul.BOSSES, g: {}, floorAt: () => 6, markFurthest: noop };
react(e, kit);
return played;
};
test("Ghoul Rush's Eye: a voice for every act in tones.js, every event plays its own sound once, and every cause has words and a sound", () => {
const known = new Set(toneNames());
for (const kind of ["marroweye", "eyeShade"]) for (const [act, name] of Object.entries(VOICES[kind])) assert.ok(known.has(name), `${kind} ${act}: ${name} is a tone`);
const eye = { marroweye: { eyeFlare: "flare", eyeFlareStep: "flareStep", eyeOpen: "open", eyeShut: "shut", eyeDud: "dud", eyeDoor: "door", eyeCreak: "creak", eyeCreakStep: "creakStep", eyeLurch: "lurch", eyeDresserCrash: "crash", eyeDresserSmash: "smash", eyeBurst: "burst", eyePeel: "peel", eyeCrack: "crack", eyeGasp: "gasp", eyeSink: "sink", eyeGone: "gone", bossWake: "wake", bossHit: "hurt", bossDown: "die" }, eyeShade: { eyeShadeIn: "come", eyeShadeOut: "fade", eyeShadeWind: "wind", eyeShadeSlam: "slam", eyeSkullThrow: "throw", eyeShadeGrind: "grind", eyeScythe: "scythe", eyeNote: "note", eyeShadeDash: "dash", eyeShadeLeap: "leap", eyePounce: "pounce", eyeKnock: "knock", eyeRockLand: "rock", eyeHoop: "hoop", eyeIcicleLand: "icicle", eyeMud: "mud", hit: "hurt", kill: "die" } };
for (const [kind, cases] of Object.entries(eye)) {
for (const [type, act] of Object.entries(cases)) {
const played = heard({ type, kind, x: 80, y: 20, xs: [70], ty: 20, tx: 70, at: 70, n: 1, dir: 1, move: "hop", how: "eye", points: 1, mult: 1, life: true });
assert.equal(played.filter((n) => n === VOICES[kind][act]).length, 1, `${type}: ${VOICES[kind][act]} once`);
}
}
// Every event the rules push is one of those.
const pushed = new Set();
const round = eyeFight();
round.you.safeMs = 1e9;
round.boss.hp = Math.floor(round.boss.max * 0.3);
Object.assign(round.boss.eye, { state: "shut", ms: 1 });
round.boss.lurch.ms = 0;
round.boss.shadeMs = 0;
const random = seededRandom(9);
for (let t = 0; t < 60000; t += 4) {
round.you.safeMs = 1e9;
ghoul.advance(round, 4, random);
for (const e of round.events) if (e.type.startsWith("eye")) pushed.add(e.type);
round.events.length = 0;
}
const all = new Set([...Object.keys(eye.marroweye), ...Object.keys(eye.eyeShade), "eyeSkullTurn"]);
for (const type of pushed) assert.ok(all.has(type), `${type} has a reaction`);
for (const cause of ["marroweye", "eyeShade", "eyeRipple", "eyeSkull", "eyeScythe", "eyeNote", "eyePounce", "eyeRock", "eyeHoop", "eyeIcicle", "eyeMud", "eyeDresser"]) {
assert.ok(LOSE_WORDS[cause], `${cause}: words`);
assert.ok(known.has(LOSE_SOUNDS[cause][0]), `${cause}: a sound`);
}
});
test("Ghoul Rush's dollhouse draws: the landing, the fight with the Eye in every state, every keeper's shade and move, the lurch, every beat of the retreat, lit and dark, and its card with the card's fake view", () => {
const { canvas, calls, ctx } = stubCanvas();
const g = ghoul.default.create({ canvas });
g.resize(900, 900);
g.stageSelect();
for (let i = 0; i < ghoul.SELECTABLE.length; i++) g.key("down");
for (let i = 0; i < ghoul.FINALE.rooms.indexOf("dollhouse"); i++) g.key("right");
g.key("action");
for (let n = 0; n < 2 && g.round.phase !== "ready"; n++) {
for (let ms = 0; ms < ghoul.INTRO_MIN_MS + 50; ms += 16) g.tick(16);
g.key("action");
}
const r = g.round;
assert.equal(r.spec.id, "dollhouse");
r.infinite = true;
const frame = (label) => {
const before = calls.count;
g.tick(16);
assert.ok(calls.count > before, `${label} draws`);
};
for (const dark of [false, true]) {
r.dark = dark;
standAt(r, 10);
frame("the landing");
standAt(r, r.spec.arena + 14);
// The House's intro runs a seed-dependent while: tick until its Eye exists, not a fixed time.
for (let ms = 0; ms < 1600 || (!r.boss.eye && ms < 20000); ms += 16) g.tick(16);
for (const [state, decoy] of [["flare", -1], ["flare", 6], ["open", -1], ["closing", -1], ["shut", -1]]) {
Object.assign(r.boss.eye, { state, ms: 300, full: 1000, room: 4, decoy });
frame(`the Eye ${state}`);
}
for (const st of ghoul.STAGES) {
Object.assign(r, { phase: "play" });
Object.assign(r.you, { out: 0, safeMs: 1e9 });
shadeAt(r, st.boss, 90, 1);
for (let ms = 0; ms < 1500; ms += 16) frame(`${st.boss}'s shade`);
r.monsters.length = 0;
r.hazards.length = 0;
}
Object.assign(r.boss.lurch, { state: "creak", ms: 300 });
r.boss.planLurch = 1;
for (let ms = 0; ms < 2000; ms += 16) frame("the lurch");
for (const t of [100, ey.PEEL_AT + 300, ey.CRACK_AT[2] + 100, ey.GASP_AT + 200, ey.SINK_AT + 900, ey.GONE_AT + 100]) {
Object.assign(r.boss, { state: "down", t, gone: t >= ey.GONE_AT });
frame(`the retreat at ${t}`);
}
Object.assign(r.boss, { state: "fight", t: 0, gone: false });
}
// The card draws the boss with its own fake view: no round, no spec, FIELD_H 0.
const before = calls.count;
g.stageSelect();
for (let i = 0; i < ghoul.SELECTABLE.length; i++) g.key("down");
for (let i = 0; i < ghoul.FINALE.rooms.indexOf("dollhouse"); i++) g.key("right");
g.key("action");
assert.equal(g.round.phase, "bossintro");
for (let ms = 0; ms < 3000; ms += 100) {
g.round.introMs = ms;
g.tick(1);
}
assert.ok(calls.count > before, "the card draws");
});
test("Ghoul Rush's Eye draws on its card through its own art with the card's fake view, and every shade through its keeper's", async () => {
const { eyeArt } = await import("../src/web-console/public/activities/ghoul-rush/stages/marrow/ghoul-marrow-eye-draw.js");
const { ctx } = stubCanvas();
const noop = () => {};
let borrowed = 0;
const art = eyeArt({ ellipse: noop, circle: noop, roundRect: noop, line: noop, rotate: noop, eye: noop, hash: (a, b) => Math.abs(a * 31 + b) % 997, say: noop, gate: () => true, label: noop, bossArt: () => () => borrowed++, DANGER: "#f00", GOLD: "#fc0" });
const v = { g: { FIELD_H: 0 }, clock: 1000, spec: null, groundAt: () => 0, eyes: [] };
const b = { kind: "marroweye", x: 0, y: 0, w: 30, h: 30, hurt: 0, dir: -1, state: "fight", t: 0, hp: 1, max: 1 };
assert.doesNotThrow(() => art.bosses.marroweye(ctx, v, b));
const game = { g: { FIELD_H: 54 }, clock: 1000, spec: ghoul.roomFor("dollhouse"), round: {}, bosses: ghoul.BOSSES, eyes: [] };
for (const st of ghoul.STAGES) art.monsters.eyeShade(ctx, game, { of: st.boss, act: "idle", wait: 0, dir: 1, move: ey.SHADE_MOVES[st.boss], floor: 6, y: 6 }, 60, 48, 0, false);
assert.equal(borrowed, ghoul.STAGES.length, "each shade drawn through its keeper's art");
});
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's Frozen Lake stage: its rooms (Ice Fishing Huts, Snowbound Lodge, The Black Ice, the Widow's Web), slippery ice and thin ice that cracks and breaks, under-ice hands, snow shades you only see by their footprints, frozen ghouls that slide and shatter, ice wraiths whose dive leaves you frozen, Hot Cocoa and the Road Flare (found only here), and the Frost Widow, whose veil melts only to a burning barrel or a flare. // Web console tests, Ghoul Rush's Frozen Lake stage: its rooms (Ice Fishing Huts, Snowbound Lodge, The Black Ice, the Widow's Web), slippery ice and thin ice that cracks and breaks, under-ice hands, snow shades you only see by their footprints, frozen ghouls that slide and shatter, ice wraiths whose dive leaves you frozen, Hot Cocoa and the Road Flare (found only here), and the Frost Widow, whose veil melts only to a burning barrel or a flare.
import "./seed-random.mjs";
import { test } from "node:test"; import { test } from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js"; import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -818,7 +819,7 @@ test("Ghoul Rush's Frost Widow hangs from the roof with her veil up, three fire
const barrels = round.hazards.filter((h) => h.kind === "barrel"); const barrels = round.hazards.filter((h) => h.kind === "barrel");
assert.deepEqual(barrels.map((h) => h.x), fz.BARREL_SPOTS.map((o) => round.spec.arena + o)); assert.deepEqual(barrels.map((h) => h.x), fz.BARREL_SPOTS.map((o) => round.spec.arena + o));
assert.ok(barrels.every((h) => h.state === "still" && h.y === 6)); assert.ok(barrels.every((h) => h.state === "still" && h.y === 6));
assert.equal(ghoul.roomFor("widow", 7).bossHp, Math.round(90 * (1 + ghoul.BOSS_DEPTH_HP * 7))); assert.equal(ghoul.roomFor("widow", 7).bossHp, Math.round(90 * (1 + ghoul.BOSS_DEPTH_HP * Math.min(14, ghoul.BOSS_DEPTH_MAX))), "seven stages in counts as fourteen steps, capped");
// A shot at her glances off: the veil, and she is off the floor besides. // A shot at her glances off: the veil, and she is off the floor besides.
for (const [act, y] of [["hang", 26], ["low", 6]]) { for (const [act, y] of [["hang", 26], ["low", 6]]) {
Object.assign(b, { act, y, x: 170, wait: 1e9, lowMs: 1e9 }); Object.assign(b, { act, y, x: 170, wait: 1e9, lowMs: 1e9 });
@@ -1,8 +1,10 @@
// Web console tests, Ghoul Rush's game over: a lost end plays the mechanical laugh track (and a win does not), and the "G A M E - O V E R" banner drops in letter by letter and draws on a fake canvas. // Web console tests, Ghoul Rush's game over: a lost end plays the mechanical laugh track (and a win does not), and the "G A M E - O V E R" banner drops in letter by letter and draws on a fake canvas.
import "./seed-random.mjs";
import { test } from "node:test"; import { test } from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js"; import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
import { skipStory } from "../src/web-console/public/activities/ghoul-rush/story/ghoul-story.js"; import { skipStory } from "../src/web-console/public/activities/ghoul-rush/story/ghoul-story.js";
import { skipEnding } from "../src/web-console/public/activities/ghoul-rush/story/ghoul-ending.js";
import { dropAt, gameOverBanner, OVER_WORD } from "../src/web-console/public/activities/ghoul-rush/story/ghoul-gameover-draw.js"; import { dropAt, gameOverBanner, OVER_WORD } from "../src/web-console/public/activities/ghoul-rush/story/ghoul-gameover-draw.js";
import { toneNames } from "../src/web-console/public/tones.js"; import { toneNames } from "../src/web-console/public/tones.js";
@@ -23,9 +25,14 @@ function winRun(h) {
const r = h.round; const r = h.round;
through(r); through(r);
while (!r.over) { while (!r.over) {
// The ending's pages once the House is dead.
if (r.phase === "ending") {
skipEnding(r);
continue;
}
r.phaseMs = 0; r.phaseMs = 0;
ghoul.pickStage(r); ghoul.pickStage(r);
for (let k = 0; k < 4; k++) through(r); for (let k = 0; k < 4 && r.phase !== "ending" && !r.over; k++) through(r);
} }
} }
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's Graveyard stage: its four rooms, grasping hands, mourners and their wail, grave robbers, rotters and the legs they leave, carrion crows, the graves rotters climb out of, and Mother Mourning, who can only be hurt while she watches and drops a stone fist on whatever moves. // Web console tests, Ghoul Rush's Graveyard stage: its four rooms, grasping hands, mourners and their wail, grave robbers, rotters and the legs they leave, carrion crows, the graves rotters climb out of, and Mother Mourning, who can only be hurt while she watches and drops a stone fist on whatever moves.
import "./seed-random.mjs";
import { test } from "node:test"; import { test } from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js"; import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's Grounds stage: its four rooms, topiary beasts that creep only when your back is turned, rootlings under the lawn, lantern moths, mulch crawlers, the Hedge shears (found only here), and the Groundskeeper, whose lantern takes triple damage, whose scythe is jumped, whose fire burns the floor and who mounts a mower at half his hp. // Web console tests, Ghoul Rush's Grounds stage: its four rooms, topiary beasts that creep only when your back is turned, rootlings under the lawn, lantern moths, mulch crawlers, the Hedge shears (found only here), and the Groundskeeper, whose lantern takes triple damage, whose scythe is jumped, whose fire burns the floor and who mounts a mower at half his hp.
import "./seed-random.mjs";
import { test } from "node:test"; import { test } from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js"; import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,5 +1,6 @@
// Web console tests, Ghoul Rush's Code Blue (Blackmoor Sanatorium's bonus round, between the Surgical Theater and the Night Ward): its shape (every elevator shaft clears with a jump and swallows a gurney that does not jump, every low can be ducked, spacing, the surge lamps and the blackout waves, checkpoints, the clock), the gurney's speed on slopes, its jump, ducking, a wheelchair that rolls, an IV stand, a lamp or a door overhead, an orderly in a doorway, the surge lamp shot from the air, the lights-out rhythm (the countdown, the dark, the lights back), the heartbeat monitor, a fall down a shaft, the checkpoint, the jump off the end and the door, the bonus round's hearts and dice (3 to 9) and the clean-dark-stretches die, endless lives for every cause, a voice for every event, the drawing, and bots that ride the whole way (one that dodges well, one that never does). // Web console tests, Ghoul Rush's Code Blue (Blackmoor Sanatorium's bonus round, between the Surgical Theater and the Night Ward): its shape (every elevator shaft clears with a jump and swallows a gurney that does not jump, every low can be ducked, spacing, the surge lamps and the blackout waves, checkpoints, the clock), the gurney's speed on slopes, its jump, ducking, a wheelchair that rolls, an IV stand, a lamp or a door overhead, an orderly in a doorway, the surge lamp shot from the air, the lights-out rhythm (the countdown, the dark, the lights back), the heartbeat monitor, a fall down a shaft, the checkpoint, the jump off the end and the door, the bonus round's hearts and dice (3 to 9) and the clean-dark-stretches die, endless lives for every cause, a voice for every event, the drawing, and bots that ride the whole way (one that dodges well, one that never does).
// Run with: node --test scripts/test-web-console-activities-ghoul-gurney.mjs // Run with: node --test scripts/test-web-console-activities-ghoul-gurney.mjs
import "./seed-random.mjs";
import { test } from "node:test"; import { test } from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js"; import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,5 +1,6 @@
// Web console tests, Ghoul Rush's Midnight Hearse (the Graveyard's bonus round, between the Mausoleum Row and Angel's Rest): its shape (two lanes, the gates, every thing spaced for a player, the closed stretches with a gate before each), the hearse's motion (a steady speed, a jump, a duck, a hop between lanes only at a gate), each obstacle and its cost (grave, headstone, cross, branch, hand, crow, wreck), the lamp and its lanterns, the coffins thrown out and the ghouls that sit up in them, the hearts and the grade and the dice, endless lives, the drawing and the sounds, and bots that play it. // Web console tests, Ghoul Rush's Midnight Hearse (the Graveyard's bonus round, between the Mausoleum Row and Angel's Rest): its shape (two lanes, the gates, every thing spaced for a player, the closed stretches with a gate before each), the hearse's motion (a steady speed, a jump, a duck, a hop between lanes only at a gate), each obstacle and its cost (grave, headstone, cross, branch, hand, crow, wreck), the lamp and its lanterns, the coffins thrown out and the ghouls that sit up in them, the hearts and the grade and the dice, endless lives, the drawing and the sounds, and bots that play it.
// Run with: node --test scripts/test-web-console-activities-ghoul-hearse.mjs // Run with: node --test scripts/test-web-console-activities-ghoul-hearse.mjs
import "./seed-random.mjs";
import { test } from "node:test"; import { test } from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js"; import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -0,0 +1,577 @@
// Web console tests, Ghoul Rush's finale, Kill III, The Pit: the room (dark, a pit each side of the
// heart's plinth, the door at its end), the beat (its interval falling with hp, a wave each way on
// the dub, the ribs open only between beats: a bolt counts then and clanks otherwise), each move's
// warning seen and heard before it can hurt, its cost and its dodge, the beat stopping dead and the
// big double wave, the last hp no bolt can take and the HOLD FIRE flood that ends it (the meter,
// the weak beats that only knock it back, the white, the last thump, the fall, the daylight and its
// door), a life lost keeping it all, a bot's fight length at full depth, the voices, words and drawing.
// Run with: node --test scripts/test-web-console-activities-ghoul-heart.mjs
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
import * as hr from "../src/web-console/public/activities/ghoul-rush/stages/marrow/ghoul-marrow-heart.js";
import { LOSE_SOUNDS, LOSE_WORDS, VOICES, heartArt } from "../src/web-console/public/activities/ghoul-rush/stages/marrow/ghoul-marrow-heart-draw.js";
import { react } from "../src/web-console/public/activities/ghoul-rush/draw/ghoul-draw.js";
import { bossIntroFor } from "../src/web-console/public/activities/ghoul-rush/story/ghoul-boss-intros.js";
import { toneNames } from "../src/web-console/public/tones.js";
const steady = () => 0.5;
const events = (round, type) => round.events.filter((e) => e.type === type);
const seededRandom = (seed) => {
let s = seed;
return () => (s = (s * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;
};
function stubCanvas() {
const calls = { count: 0 };
const ctx = new Proxy({}, {
get: (target, name) => (name in target ? target[name] : () => { calls.count += 1; }),
set: (target, name, value) => { target[name] = value; return true; },
});
return { canvas: { width: 0, height: 0, getContext: () => ctx }, calls, ctx };
}
function standAt(round, x, shelf = -1) {
const y = shelf >= 0 ? round.spec.shelves[shelf][2] : ghoul.groundAt(round.spec, x);
Object.assign(round.you, { x, y, vx: 0, vy: 0, state: "run", shelf, coyote: 0, drop: -1, cuttable: false, out: 0, safeMs: 0, face: 1 });
}
function run(round, ms, keys = {}, random = steady) {
Object.assign(round.input, keys);
for (let t = 0; t < ms; t += 4) ghoul.advance(round, 4, random);
for (const k of Object.keys(keys)) round.input[k] = false;
}
// A run in the Pit, `depth` stages behind it, the finale's last room, nothing else awake.
function pitRound(depth = ghoul.RUN_STAGES) {
const round = ghoul.newRound(5);
round.dice = 0;
round.cleared = ghoul.STAGES.slice(0, depth).map((st) => st.id);
round.stage = ghoul.FINALE.id;
round.stageAt = ghoul.FINALE.rooms.indexOf("pit");
ghoul.setupRoom(round, "pit");
round.phase = "play";
round.items.fill(true);
round.candy.fill(true);
round.events.length = 0;
return round;
}
// The fight under way: in the arena, the heart awake, the next move a long way off.
function pitFight(depth = ghoul.RUN_STAGES) {
const round = pitRound(depth);
standAt(round, 100);
run(round, ghoul.BOSS_INTRO_MS + 100);
assert.equal(round.boss.state, "fight");
calm(round);
return round;
}
// Nothing coming: no move for a long while, no beat due, nothing on the field.
function calm(round) {
Object.assign(round.boss, { act: "idle", wait: 1e9, beatMs: -1e9, dubbed: true, opened: true, stopMs: 0, echo: 0 });
round.hazards.length = 0;
round.waves.length = 0;
round.events.length = 0;
}
// The ribs held open (or shut) a long while.
const holdOpen = (b) => Object.assign(b, { beatT: 1e9, beatMs: hr.OPEN_AT + 1, opened: true, dubbed: true });
const holdShut = (b) => Object.assign(b, { beatT: 1e9, beatMs: -1e9, opened: true, dubbed: true });
/* ------------------------------------------------------------ the room */
test("Ghoul Rush's Pit: the finale's last room, always dark, the heart's boss room with a pit each side of its plinth and the door at the end, and its card", () => {
assert.equal(ghoul.FINALE.rooms.at(-1), "pit");
const base = ghoul.roomById("pit");
assert.equal(base.boss, "marrowheart");
assert.equal(base.dark, true);
assert.ok(base.door > base.length - 14);
const spec = ghoul.roomFor("pit", ghoul.RUN_STAGES);
assert.equal(ghoul.groundAt(spec, hr.HEART_X), 6, "the plinth");
assert.equal(ghoul.groundAt(spec, hr.LEFT_LIP + 1), -Infinity, "a pit on its left");
assert.equal(ghoul.groundAt(spec, hr.RIGHT_LIP - 1), -Infinity, "and on its right");
assert.ok(spec.arena < hr.LEFT_LIP - 40, "room to fight on the left");
const info = bossIntroFor("marrowheart");
assert.deepEqual([info.name, info.epithet], ["The Heart of Marrow", "It has never once skipped a beat"]);
assert.equal(ghoul.BOSSES.marrowheart.name, info.name);
const r = pitFight();
const b = r.boss;
assert.deepEqual([b.x, b.y, b.w, b.h], [hr.HEART_X, 6, hr.HEART_BOX_W, hr.HEART_BOX_H], "its box is the plinth");
assert.ok(b.x - b.w / 2 <= hr.LEFT_LIP + 6 && b.x + b.w / 2 >= hr.RIGHT_LIP - 6, "nowhere to stand beside it");
assert.equal(r.dark, true);
// A fall down a pit costs a life.
standAt(r, hr.LEFT_LIP + 2);
r.you.y = 6;
r.you.state = "air";
r.you.vy = -10;
const lives = r.lives;
run(r, 1500);
assert.ok(events(r, "lose").some((e) => e.cause === "pit") || r.lives < lives, "into the dark");
});
/* ------------------------------------------------------------ the beat */
test("Ghoul Rush's Pit: the beat comes every 1.5 s at full hp and quickens toward 0.75 s, a lub then the dub, and the dub sends a wave each way from the lips of the pits", () => {
assert.equal(hr.beatFor(1), 1500);
assert.equal(hr.beatFor(0), 750);
assert.ok(hr.openFor(1) > hr.openFor(0.2), "the ribs' window narrows with hp");
const r = pitFight();
const b = r.boss;
Object.assign(b, { beatT: 1500, beatMs: 1499, dubbed: true, opened: true });
run(r, 8);
assert.equal(events(r, "heartBeat").length, 1, "the lub");
assert.equal(r.waves.length, 0, "no wave yet");
run(r, hr.DUB_MS);
assert.equal(events(r, "heartWave").length, 1, "the dub");
const xs = r.waves.map((w) => [w.kind, w.dir, Math.round(w.x)]);
assert.deepEqual(xs.sort(), [["heartBeat", -1, hr.LEFT_LIP - 1], ["heartBeat", 1, hr.RIGHT_LIP + 1]].sort(), "out of each pit's lip");
// Low on hp, the beats come faster.
calm(r);
b.hp = Math.round(b.max * 0.1);
Object.assign(b, { beatT: 1500, beatMs: 1499 });
let lubs = 0;
const times = [];
for (let t = 0; t < 6000; t += 4) {
ghoul.advance(r, 4, steady);
r.you.safeMs = 1e9;
if (events(r, "heartBeat").length) times.push(t);
lubs += events(r, "heartBeat").length;
r.events.length = 0;
}
const gap = times[2] - times[1];
assert.ok(gap >= 780 && gap <= 900, `quick beats at a tenth of its hp (${gap} ms)`);
});
test("Ghoul Rush's Pit: a bolt into the open ribs hurts it, one while they are shut clanks off, and its weak spot is open only between beats", () => {
const r = pitFight();
const b = r.boss;
standAt(r, 100);
holdShut(b);
run(r, 600, { fire: true });
assert.equal(b.hp, b.max, "shut: no damage");
assert.ok(events(r, "bossBlock").length > 0, "a clank");
calm(r);
r.heat = 0;
r.events.length = 0;
holdOpen(b);
run(r, 600, { fire: true });
assert.ok(b.hp < b.max, "open: it hurts");
assert.ok(events(r, "bossHit").length > 0);
// Over a normal beat, open only in its window.
calm(r);
Object.assign(b, { beatT: 1500, beatMs: 1499 });
const open = [];
for (let t = 0; t < 1500; t += 4) {
r.you.safeMs = 1e9;
ghoul.advance(r, 4, steady);
open.push([t, b.open]);
}
const first = open.find(([, o]) => o);
const last = open.filter(([, o]) => o).at(-1);
assert.ok(first[0] >= hr.OPEN_AT - 10 && first[0] <= hr.OPEN_AT + 10, "opens after the dub");
assert.ok(last[0] - first[0] <= hr.openFor(1) * 1500 + 10, "for its share of the beat");
assert.equal(events(r, "heartOpen").length, 1, "heard once");
});
test("Ghoul Rush's Pit: the beat's wave costs a life standing still (shaken off your feet) and is jumped", () => {
const r = pitFight();
const b = r.boss;
standAt(r, 100);
Object.assign(b, { beatT: 1e9, beatMs: hr.DUB_MS - 1, dubbed: false });
run(r, 900);
assert.deepEqual(events(r, "lose").map((e) => e.cause), ["heartBeat"]);
const j = pitFight();
standAt(j, 100);
Object.assign(j.boss, { beatT: 1e9, beatMs: hr.DUB_MS - 1, dubbed: false });
for (let t = 0; t < 900; t += 4) {
const w = j.waves.find((q) => q.dir < 0);
if (w && w.x - j.you.x > 0 && w.x - j.you.x < 4 && j.you.state === "run") j.input.jump = ghoul.JUMP_BUFFER_MS;
ghoul.advance(j, 4, steady);
}
assert.deepEqual(events(j, "lose"), [], "jumped");
});
/* ------------------------------------------------------------ the moves */
// The fight with `move` next, YOU at x (on a ledge's index when given).
function moveRound(move, x = 100, shelf = -1, share = 1) {
const r = pitFight();
r.boss.hp = Math.max(2, Math.round(r.boss.max * share));
standAt(r, x, shelf);
holdShut(r.boss);
Object.assign(r.boss, { plan: move, wait: 0 });
return r;
}
const HAZARD = { roots: "heartRoot", grab: "heartGrab", clots: "heartClot", quake: "heartChunk" };
const WIND = { roots: "heartRootWind", grab: "heartGrabWind", clots: "heartClotWind", quake: "heartQuake" };
test("Ghoul Rush's Pit: every move is seen and heard well before it can hurt, hurts standing YOU with its own cause, and is dodged", () => {
const cases = [["roots", 100, -1, 1], ["grab", 99, 1, 1], ["clots", 100, -1, 1], ["quake", 100, -1, 0.2]];
for (const [move, x, shelf, share] of cases) {
const r = moveRound(move, x, shelf, share);
ghoul.advance(r, 4, steady);
assert.equal(events(r, WIND[move]).length, 1, `${move}: its warning, heard`);
const hz = r.hazards.filter((h) => h.kind === HAZARD[move]);
assert.ok(hz.length >= 1, `${move}: something placed`);
assert.ok(hz.every((h) => !(h.live > 0) && h.warn >= 900), `${move}: a warning of nearly a second or more before any can hurt`);
// Standing still (the ledge's grab: staying on it) costs a life with its cause.
const lost = [];
for (let t = 0; t < 2500 && !lost.length; t += 4) {
ghoul.advance(r, 4, steady);
if (r.boss.act === "idle") r.boss.wait = 1e9;
lost.push(...events(r, "lose"));
r.events.length = 0;
}
assert.deepEqual(lost.map((e) => e.cause), [HAZARD[move]], `${move}: hurts`);
// Dodged: off the ledge, or a few steps aside from where it will come.
const d = moveRound(move, x, shelf, share);
ghoul.advance(d, 4, steady);
const far = [];
for (let t = 0; t < 2500; t += 4) {
if (d.phase === "play") {
const threat = d.hazards.find((h) => Math.abs(h.x - d.you.x) < (h.w + 2.4) / 2 + 1.2);
if (shelf >= 0) {
if (d.you.shelf >= 0) standAt(d, 75);
} else if (threat) standAt(d, Math.max(d.spec.arena + 4, Math.min(hr.LEFT_LIP - 3, threat.x + (threat.x > d.you.x ? -3.6 : 3.6))));
}
ghoul.advance(d, 4, steady);
if (d.boss.act === "idle") d.boss.wait = 1e9;
far.push(...events(d, "lose"));
d.events.length = 0;
}
assert.deepEqual(far.map((e) => e.cause), [], `${move}: dodged`);
}
});
test("Ghoul Rush's Pit: the pick never plays a move three times running, grabs only while YOU are on a ledge, and the quake only below a quarter", () => {
const b = {};
const random = seededRandom(4);
const picks = [];
for (let i = 0; i < 300; i++) picks.push(hr.pickMove(b, 0, random, false));
for (let i = 2; i < picks.length; i++) assert.ok(!(picks[i] === picks[i - 1] && picks[i] === picks[i - 2]), "never three running");
assert.ok(!picks.includes("grab") && !picks.includes("quake"));
const high = [];
for (let i = 0; i < 200; i++) high.push(hr.pickMove(b, 2, random, true));
assert.ok(high.includes("grab") && high.includes("quake"));
assert.ok(high.filter((p) => p === "grab").length > high.filter((p) => p === "roots").length, "on a ledge, grabs most of all");
assert.equal(hr.phaseFor(0.6), 0);
assert.equal(hr.phaseFor(0.5), 1);
assert.equal(hr.phaseFor(0.25), 2);
});
/* ------------------------------------------------------- the beat stops dead */
test("Ghoul Rush's Pit: below half the beat stops dead: silence, its swell heard well before, then a big double wave each way, and a long gasp of open ribs", () => {
const r = pitFight();
const b = r.boss;
b.hp = Math.round(b.max * 0.45);
r.you.safeMs = 1e9;
Object.assign(b, { beatT: 1500, beatMs: 1499, beats: 99, stopAt: 3 });
const seen = [];
let opened = 0;
let wasOpen = false;
let openMs = 0;
for (let t = 0; t < hr.STOP_MS + 1500; t += 4) {
r.you.safeMs = 1e9;
ghoul.advance(r, 4, steady);
for (const e of r.events) if (e.type.startsWith("heart")) seen.push([e.type, t, !!e.echo]);
if (b.open) openMs += 4;
if (b.open && !wasOpen) opened++;
wasOpen = b.open;
r.events.length = 0;
}
const types = seen.map(([type]) => type);
assert.equal(types[0], "heartStop");
const swell = seen.find(([type]) => type === "heartSwell");
const slams = seen.filter(([type]) => type === "heartSlam");
assert.ok(swell && swell[1] >= hr.STOP_MS - hr.SWELL_MS - 10 && swell[1] <= hr.STOP_MS - hr.SWELL_MS + 10, "the swell, SWELL_MS before");
assert.ok(!types.slice(0, types.indexOf("heartSlam")).includes("heartBeat"), "no beat in the silence");
assert.equal(slams.length, 2, "a double wave");
assert.ok(Math.abs(slams[1][1] - slams[0][1] - hr.BIG_GAP_MS) <= 8, "BIG_GAP_MS apart");
assert.ok(openMs >= hr.openFor(0.45) * hr.beatFor(0.45) * hr.GASP * 0.9, `a long gasp open after it (${openMs} ms)`);
});
/* ------------------------------------------------------------ the hold */
test("Ghoul Rush's Pit: no bolt takes its last hp: it holds at 1, the ribs lock open and HOLD FIRE begins, once, with the story's click; the blaster fires nothing and cools", () => {
const r = pitFight();
const b = r.boss;
standAt(r, 100);
holdOpen(b);
b.hp = 3;
r.heat = 20;
run(r, 1500, { fire: true });
assert.equal(b.hp, 1, "held at 1");
assert.equal(b.state, "fight");
assert.equal(events(r, "heartHold").length, 1, "the hold, once");
assert.equal(r.flood, true);
assert.equal(r.heart.hold, true);
assert.equal(VOICES.marrowheart.hold, "ghoulStoryClick");
const shots = r.stats.shots;
const heat = r.heat;
run(r, 600, { fire: true });
assert.equal(r.stats.shots, shots, "fire held fires nothing");
assert.ok(r.heat <= heat, "and the heat cools");
// A weapon's blow glances off in the hold (the guard).
assert.equal(ghoul.guarded(r.boss), true);
});
test("Ghoul Rush's Pit: in the hold the meter fills over about 4 s of fire held, drains slowly let go; weak beats every 1.5 s send ripples that only knock it back, never a life", () => {
const r = pitFight();
const b = r.boss;
standAt(r, 100);
b.hp = 1;
hr.startHold(r, b);
r.events.length = 0;
// No weak beat for now: the meter alone.
r.heart.beatMs = -1e9;
run(r, 2000, { fire: true });
assert.ok(Math.abs(r.heart.meter - 2000 / hr.HOLD_FILL_MS) < 0.03, `filling (${r.heart.meter})`);
const m = r.heart.meter;
run(r, 1000);
assert.ok(r.heart.meter < m && r.heart.meter > m - 0.2, "drains slowly");
r.heart.beatMs = 0;
run(r, hr.HOLD_BEAT_MS + 20);
assert.equal(events(r, "heartWeakBeat").length, 1, "a weak beat");
assert.equal(r.heart.waves.length, 1, "and its ripple");
r.heart.waves.length = 0;
// A ripple reaching YOU knocks the meter back and costs nothing.
const lives = r.lives;
r.heart.meter = 0.6;
r.heart.waves.push({ x: r.you.x + 0.5, y: 6, dir: -1 });
run(r, 40, { fire: true });
assert.equal(events(r, "heartKnock").length, 1);
assert.ok(r.heart.meter < 0.6 - hr.HOLD_KNOCK + 0.05, "knocked back");
assert.equal(r.lives, lives);
assert.deepEqual(events(r, "lose"), []);
// The flood swells out loud at each quarter climbed.
r.heart.meter = 0.2;
r.heart.step = 0;
r.heart.beatMs = -1e9;
r.heart.waves.length = 0;
r.events.length = 0;
run(r, 2400, { fire: true });
assert.deepEqual(events(r, "heartFlood").map((e) => e.n), [1, 2, 3]);
});
test("Ghoul Rush's Pit: the meter full turns the screen white, the last thump, the fall (a life, the points), then the daylight and its door, the finale's end", () => {
const r = pitFight();
const b = r.boss;
standAt(r, 100);
b.hp = 1;
hr.startHold(r, b);
r.heart.meter = 0.99;
r.heart.step = 3;
r.events.length = 0;
const lives = r.lives;
const order = [];
for (let t = 0; t < hr.FALL_AT + hr.DAYLIGHT_AT + 800; t += 4) {
r.input.fire = t < 300;
ghoul.advance(r, 4, steady);
for (const e of r.events) if (e.type.startsWith("heart") || e.type === "bossDown") order.push([e.type, t]);
if (t > 400 && t < hr.WHITE_HOLD_MS) assert.ok(hr.whiteOf(r) > 0.9, "white");
// (The fall's own slice hands the key over; the next takes it back till the daylight.)
if (b.state === "down" && !b.gone && b.t > 8) assert.equal(r.hasKey, false, "no door until the daylight");
r.events.length = 0;
}
assert.deepEqual(order.map(([type]) => type), ["heartWhite", "heartLast", "bossDown", "heartDaylight"]);
assert.ok(order[1][1] - order[0][1] >= hr.LAST_AT - 10, "the last thump, after the white");
assert.ok(order[2][1] - order[0][1] >= hr.FALL_AT - 10, "then the fall");
assert.equal(b.state, "down");
assert.equal(r.lives, lives + 1, "a life, as every boss gives");
assert.equal(b.gone, true);
assert.equal(r.hasKey, true);
assert.equal(r.flood, false);
assert.equal(hr.whiteOf(r), 0, "the white gone again");
// Through the door of light: the finale's end.
standAt(r, r.spec.door);
run(r, 50);
assert.equal(r.phase, "clear");
run(r, ghoul.CLEAR_MS + 50);
assert.ok(r.phase === "ending" || r.won, `the run's end (${r.phase})`);
});
test("Ghoul Rush's Pit: a life lost keeps its hp and the hold, and the endless-lives code spares every hit", () => {
const r = pitFight();
const b = r.boss;
b.hp = Math.round(b.max * 0.7);
const hp = b.hp;
standAt(r, 100);
Object.assign(b, { beatT: 1e9, beatMs: hr.DUB_MS - 1, dubbed: false });
run(r, 4000);
assert.ok(events(r, "lose").length >= 1);
assert.equal(r.boss.hp, hp, "its hp kept");
// In the hold, a respawn holds on.
const h = pitFight();
h.boss.hp = 1;
hr.startHold(h, h.boss);
h.heart.meter = 0.4;
standAt(h, hr.LEFT_LIP - 1);
h.you.x = hr.LEFT_LIP + 2;
h.you.state = "air";
run(h, 3500);
assert.ok(events(h, "lose").some((e) => e.cause === "pit"));
assert.equal(h.boss.hp, 1);
assert.equal(h.heart.hold, true);
run(h, ghoul.BOSS_INTRO_MS + 200);
assert.equal(h.flood, true, "still holding");
// The endless-lives code.
const e = moveRound("roots");
e.infinite = true;
const lives = e.lives;
run(e, 2500);
assert.ok(events(e, "lose").length >= 1, "hit");
assert.equal(e.lives, lives, "no life spent");
});
/* ------------------------------------------------------------ the fight */
// A steady player on the floor at HOME: fires so its bolts land while the ribs are open, jumps each wave,
// steps aside from a root, a clot or a chunk, and in the hold holds fire and jumps the ripples.
const HOME = 100;
function fight(seed, skilled = true) {
const round = pitFight();
const random = seededRandom(seed);
const b = round.boss;
Object.assign(b, { wait: 600, beatT: 0 });
let t = 0;
const causes = [];
for (; t < 240000 && b.state !== "down" && !round.over; t += 4) {
const you = round.you;
const inp = round.input;
inp.left = inp.right = inp.fire = false;
if (round.phase === "ask") ghoul.answerDie(round, false);
if (skilled && round.phase === "play" && you.out <= 0) {
const h = round.heart;
const waves = h && h.hold ? h.waves : round.waves;
const wave = waves.find((w) => w.dir < 0 && w.x - you.x > 0 && w.x - you.x < (h && h.hold ? 3 : 5));
const threat = round.hazards.find((q) => (q.warn > 0 || q.live > 0) && Math.abs(q.x - you.x) < (q.w + 2.4) / 2 + 0.8);
if (wave && you.state === "run") inp.jump = ghoul.JUMP_BUFFER_MS;
if (threat) {
const dir = threat.x >= you.x ? -1 : 1;
const lo = round.spec.arena + 4;
const hi = hr.LEFT_LIP - 4;
inp[(dir < 0 ? you.x - 3 > lo : you.x + 3 > hi) ? "left" : "right"] = true;
} else if (Math.abs(you.x - HOME) > 6 && !round.hazards.length) inp[you.x < HOME ? "right" : "left"] = true;
else you.face = 1;
// Fired so each bolt lands while the ribs are open (the way a player learns the beat).
const travel = ((hr.HEART_X - hr.HEART_BOX_W / 2 - you.x - 1.8) / 130) * 1000;
const span = hr.openFor(b.hp / b.max) * b.beatT * (b.gasp ? hr.GASP : 1);
const at = (b.beatMs || 0) + travel;
inp.fire = h && h.hold ? true : !(b.stopMs > 0) && at >= hr.OPEN_AT + 10 && at <= hr.OPEN_AT + span - 10 && you.face === 1;
}
ghoul.advance(round, 4, random);
causes.push(...events(round, "lose").map((e) => e.cause));
round.events.length = 0;
}
return { won: b.state === "down", secs: t / 1000, causes, round };
}
test("Ghoul Rush's Pit takes a steady player a real fight at full depth: 60 to 120 seconds on most seeds, with lives to spare; a player who stands still dies", () => {
const times = [];
const lives = [];
let good = 0;
for (const seed of [3, 7, 19, 41]) {
const f = fight(seed);
assert.ok(f.won, `seed ${seed}: it stopped (${f.causes}; ${f.secs.toFixed(1)} s, hp ${f.round.boss.hp})`);
assert.ok(f.round.lives > 0, `seed ${seed}: lives to spare (${f.causes})`);
for (const c of f.causes) assert.ok(LOSE_WORDS[c] || c === "pit", `${c} is the heart's`);
if (f.secs >= 60 && f.secs <= 120) good++;
times.push(f.secs);
lives.push(f.round.lives);
}
assert.ok(good >= 3, `most seeds in 60 to 120 s (${times.map((x) => x.toFixed(1))}; lives ${lives})`);
const idle = fight(7, false);
assert.equal(idle.won, false);
assert.ok(idle.round.over, `game over (${idle.causes})`);
assert.equal(idle.round.boss.hp, idle.round.boss.max, "and not a scratch on it");
});
/* ------------------------------------------------- voices, words, drawing */
const heard = (e) => {
const played = [];
const noop = () => {};
const kit = { tone: (name) => played.push(name), burst: noop, float: noop, ring: noop, banner: () => null, shake: noop, flash: noop, glow: noop, splat: noop, fx: { clock: 1e6 }, monsters: ghoul.MONSTERS, powers: ghoul.POWERS, bosses: ghoul.BOSSES, g: {}, floorAt: () => 6, markFurthest: noop };
react(e, kit);
return played;
};
test("Ghoul Rush's heart: a voice for every act in tones.js, every event plays its own sound once, and every cause has words and a sound", () => {
const known = new Set(toneNames());
for (const [act, name] of Object.entries(VOICES.marrowheart)) assert.ok(known.has(name), `${act}: ${name} is a tone`);
const at = { kind: "marrowheart", x: 120, y: 20, xs: [100], n: 1 };
const cases = { heartBeat: "beat", heartOpen: "open", heartRootWind: "rootWind", heartRootCrack: "rootCrack", heartRootUp: "rootUp", heartGrabWind: "grabWind", heartGrabTense: "grabTense", heartGrabLash: "grabLash", heartClotWind: "clotWind", heartClotLand: "clotLand", heartQuake: "quake", heartChunkLand: "chunk", heartStop: "stop", heartSwell: "swell", heartSlam: "slam", heartHold: "hold", heartWeakBeat: "weakBeat", heartKnock: "knock", heartFlood: "flood", heartWhite: "white", heartLast: "last", heartDaylight: "daylight", bossWake: "wake", bossHit: "hurt", bossDown: "die" };
for (const [type, act] of Object.entries(cases)) {
const played = heard({ type, ...at, how: "shot", points: 1, life: true });
assert.equal(played.filter((n) => n === VOICES.marrowheart[act]).length, 1, `${type}: ${VOICES.marrowheart[act]} once`);
}
assert.deepEqual(heard({ type: "heartWave", ...at }), [], "the dub is the beat's own second thump");
for (const cause of ["marrowheart", "heartBeat", "heartBig", "heartRoot", "heartGrab", "heartClot", "heartChunk"]) {
assert.ok(LOSE_WORDS[cause], `${cause}: words`);
assert.ok(known.has(LOSE_SOUNDS[cause][0]), `${cause}: a sound`);
}
});
test("Ghoul Rush's Pit draws: the walk in, the heart asleep, every beat's moment, every move's warning and hit, the stopped beat and the slam, the hold, the white, the stopped heart and the daylight, lit and dark, and its card", () => {
const { canvas, calls } = stubCanvas();
const g = ghoul.default.create({ canvas });
g.resize(900, 900);
g.stageSelect();
for (let i = 0; i < ghoul.SELECTABLE.length; i++) g.key("down");
for (let i = 0; i < ghoul.FINALE.rooms.indexOf("pit"); i++) g.key("right");
g.key("action");
for (let n = 0; n < 3 && g.round.phase !== "ready" && g.round.phase !== "play"; n++) {
for (let ms = 0; ms < ghoul.INTRO_MIN_MS + 50; ms += 16) g.tick(16);
g.key("action");
}
const r = g.round;
assert.equal(r.spec.id, "pit");
r.infinite = true;
const frame = (label) => {
const before = calls.count;
g.tick(16);
assert.ok(calls.count > before, `${label} draws`);
};
for (const dark of [false, true]) {
r.dark = dark;
standAt(r, 20);
frame("the walk in");
standAt(r, 100);
for (let ms = 0; ms < 1600; ms += 16) g.tick(16);
for (const beatMs of [10, 200, 320, 500, 1300]) {
Object.assign(r.boss, { beatT: 1500, beatMs, wait: 1e9 });
frame(`the beat at ${beatMs}`);
}
for (const [move, share] of [["roots", 1], ["clots", 0.6], ["quake", 0.2]]) {
r.boss.hp = Math.round(r.boss.max * share);
Object.assign(r.boss, { plan: move, act: "idle", wait: 0 });
for (let ms = 0; ms < 1600; ms += 16) frame(move);
}
standAt(r, 99, 1);
Object.assign(r.boss, { plan: "grab", act: "idle", wait: 0 });
for (let ms = 0; ms < 1600; ms += 16) frame("grab");
standAt(r, 100);
Object.assign(r.boss, { stopMs: 1200, swelled: false });
for (let ms = 0; ms < 1800; ms += 16) frame("the stop and the slam");
}
r.boss.hp = 1;
hr.startHold(r, r.boss);
r.heart.meter = 0.5;
r.input.fire = true;
for (let ms = 0; ms < 2600; ms += 16) frame("the hold");
for (let ms = 0; ms < 6000; ms += 16) frame("the white, the fall and the daylight");
assert.equal(r.boss.state, "down");
// The boss card's fake view: no round, no room, the floor at 0.
const def = ghoul.BOSSES.marrowheart;
assert.ok(def.w >= 30 && def.h >= 36, "the card sizes its spotlight to the whole heart");
const noop = () => {};
const art = heartArt({ ellipse: noop, circle: noop, roundRect: noop, line: noop, rotate: noop, hash: (a, b) => Math.abs(a * 31 + b * 17) % 997, say: noop, gate: () => true, label: noop, DANGER: "#ff3030", GOLD: "#f5b301" });
const card = stubCanvas();
const fake = { kind: "marrowheart", x: 0, y: 0, w: def.w, h: def.h, hp: 1, max: 1, state: "fight", t: 0 };
for (const clock of [0, 400, 900]) art.bosses.marrowheart(card.ctx, { g: { FIELD_H: 0 }, clock, spec: null, groundAt: () => 0, eyes: [] }, fake);
assert.ok(card.calls.count > 50, "the card's heart draws");
});
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's stage intro cards: every stage has one (3 or 4 lines, short, no em dash, never the hero's name), the card shows when a stage is entered and not before the pick, any move key or fire moves it on after the minimum (repeats and early presses never do) and it never moves on by itself, and it draws on a fake canvas. // Web console tests, Ghoul Rush's stage intro cards: every stage has one (3 or 4 lines, short, no em dash, never the hero's name), the card shows when a stage is entered and not before the pick, any move key or fire moves it on after the minimum (repeats and early presses never do) and it never moves on by itself, and it draws on a fake canvas.
import "./seed-random.mjs";
import { test } from "node:test"; import { test } from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js"; import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -51,8 +52,8 @@ test("Ghoul Rush intros: every stage has a card of 3 or 4 short lines, no em das
assert.ok(size > 0 && size <= TITLE_SIZE, `${st.id}'s title has a size`); assert.ok(size > 0 && size <= TITLE_SIZE, `${st.id}'s title has a size`);
assert.ok(Math.abs(xs[0]) < field / 2 && Math.abs(xs[xs.length - 1]) < field / 2, `${st.id}'s title fits the field`); assert.ok(Math.abs(xs[0]) < field / 2 && Math.abs(xs[xs.length - 1]) < field / 2, `${st.id}'s title fits the field`);
} }
assert.deepEqual(Object.keys(INTROS).sort(), ghoul.STAGES.map((st) => st.id).sort(), "no intro for a stage that does not exist"); assert.deepEqual(Object.keys(INTROS).sort(), ghoul.SELECTABLE.map((st) => st.id).sort(), "no intro for a stage that does not exist");
assert.equal(new Set(ghoul.STAGES.flatMap((st) => introFor(st.id).lines)).size, ghoul.STAGES.reduce((n, st) => n + introFor(st.id).lines.length, 0), "no line used twice"); assert.equal(new Set(ghoul.SELECTABLE.flatMap((st) => introFor(st.id).lines)).size, ghoul.SELECTABLE.reduce((n, st) => n + introFor(st.id).lines.length, 0), "no line used twice");
assert.ok(toneNames().includes("ghoulStageIntro")); assert.ok(toneNames().includes("ghoulStageIntro"));
}); });
@@ -1,5 +1,6 @@
// Web console tests, Ghoul Rush's Drowned Lantern (Gallows Bog's bonus round, between the Stilt House and the Drowning Pool, a top-down game on one screen and not a ride): the island, the walk and the slide, the flare and the oil, the shrines and the run to the boat, each hunter's one rule (the Lurker hears steps on wood and dashes down a lane through where it heard you, the wisps guard the shrines and burst in a flare, the leeches never enter the light, the bog bodies take only someone standing still, Old Mother Bog's hand), the hearts and the grade, the clock, determinism, the balance (a bot that ignores the hunters loses, one that plays them wins), the voices, the hums and the drawing. // Web console tests, Ghoul Rush's Drowned Lantern (Gallows Bog's bonus round, between the Stilt House and the Drowning Pool, a top-down game on one screen and not a ride): the island, the walk and the slide, the flare and the oil, the shrines and the run to the boat, each hunter's one rule (the Lurker hears steps on wood and dashes down a lane through where it heard you, the wisps guard the shrines and burst in a flare, the leeches never enter the light, the bog bodies take only someone standing still, Old Mother Bog's hand), the hearts and the grade, the clock, determinism, the balance (a bot that ignores the hunters loses, one that plays them wins), the voices, the hums and the drawing.
// Run with: node --test scripts/test-web-console-activities-ghoul-lantern.mjs // Run with: node --test scripts/test-web-console-activities-ghoul-lantern.mjs
import "./seed-random.mjs";
import { test } from "node:test"; import { test } from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js"; import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -0,0 +1,644 @@
// Web console tests, Ghoul Rush's finale: the win condition (RUN_STAGES stages, then the House
// with no offer, its record one past every stage), the words that count the stages, and Kill I,
// The Lawn: the windows (hit from the surface that serves each row, passed while shuttered, out
// for good across a life lost), the rows opening, each move's telegraph, hit and dodge, the
// weighted pick, the wall in front of the house, the retreat in order and its standing door, a
// bot's fight length, the voices, words and drawing.
// Run with: node --test scripts/test-web-console-activities-ghoul-marrow.mjs
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
import * as mw from "../src/web-console/public/activities/ghoul-rush/stages/marrow/ghoul-marrow.js";
import { LOSE_SOUNDS, LOSE_WORDS, VOICES } from "../src/web-console/public/activities/ghoul-rush/stages/marrow/ghoul-marrow-draw.js";
import { react } from "../src/web-console/public/activities/ghoul-rush/draw/ghoul-draw.js";
import { bossIntroFor } from "../src/web-console/public/activities/ghoul-rush/story/ghoul-boss-intros.js";
import { introFor } from "../src/web-console/public/activities/ghoul-rush/story/ghoul-intros.js";
import { skipStory } from "../src/web-console/public/activities/ghoul-rush/story/ghoul-story.js";
import { skipEnding } from "../src/web-console/public/activities/ghoul-rush/story/ghoul-ending.js";
import { toneNames } from "../src/web-console/public/tones.js";
const steady = () => 0.5;
const events = (round, type) => round.events.filter((e) => e.type === type);
const seededRandom = (seed) => {
let s = seed;
return () => (s = (s * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;
};
function stubCanvas() {
const calls = { count: 0 };
const ctx = new Proxy({}, {
get: (target, name) => (name in target ? target[name] : () => { calls.count += 1; }),
set: (target, name, value) => { target[name] = value; return true; },
});
return { canvas: { width: 0, height: 0, getContext: () => ctx }, calls };
}
function textCanvas() {
const texts = [];
const ctx = new Proxy({}, {
get: (target, name) => (name === "fillText" ? (text) => texts.push([String(text)]) : name in target ? target[name] : () => {}),
set: (target, name, value) => { target[name] = value; return true; },
});
return { canvas: { width: 0, height: 0, getContext: () => ctx }, texts };
}
function through(round) {
round.phase = "clear";
round.phaseMs = 1;
ghoul.advance(round, 4, steady);
}
// Through the rest of the House, room by room (each card passed), then past the ending's pages: the win.
function finishHouse(round, g = null) {
for (let n = 0; n < 20 && !round.over; n++) {
if (round.phase === "ending") skipEnding(round);
else {
if (round.phase === "intro" || round.phase === "bossintro") skipCard(round);
if (round.phase === "intro" || round.phase === "bossintro") skipCard(round);
through(round);
}
if (g) g.tick(16);
}
}
function skipCard(round) {
round.introMs = ghoul.INTRO_MIN_MS;
return ghoul.takeIntro(round);
}
function standAt(round, x, shelf = -1) {
const y = shelf >= 0 ? round.spec.shelves[shelf][2] : ghoul.groundAt(round.spec, x);
Object.assign(round.you, { x, y, vx: 0, vy: 0, state: "run", shelf, coyote: 0, drop: -1, cuttable: false, out: 0, safeMs: 0, face: 1 });
}
function run(round, ms, keys = {}, random = steady) {
Object.assign(round.input, keys);
for (let t = 0; t < ms; t += 4) ghoul.advance(round, 4, random);
for (const k of Object.keys(keys)) round.input[k] = false;
}
// A run's way to the House: out of the hall, `depth` stages already behind it, into the
// finale (its stage card and the boss's passed), nothing else woken.
function lawnRound(depth = ghoul.RUN_STAGES) {
const round = ghoul.newRound(5);
round.dice = 0;
through(round);
round.cleared = ghoul.STAGES.slice(0, depth).map((st) => st.id);
round.offer = null;
through(round);
assert.equal(round.spec.id, "lawn");
skipCard(round);
skipCard(round);
round.phase = "play";
for (const st of round.spawns) st.over = true;
round.monsters.length = 0;
round.hordeMs = Infinity;
round.items.fill(true);
round.candy.fill(true);
round.events.length = 0;
return round;
}
// Nothing moves: no window lit, the next move a long way off.
function calm(round) {
const b = round.boss;
for (const w of round.marrow.windows) if (w.state === "lit") w.state = "dark";
Object.assign(b, { act: "idle", wait: 1e9, litMs: 1e9, relight: 0 });
round.hazards.length = 0;
round.waves.length = 0;
round.monsters.length = 0;
}
// The fight under way: in the arena, the boss awake and idle a long while, no window lit.
function lawnFight(depth = ghoul.RUN_STAGES) {
const round = lawnRound(depth);
standAt(round, 130);
run(round, ghoul.BOSS_INTRO_MS + 100);
assert.equal(round.boss.state, "fight");
calm(round);
round.events.length = 0;
return round;
}
// Where each row is shot from: [x, shelf index or -1 for the floor].
const SERVES = Object.freeze({ 0: [160, -1], 1: [145, 2], 2: [145, 5], 3: [162, 6] });
function lightOnly(round, id) {
for (const w of round.marrow.windows) if (w.state !== "out") w.state = w.id === id ? "lit" : "dark";
}
/* ------------------------------------------------------- the win condition */
test("Ghoul Rush's finale: a run offers RUN_STAGES picks of stages that never repeat, then goes to the House with no offer, its card and the boss's first; clearing it wins", () => {
const round = ghoul.newRound(9);
round.dice = 0;
through(round);
let picks = 0;
while (round.phase === "pick") {
picks++;
round.phaseMs = 0;
ghoul.pickStage(round);
for (let k = 0, n = ghoul.stageById(round.stage).rooms.length; k < n; k++) through(round);
}
assert.equal(picks, ghoul.RUN_STAGES, "six picks");
assert.equal(new Set(round.cleared).size, ghoul.RUN_STAGES, "no stage twice");
assert.equal(events(round, "offer").length, ghoul.RUN_STAGES, "no offer for the House");
assert.deepEqual([round.stage, round.spec.id, round.phase], [ghoul.FINALE.id, "lawn", "intro"], "the sixth clear opens the House's card");
assert.deepEqual(events(round, "stage").at(-1), { type: "stage", stage: "marrow", n: ghoul.RUN_STAGES, of: ghoul.RUN_STAGES });
assert.ok(events(round, "stageClear").every((e) => e.of === ghoul.RUN_STAGES));
assert.ok(introFor("marrow") && bossIntroFor("marrow"), "both cards exist");
assert.equal(skipCard(round), true);
assert.equal(round.phase, "bossintro", "then the boss's card");
assert.equal(skipCard(round), true);
assert.equal(round.phase, "ready");
assert.equal(round.spec.depth, ghoul.RUN_STAGES, "played at full depth");
finishHouse(round);
assert.equal(round.won, true);
assert.deepEqual(events(round, "won").map((e) => e.n), [ghoul.RUN_STAGES + 1]);
});
test("Ghoul Rush's finale is never offered, and the stage select lists it last, played at depth 0", () => {
assert.ok(!ghoul.STAGES.includes(ghoul.FINALE));
assert.equal(ghoul.SELECTABLE.at(-1), ghoul.FINALE);
assert.equal(ghoul.stageById("marrow"), ghoul.FINALE);
assert.equal(ghoul.FINALE.rooms[0], "lawn");
assert.equal(ghoul.roomById("lawn").boss, "marrow");
for (let seed = 1; seed < 30; seed++) {
const r = ghoul.newRound(seed);
r.dice = 0;
through(r);
assert.ok(!r.offer.includes("marrow"));
}
const g = ghoul.default.create({ canvas: stubCanvas().canvas });
g.resize(900, 900);
g.stageSelect();
for (let i = 0; i < ghoul.SELECTABLE.length + 2; i++) g.key("down");
assert.equal(g.round.select.at, ghoul.SELECTABLE.length - 1);
g.key("action");
assert.deepEqual([g.round.stage, g.round.spec.id, g.round.phase], ["marrow", "lawn", "intro"]);
assert.equal(g.round.spec.depth, 0, "practice plays it at depth 0");
});
test("Ghoul Rush's record: the memo counts stages up to RUN_STAGES, goes one past only on a win, never from practice, and the words count RUN_STAGES whatever STAGES holds", () => {
const { canvas, texts } = textCanvas();
let saved = 0;
const g = ghoul.default.create({ canvas, memo: { get: () => saved, set: (n) => (saved = n) } });
g.resize(900, 900);
assert.ok(ghoul.STAGES.length !== ghoul.RUN_STAGES, "the pool is bigger than a run");
assert.ok(texts.some(([t]) => t === `Run. Shoot. Clear ${ghoul.RUN_STAGES} stages, then kill the house`));
assert.ok(texts.some(([t]) => t.includes(`Best: 0 of ${ghoul.RUN_STAGES} stages`)));
g.key("action");
if (g.round.phase === "story") {
skipStory(g.round);
g.tick(0);
}
const r = g.round;
r.dice = 0;
const last = ghoul.STAGES[ghoul.RUN_STAGES - 1];
r.cleared = ghoul.STAGES.slice(0, ghoul.RUN_STAGES - 1).map((s) => s.id);
r.stage = last.id;
r.stageAt = last.rooms.length - 1;
through(r);
g.tick(16);
assert.equal(saved, ghoul.RUN_STAGES, "every stage, not yet the House");
assert.equal(g.hud.stage, "THE HOUSE: KILL 1 OF 3");
finishHouse(r, g);
g.tick(16);
assert.equal(g.state, "over");
assert.equal(saved, ghoul.RUN_STAGES + 1, "the House beaten");
texts.length = 0;
g.resize(900, 900);
assert.ok(texts.some(([t]) => t.startsWith("You escaped! Marrow starves")));
// A memo from before reads as beaten, and the start screen says so.
const again = textCanvas();
const g2 = ghoul.default.create({ canvas: again.canvas, memo: { get: () => 11, set: () => {} } });
g2.resize(900, 900);
assert.ok(again.texts.some(([t]) => t.includes("You have killed the House")));
// Practice never writes it.
let p = 0;
const g3 = ghoul.default.create({ canvas: stubCanvas().canvas, memo: { get: () => p, set: (n) => (p = n) } });
g3.resize(900, 900);
g3.stageSelect();
for (let i = 0; i < ghoul.SELECTABLE.length; i++) g3.key("down");
g3.key("action");
finishHouse(g3.round, g3);
g3.tick(16);
assert.equal(g3.round.won, true);
assert.equal(p, 0, "practice keeps nothing");
});
/* --------------------------------------------------------------- the lawn */
test("Ghoul Rush's lawn: the house fills the arena's right, YOU are kept off it, its box is out of reach and always guarded, and its hp is its windows' sum", () => {
const round = lawnFight();
const b = round.boss;
const spec = round.spec;
assert.equal(ghoul.roomById("lawn").boss, "marrow");
assert.equal(mw.houseLeft(spec), 172);
assert.ok(b.x > mw.houseLeft(spec) + mw.HOUSE_W, "its box past the house's far wall");
assert.equal(ghoul.guarded(b), true);
const share = Math.ceil(spec.bossHp / mw.WINDOWS.length);
assert.equal(b.max, share * mw.WINDOWS.length);
assert.equal(b.hp, round.marrow.windows.reduce((s, w) => s + w.hp, 0));
standAt(round, 160);
run(round, 1500, { right: true });
assert.ok(round.you.x <= mw.houseLeft(spec) - mw.WALL_GAP + 0.5, `held off the house (${round.you.x.toFixed(2)})`);
});
test("Ghoul Rush's lawn: every window can be shot from the surface that serves its row; a shuttered one lets the bolts by", () => {
mw.WINDOWS.forEach(([row, dx], id) => {
const round = lawnFight();
const win = round.marrow.windows[id];
const [x, shelf] = SERVES[row];
standAt(round, x, shelf);
const full = win.hp;
run(round, 1200, { fire: true });
assert.equal(win.hp, full, `window ${id}: shuttered, untouched`);
lightOnly(round, id);
round.heat = 0;
round.events.length = 0;
run(round, 800, { fire: true });
assert.ok(win.hp < full, `window ${id} (row ${row}): hit from ${shelf < 0 ? "the floor" : `shelf ${shelf}`}`);
assert.equal(round.boss.hp, round.marrow.windows.reduce((s, q) => s + q.hp, 0), "hp is the windows' sum");
assert.ok(events(round, "bossHit").every((e) => e.how === "window" && Math.abs(e.x - (mw.houseCenter(round.spec) + dx)) < 0.01), "the hit shows at the window");
});
});
test("Ghoul Rush's lawn: a window shot out stays out across a life lost, and lit windows come only from the rows open by how many are out", () => {
assert.deepEqual([0, 3, 4, 7, 8, 12].map(mw.rowsOpen), [1, 1, 2, 2, 3, 3]);
const round = lawnFight();
const b = round.boss;
const win = round.marrow.windows[0];
b.hp -= win.hp - 1;
win.hp = 1;
lightOnly(round, 0);
standAt(round, 160);
run(round, 400, { fire: true });
assert.equal(win.state, "out");
assert.deepEqual(events(round, "marrowWindowOut").map((e) => e.left), [mw.WINDOWS.length - 1]);
const hp = round.boss.hp;
round.lives = 5;
ghoul.lose(round, "marrowShingle");
run(round, ghoul.CRASH_MS + ghoul.READY_MS + 100);
assert.notEqual(round.boss, b, "a new boss object after the life lost");
assert.equal(round.marrow.windows[0].state, "out", "still out");
assert.equal(round.boss.hp, hp, "the same hp");
const r2 = lawnFight();
const random = seededRandom(4);
r2.boss.litMs = 0;
for (let t = 0; t < 60000; t += 4) {
r2.you.safeMs = 1e9;
r2.boss.wait = 1e9;
ghoul.advance(r2, 4, random);
const out = r2.marrow.windows.filter((w) => w.state === "out").length;
for (const w of r2.marrow.windows) if (w.state === "lit") assert.ok(w.row <= mw.rowsOpen(out), `row ${w.row} lit with ${out} out`);
// Shoot one out now and then, so every row gets its turn.
if (t % 2000 === 0 && out < mw.WINDOWS.length - 1) {
const lit = r2.marrow.windows.find((w) => w.state === "lit");
if (lit) {
r2.boss.hp -= lit.hp;
Object.assign(lit, { hp: 0, state: "out" });
r2.boss.relight = mw.RELIGHT_MS;
}
}
r2.events.length = 0;
}
assert.ok(r2.marrow.windows.filter((w) => w.state === "out").length >= 9, "the fight reached the eyes");
});
test("Ghoul Rush's lawn: the pick opens on the carpet, never one move three times running, the slow moves sit out their cooldown, the doormen only under their cap, and each phase's moves only", () => {
const random = seededRandom(11);
for (const phase of [0, 1, 2]) {
const b = {};
const picks = [];
for (let i = 0; i < 400; i++) picks.push(mw.pickMove(b, phase, random, 0));
assert.equal(picks[0], "carpet");
for (let i = 2; i < picks.length; i++) assert.ok(!(picks[i] === picks[i - 1] && picks[i] === picks[i - 2]), `phase ${phase}: never three running`);
for (const [move, n] of Object.entries(mw.COOLDOWN)) {
const at = picks.flatMap((p, i) => (p === move ? [i] : []));
for (let i = 1; i < at.length; i++) assert.ok(at[i] - at[i - 1] > n, `phase ${phase}: ${move} sits out ${n}`);
}
for (const [move, w] of Object.entries(mw.WEIGHTS)) if (!w[phase]) assert.ok(!picks.includes(move), `phase ${phase}: no ${move}`);
assert.ok(new Set(picks).size >= [3, 5, 6][phase], `phase ${phase}: varied (${[...new Set(picks)]})`);
}
const b = { picks: 3 };
for (let i = 0; i < 100; i++) assert.notEqual(mw.pickMove(b, 1, random, mw.DOORMEN_CAP), "doormen");
// Up in the oak the lightning and the crows join, and only there; the crows under their cap.
for (const phase of [0, 1, 2]) {
const up = {};
const picks = [];
for (let i = 0; i < 400; i++) picks.push(mw.pickMove(up, phase, random, 0, true, 0));
assert.ok(picks.includes("lightning") && picks.includes("crows"), `phase ${phase}: high moves when high`);
const capped = { picks: 3 };
for (let i = 0; i < 100; i++) assert.notEqual(mw.pickMove(capped, phase, random, 0, true, mw.CROWS_CAP), "crows");
}
const round = lawnFight();
standAt(round, 160);
assert.equal(mw.isHigh(round), false, "the lawn is not high");
standAt(round, 143, 2);
assert.equal(mw.isHigh(round), true, "a branch is");
});
test("Ghoul Rush's lawn: up in the oak, lightning glows on YOUR branch before it strikes (a life, struck down), and a step along it or a drop dodges it; from the second phase a second bolt waits ahead", () => {
const go = (outs) => {
const round = lawnFight();
for (const w of round.marrow.windows.slice(0, outs)) {
round.boss.hp -= w.hp;
Object.assign(w, { hp: 0, state: "out" });
}
standAt(round, 141, 2);
Object.assign(round.boss, { plan: "lightning", wait: 0, picks: 1 });
run(round, 4);
return round;
};
const hit = go(0);
assert.equal(events(hit, "marrowStorm").length, 1, "the storm gathers first");
const bolts = hit.hazards.filter((h) => h.kind === "marrowBolt");
assert.deepEqual(bolts.map((h) => [h.x, h.y]), [[141, 18]], "one glow where YOU stand, at YOUR height");
const losses = [];
const heard = [];
for (let t = 0; t < 3000 && !losses.length; t += 4) {
ghoul.advance(hit, 4, steady);
losses.push(...events(hit, "lose"));
for (const e of hit.events) if (e.type === "marrowCharge" || e.type === "marrowStrike") heard.push([e.type, t]);
if (t < mw.LIGHTNING_WARN_MS) assert.equal(losses.length, 0, "never before its glow has run");
hit.events.length = 0;
}
assert.deepEqual(losses.map((e) => e.cause), ["marrowBolt"]);
assert.deepEqual(heard.map(([type]) => type), ["marrowCharge", "marrowCharge", "marrowStrike"], "it charges up out loud twice before it strikes");
assert.ok(heard[0][1] >= 400 && heard[2][1] - heard[1][1] >= 400, "each step well apart");
for (const dodge of [(r) => standAt(r, 145.5, 2), (r) => standAt(r, 141)]) {
const safe = go(0);
dodge(safe);
const lost = [];
for (let t = 0; t < 2500; t += 4) {
ghoul.advance(safe, 4, steady);
if (safe.boss.act === "idle") safe.boss.wait = 1e9;
lost.push(...events(safe, "lose"));
safe.events.length = 0;
}
assert.deepEqual(lost, [], "dodged");
}
const two = go(4);
assert.equal(two.hazards.filter((h) => h.kind === "marrowBolt").length, 2, "a second bolt from the second phase");
});
test("Ghoul Rush's lawn: up in the oak, crows burst out of the door's mouth, climb and dive at YOU, never more than CROWS_CAP of its own", () => {
const round = lawnFight();
standAt(round, 143, 2);
round.you.safeMs = 1e9;
Object.assign(round.boss, { plan: "crows", wait: 0, picks: 1 });
run(round, 4);
assert.equal(round.boss.act, "crowsWind");
run(round, 4);
assert.equal(round.boss.mouth, true, "the door is open");
run(round, mw.CROWS_WIND_MS + 40);
const crows = round.monsters.filter((m) => m.houseCrow);
assert.equal(crows.length, mw.CROWS_N[0]);
assert.ok(crows.every((m) => m.kind === "crow" && Math.abs(m.x - mw.houseLeft(round.spec)) < 8), "out of the door");
assert.equal(events(round, "marrowCrows").length, 1);
run(round, 900);
assert.ok(round.monsters.some((m) => m.houseCrow && m.act === "dive"), "a dive at YOU");
Object.assign(round.boss, { plan: "crows", wait: 0 });
run(round, mw.CROWS_WIND_MS + 60);
assert.ok(round.monsters.filter((m) => m.houseCrow && !m.dead).length <= mw.CROWS_CAP);
});
// A move started now, YOU on the floor at `x`, `outs` windows already shot out (for its phase).
function moveRound(move, x = 150, outs = 0) {
const round = lawnFight();
for (const w of round.marrow.windows.slice(0, outs)) {
round.boss.hp -= w.hp;
Object.assign(w, { hp: 0, state: "out" });
}
standAt(round, x);
Object.assign(round.boss, { plan: move, wait: 0, picks: 1 });
run(round, 4);
assert.equal(round.boss.move, move);
return round;
}
// Steps YOU once out from under the first warning of `kind` that lands where YOU stand.
const stepOut = (kind, dx) => (r) => {
if (r.stepped) return;
const h = r.hazards.find((q) => q.kind === kind && q.warn > 0 && Math.abs(q.x - r.you.x) < 3);
if (!h) return;
r.stepped = true;
standAt(r, r.you.x + dx, r.you.shelf);
};
test("Ghoul Rush's lawn: each move telegraphs before it can hurt, hurts standing YOU with its own cause, and is dodged", () => {
const cases = [
["shingles", "marrowRoof", "marrowShingle", 0, (r) => r.stepped || ((r.stepped = true), standAt(r, 146))],
["pickets", "marrowPicketWind", "marrowPicket", 0, (r) => r.stepped || ((r.stepped = true), standAt(r, 146))],
["carpet", "marrowDoor", "marrowCarpet", 0, (r) => r.stepped || ((r.stepped = true), standAt(r, 143, 2))],
["bricks", "marrowCough", "marrowBrick", 4, stepOut("marrowBrick", -6)],
["stomp", "marrowRear", "marrowQuake", 8, (r) => { if (!r.climbed) { r.climbed = true; standAt(r, 143, 2); } stepOut("marrowShingle", 4)(r); }],
];
for (const [move, tell, cause, outs, dodge] of cases) {
const hit = moveRound(move, 150, outs);
assert.equal(events(hit, tell).length, 1, `${move}: ${tell} first`);
const losses = [];
for (let t = 0; t < 4000 && !losses.length; t += 4) {
ghoul.advance(hit, 4, steady);
losses.push(...events(hit, "lose"));
hit.events.length = 0;
if (t < 300) assert.equal(losses.length, 0, `${move}: never before its warning has run`);
}
assert.deepEqual(losses.map((e) => e.cause), [cause], `${move}: costs a life as ${cause}`);
const safe = moveRound(move, 150, outs);
const lost = [];
for (let t = 0; t < 4000; t += 4) {
dodge(safe);
ghoul.advance(safe, 4, steady);
// The move played out, nothing comes after it.
if (safe.boss.act === "idle") safe.boss.wait = 1e9;
lost.push(...events(safe, "lose"));
safe.events.length = 0;
}
assert.deepEqual(lost.map((e) => e.cause), [], `${move}: dodged`);
}
});
test("Ghoul Rush's lawn: the doormen step out of the door, never more than DOORMEN_CAP of its own, and endless lives spare every hit", () => {
const round = moveRound("doormen", 130, 4);
round.you.safeMs = 1e9;
run(round, mw.DOORMEN_WIND_MS + 50);
assert.equal(round.monsters.filter((m) => m.doorman).length, mw.DOORMEN_N);
assert.equal(events(round, "marrowDoormen").length, 1);
Object.assign(round.boss, { plan: "doormen", wait: 0 });
run(round, mw.DOORMEN_WIND_MS + 60);
assert.ok(round.monsters.filter((m) => m.doorman && !m.dead).length <= mw.DOORMEN_CAP);
const r = moveRound("pickets", 150);
r.infinite = true;
const lives = r.lives;
run(r, 2000);
assert.ok(events(r, "lose").length >= 1, "hit");
assert.equal(r.lives, lives, "no life spent");
});
test("Ghoul Rush's lawn: the last window out is a boss kill, then the retreat plays its beats once and in order, and only then is the door there to walk through", () => {
const round = lawnFight();
const b = round.boss;
for (const w of round.marrow.windows.slice(1)) Object.assign(w, { hp: 0, state: "out" });
round.marrow.windows[0].hp = 1;
b.hp = 1;
lightOnly(round, 0);
const lives = round.lives;
standAt(round, 160);
run(round, 400, { fire: true });
assert.equal(b.state, "down");
assert.equal(round.lives, lives + 1, "a life, as every boss gives");
assert.equal(round.hasKey, true);
const order = [];
for (let t = 0; t < mw.GONE_AT + 1500 && round.phase !== "clear"; t += 4) {
standAt(round, round.spec.door);
round.input.right = true;
ghoul.advance(round, 4, steady);
for (const e of round.events) if (e.type.startsWith("marrow") && e.type !== "marrowWindowOut") order.push([e.type, Math.round(b.t)]);
round.events.length = 0;
if (!b.gone) assert.ok(round.you.x <= mw.houseLeft(round.spec), "no door until it has gone");
}
assert.deepEqual(order.map(([t]) => t), ["marrowSag", "marrowFalseWin", "marrowLaugh", "marrowSink", "marrowGone"]);
assert.ok(order[1][1] >= mw.FALSE_AT && order[4][1] >= mw.GONE_AT, "on the retreat's clock");
assert.equal(b.gone, true);
assert.equal(round.phase, "clear", "through the door it left standing");
run(round, ghoul.CLEAR_MS + 50);
// On down the House's throat, or (the lawn the finale's only room) the win.
if (ghoul.FINALE.rooms.length > 1) assert.equal(round.spec.id, ghoul.FINALE.rooms[1], "on to the next of the House's rooms");
else assert.ok(round.won || round.phase === "ending");
});
/* ------------------------------------------------------------ the fight */
// A steady player: shoots the lowest lit window from the surface serving it (getting there
// takes CLIMB_MS a row, about two branches of the oak, firing nothing on the way: the bot is put there after), jumps the
// carpet and the quake on the floor, and steps out from under a slate, a ripple or a brick.
const CLIMB_MS = 1500;
function fight(seed, skilled = true) {
const round = lawnFight();
const random = seededRandom(seed);
Object.assign(round.boss, { wait: 600, litMs: 0 });
let at = 0;
let travel = 0;
let t = 0;
const causes = [];
for (; t < 240000 && round.boss.state !== "down" && !round.over; t += 4) {
const you = round.you;
const inp = round.input;
inp.left = inp.right = inp.fire = false;
if (round.phase === "ask") ghoul.answerDie(round, false);
if (skilled && round.phase === "play" && you.out <= 0 && you.state === "run") {
const lit = round.marrow.windows.filter((w) => w.state === "lit").sort((a, c) => a.row - c.row);
const threat = round.hazards.find((h) => (h.warn > 0 || h.live > 0) && Math.abs(h.x - you.x) < (h.w + 1.6) / 2 + 0.6 && (h.kind === "marrowShingle" || you.y === h.y));
const wave = round.waves.find((w) => w.y === you.y && w.x - you.x > 0 && w.x - you.x < 5);
if (wave) inp.jump = ghoul.JUMP_BUFFER_MS;
else if (threat) {
const s = you.shelf >= 0 ? round.spec.shelves[you.shelf] : [mw.houseLeft(round.spec) - 60, mw.houseLeft(round.spec) - 2];
const dir = threat.x >= you.x ? -1 : 1;
inp[(dir < 0 ? you.x - 3 > s[0] : you.x + 3 > s[1]) ? "left" : "right"] = true;
} else if (travel > 0) travel -= 4;
else if (lit.length) {
const row = lit[0].row;
const [x, shelf] = SERVES[row];
if (row !== at) {
travel = CLIMB_MS * Math.abs(row - at);
at = row;
} else {
if (you.shelf !== shelf || Math.abs(you.x - x) > 4) standAt(round, x, shelf);
you.face = 1;
inp.fire = true;
}
}
}
ghoul.advance(round, 4, random);
causes.push(...events(round, "lose").map((e) => e.cause));
round.events.length = 0;
}
return { won: round.boss.state === "down", secs: t / 1000, causes, round };
}
test("Ghoul Rush's lawn takes a steady player a real fight at full depth: 60 to 120 seconds on most seeds, with lives to spare; a player who stands still dies", () => {
const times = [];
const lives = [];
let good = 0;
for (const seed of [3, 7, 19, 41]) {
const f = fight(seed);
assert.ok(f.won, `seed ${seed}: it fell (${f.causes}; ${f.secs.toFixed(1)} s, hp ${f.round.boss.hp})`);
assert.ok(f.round.lives > 0, `seed ${seed}: lives to spare (${f.causes})`);
for (const c of f.causes) assert.ok(LOSE_WORDS[c] || ghoul.MONSTERS[c], `${c} is the House's or one of the dead`);
if (f.secs >= 60 && f.secs <= 120) good++;
times.push(f.secs);
lives.push(f.round.lives);
}
assert.ok(good >= 3, `most seeds in 60 to 120 s (${times.map((x) => x.toFixed(1))}; lives ${lives})`);
const idle = fight(7, false);
assert.equal(idle.won, false);
assert.ok(idle.round.over, `game over (${idle.causes})`);
assert.equal(idle.round.boss.hp, idle.round.boss.max, "and not a window touched");
});
/* ------------------------------------------------- voices, words, drawing */
const heard = (e) => {
const played = [];
const noop = () => {};
const kit = { tone: (name) => played.push(name), burst: noop, float: noop, ring: noop, banner: () => null, shake: noop, flash: noop, glow: noop, splat: noop, fx: { clock: 1e6 }, monsters: ghoul.MONSTERS, powers: ghoul.POWERS, bosses: ghoul.BOSSES, g: {}, floorAt: () => 6, markFurthest: noop };
react(e, kit);
return played;
};
test("Ghoul Rush's House: a voice for every act in tones.js, every event plays its own sound once, and every cause has words and a sound", () => {
const known = new Set(toneNames());
for (const [act, name] of Object.entries(VOICES.marrow)) assert.ok(known.has(name), `${act}: ${name} is a tone`);
const at = { kind: "marrow", x: 190, y: 20, xs: [150], left: 3 };
const cases = { marrowLight: "light", marrowWindowOut: "windowOut", marrowRoof: "roof", marrowDoor: "door", marrowCarpet: "carpet", marrowPicketWind: "picketWind", marrowPicketUp: "picketUp", marrowShingleLand: "shingle", marrowCough: "cough", marrowBrickLand: "brick", marrowDoormen: "doormen", marrowRear: "rear", marrowStomp: "stomp", marrowSag: "sag", marrowFalseWin: "falseWin", marrowLaugh: "laugh", marrowSink: "sink", marrowGone: "gone", marrowStorm: "storm", marrowCharge: "charge", marrowStrike: "strike", marrowCrows: "crows", bossWake: "wake", bossHit: "hurt", bossDown: "die" };
for (const [type, act] of Object.entries(cases)) {
const played = heard({ type, ...at, how: "window", points: 1, life: true });
assert.equal(played.filter((n) => n === VOICES.marrow[act]).length, 1, `${type}: ${VOICES.marrow[act]} once`);
}
for (const cause of ["marrow", "marrowShingle", "marrowCarpet", "marrowPicket", "marrowBrick", "marrowQuake", "marrowBolt"]) {
assert.ok(LOSE_WORDS[cause], `${cause}: words`);
assert.ok(known.has(LOSE_SOUNDS[cause][0]), `${cause}: a sound`);
}
});
test("Ghoul Rush's lawn draws: the run up, the fight with windows of every state, every move's warning and hit, every beat of the retreat, lit and dark", () => {
const { canvas, calls } = stubCanvas();
const g = ghoul.default.create({ canvas });
g.resize(900, 900);
g.stageSelect();
for (let i = 0; i < ghoul.SELECTABLE.length; i++) g.key("down");
g.key("action");
for (let n = 0; n < 2; n++) {
for (let ms = 0; ms < ghoul.INTRO_MIN_MS + 50; ms += 16) g.tick(16);
g.key("action");
}
const r = g.round;
r.infinite = true;
const frame = (label) => {
const before = calls.count;
g.tick(16);
assert.ok(calls.count > before, `${label} draws`);
};
for (const dark of [false, true]) {
r.dark = dark;
standAt(r, 40);
frame("the run up");
standAt(r, 130);
for (let ms = 0; ms < 1600; ms += 16) g.tick(16);
r.marrow.windows.forEach((w, i) => (w.state = ["lit", "dark", "out"][i % 3]));
frame("windows lit, shuttered and out");
for (const move of ["shingles", "pickets", "carpet", "bricks", "doormen", "stomp", "lightning", "crows"]) {
Object.assign(r.boss, { plan: move, wait: 0 });
for (let ms = 0; ms < 1400; ms += 16) frame(move);
}
for (const t of [100, mw.FALSE_AT + 100, mw.LAUGH_AT + 100, mw.SINK_AT + 800, mw.GONE_AT + 100]) {
Object.assign(r.boss, { state: "down", t, gone: t >= mw.GONE_AT });
frame(`the retreat at ${t}`);
}
Object.assign(r.boss, { state: "fight", t: 0, gone: false });
}
});
@@ -0,0 +1,915 @@
// Web console tests, Ghoul Rush's Down the Hatch (the finale's first ride, after the Front Lawn): its shape (eleven swallows, every fork's hole swallows a rider who does not jump and its gristle ledge catches one who does, every uvula can be ducked, spacing, checkpoints every 8 to 10 seconds, the lip), the ride's speed on slopes and bile, its jump and duck, a rib, a uvula-lamp, a squeeze's throb, close and ease (peristalsis), the swallowed furniture, a plunge, the checkpoints, the lip and the door, the bonus round's three hearts and dice (3 to 8), endless lives for every cause, a voice for every event, the drawing, the telegraphs, and bots that ride the whole throat (one that rides well finishes, one that never dodges loses all three hearts without a game over).
// Run with: node --test scripts/test-web-console-activities-ghoul-mat.mjs
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
import * as mt from "../src/web-console/public/activities/ghoul-rush/rides/mat/ghoul-mat.js";
import * as ct from "../src/web-console/public/activities/ghoul-rush/rides/cart/ghoul-cart.js";
import { MAT_ROOM } from "../src/web-console/public/activities/ghoul-rush/rides/mat/ghoul-mat-room.js";
import { EVENT_VOICE, LOSE_SOUNDS, LOSE_WORDS, LOOKS as MAT_LOOKS, VOICES as MAT_VOICES, telegraphMarks, telegraphs, throbAt } from "../src/web-console/public/activities/ghoul-rush/rides/mat/ghoul-mat-draw.js";
import { MAT_SFX } from "../src/web-console/public/activities/ghoul-rush/rides/mat/ghoul-sfx-mat.js";
import * as ghoulSfx from "../src/web-console/public/activities/ghoul-rush/sfx/ghoul-sfx.js";
import { LOOKS, VOICES, bonusTick, react } from "../src/web-console/public/activities/ghoul-rush/draw/ghoul-draw.js";
import { BONUS_FLOOR, diceFor, endBonus, makeBonus } from "../src/web-console/public/activities/ghoul-rush/core/ghoul-bonus.js";
import { toneNames } from "../src/web-console/public/tones.js";
const steady = () => 0.5;
// The pack draws no random number: a run on this fails on the first draw.
const never = () => {
throw new Error("the mat drew a random number");
};
const events = (round, type) => round.events.filter((e) => e.type === type);
function through(round) {
round.phase = "clear";
round.phaseMs = 1;
ghoul.advance(round, 4, steady);
}
function skipCard(round) {
round.introMs = ghoul.INTRO_MIN_MS;
return ghoul.takeIntro(round);
}
// A round in Down the Hatch reached the way a run reaches it (six stages behind it, the Front Lawn
// passed), nothing woken, the clocks long, the bonus round on (three hearts).
function matRound(seed = 5) {
const round = ghoul.newRound(seed);
round.lives = 3;
round.dice = 0;
through(round);
round.cleared = ghoul.STAGES.slice(0, ghoul.RUN_STAGES).map((st) => st.id);
round.offer = null;
through(round);
assert.equal(round.spec.id, "lawn");
skipCard(round);
skipCard(round);
through(round);
assert.equal(round.spec.id, "mat");
round.phase = "play";
for (const st of round.spawns) st.over = true;
round.monsters.length = 0;
round.hordeMs = Infinity;
round.timeMs = 1e9;
round.bonus = 1e9;
round.events.length = 0;
return round;
}
const NONE = { runner: "mat", hearts: 3, rails: 0, time: 1e9, finish: 1e6, track: [], ribs: [], lows: [], squeezes: [], furniture: [], bile: [], checks: [] };
// The same round over a ride of its own (a plain track to measure the rider on).
function synth(ride) {
const round = matRound();
round.spec = { ...round.spec, start: 10, ground: [[0, 5, 0]], ride: { ...NONE, rails: (ride.track || []).length, ...ride } };
mt.MAT.place[0](round, {});
return round;
}
const FLAT = [[[0, 20], [4000, 20]]];
const DOWN = [[[0, 40], [4000, 40 - 0.1 * 4000]]];
// The rider on line `line` of the ride at `x`, at speed `v`.
function rideAt(round, x, line, { v = mt.MAT_V, safe = false } = {}) {
const y = ct.trackY(round.spec.ride, line, x);
assert.ok(y !== null, `line ${line} runs under ${x}`);
Object.assign(round.you, { x, y, vy: 0, state: "run", shelf: -1, face: 1, out: 0, safeMs: safe ? 1e9 : 0, ducking: false });
Object.assign(round.runner, { line, v, coyote: 0 });
round.camX = Math.max(0, Math.min(round.spec.length - ghoul.FIELD_W, x - 24));
}
function run(round, ms, keys = {}, random = steady) {
Object.assign(round.input, keys);
for (let t = 0; t < ms; t += 4) ghoul.advance(round, 4, random);
for (const k of Object.keys(keys)) round.input[k] = typeof keys[k] === "number" ? 0 : false;
}
function until(round, done, ms = 6000, random = steady) {
let t = 0;
for (; t < ms && !done(); t += 4) ghoul.advance(round, 4, random);
return t;
}
const press = (round) => {
round.input.jump = ghoul.JUMP_BUFFER_MS;
round.input.up = true;
};
const heard = (e, extra = {}) => {
const played = [];
const noop = () => {};
const kit = { tone: (name) => played.push(name), burst: noop, float: noop, ring: noop, banner: () => null, shake: noop, flash: noop, glow: noop, splat: noop, fx: { clock: 1e6 }, monsters: ghoul.MONSTERS, powers: ghoul.POWERS, bosses: ghoul.BOSSES, g: {}, floorAt: () => 6, ...extra };
react({ x: 10, y: 6, tx: 20, ty: 6, ...e }, kit);
return { played };
};
const ROOM = ghoul.roomById("mat");
const R = ROOM.ride;
const lines = ct.linesOf(R);
const floorOf = (x) => ghoul.groundAt(ROOM, x);
const slopeAtLine = (L, i) => (L.pts[i + 1][1] - L.pts[i][1]) / (L.pts[i + 1][0] - L.pts[i][0]);
const floors = lines.slice(0, R.rails);
const ledges = lines.slice(R.rails);
const K = { HIT_W: ghoul.HIT_W, HIT_H: ghoul.HIT_H, DUCK_H: ghoul.DUCK_H };
/* -------------------------------------------------------------- the room */
test("Ghoul Rush's Down the Hatch is the finale's room after the Front Lawn: a bonus ride of three hearts, lit, no key, no boss, about 30 seconds long", () => {
assert.equal(MAT_ROOM.ready, true, "plays in a run");
const fin = ghoul.FINALE.rooms;
assert.equal(fin[0], "lawn");
assert.equal(fin[1], "mat", "straight after the Front Lawn");
assert.deepEqual([ROOM.title, ROOM.sub], ["Down the Hatch", "Wipe your feet"]);
assert.equal(ROOM.dark, false, "always lit");
assert.equal(ROOM.key, null);
assert.equal(ROOM.boss, null);
assert.equal(ROOM.bonus, true, "a bonus round");
assert.equal(R.runner, "mat");
assert.equal(R.hearts, 3, "three hearts, not five");
assert.equal(typeof ghoul.ROOM_MUSIC.mat, "string", "a track to play");
assert.deepEqual(Object.keys(mt.MAT.monsters), [], "no new monster kinds");
assert.equal(LOOKS.mat, MAT_LOOKS.mat);
assert.equal(LOOKS.mat.pack, "mat");
assert.ok(Object.isFrozen(R) && Object.isFrozen(R.track) && Object.isFrozen(R.track[0][0]), "frozen all the way down");
assert.ok(ROOM.horde.length === 0 && ROOM.spawns.length === 0 && ROOM.items.length === 0, "no monsters and no pickups");
assert.match(R.how, /UP jump, DOWN duck, SPACE shoot/, "the keys in the how line");
assert.equal(ROOM.ground.length, 2, "the front step and the cellar floor only");
assert.ok(ROOM.ground[0][1] < 60 && ROOM.ground[1][0] > ROOM.length - 100);
assert.equal(ROOM.ground[1][0], R.finish);
assert.ok(ROOM.door > R.finish && ROOM.door > ROOM.length - 14, "the door at the room's end");
assert.ok(floorOf(ROOM.door - 2) > -Infinity);
for (const L of lines) for (let i = 0; i + 1 < L.pts.length; i++) assert.ok(L.pts[i + 1][0] > L.pts[i][0], "x rises");
assert.ok(ct.trackY(R, 0, ROOM.start) > floorOf(ROOM.start), "the mat starts on the throat over the front step");
// About 30 seconds at the mat's speed.
const secs = (floors.at(-1).x1 - ROOM.start) / mt.MAT_V;
assert.ok(secs >= 27 && secs <= 34, `${secs.toFixed(1)} s at MAT_V`);
// The swallows: descents at about 0.10 and short climbs at about 0.3, never steeper.
let down = 0;
let total = 0;
for (const L of floors) {
for (let i = 0; i + 1 < L.pts.length; i++) {
const s = slopeAtLine(L, i);
const len = L.pts[i + 1][0] - L.pts[i][0];
assert.ok(s >= -0.15 && s <= 0.32, `a slope of ${s.toFixed(3)}`);
total += len;
if (s < 0) down += len;
}
}
assert.ok(down / total > 0.6, `${((100 * down) / total).toFixed(0)}% of the throat goes down`);
for (const L of lines) for (const [, y] of L.pts) assert.ok(y > mt.DERAIL_Y + 4 && y < 46, `a floor height of ${y}`);
assert.equal(ghoul.timeFor(ghoul.roomFor("mat")), R.time);
assert.ok(R.time >= 2 * secs * 1000, "the clock never matters on a ride");
assert.ok(ct.slopeOf(R, R.rails - 1, floors.at(-1).x1) >= mt.RAMP_SLOPE, "the lip launches");
// The bonus round: three hearts of its own.
const round = matRound();
assert.equal(round.bonusRound.hearts, 3);
assert.equal(round.bonusRound.max, 3);
assert.equal(round.runner.id, "mat");
});
test("Ghoul Rush's Down the Hatch: the lip's launch alone carries the rider onto the cellar floor at any speed it can have there", () => {
const lip = floors.at(-1);
const end = lip.pts.at(-1);
const rise = ct.slopeOf(R, R.rails - 1, lip.x1);
const floor = floorOf(R.finish + 1);
for (const v of [mt.MAT_MIN, 36, mt.MAT_V, 55, mt.MAT_MAX]) {
let vy = rise * v + mt.RAMP_POP;
let x = end[0];
let y = end[1];
for (let t = 0; t < 3; t += 0.002) {
vy -= mt.MAT_G * 0.002;
x += v * 0.002;
y += vy * 0.002;
if (vy < 0 && y <= floor) break;
}
assert.ok(x >= R.finish + 2 && x <= R.finish + 40, `at ${v} it lands ${(x - R.finish).toFixed(1)} past the floor's start`);
}
});
test("Ghoul Rush's Down the Hatch: every fork's hole is too wide to jump across and swallows a rider who does not jump, its gristle ledge catches a jump from before the hole at any speed, and off the ledge's end the rider drops back onto the floor", () => {
assert.equal(R.rails - 1, 2, "two forks");
assert.equal(ledges.length, 2, "a ledge over each");
for (let i = 0; i + 1 < R.rails; i++) {
const a = lines[i];
const b = lines[i + 1];
const gap = b.x0 - a.x1;
assert.ok(gap >= 46, `hole ${i} is ${gap} wide, past a jump at bile speed`);
const end = a.pts.at(-1);
const slope = ct.slopeOf(R, i, a.x1);
assert.ok(slope < 0, "holes lie on descents (no ramp launch)");
// The ledge over it, RAIL_SEP over the throat, from before the hole to past it.
const n = ledges.findIndex((L) => L.x0 < a.x1 && L.x1 > b.x0);
assert.ok(n >= 0, `a ledge over hole ${i}`);
const L = ledges[n];
const line = R.rails + n;
assert.ok(a.x1 - L.x0 >= 16 && L.x1 - b.x0 >= 10, "the ledge starts well before the hole and ends past it");
for (let x = L.x0; x <= Math.min(L.x1, a.x1); x += 2) assert.ok(Math.abs(ct.trackY(R, line, x) - ct.trackY(R, i, x) - mt.RAIL_SEP) < 0.15, `${mt.RAIL_SEP} over at ${x}`);
assert.ok(mt.upperLine(R, line) && !mt.upperLine(R, i));
for (const v of [mt.MAT_MIN + 6, mt.MAT_V, 55, mt.BILE_V]) {
// No jump: into the hole, and a jump with no ledge would not clear it either.
assert.equal(mt.flight(R, a.x1, end[1], slope * v, v), null, `hole ${i}, no jump, at ${v}`);
const bare = { ...R, track: R.track.slice(0, R.rails) };
assert.equal(mt.flight(bare, a.x1 - 2, ct.trackY(R, i, a.x1 - 2), mt.MAT_JUMP_V + slope * v, v), null, `hole ${i} cannot be jumped across at ${v}`);
// A jump from a few units before the ledge to the hole's edge lands on the ledge.
for (const x of [L.x0 - 6, L.x0, L.x0 + 8, a.x1 - 1]) {
const top = ct.linesAt(R, x).find(([ln]) => ln === i);
const s = mt.flight(R, x, top[1], mt.MAT_JUMP_V + ct.slopeOf(R, i, x) * v, v);
assert.ok(s && s.line === line, `hole ${i}: a jump from ${x} at ${v} lands on the ledge (${JSON.stringify(s)})`);
}
}
// Off the ledge's end: down onto the floor beyond the hole.
const tail = L.pts.at(-1);
const f = mt.flight(R, L.x1, tail[1], ct.slopeOf(R, line, L.x1) * mt.MAT_V, mt.MAT_V);
assert.ok(f && f.line === i + 1, `off ledge ${n}, onto the floor`);
}
});
test("Ghoul Rush's Down the Hatch: every thing is on a line and well inside it, spaced for a player (22 between jumps and 38 between a jump and a duck), a uvula's underside between a ducked box and a standing one, the checkpoints every 8 to 10 seconds", () => {
const jumps = [];
for (const [x, line] of R.ribs) {
assert.ok(ct.trackY(R, line, x) !== null, `a rib at ${x} stands on line ${line}`);
assert.ok(!mt.upperLine(R, line), "ribs grow out of the floor");
assert.ok(x - lines[line].x0 > 8 && lines[line].x1 - x > 14, `a rib at ${x} well inside its line`);
jumps.push([x - 2, x + 2]);
}
for (const [x, line, kind] of R.furniture) {
assert.ok(ct.trackY(R, line, x) !== null);
assert.ok([0, 1, 2].includes(kind));
assert.ok(x - lines[line].x0 > 20 && lines[line].x1 - x > 14, `furniture at ${x} has room to tumble`);
jumps.push([x - 12, x + 2]);
}
for (const L of ledges) jumps.push([L.x0 - 14, L.x0 + 26]);
const ducks = [];
for (const [x0, x1] of R.lows) ducks.push([x0, x1]);
for (const [x, line] of R.squeezes) {
assert.ok(ct.trackY(R, line, x) !== null && !mt.upperLine(R, line), `a squeeze at ${x} over the floor`);
assert.ok(!ledges.some((L) => x > L.x0 - 10 && x < L.x1 + 10), "no ledge near a squeeze");
ducks.push([x - mt.SQ_W / 2 - 6, x + mt.SQ_W / 2 + 6]);
}
jumps.sort((p, q) => p[0] - q[0]);
for (let i = 0; i + 1 < jumps.length; i++) assert.ok(jumps[i + 1][0] - jumps[i][1] >= 22, `jumps at ${jumps[i][1]} and ${jumps[i + 1][0]}`);
for (const [d0, d1] of ducks) for (const [j0, j1] of jumps) assert.ok(j0 - d1 >= 38 || d0 - j1 >= 38, `a jump at ${j0} and a duck at ${d0}`);
for (const [x0, x1, y] of R.lows) {
let hi = 0;
let lo = 99;
for (let x = x0 - K.HIT_W / 2; x <= x1 + K.HIT_W / 2; x += 0.25) {
const g = ct.linesAt(R, x)[0];
assert.ok(g, "a floor or a ledge under a uvula");
hi = Math.max(hi, g[1]);
lo = Math.min(lo, g[1]);
}
assert.ok(hi + K.DUCK_H < y, `a ducked box clears the uvula at ${x0}`);
assert.ok(lo + K.HIT_H > y, `a standing box hits the uvula at ${x0}`);
}
for (const [x0, x1] of R.bile) assert.ok(x1 > x0 && ct.linesAt(R, (x0 + x1) / 2).length, "bile lies on the floor");
assert.ok(R.ribs.length >= 4 && R.lows.length >= 2 && R.squeezes.length >= 3 && R.furniture.length >= 3 && R.bile.length >= 2);
// Checkpoints every 8 to 10 seconds of riding, on the floor, clear of a jump coming up.
const cs = R.checks;
assert.ok(cs.length >= 3);
for (let i = 0; i < cs.length; i++) {
assert.ok(ct.linesAt(R, cs[i]).length, `checkpoint ${i} on the floor`);
const gap = (cs[i] - (i ? cs[i - 1] : ROOM.start)) / mt.MAT_V;
assert.ok(gap >= 7.5 && gap <= 10, `${gap.toFixed(1)} s to checkpoint ${i}`);
for (const [j0, j1] of jumps) assert.ok(j0 - cs[i] > 20 || cs[i] - j1 > 4, `a jump at ${j0} near checkpoint ${i}`);
}
});
/* ------------------------------------------------------------ the rider */
test("Ghoul Rush's Down the Hatch rolls at MAT_V on the flat, faster down a slope, faster again on bile (BILE_V), never past MAT_MIN or MAT_MAX", () => {
const flat = synth({ track: FLAT });
assert.equal(flat.runner.v, mt.MAT_V);
run(flat, 2000);
assert.ok(Math.abs(flat.runner.v - mt.MAT_V) < 0.01);
assert.equal(flat.you.face, 1);
assert.equal(flat.you.state, "run");
assert.equal(flat.you.y, 20);
const down = synth({ track: DOWN });
run(down, 3000);
assert.ok(Math.abs(down.runner.v - (mt.MAT_V + (mt.SLOPE_G * 0.1) / mt.RELAX)) < 0.2, `${down.runner.v} down a 0.1 slope`);
const slick = synth({ track: FLAT, bile: [[0, 4000]] });
run(slick, 3000);
assert.ok(Math.abs(slick.runner.v - mt.BILE_V) < 0.2, `${slick.runner.v} on bile`);
assert.equal(events(slick, "matBile").length, 1, "one word as it starts");
const steep = synth({ track: [[[0, 10000], [4000, 6000]]] });
run(steep, 3000);
assert.equal(steep.runner.v, mt.MAT_MAX);
const wall = synth({ track: [[[0, 0], [4000, 4000]]] });
run(wall, 3000);
assert.equal(wall.runner.v, mt.MAT_MIN);
});
test("Ghoul Rush's Down the Hatch jumps about 13 high for about three quarters of a second, a press saved for a landing jumps on it, and one just after a line's end still jumps", () => {
const round = synth({ track: FLAT });
let top = 0;
press(round);
const t = until(round, () => {
top = Math.max(top, round.you.y - 20);
return round.you.state === "run" && round.you.y === 20 && round.you.vy === 0 && top > 1;
}, 3000);
assert.ok(Math.abs(top - (mt.MAT_JUMP_V * mt.MAT_JUMP_V) / (2 * mt.MAT_G)) < 0.4, `${top.toFixed(1)} high`);
assert.ok(t > 650 && t < 850, `${t} ms in the air`);
assert.equal(events(round, "matJump").length, 1);
assert.equal(events(round, "matLand").length, 1);
const buf = synth({ track: FLAT });
press(buf);
run(buf, 640);
press(buf);
until(buf, () => events(buf, "matJump").length >= 2, 1500);
assert.equal(events(buf, "matJump").length, 2, "the saved press jumped again at the landing");
const edge = synth({ track: [[[0, 20], [60, 20]], [[150, 20], [300, 20]]] });
rideAt(edge, 58.5, 0);
run(edge, 80);
assert.equal(edge.runner.line, -1, "off the end");
press(edge);
run(edge, 4);
assert.equal(events(edge, "matJump").length, 1, "coyote");
});
test("Ghoul Rush's Down the Hatch: DOWN ducks; a ducked rider passes under a uvula-lamp and a standing one or a jumping one hits it (cause matUvula), a heart and not a life, once", () => {
const duck = synth({ track: FLAT, lows: [[60, 67, 23.0]] });
run(duck, 20, { down: true });
assert.equal(events(duck, "matDuck").length, 1);
duck.input.down = true;
until(duck, () => duck.you.x > 75, 3000);
duck.input.down = false;
assert.equal(duck.bonusRound.hearts, 3);
const hit = synth({ track: FLAT, lows: [[60, 67, 23.0]] });
until(hit, () => hit.bonusRound.hearts < 3, 3000);
assert.equal(hit.bonusRound.hearts, 2);
assert.equal(hit.lives, 3, "not a life");
assert.equal(events(hit, "lose")[0].cause, "matUvula");
assert.equal(events(hit, "matCrash")[0].what, "uvula");
assert.equal(hit.phase, "play", "the ride rolls on");
assert.ok(hit.you.safeMs > 0, "blinking safe");
assert.deepEqual(hit.bonusRound.perf.hits, ["u0"]);
run(hit, 1000);
assert.equal(hit.bonusRound.hearts, 2, "the same uvula costs nothing twice");
const jump = synth({ track: FLAT, lows: [[60, 67, 23.0]] });
rideAt(jump, 40, 0);
press(jump);
until(jump, () => jump.bonusRound.hearts < 3 || jump.you.x > 80, 3000);
assert.equal(jump.bonusRound.hearts, 2, "a jump does not clear a uvula");
});
test("Ghoul Rush's Down the Hatch: a rib bone is cleared by a jump from 9 to 26 short of it and costs a heart otherwise (cause matRib), once", () => {
const hit = synth({ track: FLAT, ribs: [[60, 0]] });
until(hit, () => hit.bonusRound.hearts < 3, 3000);
assert.equal(hit.bonusRound.hearts, 2);
assert.equal(events(hit, "lose")[0].cause, "matRib");
assert.equal(events(hit, "matCrash")[0].what, "rib");
assert.deepEqual(hit.bonusRound.perf.hits, ["r0"]);
run(hit, 500);
assert.equal(hit.bonusRound.hearts, 2);
for (const from of [60 - 26, 60 - 14, 60 - 9]) {
const clear = synth({ track: FLAT, ribs: [[60, 0]] });
rideAt(clear, from, 0);
press(clear);
until(clear, () => clear.you.x > 80, 3000);
assert.equal(clear.bonusRound.hearts, 3, `jumped from ${from}`);
}
// A ducked rider is no lower than a rib.
const low = synth({ track: FLAT, ribs: [[60, 0]] });
low.input.down = true;
until(low, () => low.you.x > 70, 3000);
assert.equal(low.bonusRound.hearts, 2, "ducking does not pass a rib");
});
/* ------------------------------------------------------- peristalsis */
test("Ghoul Rush's Down the Hatch: a squeeze waits, then throbs SQ_WARN_MS (two throbs heard, the walls pulsing) at least 1.5 s before you reach it, closes, holds shut while you pass and eases; a ducked rider passes under it", () => {
const round = synth({ track: FLAT, squeezes: [[200, 0]] });
rideAt(round, 40, 0);
const s = () => round.runner.squeezes[0];
assert.equal(s().state, "wait");
run(round, 100);
assert.equal(s().state, "wait", "far off: waiting");
until(round, () => s().state === "throb", 5000);
const ahead = 200 - round.you.x;
assert.ok(ahead / round.runner.v >= 1.5, `it throbs ${(ahead / round.runner.v).toFixed(2)} s ahead`);
assert.deepEqual(events(round, "matSqueezeThrob").map((e) => e.n), [1]);
assert.ok(throbAt(round.spec.ride, round.runner, 200) > 0, "the walls throb near it");
assert.equal(throbAt(round.spec.ride, round.runner, 280), 0, "and not far from it");
assert.equal(mt.squeezeLow(s()), mt.SQ_OPEN, "still open while it throbs");
const half = until(round, () => events(round, "matSqueezeThrob").length >= 2, 2000);
assert.ok(Math.abs(half - mt.SQ_WARN_MS / 2) < 20, `the second throb ${half} ms in`);
assert.equal(events(round, "matSqueezeThrob")[1].n, 2);
until(round, () => s().state === "close", 2000);
assert.equal(events(round, "matSqueezeClose").length, 1);
until(round, () => s().state === "shut", 1000);
assert.equal(mt.squeezeLow(s()), mt.SQ_LOW);
const early = 200 - mt.SQ_W / 2 - round.you.x;
assert.ok(early > 8, `shut ${early.toFixed(1)} before you reach it`);
// Ducked through it: nothing.
round.input.down = true;
until(round, () => round.you.x > 215, 2000);
round.input.down = false;
assert.equal(round.bonusRound.hearts, 3, "ducked under it");
assert.equal(s().state, "shut", "still shut as you leave it");
until(round, () => s().state === "done", 3000);
assert.equal(mt.squeezeLow({ state: "ease", t: mt.SQ_EASE_MS }), mt.SQ_LOW);
assert.equal(mt.squeezeLow({ state: "ease", t: 0 }), mt.SQ_OPEN);
// At bile speed it still throbs well ahead and is shut before you arrive.
const fast = synth({ track: FLAT, squeezes: [[300, 0]], bile: [[0, 4000]] });
rideAt(fast, 40, 0, { v: mt.BILE_V });
until(fast, () => fast.runner.squeezes[0].state === "shut", 6000);
assert.ok(300 - mt.SQ_W / 2 - fast.you.x > 8, "shut before you get there at bile speed too");
});
test("Ghoul Rush's Down the Hatch: a squeeze shut over you costs a heart standing or jumping (cause matSqueeze), and nothing while it is still open", () => {
const stand = synth({ track: FLAT, squeezes: [[200, 0]] });
rideAt(stand, 40, 0);
until(stand, () => stand.bonusRound.hearts < 3 || stand.you.x > 220, 6000);
assert.equal(stand.bonusRound.hearts, 2);
assert.equal(events(stand, "lose")[0].cause, "matSqueeze");
assert.equal(events(stand, "matCrash")[0].what, "squeeze");
assert.deepEqual(stand.bonusRound.perf.hits, ["s0"]);
const hop = synth({ track: FLAT, squeezes: [[200, 0]] });
rideAt(hop, 40, 0);
until(hop, () => hop.runner.squeezes[0].state === "shut", 6000);
until(hop, () => 200 - hop.you.x < 18, 2000);
press(hop);
until(hop, () => hop.bonusRound.hearts < 3 || hop.you.x > 220, 3000);
assert.equal(hop.bonusRound.hearts, 2, "a jump into it hits");
// Open (a rider placed past its warning), it is nothing.
const open = synth({ track: FLAT, squeezes: [[200, 0]] });
rideAt(open, 196, 0);
open.runner.squeezes[0] = { state: "throb", t: 900, n: 1 };
run(open, 200);
assert.equal(open.bonusRound.hearts, 3);
});
/* ----------------------------------------------------------- furniture */
test("Ghoul Rush's Down the Hatch: a piece of furniture drops from the roof FURN_DROP_MS when you are FURN_LEAD_MS short of it, lands, tumbles up at you and hits (cause matFurniture) if you meet it; a jump clears it", () => {
const hit = synth({ track: FLAT, furniture: [[300, 0, 1]] });
rideAt(hit, 150, 0);
const f = () => hit.runner.furniture[0];
assert.equal(f().state, "wait");
until(hit, () => f().state === "drop", 5000);
const ahead = 300 - hit.you.x;
assert.ok(Math.abs(ahead - (mt.MAT_V * mt.FURN_LEAD_MS) / 1000) < 1, `drops ${ahead.toFixed(1)} ahead`);
assert.equal(events(hit, "matFurnDrop").length, 1);
assert.ok(mt.furnitureLift(f()) > 15, "up near the roof");
assert.equal(hit.bonusRound.hearts, 3, "falling, it hurts nobody far off");
const ms = until(hit, () => f().state === "roll", 2000);
assert.ok(Math.abs(ms - mt.FURN_DROP_MS) < 20);
assert.equal(events(hit, "matFurnLand").length, 1);
assert.ok(f().x - hit.you.x > 28 && f().x - hit.you.x < 42, `lands ${(f().x - hit.you.x).toFixed(1)} ahead: time to see it`);
const x0 = f().x;
run(hit, 100);
assert.ok(x0 - f().x > mt.FURN_V * 0.09, "it tumbles at you");
until(hit, () => hit.bonusRound.hearts < 3, 2000);
assert.equal(events(hit, "lose")[0].cause, "matFurniture");
assert.equal(events(hit, "matCrash")[0].what, "furniture");
assert.equal(f().state, "spent");
assert.deepEqual(hit.bonusRound.perf.hits, ["f0"]);
const jump = synth({ track: FLAT, furniture: [[300, 0, 0]] });
rideAt(jump, 150, 0);
until(jump, () => jump.runner.furniture[0].state === "roll" && jump.runner.furniture[0].x - jump.you.x < 16, 5000);
press(jump);
until(jump, () => jump.you.x > 330, 3000);
assert.equal(jump.bonusRound.hearts, 3);
});
test("Ghoul Rush's Down the Hatch: two bolts break a piece of furniture (FURN_POINTS, an act for the grade), along the slope; what was shot stays shot after a restart", () => {
const round = synth({ track: DOWN, furniture: [[260, 0, 2]] });
rideAt(round, 120, 0);
round.you.safeMs = 1e9;
const start = round.score;
round.input.fire = true;
until(round, () => round.runner.furniture[0].state === "broken", 5000);
round.input.fire = false;
assert.equal(round.runner.furniture[0].state, "broken");
assert.equal(events(round, "matFurnHit").length, mt.FURN_HP - 1);
assert.equal(events(round, "matFurnBreak")[0].points, mt.FURN_POINTS);
assert.equal(round.bonusRound.perf.acts, 1);
assert.ok(round.score - start >= mt.FURN_POINTS);
// A bolt flies along the slope, not level.
const probe = synth({ track: DOWN });
probe.input.fire = true;
run(probe, 300);
probe.input.fire = false;
assert.ok(probe.shots.length > 0);
for (const s of probe.shots) assert.ok(Math.abs(s.y - (40 - 0.1 * s.x) - ghoul.SHOT_Y) < 0.5, "a bolt over the floor");
// Nothing to shoot while it waits in the roof.
const idle = synth({ track: FLAT, furniture: [[300, 0, 0]] });
assert.equal(mt.MAT.target(idle, { x: 300, y: 22 }), false);
const again = synth({ track: FLAT, furniture: [[300, 0, 0]] });
again.runner.furniture[0].state = "broken";
mt.MAT.place[0](again, {});
assert.equal(again.runner.furniture[0].state, "broken");
});
/* ------------------------------------------------- forks, holes and hearts */
test("Ghoul Rush's Down the Hatch: a hole with no jump is a heart (cause matPlunge), the rider goes back on the ledge over it (or the floor beyond, with none) at MAT_V and rolls on; a jump onto the ledge passes it, with a switch up and down", () => {
const ride = { track: [[[0, 20], [100, 20]], [[160, 20], [400, 20]], [[80, 27], [175, 27]]], rails: 2 };
const fall = synth(ride);
rideAt(fall, 60, 0);
until(fall, () => fall.bonusRound.hearts < 3, 3000);
assert.equal(fall.bonusRound.hearts, 2);
assert.equal(fall.lives, 3, "not a life");
assert.equal(events(fall, "lose")[0].cause, "matPlunge");
assert.equal(fall.phase, "play");
assert.equal(fall.runner.line, 2, "caught on the ledge over the hole");
assert.equal(fall.you.y, 27);
assert.equal(fall.runner.v, mt.MAT_V);
assert.deepEqual(fall.bonusRound.perf.hits, ["g0"]);
until(fall, () => fall.you.x > 200, 3000);
assert.equal(fall.runner.line, 1, "and down off its end onto the floor");
assert.equal(fall.bonusRound.hearts, 2);
const bare = synth({ track: [[[0, 20], [100, 20]], [[160, 20], [400, 20]]] });
rideAt(bare, 60, 0);
until(bare, () => bare.bonusRound.hearts < 3, 3000);
assert.equal(bare.runner.line, 1, "with no ledge: on the floor beyond the hole");
assert.ok(bare.you.x >= 160 && bare.you.x < 165);
const hop = synth(ride);
rideAt(hop, 76, 0);
press(hop);
until(hop, () => hop.runner.line === 2, 2000);
assert.equal(hop.runner.line, 2, "on the ledge");
assert.equal(events(hop, "matSwitch")[0].up, true);
until(hop, () => hop.you.x > 200, 3000);
assert.equal(hop.runner.line, 1, "back down on the floor");
assert.equal(events(hop, "matSwitch")[1].up, false);
assert.equal(hop.bonusRound.hearts, 3);
});
test("Ghoul Rush's Down the Hatch: the last heart gone ends the round with nothing at once (BONUS LOST: no life lost, the dice in hand kept, no game over) and the run goes on to the next room", () => {
const round = matRound();
round.dice = 2;
round.bonusRound.hearts = 1;
const [x] = R.ribs[0];
rideAt(round, x - 10, ct.linesAt(R, x - 10)[0][0]);
round.you.safeMs = 0;
until(round, () => round.phase === "clear", 6000);
assert.equal(round.bonusRound.hearts, 0);
assert.equal(round.bonusRound.over, true);
assert.equal(round.bonusRound.won, false);
const end = events(round, "bonusEnd");
assert.equal(end.length, 1);
assert.equal(end[0].won, false);
assert.equal(end[0].dice, 0);
assert.equal(round.over, false, "no game over");
assert.equal(round.lives, 3);
assert.equal(round.dice, 2);
run(round, ghoul.CARD_LOST_MS + 100);
const next = ghoul.FINALE.rooms[ghoul.FINALE.rooms.indexOf("mat") + 1];
if (next) {
assert.equal(round.spec.id, next, "on to the next of the House's rooms");
assert.equal(round.bonusRound, null);
assert.equal(round.runner ?? null, null);
assert.equal(round.lives, 3);
assert.equal(round.dice, 2);
} else assert.equal(round.won, true, "the last of the House's rooms ready: on to the win");
});
test("Ghoul Rush's Down the Hatch: the checkpoints are passed in order (an event each) and the ride goes back to the last one after the last heart; another ride's slot is not its own", () => {
const round = matRound();
rideAt(round, R.checks[0] - 6, ct.linesAt(R, R.checks[0] - 6)[0][0]);
round.you.safeMs = 1e9;
until(round, () => round.runner.check >= 0, 4000);
assert.deepEqual(events(round, "matCheck").map((e) => e.n), [1]);
const c0 = round.runner.check;
round.you.x = 1;
mt.MAT.place[0](round, {});
assert.equal(round.you.x, R.checks[c0]);
assert.equal(round.runner.v, mt.MAT_V);
assert.equal(round.runner.check, c0);
assert.equal(round.camLead, mt.CAM_AHEAD);
const fresh = matRound();
assert.equal(fresh.you.x, ROOM.start);
assert.equal(fresh.runner.check, -1);
const other = matRound();
other.runner = { id: "banister" };
other.spec = { ...other.spec, ride: { ...other.spec.ride, runner: "banister" } };
mt.MAT.place[0](other, {});
assert.deepEqual(other.runner, { id: "banister" });
other.runner = { id: "mat" };
mt.MAT.place[0](other, {});
assert.equal(other.runner, null);
});
test("Ghoul Rush's Down the Hatch: off the lip the rider is spat out onto the cellar floor and stops (matFinish), the door opens, and walking out ends the round with 3 to 8 Lucky dice", () => {
const round = matRound();
round.dice = 1;
const last = R.rails - 1;
rideAt(round, lines[last].x1 - 12, last, { safe: true });
until(round, () => round.runner.done, 4000);
assert.equal(round.runner.done, true);
assert.equal(events(round, "matLaunch").length, 1);
assert.equal(events(round, "matLaunch")[0].last, true);
assert.equal(events(round, "matFinish").length, 1);
assert.ok(round.you.x > R.finish + 2 && round.you.x < R.finish + 40, `${round.you.x} landed`);
assert.equal(round.you.y, floorOf(round.you.x));
assert.equal(round.hasKey, true, "the door opens");
assert.equal(round.phase, "play");
round.input.right = true;
until(round, () => round.phase === "clear", 20000);
round.input.right = false;
const end = events(round, "bonusEnd");
assert.equal(end.length, 1);
assert.equal(end[0].won, true);
assert.ok(end[0].dice >= BONUS_FLOOR && end[0].dice <= 8, `${end[0].dice} dice`);
assert.equal(round.dice, 1 + end[0].dice);
assert.equal(round.lives, 3);
});
test("Ghoul Rush's Down the Hatch: no random number is drawn in the room (the whole ride, jumping and shooting, on a draw that throws)", () => {
const round = matRound();
rideAt(round, 20, 0, { safe: true });
round.input.fire = true;
for (let t = 0; t < 30000; t += 4) {
if (t % 1500 === 0) press(round);
ghoul.advance(round, 4, never);
round.events.length = 0;
round.you.safeMs = 1e9;
if (round.phase !== "play" || round.runner.done) break;
}
assert.ok(round.you.x > 600);
});
/* ----------------------------------------------------------- the grade */
test("Ghoul Rush's Down the Hatch's grade: three hearts earn at most one die of their share, so a perfect ride is 8 dice; shooting every piece of furniture is the acts die, and taking half the souls ('Wipe your feet') the steady one", () => {
const round = matRound();
const b = round.bonusRound;
assert.equal(b.perf.goal, R.furniture.length);
assert.equal(b.perf.total, R.ribs.length + R.lows.length + R.squeezes.length + R.furniture.length + R.rails - 1);
assert.equal(b.perf.steady, false, "no souls yet");
const mk = (perf, hearts = 3) => {
const x = makeBonus({ stats: { kills: 0 }, spec: { ride: { hearts: 3 } } });
x.hearts = hearts;
Object.assign(x.perf, { total: b.perf.total, goal: R.furniture.length }, perf);
return x;
};
assert.equal(diceFor(mk({ hits: [], acts: R.furniture.length, steady: true })), 8, "a perfect ride");
assert.equal(diceFor(mk({ hits: [], acts: 0, steady: false })), 6);
assert.equal(diceFor(mk({ hits: [], acts: 0, steady: false }, 2)), 5, "two hearts left: no hearts die");
assert.equal(diceFor(mk({ hits: ["r0", "r1", "u0", "s0", "s1", "s2", "f0", "f1", "f2", "g0", "g1", "r2", "r3", "r4", "u1", "u2", "s3"], acts: 0, steady: false }, 1)), BONUS_FLOOR);
// Half the souls taken and the die is earned.
round.candy.fill(true);
rideAt(round, 30, 0, { safe: true });
run(round, 500);
assert.equal(round.bonusRound.perf.steady, true, "souls taken");
assert.ok(round.candy.length >= 30, `${round.candy.length} souls along the throat`);
});
test("Ghoul Rush's Down the Hatch: endless lives (round.infinite) spare the hearts for every cause, through the same lose path; the Garlic shield takes a hit instead of a heart", () => {
const tries = [{ ribs: [[60, 0]] }, { lows: [[56, 62, 23.0]] }, { furniture: [[300, 0, 0]] }, { squeezes: [[200, 0]] }];
for (const t of tries) {
const r = synth({ track: FLAT, ...t });
r.infinite = true;
if (t.furniture || t.squeezes) rideAt(r, 120, 0);
until(r, () => events(r, "lose").length > 0, 6000);
assert.equal(events(r, "lose").length > 0, true, JSON.stringify(Object.keys(t)));
assert.equal(r.bonusRound.hearts, 3, JSON.stringify(Object.keys(t)));
assert.equal(r.lives, 3);
}
const hole = synth({ track: [[[0, 20], [60, 20]], [[130, 20], [400, 20]]] });
hole.infinite = true;
rideAt(hole, 30, 0);
until(hole, () => events(hole, "lose").length > 0, 3000);
assert.equal(events(hole, "lose")[0].cause, "matPlunge");
assert.equal(hole.bonusRound.hearts, 3);
const garlic = synth({ track: FLAT, ribs: [[60, 0]] });
garlic.you.garlic = true;
until(garlic, () => garlic.you.x > 70, 3000);
assert.equal(garlic.bonusRound.hearts, 3);
assert.equal(garlic.you.garlic, false, "spent");
});
/* ------------------------------------------------------ sounds and words */
test("Ghoul Rush's Down the Hatch: every event has a voice that plays once, every cause has words and a sound, and the voices are tones that exist (none longer than 1.2 s)", () => {
assert.deepEqual(Object.keys(EVENT_VOICE).sort(), [...mt.EVENTS].sort(), "a voice for every event and no more");
const tones = ghoulSfx.default.tones;
for (const [event, [kind, act]] of Object.entries(EVENT_VOICE)) {
const name = MAT_VOICES[kind] && MAT_VOICES[kind][act];
assert.ok(name, `${event} has a ${kind}.${act} voice`);
assert.ok(tones[name], `${name} exists`);
assert.equal(VOICES[kind][act], name, "joined to the game's voices");
const played = heard({ type: event, what: "rib", points: 150, n: 1, kind: 0 }).played;
assert.equal(played.filter((p) => p === name).length, 1, `${event} plays ${name} once`);
}
for (const [name, tone] of Object.entries(MAT_SFX.tones)) {
assert.ok(name.startsWith("ghoulMat"), name);
assert.ok(tones[name], `${name} is merged into the game`);
const length = Math.max(...tone.layers.map((l) => (l.delay || 0) + l.seconds));
assert.ok(length <= 1.2, `${name} is ${length.toFixed(2)} s`);
for (const l of tone.layers) assert.ok(l.gain > 0 && l.gain <= 1, `${name}'s gain`);
}
for (const cause of mt.CAUSES) {
assert.ok(LOSE_WORDS[cause], `${cause} has words`);
assert.ok(LOSE_SOUNDS[cause] && LOSE_SOUNDS[cause].length === 3 && toneNames().includes(LOSE_SOUNDS[cause][0]), `${cause} has a sound`);
assert.ok(heard({ type: "lose", cause, hearts: 2 }).played.length > 0, `${cause} sounds`);
}
});
test("Ghoul Rush's Down the Hatch: the room's own names do not collide with the game's (events, causes, tones, the shared rider slot)", () => {
for (const e of mt.EVENTS) assert.ok(e.startsWith("mat"), e);
for (const c of mt.CAUSES) assert.ok(c.startsWith("mat"), c);
assert.deepEqual(Object.keys(mt.MAT).filter((key) => ["hazards", "bosses", "boss"].includes(key)), []);
assert.equal(matRound().runner.id, "mat");
assert.equal(matRound().cart, null);
});
/* --------------------------------------------------------------- drawing */
function stubCtx() {
return new Proxy({}, { get: (t, name) => (name in t ? t[name] : () => {}), set: (t, name, value) => ((t[name] = value), true) });
}
// A live game in Down the Hatch through the stage select's finale row, its second room.
function selectInto() {
const g = ghoul.default.create({ canvas: { width: 0, height: 0, getContext: () => stubCtx() } });
g.resize(900, 900);
g.stageSelect();
const p = g.round;
for (let i = 0; i < ghoul.SELECTABLE.length - 1; i++) ghoul.steerSelect(p, 1, 0);
ghoul.steerSelect(p, 0, 1);
assert.equal(p.select.room, 1);
g.tick(16);
ghoul.takeSelect(p);
return g;
}
test("Ghoul Rush's Down the Hatch draws: the room lit and dark, the rider on the floor, on a ledge, in the air and ducking, each thing in each state (squeezes waiting, throbbing, closing, shut and easing, furniture falling and tumbling), a crash, the finish and the cards; the stage select goes straight into it", () => {
const g = selectInto();
const r = g.round;
assert.equal(r.spec.id, "mat");
assert.equal(r.runner.line, 0);
assert.equal(r.you.y, ct.trackY(R, 0, ROOM.start));
assert.equal(r.bonusRound.hearts, 3);
r.lives = 99;
const spots = [ROOM.start + 4, R.ribs[0][0] - 10, R.lows[0][0] - 5, R.squeezes[0][0] - 14, R.furniture[0][0] - 20, R.bile[0][0] + 6, R.checks[0], ledges[0].x0 + 20, lines[0].x1 + 10, R.finish - 30];
const SQ = ["wait", "throb", "close", "shut", "ease", "done"];
const FU = ["wait", "drop", "roll", "broken", "spent"];
for (const dark of [true, false]) {
for (const x of spots) {
r.dark = dark;
r.phase = "play";
for (const st of r.spawns) st.over = true;
r.monsters.length = 0;
const top = ct.linesAt(R, x)[0] || [R.rails - 1, 20];
rideAt(r, x, top[0], { safe: true });
r.runner.squeezes = r.runner.squeezes.map((s, i) => ({ state: SQ[(i + (x | 0)) % SQ.length], t: 300, n: 1 }));
r.runner.furniture = r.runner.furniture.map((f, i) => ({ ...f, state: FU[(i + (x | 0)) % FU.length], t: 400 }));
for (const air of [false, true]) {
if (air) Object.assign(r.you, { state: "air", vy: 20, y: r.you.y + 4 });
if (air) r.runner.line = -1;
r.you.ducking = !air && x === R.lows[0][0] - 5;
r.shots.push({ x: x + 6, y: r.you.y + 2.4, vx: 130, vy: -10, gone: 0 });
for (let k = 0; k < 4; k++) g.tick(16);
r.you.safeMs = 1e9;
rideAt(r, x, top[0], { safe: true });
}
}
}
// A crash.
r.you.safeMs = 0;
rideAt(r, R.ribs[0][0] - 3, R.ribs[0][1]);
for (let k = 0; k < 30; k++) g.tick(16);
assert.ok(r.bonusRound.hearts < r.bonusRound.max || r.phase !== "play", "the crash draws too");
// The finish, the won and lost cards.
const done = selectInto();
const d = done.round;
d.phase = "play";
d.runner.done = true;
d.runner.restX = R.finish + 20;
Object.assign(d.you, { x: R.finish + 30, y: floorOf(R.finish + 30), state: "run" });
d.camX = R.finish - 40;
for (let k = 0; k < 10; k++) done.tick(16);
for (const won of [true, false]) {
endBonus(d, won, { ROOM_POINTS: 300, award: (rd, pts) => (rd.score += pts) });
d.bonusRound.over = true;
for (let k = 0; k < 10; k++) {
done.tick(16);
bonusTick(d, { tone() {}, fx: {} });
}
d.bonusRound.over = false;
}
});
/* ------------------------------------------------------------ telegraphs */
test("Ghoul Rush's Down the Hatch telegraphs: JUMP over ribs and at each fork's ledge, DUCK under uvulas and squeezes, none for furniture (it warns by itself), words only on the first three of each kind, the same every time", () => {
const marks = telegraphMarks(R);
const answers = { rib: "JUMP", fork: "JUMP", uvula: "DUCK", squeeze: "DUCK" };
assert.equal(marks.length, R.ribs.length + ledges.length + R.lows.length + R.squeezes.length);
for (const m of marks) assert.equal(m.answer, answers[m.kind], m.kind);
const m = marks.find((q) => q.kind === "squeeze");
const alphaOf = (x) => (telegraphs(R, x).find((t) => t.kind === "squeeze" && t.lead === m.lead) || { alpha: 0 }).alpha;
assert.equal(alphaOf(m.lead - 45), 0, "not yet in view");
assert.ok(alphaOf(m.lead - 36) > 0 && alphaOf(m.lead - 36) < 1, "fading in");
assert.equal(alphaOf(m.lead - 10), 1);
assert.equal(alphaOf(m.lead + 7), 0, "gone once passed");
assert.deepEqual(telegraphs(R, m.lead - 33), telegraphs(R, m.lead - 33), "deterministic");
for (const kind of ["rib", "squeeze"]) {
const of = marks.filter((q) => q.kind === kind).sort((p, q) => p.lead - q.lead);
of.forEach((q, i) => {
assert.equal(q.n, i);
const shown = telegraphs(R, q.lead - 32).find((t) => t.lead === q.lead && t.kind === kind);
assert.equal(shown.words, i < 3, `${kind} ${i}`);
});
}
});
/* ----------------------------------------------------------- the bots */
// A bot that rides well: it jumps 9 to 15 short of a rib, onto each fork's ledge a few units before
// it starts, over a piece of furniture tumbling at it when it is 6 to 17 short (and holds the
// blaster, which usually breaks it first), and ducks under every uvula and every squeeze. `miss`
// is the share of things it fails to dodge (by a hash).
const mix = (a, b) => {
let h = Math.imul(a + 0x9e37, 0x85ebca6b) ^ Math.imul(b + 0x7f4a, 0xc2b2ae35);
h ^= h >>> 13;
h = Math.imul(h, 0x5bd1e995);
h ^= h >>> 15;
return (h >>> 0) / 4294967296;
};
function goodBot(round, seed, miss = 0.04) {
const { you, runner: c, input: inp } = round;
inp.left = inp.right = inp.down = false;
inp.fire = true;
if (round.phase !== "play" || !c || c.done) {
inp.up = false;
return;
}
const ok = (x) => mix(seed, Math.round(x)) >= miss;
const look = 9 + (seed % 7);
let jump = false;
if (c.line >= 0) {
const line = c.line;
const onFloor = !mt.upperLine(R, line);
for (const [x, ln] of R.ribs) if (ln === line && x - you.x > 6 && x - you.x < look && ok(x)) jump = true;
if (onFloor) for (const L of ledges) if (L.x0 - you.x > 1 && L.x0 - you.x < 6 && ok(L.x0)) jump = true;
R.furniture.forEach(([, ln], i) => {
const f = c.furniture[i];
if (ln === line && f.state === "roll" && f.x - you.x > 6 && f.x - you.x < 17 && ok(f.x)) jump = true;
});
for (const [x0, x1] of R.lows) if (you.x > x0 - 10 && you.x < x1 + 3 && ok(x0)) inp.down = true;
for (const [x] of R.squeezes) if (you.x > x - mt.SQ_W / 2 - 10 && you.x < x + mt.SQ_W / 2 + 3 && ok(x)) inp.down = true;
}
if (jump && !inp.down) press(round);
else inp.up = false;
}
function idleBot(round) {
const inp = round.input;
inp.left = inp.right = inp.down = false;
inp.up = false;
inp.fire = true;
}
function rideWith(seed, bot, limit = 60000) {
const round = matRound(seed);
const lost = [];
let t = 0;
for (; t < limit && round.phase !== "clear" && !round.over; t += 16) {
bot(round);
if (round.runner && round.runner.done && round.phase === "play") round.input.right = true;
ghoul.advance(round, 16, steady);
for (const e of round.events) if (e.type === "lose") lost.push(e.cause);
if (round.runner && !round.runner.done) {
const off = round.you.x - round.camX;
assert.ok(off > 4 && off < 70, `the rider stays in view (${off.toFixed(1)} from the left edge at ${round.you.x.toFixed(0)})`);
}
round.events.length = 0;
}
return { round, lost, ms: t };
}
test("Ghoul Rush's Down the Hatch: a bot that rides well finishes the whole throat in about 30 seconds, 5 to 8 dice, a heart lost at most, past every checkpoint, never a run life", () => {
const dice = [];
for (let seed = 1; seed <= 12; seed++) {
const { round, lost, ms } = rideWith(seed, (r) => goodBot(r, seed));
const b = round.bonusRound;
assert.equal(b.won, true, `seed ${seed} finished (lost ${lost.join(",")})`);
assert.ok(ms > 26000 && ms < 38000, `${ms} ms`);
assert.ok(b.dice >= 5 && b.dice <= 8, `${b.dice} dice`);
assert.ok(lost.length <= 1, `lost ${lost.join(",")}`);
assert.equal(round.lives, 3, "never a run life");
assert.equal(round.runner.check, R.checks.length - 1, "past every checkpoint");
dice.push(b.dice);
}
assert.ok(dice.reduce((a, b) => a + b, 0) / dice.length >= 6, `${dice.join(",")}`);
});
test("Ghoul Rush's Down the Hatch: a bot that never dodges (holding fire) loses all three hearts early, ends with 0 dice (BONUS LOST), and the run goes on: no game over, never a run life", () => {
for (let seed = 1; seed <= 6; seed++) {
const { round, lost } = rideWith(seed, idleBot);
const b = round.bonusRound;
assert.equal(b.won, false, "never finishes");
assert.equal(b.dice, 0);
assert.equal(b.hearts, 0);
assert.equal(lost.length, 3, `lost ${lost.join(",")}`);
assert.ok(round.you.x < ROOM.length * 0.4, `out at ${round.you.x}`);
assert.equal(round.lives, 3);
assert.equal(round.over, false);
assert.equal(round.phase, "clear", "the lost card, then the next room");
}
});
test("Ghoul Rush's Down the Hatch's intro banner says the controls plainly", () => {
assert.match(R.how, /UP jump/);
assert.match(R.how, /DOWN duck/);
assert.match(R.how, /SPACE shoot/);
assert.match(R.how, /throb/);
});
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's Deep Seam Mine stage: its four rooms (always dark, the cage lifts, the water, the rockfall), rocks that fall after a dust warning and crush monsters and cost a life, the knocker imp that steals your light but never a life, the canary ghost whose scream brings three rocks down, the dead miner that digs out of the wall, the blind crawler that hunts by sound, the cage you can ride, the Hard Hat and Dynamite (found only here), and the Tommyknocker, who knocks, sweeps his hammer, puts the lights out, sinks into the seam and bursts out dazed, and rages at half his hp. // Web console tests, Ghoul Rush's Deep Seam Mine stage: its four rooms (always dark, the cage lifts, the water, the rockfall), rocks that fall after a dust warning and crush monsters and cost a life, the knocker imp that steals your light but never a life, the canary ghost whose scream brings three rocks down, the dead miner that digs out of the wall, the blind crawler that hunts by sound, the cage you can ride, the Hard Hat and Dynamite (found only here), and the Tommyknocker, who knocks, sweeps his hammer, puts the lights out, sinks into the seam and bursts out dazed, and rages at half his hp.
import "./seed-random.mjs";
import { test } from "node:test"; import { test } from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js"; import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,5 +1,6 @@
// Web console tests, Ghoul Rush's Gardener's Revenge (the Grounds' bonus round, between the Gazebo and the Groundskeeper's Yard): its shape (every pond and ditch clears with a jump and swallows a mower that does not jump, every low can be ducked), the mower's motion, each obstacle's cost and cause, the blades (cutting, the heat, the jam, the lawn cut), the topiary beasts, the hearts, the checkpoints, the finish and the dice, endless lives, the art on a fake canvas, and the two bots (one that plays well finishes in time, one that never dodges loses). // Web console tests, Ghoul Rush's Gardener's Revenge (the Grounds' bonus round, between the Gazebo and the Groundskeeper's Yard): its shape (every pond and ditch clears with a jump and swallows a mower that does not jump, every low can be ducked), the mower's motion, each obstacle's cost and cause, the blades (cutting, the heat, the jam, the lawn cut), the topiary beasts, the hearts, the checkpoints, the finish and the dice, endless lives, the art on a fake canvas, and the two bots (one that plays well finishes in time, one that never dodges loses).
// Run with: node --test scripts/test-web-console-activities-ghoul-mower.mjs // Run with: node --test scripts/test-web-console-activities-ghoul-mower.mjs
import "./seed-random.mjs";
import { test } from "node:test"; import { test } from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js"; import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,5 +1,6 @@
// Web console tests, Ghoul Rush's Holy Roller (the Chapel's bonus round, between the Organ Loft and the Choir): an endless-runner seen from behind, in three lanes. Its room and its seeded course (every thing in the way has a safe answer, a safe path exists at every moment), the speed ramp, the lanes and the wall bump, the jump and the slide, each kind of obstacle's cost and cause, the gargoyles and the bell ropes, the wax souls, the combo and the halo's magnet, the grade, the last heart ending the round with the run going on, endless lives, the Garlic shield, the sounds and words, the drawing on a fake canvas, and bots that play it well and badly. // Web console tests, Ghoul Rush's Holy Roller (the Chapel's bonus round, between the Organ Loft and the Choir): an endless-runner seen from behind, in three lanes. Its room and its seeded course (every thing in the way has a safe answer, a safe path exists at every moment), the speed ramp, the lanes and the wall bump, the jump and the slide, each kind of obstacle's cost and cause, the gargoyles and the bell ropes, the wax souls, the combo and the halo's magnet, the grade, the last heart ending the round with the run going on, endless lives, the Garlic shield, the sounds and words, the drawing on a fake canvas, and bots that play it well and badly.
// Run with: node --test scripts/test-web-console-activities-ghoul-pew.mjs // Run with: node --test scripts/test-web-console-activities-ghoul-pew.mjs
import "./seed-random.mjs";
import { test } from "node:test"; import { test } from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js"; import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
Loaded 100 of 268 files, more files were not shown because too many files have changed in this diff. Show more