Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
81d14c8e78 | ||
|
|
e963513a8a | ||
|
|
9583b68a2e | ||
|
|
cc02631ab5 | ||
|
|
cc97161a23 | ||
|
|
bc2c7c6c41 | ||
|
|
f8a0a6bfc7 | ||
|
|
eb235dd91e | ||
|
|
7f1851fbb9 | ||
|
|
7509b09b81 | ||
|
|
bf23d7eeea | ||
|
|
ff1c793633 | ||
|
|
6cd7a7ff80 | ||
|
|
88c72dc2ce | ||
|
|
82298d256c | ||
|
|
aecc3afb4c | ||
|
|
e681d1f70d |
No files matched your search
@@ -5,7 +5,7 @@
|
||||
|
||||
```
|
||||
plan2code/
|
||||
├── src/ # Source workflow prompts (17 markdown files)
|
||||
├── src/ # Source workflow prompts (19 markdown files)
|
||||
│ ├── plan2code-0-pathfinder-references/ # Reference files for pathfinder skill
|
||||
│ │ ├── brief.md # Dated plain-English decision briefs
|
||||
│ │ ├── chart.md # MODE A: destination + frontier grills, templates
|
||||
@@ -16,9 +16,9 @@ plan2code/
|
||||
│ │ ├── handoff.md # Clearing gate + PLAN-DRAFT handoff
|
||||
│ │ └── trail.md # Every-response map visual + pathed resume command
|
||||
│ ├── shared-references/ # Reference files shared across skills
|
||||
│ │ ├── building-habits.md # Find the cause, test first, pin behavior (quick-task, implement, implement-review)
|
||||
│ │ ├── helper-strength.md # How strong a model and how much effort each helper gets (init, init-update, pathfinder, plan, revise-plan, document, quick-task, implement, implement-review, review, finalize, xray, diagnose)
|
||||
│ │ └── test-runs.md # Choosing what tests to run: targeted per task and phase, full suite only where the plan puts it (document, implement, implement-review, quick-task, review, finalize)
|
||||
│ │ ├── 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, 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, pr-prep, test)
|
||||
│ ├── plan2code-review-references/ # Reference files for review skill
|
||||
│ │ ├── verification-protocol.md # Deep verification + confidence calibration
|
||||
│ │ ├── 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
|
||||
│ ├── plan2code-4-finalize-references/ # Reference files for finalize skill
|
||||
│ │ └── 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)
|
||||
│ └── plan2code-<skill>-scripts/ # A skill's own scripts, same copy rule (pathfinder, finalize, changelog, git and xray each have one)
|
||||
│ ├── 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, 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-metrics/ # Recursive self-improvement toolchain
|
||||
│ ├── 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-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-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-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 |
|
||||
| `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 |
|
||||
| `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` |
|
||||
@@ -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.
|
||||
|
||||
**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/`)
|
||||
|
||||
@@ -238,8 +247,8 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `static.mjs` | serving the page's own files: `SERVABLE` (the allow-list), `TYPES`, caching and ETags, the accent colors, and `CSS_ORDER` + `joinedStyles()`, the one place the cascade order is stated |
|
||||
| `workspace.mjs` | the session's extra folders, and the folders remembered per project and spec |
|
||||
| `public/activities.js` | the list of activities (`ACTIVITIES`: each game's id, title, picker card line `blurb` and module path) an optional `courses` list (Mini golf's six course ids, which open a course dashboard), `bestKey(id, course?)`, the flat looks.json key for its best score (`activityBestSnake`, one per golf course `activityBestGolfPirate` to `activityBestGolfFrost`, `activityBestTrails`, `activityBestBugs`, `activityBestDrive`, `activityBestStack`, `activityBestBumper`, `activityBestRapids`, `activityBestFuse`, `activityBestHop`, `activityBestBounce`, `activityBestGhoul`); lists Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road and Ghoul Rush, `bestKeys(entry)`, every best key a game keeps, and documents the game contract including the course parts (`courses` and `preview()` on the export, `setCourse()` and `course` on the game), the optional `pointer(type, x, y)`, `release(name)` (a game key let go) and `lowerIsBetter`; data only, imported by the page and by Node |
|
||||
| `public/activities/snake.js` | Snake: its rules as plain exported functions and the game contract (`create({ canvas, tone, onScore })` returning `start`, `pause`, `resume`, `key`, `tick`, `resize`, `score`, `state`); it never runs a timer or listens for keys, so the Activities window drives it |
|
||||
| `public/activities/trails.js` | Light Trails: its rules as plain exported functions (`newRound`, `newHeat`, `turn`, `boost`, `advance` in 8 ms slices (where your crash is held for `GRACE_MS`, a turn in that time riding out of it; rivals get no grace), `choose` and `room` for the rivals' flood-fill steering, `applyPower`, `spawnItem`, `closeRing`), the `ARENAS` (rivals, sharpness and what each adds), the `POWERS` pads and the game contract; memo is the furthest arena reached; a read-only `round` getter for the tests only |
|
||||
| `public/activities/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` (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/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 |
|
||||
@@ -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/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/flock.js` | Flock Dash: its rules as plain exported functions over a round (`newRound(seed)`, `steer`, `recordPath`, `placeFlock`, `screenX`, `collect`, `spawnStrays`, `advance`) and the game contract. The flock is a recorded path with running arc length: follower k sits `k * SPACING` behind the leader along it. |
|
||||
| `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, the strays, the flock, Planny as the lead bird with a star for an eye, and the pills. |
|
||||
| `public/activities/fuse.js` | Hot Potato: its rules as plain exported functions over a round on a 104 by 70 arena (`newRound`, `newMatch(round, venue)`, which lights each bomb on a rival, never you, in a match's first fuse, `advance` in 8 ms slices over `round.input`, which `key()` and `release()` set, `move` (speed eased toward the held direction at `GRIP`, a dash holding its line, belts and ice from the floor), `dash` (a holder's dash is a numbered lunge), `tag` (a holder touching a runner with no bomb passes it, never inside `NO_TAGBACK_MS` of the bomb changing hands, nor back to the one who just passed it within `TAGBACK_MS` while three or more are left, `tagBack`, with `tagSafe` saying who is safe that way for the drawing; a fuse under `PASS_FLOOR_MS`, `NO_TAGBACK_MS` plus `PASS_REACT_MS`, is raised to it on any pass, once a fuse for each runner (`bomb.lifted`); your pass scores, a hot one under `HOT_MS` as passed steps the streak), `burn` (Freeze takes its share first), `blast` (the holder out, everyone near knocked back, the match over when that was you or one is left), `nextFuse` (a survivor with no bomb, the next shorter fuse from `fuseFor`, never more bombs than one for every two left), `think` (a holder chases by its own flood-fill path, weighted toward a boxed-in or dashless target; a runner without a bomb scores candidate spots by the holders' path distance against its own and flees to the best; personalities bend both), `applyPower`, `spawnPickup`, `speedOf`, `clearLine`, `rivalPower` and `venueFor` (each built once per venue), `rivalColors(you)`), the `VENUES`, `LAYOUTS`, `RIVALS` and `POWERS`, and the game contract with `release()` (`key(name, repeat)` never dashes on a repeat); a rival holder winds up (`WINDUP_MS`, shorter when sharp) or, a Trickster, feints (`FAKE_MS`) before a lunge, and a runner a lunge comes at dodges once a lunge at its venue's odds after its reaction time; the fuse ticks quicker and higher as it burns down, on one clock however many bombs burn (yours, else the shortest); a bomb whose fuse has run out passes to nobody; memo is the furthest venue reached, which can pass 9; a read-only `round` getter for the tests only. Tuned by a scratch sim (see "As built" in `game-ideas/hot-potato.md`) |
|
||||
| `public/activities/fuse-draw.js` | Hot Potato's drawing: `drawScene(ctx, view)` from one view object `fuse.js` refills each frame, in arena units: the strip above the arena in the page's colors with the pills (laid out by `hudLayout`, which starts a second row rather than run into the fuse and centers its rows in the strip), each venue's floor in its fixed palette (`themeFor`, `venueColor`), ice, running belts, the Rooftop's open edge, the things to run round, pickups, the runners (Planny on his feet with his star eye and stick arms, flailing while he holds a bomb, and still Planny when charred; arms and feet on the floor in `limbInk(level)`, the ink that stands out from that venue's tiles; rivals with a mark per personality; a white ring with a dark edge at the feet of a runner safe from a tag-back; the charred waddle to the nearest wall and the fall from the roof), the bomb over its holder (a red ball with a `<<<` band, growing and glowing as it burns, flashing white while it cannot be passed, its fuse a shortening curl with a spark, the last seconds in big numbers (under the holder's feet when there is no room above, `countY`), a hop across on a pass), blast clouds, the Blackout's dark worked out once a frame in cells, the red edge pulse in a fuse's last second, banners and the start and end strip with the big final score, and `readColors(canvas)`; decides nothing |
|
||||
| `public/activities/hop.js` | Crossing Rush: its rules as plain exported functions over a round on a strip `COLS` (11) cells wide of 30 to 40 lanes, `VIEW_ROWS` (14) on the board at once (`newRound`, `newHeat(round, zone)`, which builds the heat's lanes from the round's seed, kept when a heat runs again, `buildLanes(zone, seed)` (groups of road, highway, ice, river, turtle, rapids or rail lanes with a grass row between each two, the zone's new thing first; the same seed builds the same lanes), `advance` in 8 ms slices (lanes flow, riders drift with their log, rivals choose, everyone is checked where they stand before any hop moves on, then hops and flights; hoppers home in the same slice finish by the moment each landed, a dead heat to you), `hop(round, hopper, dir)` (one cell, two with a Spring; a hopper counts in the cell it leaves for the first half and the one it lands on for the second; an icy lane slides it a cell more), `laneAt`, `occupied(round, row, col, atMs)` (a car or a train on it, or in a river no float or the edge, `atMs` ahead through `shiftAt`, which follows a lane's flips, surges and a Horn exactly), `sendBack` (to the last grass row, `safeBelow`, crediting a shove within `SHOVE_CREDIT_MS`), `shove(round, from, to)` (a cell the way `from` faces, only on a hopper `inReach` and never on one past the half of its hop home, once every `SHOVE_MS`), `plan(round, hopper, random, power)` (a look ahead of `LOOKAHEAD` to `LOOKAHEAD_SHARP` hops over the lanes as they will move, each hop followed by the hopper's wait where it lands; never a hop where it would be hit or fall in at full sharpness; a sloppy rival now and then hops on regardless), `applyPower`, `zoneFor` and `rivalPower` (each built once per zone), `rivalColors(you)`, `standings`), the `ZONES`, `RIVALS` and `POWERS`, and the game contract with `release()` (`key(name, repeat)` hops once a press: never on a repeat, never again until the arrow is let go, never with the press that plays on, and with one hop queued behind the one in the air; a pause drops what is held and the queue); rivals wait `REACT_MS` down to a sharp rival's after each landing, a Bruiser shoves anyone beside it into a lane, a Tagalong follows a row behind you and shoves near the top, and a rival that lets a shove go weighs the next one only after `SHOVE_LOOK_MS`; memo is the furthest zone reached, which can pass 9; a read-only `round` getter for the tests only. Tuned by a scratch sim (see "As built" in `game-ideas/crossing-rush.md`) |
|
||||
@@ -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-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/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/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). |
|
||||
@@ -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-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-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 |
|
||||
| `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 |
|
||||
@@ -410,9 +448,11 @@ 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/spec-states.js` | the spec states (`diagnosed`, `fixed`, `exploring`, `mapped`, `planned`, `documented`, `building`, `built`, `unrecognized`): each one's picker label, the card it is the natural next step for and its recommendation, data only; which cards a state lights lives in `skills.js`, how a folder maps to a state in `classifySpec()` in `scan.mjs` |
|
||||
| `public/state.js` | the page's shared state (`page.S` the server's truth, `page.local` what is staged) and the `redraw()` / save hooks every screen calls; defines only |
|
||||
| `public/tones.js` | the activities' sound engine, all synthesized in the browser. Three parts: a shared kit of rich one-shot sounds (`RICH`: `layers` of parts played together, each a wave or a noise (`noise`, `pink`, `brown`) with its own `delay`, `gain`, `attack`, a sweeping `filter` and `vibrato`: `explode`, `smash`, `skid`, `whoosh`, `splashBig`, `fanfare`, `gameOver` and some fifty more, up to 1.2 s, at most `MAX_VOICES` parts sounding at once), held **hums** (`hum(id, name, level, pitch)`, called every frame a game wants it: oscillators and noise through one filter that follows the pitch, pulsed for an engine's strokes; a hum not asked for within `HUM_HOLD_MS` fades by itself, so a paused or closed game goes quiet without saying so, `hushTones()` quiets every one and the Activities window calls it whenever it stops ticking; at most `MAX_HUMS`; shared ones `car`, `toycar`, `electric`, `outboard`, `river`, `wind`, `cycle`, `fuse`, `haunt`, `squeal`, `meter`, `swarm`, `train`, `crowd`), and each game's own extras in `public/activities/<id>-sfx.js` (`{ tones, hums }`, plain objects, names prefixed with the game id, merged and frozen here; a name may be defined once across all of them, which `scripts/test-web-console-tones.mjs` checks along with every spec's shape and every name a game's source asks for). Everything plays through one compressor. The older single blips (`BLIPS`): `tone(name, level, pitch)` with an optional loudness from 0 to 1 and an optional pitch that scales every frequency, kept between 0.25 and 4, `unlockTones()`; Snake's blips plus golf's `putt`, `wall`, `bump`, `cup`, `ace` (a three-note rise), `splash`, `power` (a power-up, three notes), `tunnel`, `boom` (a cannon putt), `sizzle` (lava) and `fall` (the pit), the countdown's `count` and `go`, Stack Deploy's `thunk`, `slice` and `perfect`, which it pitches up a scale step for each perfect in a row, and Bumper Ring's `ram`, pitched and leveled by how hard the hit, and `rev`, a rival winding up a dash, and Hot Potato's `tick`, the fuse, which it ticks quicker and pitches higher as the fuse burns down, and `pop`, a pass, and Crossing Rush's `hop`, which it pitches up a step for each quick hop forward in a row, `boing`, a send-back, `bell`, a train coming, and `horn`, and Bounce Road's `engine`, a soft low triangle hum it plays every few frames while you pick up speed (quiet once you cruise or coast), pitched up with your speed, `spring`, a jump, pitched with your speed, and `squash`, a rival flattened, pitched up a step for each in a chain, and `beat`, a low thump while your wheels run on the verge (it borrows the other games' blips for its hazards and rivals), and Rapids Run's `pew` (a shot, a short soft triangle played quietly about seven times a second while fire is held), `charge` (a buoy taken), `lowcell` (the low battery's two-note beep, quicker the lower it runs), `dambreak` (a dam bursting) and `skim` (a bank skimmed at speed, pitched up the more you have skimmed), and Ghoul Rush's `ghoulBlast` (the blaster's bolt, a short soft triangle repeated while fire is held), `zombiePop` (a kill, pitched up a step for each in the chain), `ghoulStomp`, `ghoulBoo`, `ghoulRoar` and `zombieGroan` (now kept for the other games and the tests: Ghoul Rush's monsters speak with their own voices from `ghoul-sfx.js`), `ghoulCandy` (pitched up for candy in quick succession), `batSwoop` (a bat's kill), `doorUnlock` (the key), `doorThrough` (the door to the next room) and `creakBoard` (a crawler coming up, a chandelier or a crumbling board about to go), all soft triangles and sines), silent while Play sounds is off; separate from `sound.js`'s cue queue |
|
||||
| `public/music.js` | the games' chiptune music: a small sequencer over `tones.js`'s context and compressor (`audioOut()`). A game calls `music(name, intensity)` from its `tick`; the track fades out within `MUSIC_HOLD_MS` once it stops being asked for, picks up again on the bar it left, asking for a different track crossfades the two over `CROSSFADE_S` (the old one keeps playing as it fades, so a new level is not a cut), and `hushMusic()` stops it at once. Tracks are note data under `music` in each game's `activities/<id>-sfx.js` (`{ bpm, rush, voices, patterns, order }`: pulse, triangle and noise-drum voices, each joining once the intensity reaches its `from`; a step a token, `A4`, `-` to hold, `.` a rest, `A3^037` an arpeggio, drums `k s h o`), read by `compileTrack()` and booked `LOOKAHEAD_S` ahead on the audio clock. The window plays it only while Play sounds, Play game sounds and Play game music (`looks.gameMusic`, off by default) are all on |
|
||||
| `public/activities/snake-sfx.js` · `public/activities/golf-sfx.js` · `public/activities/trails-sfx.js` · `public/activities/bugs-sfx.js` · `public/activities/drive-sfx.js` · `public/activities/stack-sfx.js` · `public/activities/bumper-sfx.js` · `public/activities/rapids-sfx.js` · `public/activities/fuse-sfx.js` · `public/activities/hop-sfx.js` · `public/activities/bounce-sfx.js` · `public/activities/ghoul-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/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, 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/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` has `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/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/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) |
|
||||
@@ -432,6 +472,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-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-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/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 |
|
||||
@@ -484,7 +529,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 |
|
||||
| `console.md` | the core of the agent-facing contract, read once per conversation (every skill ships the same copy, so a dashboard hop never re-reads it): starting, the turn (`post --wait`, the exit codes, handling a send, `settle`), posting, the payload and its kinds, documents (including `file` blocks), the house rules, and an index of the topic files below with the moment each is read. A test caps it at 24,000 characters |
|
||||
| `console-finish.md` · `console-stop.md` · `console-chat.md` · `console-workspace.md` · `console-subagents.md` · `console-launches.md` · `console-meter.md` · `console-attachments.md` · `console-trouble.md` | topic files, each read only when its moment first comes: finishing (the finish and its buttons), stop requests (the way home mid-workflow, `stopWarning`, resuming a pause), Quick questions, the Workspace, standing instructions and helper reports, dashboard launches and the menu payload, the session meter's `run` events (read only when a `run` is refused: the notes inline every `run`), keeping a cited note attachment, and recovery |
|
||||
| `notes/<workflow>.md` | per-workflow notes (`init` for both inits, `pathfinder` with Briefs, `plan`, `revise-plan`, `document`, `implement` for both builds, `loop` for a build the desktop app's Implementation Loop runs with `--loop` (where it reports a `loopOutcome` instead of asking for sign-off), `quick-task`, `review`, `finalize`, `handoff`, `changelog`, `git`, `xray`, `diagnose`). Each skill's Interface line reads `<D>/console.md` and its own notes file right after `open`; a test checks every skill names one that exists |
|
||||
| `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 |
|
||||
|
||||
Key design points:
|
||||
@@ -530,7 +575,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`.
|
||||
- **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.
|
||||
- **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.
|
||||
|
||||
@@ -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` |
|
||||
| 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 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` |
|
||||
|
||||
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.
|
||||
|
||||
@@ -21,7 +21,7 @@ Run from the repo root (the folder holding `install.js` and `src/launcher/`). Ru
|
||||
|
||||
### 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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
### 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
|
||||
|
||||
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`.
|
||||
- Ids are unique within each list, and labels are unique within each list.
|
||||
- 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`:**
|
||||
|
||||
|
||||
@@ -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
|
||||
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.
|
||||
- **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
|
||||
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
|
||||
@@ -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,
|
||||
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
|
||||
Drive has a song for each road, Ghoul Rush a track for each room, played at
|
||||
one steady level and fuller in a boss fight): turn on **Play game music** in **User Preferences → Sounds &
|
||||
activities** (it starts off). **Play game sounds** there turns the games'
|
||||
Drive has a song for each road, Snake a different one at every level, dealt from ten at
|
||||
the start of a round so none repeats, and Ghoul Rush a track for each room, played at
|
||||
one steady level and fuller in a boss fight), and Light Trails plays five
|
||||
recorded songs as background music, each in full, one after another in an
|
||||
order shuffled for every run: turn on **Play game music** in **User
|
||||
Preferences → Sounds & activities** (it starts off). **Play game sounds** there turns the games'
|
||||
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
|
||||
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
|
||||
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 and Sunset Drive start at 70,
|
||||
Ghoul Rush at 65).
|
||||
|
||||
- **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
|
||||
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
|
||||
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**
|
||||
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,
|
||||
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
|
||||
crash costs one of your three lives and runs the heat again, and you and the
|
||||
last rival out at once is a draw that costs nothing. Each arena brings
|
||||
something: a second rival and **power-up pads** at 2 (**Boost**, a charge;
|
||||
**Phase**, ride through trails for 3 seconds; **Eraser**, wipes the trails
|
||||
around you; **Slow-mo**, the rivals crawl; coins; and from arena 4 a
|
||||
**1UP**), **crystals** at 3, a third rival and a pair of **portals** at 4,
|
||||
**closing walls** at 5 (from 10 seconds in, the outer ring turns to stone
|
||||
every 3.5 seconds, flashing red first), and a second pair of portals at 6.
|
||||
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 it hit your trail), 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.
|
||||
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. Every 750 points gives
|
||||
a life back (up to nine). Each arena brings something: a second rival and
|
||||
**power-up pads** at 2 (**Boost**, a charge; **Phase**, ride through trails
|
||||
for 3 seconds; **Eraser**, wipes the trails around you; **Slow-mo**, the
|
||||
rivals crawl; coins; a beating **Heart**, a life; and a **Shield**, held
|
||||
from heat to heat until it takes a crash for you, wiping the trails around
|
||||
you and riding on), **crystals** at 3 with a **Laser** (for 6 seconds it
|
||||
fires at any rival head in your line up to 16 cells ahead, cutting through
|
||||
trails but not crystals, three shots, each a rival out with the cut bonus)
|
||||
and **Score x2** (8 seconds of double points), a third rival and a pair of
|
||||
**portals** at 4 with a **Wide Trail** (4 seconds of a wall three cells
|
||||
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
|
||||
(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
|
||||
@@ -982,8 +1000,12 @@ Ghoul Rush at 65).
|
||||
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
|
||||
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.
|
||||
Each stage cleared makes the next quicker and tougher. Every other room keeps a **horde**
|
||||
out, space or up goes in. Clear six stages and the run takes you back to
|
||||
**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
|
||||
never safe. **Zombies** shamble out of doors in the wall and sprint once
|
||||
you are close, **crawlers** drag themselves up through loose boards,
|
||||
@@ -1717,6 +1739,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.
|
||||
|
||||
**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:
|
||||
|
||||
- **Start prompt**: `/plan2code` by default. Leave it blank to start the agent with nothing typed.
|
||||
|
||||
@@ -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 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`).
|
||||
- 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.
|
||||
- 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).
|
||||
- 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.
|
||||
|
||||
@@ -14,8 +14,9 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
- **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".
|
||||
- **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.
|
||||
- **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**: **Ask for suggestions**, a chip in the **Notes on this** panel of an open choice, multi or confirm card, asks Plan2Code what it would pick and why, on its own: it sends one request for that card (with anything typed in the note box), and every pick already staged, on that card or another, stays staged. The request shows in the thread tagged **Asked for suggestions** until the agent replies there, with the chip held off meanwhile; `console.md` tells the agent to answer a `Suggestions wanted on <title>:` line in the item's thread with each suggestion and why, re-posting the question only when that helps. A re-post that drops an option clears only the pick staged on it, and a banner names the question.
|
||||
- **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**: 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.
|
||||
- **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 five lives and runs the heat again, and every 750 points gives a life back (up to nine). 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, a beating Heart for a life, and a Shield, held from heat to heat until it takes a crash for you), crystals at 3 with a Laser that zaps rival heads in your line through their trails and Score x2, portals at 4 with a Wide Trail three cells across (you can turn onto the side cells just laid, so a corner never crashes you) and Coin Rain, walls that close in a ring at a time, flashing first, at 5 with a Hyperjump out to open space, and at 6 a rainbow Mystery pad that could be any of them; the first pad of each kind in a run says it is new. A rival out while you still ride scores points, and more when your trail or your laser got it. You ride with Planny's star eye, and the start and end screens show the furthest arena you have reached and what waits next.
|
||||
- **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.
|
||||
- **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.
|
||||
@@ -32,6 +33,7 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
- **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**: Light Trails has background music: five recorded songs that play one after another, each in full, for as long as a run lasts. Every new run shuffles them into a fresh order and starts the first from the top, never the song the last run was playing, and once all five have played they are shuffled again. A pause picks the song up where it stopped. It plays under **Play game music**, at the game's own **Music** slider. The light cycles' engine drones (yours and the nearest rival's) are much quieter now, so the songs carry the run, and the game's other sounds are a little louder (1.4 times), so they still cut through.
|
||||
- **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.
|
||||
@@ -52,10 +54,15 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
- **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`.
|
||||
- **pr-prep**: a new dashboard utility, **Get a PR ready** (`/plan2code-pr-prep`), for the moment before you open a pull request. It reads what changed on the branch, asks first whether to include uncommitted work, and picks the checks that cover the changes from the project's test map (or, with no map, from commands it finds in the project's config files and confirms with you), each with a reason, plus the full suite when shared ground was touched. You untick what to skip; it runs the rest with a timeout per check and says **Ready**, **Ready with notes** (something trimmed, timed out, could not start, or a changed file no test covers) or **Not ready**. It writes a PR description to copy, following the repo's pull-request template when there is one, with the create-a-PR link (no `gh` needed), and offers to save the report as `PR-READINESS-<date>.md` in the branch's spec folder. It never commits, pushes or opens the PR.
|
||||
- **test**: a new dashboard utility, **Write missing tests** (`/plan2code-test`). It asks where to look (the branch's changes, a folder or the whole project), finds the source files no test covers by matching them to tests by name, folder and imports, and offers a real coverage run on top when the project already has a coverage tool (Node's test runner, Jest, Go, or Vitest, pytest-cov and Coverlet when installed), never running it silently. The plan opens with **How this project writes tests** for each runner (folder, file naming, command, helpers, assertion style), so the new tests match the old ones; on your approval it writes and runs unit and integration tests. It never changes source code: a test that exposes a real bug is kept, on a yes, as the reproduction for `/plan2code-diagnose`. A project with no runner is offered its language's built-in one (`node --test`, `unittest`, `go test`, `cargo test`), and a job past 8 source files, 8 new test files or 2 runners can **Continue** with the top 8 gaps or **Escalate** to a PLAN-DRAFT that `/plan2code-1-plan` resumes at Phase 2.
|
||||
- **test map**: projects can describe their tests in one Markdown table under `## Test map` in `AGENTS.md` (or behind one link to `.agents-docs/AGENTS-test-map.md`), with the columns `Area`, `Paths` (globs), `Run` (the command for that area) and `Shared` (`yes` when a change there reaches everything). PR Prep and Test read it to pick checks and runners, and offer to write or update it at the end of a run. **Init** proposes one when it finds test commands, and **Init Update** checks an existing map's paths and commands still match the project and offers one when tests exist but no map does; nothing is written without a yes.
|
||||
- **git**: after a push or publish, or when the branch is pushed with nothing left to commit, the git skill now names `/plan2code-pr-prep` as the likely next step: run the checks and write the PR description.
|
||||
- **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.
|
||||
- **desktop app**: the Implementation Loop setup has **Set strength per phase**: pick Thrifty, Balanced, Best or Match my session for each phase of the spec, and each phase's agent starts on the model and effort that strength maps to for the loop's agent. A phase left alone runs on the launch choice, so a loop with the toggle off behaves as before. The phase's helpers follow its strength, the one retry steps up a strength, and the loop strip and the loop report show what each phase ran on. Claude Code and Devin ship with a mapping; for any other agent **Strengths in the loop** in User Preferences, Agents & models, maps each strength to one of its models.
|
||||
|
||||
### 💥 Breaking
|
||||
|
||||
|
||||
@@ -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/`) |
|
||||
| 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 |
|
||||
| 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 |
|
||||
| git | /plan2code-git | Your repo | Commits (`<subject>` / `AI Assisted`), branches, pull with conflict help, push, publish |
|
||||
|
||||
|
||||
@@ -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 |
|
||||
| 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 |
|
||||
| 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 |
|
||||
| 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-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-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-git` | Branches, pull, push and commits on one board (or plain instructions in the terminal); asks before every push, publish and delete |
|
||||
|
||||
|
||||
@@ -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
|
||||
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).
|
||||
- **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
|
||||
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**.
|
||||
|
||||
|
Before Width: | Height: | Size: 110 KiB After Width: | Height: | Size: 119 KiB |
|
Before Width: | Height: | Size: 114 KiB After Width: | Height: | Size: 122 KiB |
|
Before Width: | Height: | Size: 89 KiB After Width: | Height: | Size: 90 KiB |
|
Before Width: | Height: | Size: 97 KiB After Width: | Height: | Size: 95 KiB |
|
Before Width: | Height: | Size: 109 KiB After Width: | Height: | Size: 113 KiB |
|
Before Width: | Height: | Size: 119 KiB After Width: | Height: | Size: 123 KiB |
|
Before Width: | Height: | Size: 115 KiB After Width: | Height: | Size: 117 KiB |
|
Before Width: | Height: | Size: 122 KiB After Width: | Height: | Size: 122 KiB |
|
Before Width: | Height: | Size: 97 KiB After Width: | Height: | Size: 97 KiB |
|
Before Width: | Height: | Size: 103 KiB After Width: | Height: | Size: 101 KiB |
|
Before Width: | Height: | Size: 106 KiB After Width: | Height: | Size: 109 KiB |
|
Before Width: | Height: | Size: 117 KiB After Width: | Height: | Size: 119 KiB |
|
Before Width: | Height: | Size: 96 KiB After Width: | Height: | Size: 97 KiB |
|
Before Width: | Height: | Size: 104 KiB After Width: | Height: | Size: 105 KiB |
@@ -143,7 +143,7 @@ const SOURCE_PROMPTS = [
|
||||
displayName: 'Init Mode',
|
||||
description: 'Generate AGENTS.md file for project-specific guidance',
|
||||
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: [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' }
|
||||
@@ -156,7 +156,7 @@ const SOURCE_PROMPTS = [
|
||||
displayName: 'Init Update Mode',
|
||||
description: 'Update existing AGENTS.md with new learnings',
|
||||
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: [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ 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: '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',
|
||||
stepNumber: 'changelog',
|
||||
@@ -380,6 +409,8 @@ function generateStepLabel(prompt) {
|
||||
if (prompt.stepNumber === 'git') return 'Git';
|
||||
if (prompt.stepNumber === 'xray') return 'X-ray';
|
||||
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 === 'quick') return 'Quick Task';
|
||||
return `Step ${prompt.stepNumber}`;
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
"fix:eol": "node scripts/fix-line-endings.mjs",
|
||||
"play": "node scripts/play.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": {
|
||||
"gpt-tokenizer": "2.9.0",
|
||||
|
||||
@@ -207,6 +207,8 @@ impl AgentManager {
|
||||
},
|
||||
brief,
|
||||
prompt,
|
||||
None,
|
||||
Vec::new(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -231,6 +233,42 @@ impl AgentManager {
|
||||
},
|
||||
None,
|
||||
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,
|
||||
restart_brief: Option<String>,
|
||||
first_prompt: String,
|
||||
launch_choice: Option<StartChoice>,
|
||||
launch_env: Vec<(String, String)>,
|
||||
) -> Result<(), String> {
|
||||
let mut inner = lock(&self.shared.inner);
|
||||
if inner.state == AgentState::Running {
|
||||
@@ -249,7 +289,10 @@ impl AgentManager {
|
||||
}
|
||||
inner.brief_note = None;
|
||||
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(()),
|
||||
Err(e) => {
|
||||
// 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
|
||||
/// prompt again.
|
||||
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);
|
||||
if inner.last_start.is_none() {
|
||||
return Err("no agent has been started".to_string());
|
||||
@@ -282,7 +361,7 @@ impl AgentManager {
|
||||
let _ = old.host.kill();
|
||||
}
|
||||
}
|
||||
match self.shared.spawn(&mut inner, prompt) {
|
||||
match self.shared.spawn(&mut inner, prompt, choice, extra_env) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => {
|
||||
inner.state = AgentState::Ended {
|
||||
@@ -427,11 +506,28 @@ impl Shared {
|
||||
/// end. `prompt` is this launch's first prompt: the stored brief for a
|
||||
/// start or a Restart, or a transient one (`start_fresh`,
|
||||
/// `start_transient`) that a Restart must not repeat.
|
||||
fn spawn(self: &Arc<Self>, inner: &mut Inner, prompt: String) -> Result<(), String> {
|
||||
let (choice, _) = inner
|
||||
.last_start
|
||||
.clone()
|
||||
.ok_or("no agent has been started")?;
|
||||
///
|
||||
/// `choice_override` runs this launch on another choice than the stored
|
||||
/// one (which it never replaces), and `launch_env` is added to the
|
||||
/// process env after the manager's own; both are empty for every caller
|
||||
/// 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(
|
||||
&choice.kind,
|
||||
&self.folder,
|
||||
@@ -443,6 +539,7 @@ impl Shared {
|
||||
if let Ok(extra) = self.extra_env.lock() {
|
||||
spec.env.extend(extra.iter().cloned());
|
||||
}
|
||||
spec.env.extend(launch_env);
|
||||
let generation = self.generation.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
|
||||
let on_output = {
|
||||
@@ -520,7 +617,7 @@ impl Shared {
|
||||
.unwrap_or_else(|| choice.kind.default_prompt().to_string())
|
||||
})
|
||||
.ok_or("no agent has been started")?;
|
||||
match self.spawn(inner, prompt) {
|
||||
match self.spawn(inner, prompt, None, Vec::new()) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => {
|
||||
inner.state = AgentState::Ended {
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
//! retry; every other failure stops at once through `stop_loop`, the one place
|
||||
//! a stop goes, with its evidence on the page.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
@@ -27,6 +28,7 @@ use crate::loop_commit;
|
||||
use crate::loop_notify::{self, NotifyKind};
|
||||
use crate::loop_report::{self, EntryResult, LoopReport, ReportEntry};
|
||||
use crate::loop_tools;
|
||||
use crate::models::{self, StrengthRow};
|
||||
use crate::session_reader::{self, ReadError};
|
||||
|
||||
// ---------------------------------------------------------------- the setup
|
||||
@@ -74,6 +76,57 @@ pub enum AfterLast {
|
||||
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`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
@@ -97,6 +150,10 @@ pub struct LoopSetup {
|
||||
/// The query parameter or JSON field that carries the message, for the
|
||||
/// kinds that let the person name it.
|
||||
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 {
|
||||
@@ -114,6 +171,8 @@ impl Default for LoopSetup {
|
||||
notify_kind: NotifyKind::Query,
|
||||
notify_url: String::new(),
|
||||
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 subject: Option<String>,
|
||||
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)]
|
||||
@@ -321,6 +383,37 @@ pub struct RunningRecord {
|
||||
/// 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.
|
||||
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 {
|
||||
@@ -375,6 +468,48 @@ impl RunningRecord {
|
||||
start_head: None,
|
||||
own_dirty: Vec::new(),
|
||||
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,
|
||||
/// Stop after this phase can be turned on (false on the run's last phase).
|
||||
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 {
|
||||
@@ -422,6 +562,9 @@ impl LoopStateEvent {
|
||||
stop_after_phase: false,
|
||||
stopping: 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)
|
||||
.and_then(|at| rec.phases.get(at))
|
||||
.filter(|p| p.status == PhaseStatus::Done);
|
||||
let run = rec.phase_run(rec.current);
|
||||
LoopStateEvent {
|
||||
running: true,
|
||||
spec_name: rec
|
||||
@@ -452,6 +596,12 @@ pub fn state_event(rec: &RunningRecord) -> LoopStateEvent {
|
||||
stop_after_phase: rec.stop_after_phase,
|
||||
stopping: rec.stop_now,
|
||||
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,
|
||||
subject: None,
|
||||
retries: 0,
|
||||
strength: phase_pick(&setup, spec, n, p["name"].as_str().unwrap_or("")),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
@@ -1020,6 +1171,33 @@ pub fn prepare_with(
|
||||
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
|
||||
/// them. Writes to the spec, so Start calls it only after the confirm.
|
||||
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")?;
|
||||
// A build that stopped earlier carries on in the same report.
|
||||
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) {
|
||||
rec.report = report;
|
||||
}
|
||||
@@ -1340,6 +1523,32 @@ 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.
|
||||
pub fn fix_prompt(spec: &str) -> String {
|
||||
format!("/plan2code-3-implement {spec}/overview.md --web")
|
||||
@@ -1376,12 +1585,21 @@ fn start_phase(ctx: &Ctx, index: usize) -> Result<(), String> {
|
||||
rec.phase_started_at = Instant::now();
|
||||
rec.activity_checked = Instant::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,
|
||||
// and says what is happening between phases.
|
||||
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;
|
||||
if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) {
|
||||
rec.generation = generation;
|
||||
@@ -1719,6 +1937,10 @@ fn fail(ctx: &Ctx, snap: &Snapshot, cause: StopCause, detail: String) -> bool {
|
||||
return false;
|
||||
}
|
||||
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 name = phase_name(ctx);
|
||||
add_entry(
|
||||
@@ -2098,11 +2320,19 @@ fn phase_assumptions(
|
||||
/// 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.
|
||||
fn add_entry(ctx: &Ctx, entry: ReportEntry) {
|
||||
let mut entry = entry;
|
||||
let saved = {
|
||||
let mut guard = lock(&ctx.slot);
|
||||
let Some(rec) = guard.as_mut().filter(|r| r.run_id == ctx.run_id) else {
|
||||
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.project.clone(), rec.report.clone())
|
||||
};
|
||||
@@ -2575,6 +2805,11 @@ fn stop_loop(ctx: &Ctx, cause: StopCause, line: String, can: &[&str]) {
|
||||
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_failure = loop_report::save(&ctx.home, &rec.project, &rec.report).err();
|
||||
let mut evidence = evidence_with_report(&evidence_markdown(&cause, &line, &rec), &rec);
|
||||
@@ -3048,6 +3283,7 @@ mod tests {
|
||||
commit: None,
|
||||
subject: None,
|
||||
retries: 0,
|
||||
strength: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3545,6 +3781,43 @@ second line"
|
||||
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]
|
||||
fn the_setup_is_found_under_the_consoles_folded_key() {
|
||||
let dir = std::env::temp_dir().join(format!("plan2code-loop-setup-{}", std::process::id()));
|
||||
@@ -4428,6 +4701,223 @@ second 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]
|
||||
fn a_refused_commit_stops_the_loop() {
|
||||
if !harness_ready("refused commit") {
|
||||
@@ -5984,9 +6474,17 @@ second line"
|
||||
}
|
||||
|
||||
fn wait_for_generations(seen: &Arc<Mutex<String>>, count: usize) {
|
||||
wait_until("the agent generations", || {
|
||||
launched_prompts(seen).len() >= count
|
||||
});
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
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]
|
||||
|
||||
@@ -59,6 +59,12 @@ pub struct ReportEntry {
|
||||
/// Things the app noticed that did not stop the phase (leftover Suggestions).
|
||||
pub warnings: Vec<String>,
|
||||
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 {
|
||||
@@ -281,6 +287,14 @@ fn entry_markdown(md: &mut String, e: &ReportEntry) {
|
||||
} else if e.result == EntryResult::Passed {
|
||||
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 {
|
||||
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();
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,9 @@
|
||||
//! agents never come through here: their menu is their own `models` in
|
||||
//! agents.json.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
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)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -211,7 +332,7 @@ mod tests {
|
||||
assert!(baked.len() > 1);
|
||||
std::fs::write(&missing, "{ nope").unwrap();
|
||||
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]
|
||||
@@ -234,4 +355,157 @@ mod tests {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -432,3 +432,57 @@ fn a_custom_agent_runs_the_override_too_and_restart_keeps_its_id() {
|
||||
);
|
||||
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());
|
||||
}
|
||||
@@ -181,7 +181,22 @@ export function loopBanner(state) {
|
||||
}
|
||||
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})` : "";
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1891,6 +1891,169 @@
|
||||
"args": [
|
||||
"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": [
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -64,10 +64,11 @@ export function scrubbedEnv(extra = {}) {
|
||||
for (const k of AMBIENT_GIT_ENV) delete process.env[k];
|
||||
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], {
|
||||
cwd: cwd || ROOT,
|
||||
encoding: "utf8",
|
||||
input,
|
||||
env: scrubbedEnv({ PLAN2CODE_NOW: NOW, ...env }),
|
||||
});
|
||||
let json = null;
|
||||
|
||||
@@ -11,7 +11,7 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
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";
|
||||
|
||||
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, []);
|
||||
});
|
||||
|
||||
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", () => {
|
||||
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" }]) {
|
||||
|
||||
@@ -36,12 +36,14 @@ export const BUDGETS = {
|
||||
"handoff.md": 300,
|
||||
"implement.md": 5700,
|
||||
"init.md": 300,
|
||||
"loop.md": 11100,
|
||||
"loop.md": 11600,
|
||||
"pathfinder.md": 2400,
|
||||
"plan.md": 700,
|
||||
"pr-prep.md": 4500,
|
||||
"quick-task.md": 4000,
|
||||
"review.md": 1000,
|
||||
"revise-plan.md": 1200,
|
||||
"test.md": 5400,
|
||||
"xray.md": 2500,
|
||||
},
|
||||
// One printed line each, for a session with one choice card.
|
||||
|
||||
@@ -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" }]);
|
||||
});
|
||||
|
||||
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", () => {
|
||||
const shipped = JSON.parse(fs.readFileSync(path.join(path.dirname(LAUNCHER), "models.json"), "utf8"));
|
||||
assert.ok(shipped.claude.length > 0);
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
// 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);
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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`);
|
||||
}
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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"));
|
||||
});
|
||||
@@ -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}`);
|
||||
}
|
||||
});
|
||||
@@ -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"))) {
|
||||
const t = fs.readFileSync(path.join(dir, f), "utf8");
|
||||
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?)`);
|
||||
}
|
||||
}
|
||||
// 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 */
|
||||
@@ -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"]);
|
||||
});
|
||||
|
||||
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 () => {
|
||||
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);
|
||||
|
||||
@@ -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/);
|
||||
});
|
||||
|
||||
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.
|
||||
if (process.env.npm_lifecycle_event !== "test") {
|
||||
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-review",
|
||||
"plan2code-4-finalize",
|
||||
"plan2code-pr-prep",
|
||||
"plan2code-quick-task",
|
||||
"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", () => {
|
||||
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, /which checks are quick/);
|
||||
assert.match(init, /run single test \(and beside it a note of 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");
|
||||
assert.match(upd, /\*\*4\. Testing\*\* - .*the test map and quick checks/);
|
||||
assert.match(upd, /\| Testing \| Commands\? Test map and quick checks stale\?/);
|
||||
assert.match(upd, /\*\*4\. Testing\*\* - .*the `## Test map` table and quick checks/);
|
||||
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");
|
||||
});
|
||||
@@ -0,0 +1,765 @@
|
||||
// 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 { 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(",")}`);
|
||||
}
|
||||
});
|
||||
@@ -34,6 +34,11 @@ function selectInto(at, room, texts = [], opts = {}) {
|
||||
g.round.select = { at, room };
|
||||
g.round.practice = true;
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -244,7 +249,8 @@ test("Ghoul Rush boss intros: the card draws for every boss at many moments, thr
|
||||
const sizes = { W: 96, H: 54 };
|
||||
for (const room of bossRooms) {
|
||||
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 BOSS_ART = new Proxy({}, { get: (t, k) => (k === id ? (ctx, pic, b) => calls.push([pic, b]) : undefined) });
|
||||
const texts = [];
|
||||
@@ -261,7 +267,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`);
|
||||
// The same through the game's own drawing, with the real art.
|
||||
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);
|
||||
for (let ms = 0; ms < 5000; ms += 80) {
|
||||
g.round.introMs = ms;
|
||||
|
||||
@@ -102,7 +102,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");
|
||||
});
|
||||
|
||||
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 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);
|
||||
@@ -110,12 +110,13 @@ test("Ghoul Rush: picking up Lucky dice stacks them to nine, then pays points li
|
||||
assert.equal(round.dice, 1);
|
||||
assert.equal(round.drops.length, 0);
|
||||
assert.equal(events(round, "power")[0].kind, "die");
|
||||
for (let k = 0; k < 8; k++) ghoul.applyPower(round, "die");
|
||||
assert.equal(round.dice, 9);
|
||||
assert.equal(ghoul.MAX_HELD_DICE, 13);
|
||||
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;
|
||||
ghoul.applyPower(round, "die");
|
||||
assert.equal(round.dice, 10, "no cap");
|
||||
assert.equal(round.score, score, "no points instead");
|
||||
assert.equal(round.dice, ghoul.MAX_HELD_DICE, "no more past it");
|
||||
assert.equal(round.score, score + ghoul.POWER_POINTS, "points instead");
|
||||
const canvas = { getContext: () => null };
|
||||
const game = ghoul.default.create({ canvas });
|
||||
game.start();
|
||||
@@ -239,13 +240,18 @@ test("Ghoul Rush: a 5 saves him with a heart and no shield, a 4 just saves him,
|
||||
lose(held, "pit");
|
||||
ghoul.advance(held, ghoul.ROLL_MS + 8, rolls(FOUR));
|
||||
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);
|
||||
full.lives = 9;
|
||||
full.lives = ghoul.MAX_LIVES;
|
||||
const score = full.score;
|
||||
lose(full, "zombie");
|
||||
ghoul.advance(full, ghoul.ROLL_MS + 8, rolls(FIVE));
|
||||
assert.equal(full.lives, 10, "no cap");
|
||||
assert.equal(full.score, score, "no points instead");
|
||||
assert.equal(full.lives, ghoul.MAX_LIVES, "never past MAX_LIVES (13)");
|
||||
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", () => {
|
||||
|
||||
@@ -0,0 +1,380 @@
|
||||
// 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 { 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,703 @@
|
||||
// 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 { 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);
|
||||
for (let ms = 0; ms < 1600; 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");
|
||||
});
|
||||
@@ -818,7 +818,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");
|
||||
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.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.
|
||||
for (const [act, y] of [["hang", 26], ["low", 6]]) {
|
||||
Object.assign(b, { act, y, x: 170, wait: 1e9, lowMs: 1e9 });
|
||||
|
||||
@@ -3,6 +3,7 @@ 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 { 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 { toneNames } from "../src/web-console/public/tones.js";
|
||||
|
||||
@@ -23,9 +24,14 @@ function winRun(h) {
|
||||
const r = h.round;
|
||||
through(r);
|
||||
while (!r.over) {
|
||||
// The ending's pages once the House is dead.
|
||||
if (r.phase === "ending") {
|
||||
skipEnding(r);
|
||||
continue;
|
||||
}
|
||||
r.phaseMs = 0;
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,576 @@
|
||||
// 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 { 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");
|
||||
});
|
||||
@@ -51,8 +51,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(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.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.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.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"));
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,643 @@
|
||||
// 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 { 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,914 @@
|
||||
// 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 { 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/);
|
||||
});
|
||||
@@ -12,6 +12,7 @@ import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
|
||||
import { skipStory as storySkip } 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 { BANNER_SHADE, CHUNK, GAUGE_COOL, GAUGE_HOT, GAUGE_WARM, LOOKS, SEAM, VOICES, contrast, gaugeColor, hudLayout, labelSpot, limbInk } from "../src/web-console/public/activities/ghoul-rush/draw/ghoul-draw.js";
|
||||
import { ACCENTS } from "../src/web-console/public/palette.js";
|
||||
import { humNames, toneNames } from "../src/web-console/public/tones.js";
|
||||
@@ -379,7 +380,7 @@ test("Ghoul Rush: shelves are one way (jumped up through from below, landed on f
|
||||
const tops = r.spec.shelves.filter(([a, b]) => x >= a && x <= b).map(([, , y]) => y);
|
||||
const want = Math.max(ground, ...tops);
|
||||
if (want === -Infinity) continue;
|
||||
Object.assign(r.you, { x, y: 40, vy: -ghoul.FALL_MAX, state: "air", shelf: -1, drop: -1, out: 0 });
|
||||
Object.assign(r.you, { x, y: 48, vy: -ghoul.FALL_MAX, state: "air", shelf: -1, drop: -1, out: 0 });
|
||||
for (let k = 0; k < 500 && r.you.state === "air"; k++) ghoul.moveYou(r, 4);
|
||||
assert.equal(r.you.y, want, `${r.spec.id} at ${x.toFixed(1)}`);
|
||||
}
|
||||
@@ -1709,7 +1710,7 @@ test("Ghoul Rush: with the time bonus run out, a zombie shambles in from the edg
|
||||
test("Ghoul Rush: each stage is three rooms and a boss's, every room in one stage but the hall, and roomFor builds a room deeper into a run quicker and tougher, its boss with more hp and points, each capped", () => {
|
||||
assert.equal(ghoul.ROOMS[0].id, "hall", "every run starts in the hall");
|
||||
assert.equal(ghoul.ROOMS[0].boss, null);
|
||||
const placed = ghoul.STAGES.flatMap((st) => st.rooms);
|
||||
const placed = ghoul.SELECTABLE.flatMap((st) => st.rooms);
|
||||
assert.equal(new Set(placed).size, placed.length, "no room in two stages");
|
||||
// Every room but the hall is in a stage; one in none is a room forgotten.
|
||||
assert.deepEqual([...placed].sort(), ghoul.ROOMS.slice(1).map((r) => r.id).sort(), "every room but the hall in a stage");
|
||||
@@ -1734,9 +1735,9 @@ test("Ghoul Rush: each stage is three rooms and a boss's, every room in one stag
|
||||
const far = ghoul.roomFor("ballroom", 400);
|
||||
assert.ok(far.pace <= 1.4 && far.every >= 0.55 && far.tough <= 2 && far.extra <= 2);
|
||||
assert.equal(far.bossHp, ghoul.roomFor("ballroom", ghoul.BOSS_DEPTH_MAX).bossHp, "boss hp stops growing");
|
||||
const r = ghoulRound("foyer", 3);
|
||||
const r = ghoulRound("foyer", 2);
|
||||
const z = put(r, "zombie", 80);
|
||||
assert.equal(z.hp, ghoul.MONSTERS.zombie.hp + 1, "three stages in, zombies take a bolt more");
|
||||
assert.equal(z.hp, ghoul.MONSTERS.zombie.hp + 1, "two stages in (four steps), zombies take a bolt more");
|
||||
});
|
||||
|
||||
test("Ghoul Rush: out of the hall, and out of each boss's room, you pick the next stage from two not yet played; left and right move the pick, a press only takes one once the offer settles, and a stage never comes again", () => {
|
||||
@@ -1774,7 +1775,7 @@ test("Ghoul Rush: out of the hall, and out of each boss's room, you pick the nex
|
||||
through(r2);
|
||||
assert.deepEqual(r2.cleared, [want]);
|
||||
assert.equal(r2.stats.stages, 1);
|
||||
assert.deepEqual(events(r2, "stageClear").map((e) => [e.stage, e.n, e.of]), [[want, 1, ghoul.STAGES.length]]);
|
||||
assert.deepEqual(events(r2, "stageClear").map((e) => [e.stage, e.n, e.of]), [[want, 1, ghoul.RUN_STAGES]]);
|
||||
assert.equal(r2.phase, "pick");
|
||||
assert.ok(!r2.offer.includes(want), "a stage cleared is never offered again");
|
||||
assert.deepEqual(ghoul.stagesLeft(r2).map((st) => st.id), ghoul.STAGES.filter((st) => st.id !== want).map((st) => st.id));
|
||||
@@ -1791,19 +1792,28 @@ test("Ghoul Rush: out of the hall, and out of each boss's room, you pick the nex
|
||||
assert.equal(seen.size, ghoul.STAGES.length, "the offer is shuffled: any stage can come first");
|
||||
});
|
||||
|
||||
test("Ghoul Rush: clearing every stage wins the run, and its end says so", () => {
|
||||
test("Ghoul Rush: clearing RUN_STAGES stages and then the finale's rooms wins the run, and its end says so", () => {
|
||||
const round = ghoul.newRound(5);
|
||||
round.dice = 0;
|
||||
through(round);
|
||||
while (!round.over) {
|
||||
while (round.cleared.length < ghoul.RUN_STAGES) {
|
||||
assert.equal(round.phase, "pick");
|
||||
round.phaseMs = 0;
|
||||
ghoul.pickStage(round);
|
||||
for (let k = 0, n = ghoul.stageById(round.stage).rooms.length; k < n; k++) through(round);
|
||||
}
|
||||
assert.equal(round.stage, ghoul.FINALE.id, "on to the House, with no offer");
|
||||
for (const id of ghoul.FINALE.rooms) {
|
||||
assert.equal(round.over, false);
|
||||
assert.equal(round.spec.id, id);
|
||||
through(round);
|
||||
}
|
||||
assert.equal(round.phase, "ending", "the ending's pages first");
|
||||
skipEnding(round);
|
||||
assert.equal(round.won, true);
|
||||
assert.equal(round.cleared.length, ghoul.STAGES.length);
|
||||
assert.deepEqual(new Set(round.cleared), new Set(ghoul.STAGES.map((st) => st.id)), "each stage once");
|
||||
assert.equal(round.cleared.length, ghoul.RUN_STAGES);
|
||||
assert.equal(new Set(round.cleared).size, ghoul.RUN_STAGES, "each stage once");
|
||||
assert.ok(!round.cleared.includes(ghoul.FINALE.id), "the finale is no stage cleared");
|
||||
assert.equal(events(round, "won").length, 1);
|
||||
assert.equal(ghoul.advance(round, 16, steady), "over");
|
||||
});
|
||||
@@ -2104,7 +2114,8 @@ test("Ghoul Rush: every room can be finished: a route from the start to the key
|
||||
const start = surfaceAt(list, base.start, ghoul.groundAt(base, base.start));
|
||||
const door = surfaceAt(list, base.door, ghoul.groundAt(base, base.door));
|
||||
assert.ok(start && door, `${base.id}: start and door on the ground`);
|
||||
assert.ok(base.door > base.length - 14, `${base.id}: the door at the room's end`);
|
||||
// The House stands over its front door until it sinks; that door is the way on.
|
||||
if (base.boss !== "marrow") assert.ok(base.door > base.length - 14, `${base.id}: the door at the room's end`);
|
||||
let from = start;
|
||||
if (base.key) {
|
||||
const key = surfaceAt(list, base.key[0], base.key[1]);
|
||||
@@ -2422,7 +2433,8 @@ test("Ghoul Rush: of ten runs a sharp bot gets nearly all through the hall and t
|
||||
// added: Hollow End's Main Street takes the bot up to a minute). The
|
||||
// Gourd's bound has room for the slow end of the bot's spread, about a
|
||||
// minute, which is one seed or two in thirty.
|
||||
per.forEach((p, i) => assert.ok(p.secs >= 10 && p.secs <= (i === 4 ? 65 : i === 5 ? 70 : 40), `seed ${seed}: room ${i + 1} took ${p.secs.toFixed(1)} s`));
|
||||
// The blaster went to 80% of its old rate (FIRE_MS 124), so the Gourd's fight runs about a quarter longer: 80 s.
|
||||
per.forEach((p, i) => assert.ok(p.secs >= 10 && p.secs <= (i === 4 ? 80 : i === 5 ? 70 : 40), `seed ${seed}: room ${i + 1} took ${p.secs.toFixed(1)} s`));
|
||||
}
|
||||
assert.ok(outOfFoyer >= 9, `${outOfFoyer} of 10 through the hall and out of the Foyer`);
|
||||
assert.ok(pastGourd >= 5, `${pastGourd} of 10 past the Gourd`);
|
||||
@@ -2466,10 +2478,12 @@ function takeManor(g) {
|
||||
}
|
||||
|
||||
// Past a stage's intro card the way a player does: the minimum wait, then fire.
|
||||
// Past every card up (the finale's stage card leads straight into its boss's).
|
||||
function leaveIntro(g) {
|
||||
if (g.round.phase !== "intro" && g.round.phase !== "bossintro") return;
|
||||
for (let ms = 0; ms < ghoul.INTRO_MIN_MS + 50; ms += 16) g.tick(16);
|
||||
g.key("action");
|
||||
for (let n = 0; n < 3 && (g.round.phase === "intro" || g.round.phase === "bossintro"); n++) {
|
||||
for (let ms = 0; ms < ghoul.INTRO_MIN_MS + 50; ms += 16) g.tick(16);
|
||||
g.key("action");
|
||||
}
|
||||
}
|
||||
|
||||
// Starts a game with nothing waking.
|
||||
@@ -2570,7 +2584,7 @@ test("Ghoul Rush game: the start screen names the record, the pick screen shows
|
||||
const scores = [];
|
||||
const g = ghoul.default.create({ canvas, memo, onScore: (n) => scores.push(n) });
|
||||
g.resize(900, 900);
|
||||
assert.ok(texts.some(([t]) => t.includes(`Best: 0 of ${ghoul.STAGES.length} stages`)), "the start screen names the record");
|
||||
assert.ok(texts.some(([t]) => t.includes(`Best: 0 of ${ghoul.RUN_STAGES} stages`)), "the start screen names the record");
|
||||
g.key("action");
|
||||
skipStory(g);
|
||||
g.round.dice = 0;
|
||||
@@ -2613,7 +2627,7 @@ test("Ghoul Rush game: the start screen names the record, the pick screen shows
|
||||
assert.equal(g.round.phase, "pick");
|
||||
texts.length = 0;
|
||||
g.tick(16);
|
||||
assert.ok(texts.some(([t]) => t === `STAGE 1 OF ${ghoul.STAGES.length} CLEARED`));
|
||||
assert.ok(texts.some(([t]) => t === `STAGE 1 OF ${ghoul.RUN_STAGES} CLEARED`));
|
||||
for (let ms = 0; ms < ghoul.PICK_HOLD_MS + 50; ms += 16) g.tick(16);
|
||||
g.key("up");
|
||||
assert.ok(g.round.stage && g.round.stage !== want, "up takes one too, never the stage just cleared");
|
||||
@@ -2628,7 +2642,7 @@ test("Ghoul Rush game: the start screen names the record, the pick screen shows
|
||||
texts.length = 0;
|
||||
g.resize(900, 900);
|
||||
assert.ok(texts.some(([t, font]) => t === String(g.score) && /\b7px/.test(font)), "the score, big");
|
||||
assert.ok(texts.some(([t]) => t.startsWith(`Cleared 1 of ${ghoul.STAGES.length} stages, out in `) && t.includes("A new record!")), "how far, and the record");
|
||||
assert.ok(texts.some(([t]) => t.startsWith(`Cleared 1 of ${ghoul.RUN_STAGES} stages, out in `) && t.includes("A new record!")), "how far, and the record");
|
||||
const again = ghoul.default.create({ canvas, memo: { get: () => 9, set: () => assert.fail("never lowered") } });
|
||||
again.resize(900, 900);
|
||||
again.key("action");
|
||||
@@ -2654,7 +2668,7 @@ test("Ghoul Rush game: stageSelect() (the window's stage code) opens a practice
|
||||
for (let i = 0; i < 30; i++) g.tick(16);
|
||||
assert.equal(r.phase, "select", "it waits on a choice");
|
||||
assert.equal(r.clock, 0, "nothing moves");
|
||||
const last = ghoul.STAGES.length - 1;
|
||||
const last = ghoul.SELECTABLE.length - 1;
|
||||
for (let i = 0; i < last + 3; i++) g.key("down");
|
||||
assert.equal(r.select.at, last, "down stops at the last stage");
|
||||
// Two up clamps inside the list; then steer on to the Manor, whose second
|
||||
@@ -2664,7 +2678,7 @@ test("Ghoul Rush game: stageSelect() (the window's stage code) opens a practice
|
||||
g.key("up");
|
||||
assert.equal(r.select.at, last - 2);
|
||||
const st = ghoul.STAGES[0];
|
||||
for (let i = 0; i < ghoul.STAGES.length; i++) g.key("up");
|
||||
for (let i = 0; i < ghoul.SELECTABLE.length; i++) g.key("up");
|
||||
assert.equal(r.select.at, 0, "the Manor");
|
||||
for (let i = 0; i < st.rooms.length + 3; i++) g.key("right");
|
||||
assert.equal(r.select.room, st.rooms.length - 1, "right stops at the boss room");
|
||||
@@ -2675,7 +2689,7 @@ test("Ghoul Rush game: stageSelect() (the window's stage code) opens a practice
|
||||
assert.equal(r.stage, st.id);
|
||||
assert.equal(r.stageAt, st.rooms.length - 2);
|
||||
assert.equal(r.spec.id, st.rooms[st.rooms.length - 2], "straight into the room picked");
|
||||
r.events.push({ type: "stageClear", stage: st.id, n: 3, of: ghoul.STAGES.length });
|
||||
r.events.push({ type: "stageClear", stage: st.id, n: 3, of: ghoul.RUN_STAGES });
|
||||
g.tick(16);
|
||||
assert.equal(saved, 0, "a practice run never sets the record");
|
||||
r.score = 5000;
|
||||
@@ -2700,9 +2714,14 @@ test("Ghoul Rush game: a run that clears every stage ends in a win, with a fanfa
|
||||
const r = g.round;
|
||||
through(r);
|
||||
while (!r.over) {
|
||||
// The ending's pages once the House is dead.
|
||||
if (r.phase === "ending") {
|
||||
skipEnding(r);
|
||||
continue;
|
||||
}
|
||||
r.phaseMs = 0;
|
||||
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);
|
||||
}
|
||||
g.tick(16);
|
||||
assert.equal(g.state, "over");
|
||||
@@ -3028,7 +3047,7 @@ test("Ghoul Rush: every pill's text reads at 4.5:1 on its backing and its timer'
|
||||
assert.ok(k >= 4.5, `${theme}/${id}: "${p.text}" in ${p.ink} on ${under} reads ${k.toFixed(2)}:1`);
|
||||
}
|
||||
}
|
||||
for (const want of ["THE LONG HALL", `STAGE 0 OF ${ghoul.STAGES.length}`, "♥", "BONUS 0", "~CHAIN x4", "~SPREAD", "~RAPID", "GARLIC"]) {
|
||||
for (const want of ["THE LONG HALL", `STAGE 0 OF ${ghoul.RUN_STAGES}`, "♥", "BONUS 0", "~CHAIN x4", "~SPREAD", "~RAPID", "GARLIC"]) {
|
||||
const tinted = want.startsWith("~");
|
||||
const text = tinted ? want.slice(1) : want;
|
||||
assert.ok(seen.some((p) => p.text.includes(text) && (!tinted || p.tints.length)), `${theme}/${id}: "${text}" drawn (${seen.map((p) => p.text)})`);
|
||||
@@ -3048,7 +3067,7 @@ test("Ghoul Rush: the top bar names the stage (or the hall) and counts the stage
|
||||
g.tick(16);
|
||||
const seen = pills();
|
||||
const at = seen.findIndex((p) => p.text.startsWith("♥"));
|
||||
assert.deepEqual(seen.slice(0, 2).map((p) => p.text), ["THE LONG HALL", `STAGE 0 OF ${ghoul.STAGES.length}`], "the hall, nothing cleared yet");
|
||||
assert.deepEqual(seen.slice(0, 2).map((p) => p.text), ["THE LONG HALL", `STAGE 0 OF ${ghoul.RUN_STAGES}`], "the hall, nothing cleared yet");
|
||||
assert.equal(at, 2, `right after the stage pills (${seen.map((p) => p.text)})`);
|
||||
assert.equal(seen[at].text, livesText(g.round.lives));
|
||||
assert.equal(seen[at].backing, LIVES_BACK);
|
||||
@@ -3251,9 +3270,9 @@ test("Ghoul Rush game: every room and boss draws, and each pick of stage, throug
|
||||
g.resize(900, 900);
|
||||
g.key("action");
|
||||
skipStory(g);
|
||||
// Every room a run can reach: the hall and each stage's, not the retired Bog Runner.
|
||||
const LIVE = 1 + ghoul.STAGES.flatMap((st) => st.rooms).length;
|
||||
for (let n = 1; n <= LIVE; n++) {
|
||||
// Every room the run reaches: the hall, each of its RUN_STAGES stages' and the finale's.
|
||||
for (let n = 1; g.state === "running"; n++) {
|
||||
assert.ok(n < 80, "the run ends");
|
||||
const r = g.round;
|
||||
r.lives = 99;
|
||||
const bot = makeBot(ghoul, 1, ghoul.seeded(n));
|
||||
@@ -3266,7 +3285,8 @@ test("Ghoul Rush game: every room and boss draws, and each pick of stage, throug
|
||||
}
|
||||
assert.ok(calls.count > drawn, `room ${n} draws`);
|
||||
leaveIntro(g);
|
||||
if (r.boss) r.boss.state = "down";
|
||||
// A fallen boss, and the House gone from in front of its door.
|
||||
if (r.boss) Object.assign(r.boss, { state: "down", gone: true });
|
||||
r.hasKey = true;
|
||||
// Through the door, once any life lost in the run is over with.
|
||||
for (let ms = 0; ms < 8000 && g.round.room === n && g.state === "running"; ms += 16) {
|
||||
@@ -3278,6 +3298,7 @@ test("Ghoul Rush game: every room and boss draws, and each pick of stage, throug
|
||||
r.ask.t = ghoul.ASK_GUARD_MS;
|
||||
ghoul.answerDie(r, true);
|
||||
}
|
||||
if (r.phase === "ending") skipEnding(r);
|
||||
if (r.phase === "pick") {
|
||||
const before = calls.count;
|
||||
g.tick(16);
|
||||
@@ -3287,7 +3308,7 @@ test("Ghoul Rush game: every room and boss draws, and each pick of stage, throug
|
||||
}
|
||||
g.tick(16);
|
||||
}
|
||||
if (n === LIVE) break;
|
||||
if (g.state !== "running") break;
|
||||
leaveIntro(g);
|
||||
for (let ms = 0; ms < ghoul.READY_MS + 100; ms += 16) g.tick(16);
|
||||
assert.equal(g.round.room, n + 1);
|
||||
|
||||
@@ -11,7 +11,7 @@ import assert from "node:assert/strict";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { ACTIVITIES, bestKey, bestKeys, memoKey, musicKey, musicLevel } from "../src/web-console/public/activities.js";
|
||||
import { BOSS_BITES, COMBO_MS, DISCOVERIES, FOOD_PER_LEVEL, FRUITS, GRID, ICE_STEPS, LEVELS, MAX_COMBO, MIN_CELL, MIN_STEP_MS, POWERS, STEP_MS, SURPRISES, age, applyPower, applySurprise, fruitFor, tallyBit, newRound, onFood, SPECIALS, pace, placeFood, step, stepMs, turn } from "../src/web-console/public/activities/snake.js";
|
||||
import { BOSS_BITES, COMBO_MS, MAX_LEVEL, MUSIC_TRACKS, dealMusic, heat, trackFor, DISCOVERIES, FOOD_PER_LEVEL, FRUITS, GRID, ICE_STEPS, LEVELS, MAX_COMBO, MIN_CELL, MIN_STEP_MS, POWERS, STEP_MS, SURPRISES, age, applyPower, applySurprise, fruitFor, tallyBit, newRound, onFood, SPECIALS, pace, placeFood, step, stepMs, turn } from "../src/web-console/public/activities/snake.js";
|
||||
import golf, * as golfRules from "../src/web-console/public/activities/golf.js";
|
||||
import { COURSE_W, COURSE_H, COURSES, FRONT_NINE, HOLE_COUNT, courseById } from "../src/web-console/public/activities/golf-holes.js";
|
||||
import { holeQuip, holeWord, knownGround, knownLiquid } from "../src/web-console/public/activities/golf-draw.js";
|
||||
@@ -308,13 +308,13 @@ test("memoKey builds a flat looks.json key from a list id", () => {
|
||||
|
||||
test("musicKey builds a flat looks.json key, and a game with music has a default volume a saved one replaces", () => {
|
||||
assert.equal(musicKey("ghoul"), "activityMusicGhoul");
|
||||
assert.deepEqual(ACTIVITIES.filter((a) => a.music !== undefined).map((a) => [a.id, a.music]), [["drive", 70], ["ghoul", 65]], "the games with music, at about the level they were picked at on the prototype pages");
|
||||
assert.deepEqual(ACTIVITIES.filter((a) => a.music !== undefined).map((a) => [a.id, a.music]), [["snake", 70], ["trails", 70], ["drive", 70], ["ghoul", 65]], "the games with music, at about the level they were picked at on the prototype pages");
|
||||
const ghoulEntry = ACTIVITIES.find((a) => a.id === "ghoul");
|
||||
assert.equal(musicLevel(ghoulEntry, undefined), 0.65, "nothing saved: the default");
|
||||
assert.equal(musicLevel(ghoulEntry, "loud"), 0.65, "not a number: the default");
|
||||
assert.equal(musicLevel(ghoulEntry, 0), 0, "turned all the way down");
|
||||
assert.equal(musicLevel(ghoulEntry, 140), 1, "never past full");
|
||||
assert.equal(musicLevel(ACTIVITIES[0], 80), 0, "a game with no music has none");
|
||||
assert.equal(musicLevel(ACTIVITIES.find((a) => a.id === "golf"), 80), 0, "a game with no music has none");
|
||||
});
|
||||
|
||||
test("every listed game, and a stub second game, answers the game contract", async () => {
|
||||
@@ -457,6 +457,58 @@ test("Snake: a wall hit ends the round and onScore fires once", async () => {
|
||||
assert.equal(scores.length, 1, "no second onScore after the round is over");
|
||||
});
|
||||
|
||||
test("Snake: a round deals every track once, never opens on the last opener, and gives each level its own", () => {
|
||||
let n = 7;
|
||||
const random = () => (n = (n * 1664525 + 1013904223) % 4294967296) / 4294967296;
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const last = MUSIC_TRACKS[i % MUSIC_TRACKS.length];
|
||||
const deck = dealMusic(random, last);
|
||||
assert.deepEqual([...deck].sort(), [...MUSIC_TRACKS].sort(), "every track once");
|
||||
assert.notEqual(deck[0], last, "never opens on the last opener");
|
||||
}
|
||||
const deck = dealMusic(random, null);
|
||||
const heard = Array.from({ length: MAX_LEVEL }, (_, i) => trackFor(deck, i + 1));
|
||||
assert.equal(new Set(heard).size, MAX_LEVEL, "nine levels hear nine different tracks");
|
||||
assert.equal(trackFor(deck, 0), deck[0], "a level below one hears the first");
|
||||
assert.equal(trackFor(deck, MUSIC_TRACKS.length + 1), deck[0], "past the deck it comes round again");
|
||||
assert.notDeepEqual(dealMusic(random, null), dealMusic(random, null), "a new deal is a new order");
|
||||
});
|
||||
|
||||
test("Snake: the music's heat starts at 0.3, climbs with the snake's speed to 1 and thins out in Slow-mo", () => {
|
||||
const round = newRound(GRID, () => 0);
|
||||
assert.ok(Math.abs(heat(round) - 0.3) < 1e-9, "the opening pace is 0.3, so the lead and drums are in from the first step");
|
||||
round.snake = Array.from({ length: 30 }, (_, i) => ({ x: i % GRID, y: 0 }));
|
||||
assert.equal(heat(round), 1, "a long snake at its fastest pace is 1");
|
||||
round.effects = { slow: 7000 };
|
||||
assert.ok(heat(round) < 1 && heat(round) >= 0.3, "Slow-mo thins it out");
|
||||
round.snake = round.snake.slice(0, 3);
|
||||
assert.equal(heat(round), 0.3, "and never under 0.3");
|
||||
});
|
||||
|
||||
test("Snake: it asks for the deal's track while a round runs, and the next round opens on another", async () => {
|
||||
const { canvas } = stubCanvas();
|
||||
const asked = [];
|
||||
const game = (await import("../src/web-console/public/activities/snake.js")).default;
|
||||
const g = game.create({ canvas, music: (name, level) => asked.push([name, level]) });
|
||||
g.resize(GRID * MIN_CELL, GRID * MIN_CELL);
|
||||
g.tick(STEP_MS);
|
||||
assert.equal(asked.length, 0, "silent before a round");
|
||||
g.start();
|
||||
g.tick(16);
|
||||
assert.equal(asked.length, 1, "asked once a tick");
|
||||
const [first, opening] = asked[0];
|
||||
assert.ok(MUSIC_TRACKS.includes(first), "a track the game has");
|
||||
assert.ok(Math.abs(opening - 0.3) < 1e-9, "at the opening heat");
|
||||
for (let i = 0; i < GRID + 2 && g.state === "running"; i++) g.tick(STEP_MS);
|
||||
assert.equal(g.state, "over");
|
||||
const before = asked.length;
|
||||
g.tick(STEP_MS * 10);
|
||||
assert.equal(asked.length, before, "nothing asked for once the round is over");
|
||||
g.start();
|
||||
g.tick(16);
|
||||
assert.notEqual(asked.at(-1)[0], first, "the next round opens on another track");
|
||||
});
|
||||
|
||||
test("Snake: running into its own body ends the round", () => {
|
||||
const round = newRound(GRID, () => 0);
|
||||
// Head at (5,5) heading right into (6,5), which is body, not the tail.
|
||||
@@ -2038,7 +2090,7 @@ function racing(round) {
|
||||
|
||||
const trailsEvents = (round, type) => round.events.filter((e) => e.type === type);
|
||||
|
||||
test("Light Trails: a round starts at level 1 with three lives, two boosts and one rival, everyone on the grid", () => {
|
||||
test("Light Trails: a round starts at level 1 with five lives, two boosts and one rival, everyone on the grid", () => {
|
||||
const round = trails.newRound(still);
|
||||
assert.equal(round.level, 1);
|
||||
assert.equal(round.lives, trails.START_LIVES);
|
||||
@@ -2271,6 +2323,190 @@ test("Light Trails: pads turn up from level 2, never at level 1", () => {
|
||||
assert.ok(Object.hasOwn(trails.POWERS, two.items[0].kind));
|
||||
});
|
||||
|
||||
test("Light Trails: five lives to start, a life back every LIFE_SCORE points, never past MAX_LIVES", () => {
|
||||
const round = racing(trails.newRound(still));
|
||||
assert.equal(trails.START_LIVES, 5);
|
||||
assert.equal(round.lives, 5);
|
||||
round.score = trails.LIFE_SCORE - 1;
|
||||
trails.awardLives(round);
|
||||
assert.equal(round.lives, 5, "not yet");
|
||||
round.score = trails.LIFE_SCORE;
|
||||
trails.awardLives(round);
|
||||
assert.equal(round.lives, 6, "one life at the mark");
|
||||
assert.deepEqual(trailsEvents(round, "bonusLife").map((e) => e.lives), [6]);
|
||||
round.score = trails.LIFE_SCORE * 3 + 10;
|
||||
trails.awardLives(round);
|
||||
assert.equal(round.lives, 8, "one for each mark passed");
|
||||
round.lives = trails.MAX_LIVES;
|
||||
round.score = trails.LIFE_SCORE * 10;
|
||||
trails.awardLives(round);
|
||||
assert.equal(round.lives, trails.MAX_LIVES, "capped");
|
||||
assert.equal(round.nextLifeAt, trails.LIFE_SCORE * 11, "and the mark moves on, so none is saved up");
|
||||
});
|
||||
|
||||
test("Light Trails: every pad turns up only from its own arena, a Heart only while there is room for a life, and a Mystery never becomes another", () => {
|
||||
const round = trails.newRound(still);
|
||||
let n = 1;
|
||||
const random = () => (n = (n * 1664525 + 1013904223) % 4294967296) / 4294967296;
|
||||
for (let level = 2; level <= trails.MAX_LEVEL; level++) {
|
||||
round.level = level;
|
||||
const seen = new Set(Array.from({ length: 3000 }, () => trails.pickPower(round, random)));
|
||||
const due = Object.keys(trails.POWERS).filter((k) => trails.POWERS[k].from <= level);
|
||||
assert.deepEqual([...seen].sort(), due.sort(), `level ${level} offers exactly the pads due by then`);
|
||||
}
|
||||
assert.equal(trails.POWERS.life.from, 2, "a Heart from the first arena with pads");
|
||||
round.lives = trails.MAX_LIVES;
|
||||
assert.ok(Array.from({ length: 2000 }, () => trails.pickPower(round, random)).every((k) => k !== "life"), "no Heart at full lives");
|
||||
round.lives = 3;
|
||||
assert.ok(Array.from({ length: 2000 }, () => trails.pickPower(round, random, true)).every((k) => k !== "mystery"));
|
||||
});
|
||||
|
||||
test("Light Trails: a Heart pad gives a life", () => {
|
||||
const round = racing(trails.newRound(still));
|
||||
trails.applyPower(round, "life");
|
||||
assert.equal(round.lives, trails.START_LIVES + 1);
|
||||
});
|
||||
|
||||
test("Light Trails: a Shield takes your next crash, wiping the trails round you and riding on, and is held from heat to heat until then", () => {
|
||||
const round = racing(trails.newRound(still));
|
||||
const you = round.riders[0];
|
||||
trails.applyPower(round, "shield");
|
||||
assert.equal(round.shield, true);
|
||||
park(round, you, 10, 15, "right");
|
||||
round.grid[15 * trails.COLS + 11] = 2;
|
||||
round.grid[14 * trails.COLS + 10] = 2;
|
||||
round.grid[16 * trails.COLS + 10] = 2;
|
||||
trails.advance(round, trails.STEP_MS + trails.GRACE_MS + 8, still);
|
||||
assert.equal(you.alive, true, "boxed in on three sides, and the Shield saved you");
|
||||
assert.equal(round.shield, false, "it is used up");
|
||||
assert.equal(trailsEvents(round, "shield").length, 1);
|
||||
assert.equal(round.grid[15 * trails.COLS + 11] === 2, false, "the trail ahead was wiped");
|
||||
assert.equal(round.lives, trails.START_LIVES);
|
||||
// Held through a heat won.
|
||||
const two = racing(trails.newRound(still));
|
||||
trails.applyPower(two, "shield");
|
||||
trails.newHeat(two, still);
|
||||
assert.equal(two.shield, true, "a new heat keeps it");
|
||||
// A wall all round is still a crash.
|
||||
const three = racing(trails.newRound(still));
|
||||
trails.applyPower(three, "shield");
|
||||
park(three, three.riders[0], 0, 0, "left");
|
||||
three.grid[1] = trails.WALL;
|
||||
three.grid[trails.COLS] = trails.WALL;
|
||||
trails.advance(three, trails.STEP_MS + trails.GRACE_MS + 8, still);
|
||||
assert.equal(three.riders[0].alive, false, "nowhere to go");
|
||||
});
|
||||
|
||||
test("Light Trails: a Laser zaps a rival head in your line through trails, scoring the cut, but holds fire behind a crystal", () => {
|
||||
const round = racing(trails.newRound(still));
|
||||
const [you, rival] = round.riders;
|
||||
park(round, you, 5, 15, "right");
|
||||
park(round, rival, 15, 15, "up");
|
||||
round.grid[15 * trails.COLS + 9] = 2;
|
||||
trails.applyPower(round, "laser");
|
||||
assert.equal(rival.alive, false, "zapped at once");
|
||||
assert.equal(rival.by, "laser");
|
||||
assert.equal(round.grid[15 * trails.COLS + 9], 0, "the trail in the beam is cut");
|
||||
assert.equal(round.shots, trails.LASER_SHOTS - 1);
|
||||
const [out] = trailsEvents(round, "out");
|
||||
assert.equal(out.points, trails.OUT_POINTS + trails.CUT_POINTS, "a laser out pays the cut");
|
||||
assert.equal(trailsEvents(round, "laser").length, 1);
|
||||
|
||||
const two = trails.newRound(still);
|
||||
two.level = 3;
|
||||
racing(trails.newHeat(two, still));
|
||||
const [me, foe] = two.riders;
|
||||
park(two, me, 5, 15, "right");
|
||||
park(two, foe, 15, 15, "up");
|
||||
two.grid[15 * trails.COLS + 10] = trails.BLOCK;
|
||||
trails.applyPower(two, "laser");
|
||||
assert.equal(foe.alive, true, "a crystal in the way holds the shot");
|
||||
assert.equal(two.shots, trails.LASER_SHOTS);
|
||||
park(two, foe, 3, 15, "up");
|
||||
assert.equal(trails.fireLaser(two), false, "and it only fires ahead");
|
||||
});
|
||||
|
||||
test("Light Trails: Score x2 doubles every point while it runs", () => {
|
||||
const round = racing(trails.newRound(still));
|
||||
round.level = 2;
|
||||
trails.applyPower(round, "coin");
|
||||
const single = round.score;
|
||||
trails.applyPower(round, "double");
|
||||
trails.applyPower(round, "coin");
|
||||
assert.equal(round.score - single, single * 2);
|
||||
});
|
||||
|
||||
test("Light Trails: a Wide Trail lays your wall three cells wide, and the cells go with the trail", () => {
|
||||
const round = racing(trails.newRound(still));
|
||||
const you = round.riders[0];
|
||||
park(round, you, 10, 15, "right");
|
||||
trails.applyPower(round, "wide");
|
||||
trails.advance(round, trails.STEP_MS, still);
|
||||
assert.equal(you.x, 11);
|
||||
assert.equal(round.grid[14 * trails.COLS + 11], 1, "above");
|
||||
assert.equal(round.grid[16 * trails.COLS + 11], 1, "and below");
|
||||
assert.equal(you.wide.length, 2);
|
||||
trails.applyPower(round, "eraser");
|
||||
assert.equal(you.wide.length, 0, "wiped cells leave the list");
|
||||
});
|
||||
|
||||
test("Light Trails: Hyperjump moves you to an open cell clear of everyone, facing open space", () => {
|
||||
const round = racing(trails.newRound(still));
|
||||
const you = round.riders[0];
|
||||
let n = 9;
|
||||
const random = () => (n = (n * 1664525 + 1013904223) % 4294967296) / 4294967296;
|
||||
// Fill the left half with trail, so the jump has to take you right.
|
||||
for (let y = 0; y < trails.ROWS; y++) for (let x = 0; x < 18; x++) if (!(x === you.x && y === you.y)) round.grid[y * trails.COLS + x] = 2;
|
||||
assert.equal(trails.hyperjump(round, random), true);
|
||||
assert.ok(you.x >= 18, "out in the open half");
|
||||
assert.equal(round.grid[you.y * trails.COLS + you.x], 1, "on a cell of your own");
|
||||
for (const r of round.riders.slice(1)) assert.ok(Math.abs(r.x - you.x) + Math.abs(r.y - you.y) >= 4, "clear of the rivals");
|
||||
const d = { up: [0, -1], down: [0, 1], left: [-1, 0], right: [1, 0] }[you.dir];
|
||||
assert.equal(round.grid[(you.y + d[1]) * trails.COLS + you.x + d[0]], 0, "facing an open cell");
|
||||
assert.equal(trailsEvents(round, "jump").length, 1);
|
||||
});
|
||||
|
||||
test("Light Trails: Coin Rain drops coins all over that never hold back the pads", () => {
|
||||
const round = trails.newRound(still);
|
||||
round.level = 4;
|
||||
racing(trails.newHeat(round, still));
|
||||
let n = 4;
|
||||
const random = () => (n = (n * 1664525 + 1013904223) % 4294967296) / 4294967296;
|
||||
trails.applyPower(round, "rain", random);
|
||||
const coins = round.items.filter((it) => it.kind === "coin" && it.rain);
|
||||
assert.equal(coins.length, trails.RAIN_COINS);
|
||||
round.nextItem = 1;
|
||||
trails.advance(round, 8, random);
|
||||
assert.equal(round.items.filter((it) => !it.rain).length, 1, "a pad still turns up");
|
||||
});
|
||||
|
||||
test("Light Trails: a Mystery pad turns into another pad and says which", () => {
|
||||
const round = trails.newRound(still);
|
||||
round.level = 9;
|
||||
racing(trails.newHeat(round, still));
|
||||
trails.applyPower(round, "mystery", () => 0.1);
|
||||
const [m] = trailsEvents(round, "mystery");
|
||||
assert.ok(m && m.kind !== "mystery" && Object.hasOwn(trails.POWERS, m.kind));
|
||||
assert.deepEqual(trailsEvents(round, "power").map((e) => e.kind), [m.kind], "the pad it became is applied");
|
||||
});
|
||||
|
||||
test("Light Trails game: every new pad, its effects and its events draw and sound without throwing", () => {
|
||||
const { canvas } = stubCanvas();
|
||||
const tones = [];
|
||||
const g = trails.default.create({ canvas, tone: (n) => tones.push(n) });
|
||||
g.resize(800, 600);
|
||||
g.start();
|
||||
g.cheat(true);
|
||||
const round = g.round;
|
||||
round.level = 9;
|
||||
trails.newHeat(round, still);
|
||||
g.tick(2000);
|
||||
for (const kind of Object.keys(trails.POWERS)) trails.spawnItem(round, kind);
|
||||
for (const kind of ["shield", "laser", "double", "wide", "jump", "rain", "mystery", "life"]) trails.applyPower(round, kind);
|
||||
for (let i = 0; i < 60; i++) g.tick(50);
|
||||
for (const name of ["trailsHeart", "shieldUp", "trailsJump", "mystery"]) assert.ok(tones.includes(name), `${name} played`);
|
||||
});
|
||||
|
||||
test("Light Trails: from level 5 the walls close in a ring at a time, warning first, and catch anyone on the ring", () => {
|
||||
const round = trails.newRound(still);
|
||||
round.level = 5;
|
||||
@@ -2302,11 +2538,107 @@ test("Light Trails: the start screen reads the furthest arena from the memo and
|
||||
|
||||
test("Light Trails: every pill's text reads at 4.5:1 on its backing and its timer's tint, lives and running effects included, in light and dark under every highlight", () => {
|
||||
checkPills(trails.default, {
|
||||
setup: (r) => Object.assign(r.effects, { boost: trails.BOOST_MS / 2, phase: 1500, slow: 2000 }),
|
||||
expect: ["LV 1", "♥", "~BOOST", "~PHASE", "~SLOW-MO", "1 RIVAL"],
|
||||
setup: (r) => {
|
||||
Object.assign(r.effects, { boost: trails.BOOST_MS / 2, phase: 1500, slow: 2000, laser: 3000, double: 4000, wide: 2000 });
|
||||
Object.assign(r, { shield: true, shots: 2 });
|
||||
},
|
||||
expect: ["LV 1", "♥", "~BOOST", "~PHASE", "~SLOW-MO", "1 RIVAL", "SHIELD", "~LASER", "x2 SCORE", "WIDE"],
|
||||
});
|
||||
});
|
||||
|
||||
test("Light Trails: its sounds play SFX_LOUDER times as loud, but for the engine drones, left low under the songs", () => {
|
||||
const { canvas } = stubCanvas();
|
||||
const tones = [];
|
||||
const hums = [];
|
||||
const g = trails.default.create({ canvas, tone: (...a) => tones.push(a), hum: (...a) => hums.push(a) });
|
||||
g.resize(800, 600);
|
||||
g.start();
|
||||
g.cheat(true);
|
||||
for (let i = 0; i < 200; i++) g.tick(50);
|
||||
assert.ok(trails.SFX_LOUDER > 1, "louder than made");
|
||||
assert.ok(tones.length && tones.every((a) => a[3] === trails.SFX_LOUDER), "every tone lifted");
|
||||
const drones = hums.filter((a) => a[0] === "trails:you" || a[0] === "trails:rival");
|
||||
assert.ok(drones.length && drones.every((a) => a[4] === 1), "the drones are not");
|
||||
assert.ok(hums.filter((a) => !drones.includes(a)).every((a) => a[4] === trails.SFX_LOUDER), "every other hum is");
|
||||
});
|
||||
|
||||
test("Light Trails: a deal holds every song once and never opens on the last song", () => {
|
||||
let n = 11;
|
||||
const random = () => (n = (n * 1664525 + 1013904223) % 4294967296) / 4294967296;
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const last = trails.MUSIC_TRACKS[i % trails.MUSIC_TRACKS.length];
|
||||
const deck = trails.dealMusic(random, last);
|
||||
assert.deepEqual([...deck].sort(), [...trails.MUSIC_TRACKS].sort(), "every song once");
|
||||
assert.notEqual(deck[0], last, "never opens on the last song");
|
||||
}
|
||||
assert.notDeepEqual(trails.dealMusic(random, null), trails.dealMusic(random, null), "a new deal is a new order");
|
||||
});
|
||||
|
||||
test("Light Trails: a run plays each song in full from the top, moves on only when one ends, and deals again after the last", () => {
|
||||
const { canvas } = stubCanvas();
|
||||
const asked = [];
|
||||
let reply = "playing";
|
||||
const g = trails.default.create({ canvas, music: (name, intensity, options) => (asked.push({ name, restart: Boolean(options && options.restart) }), reply) });
|
||||
g.resize(800, 600);
|
||||
g.start();
|
||||
g.cheat(true);
|
||||
g.tick(16);
|
||||
g.tick(16);
|
||||
assert.deepEqual(asked.map((a) => a.restart), [true, false], "the first song starts from the top, then plays on");
|
||||
assert.equal(asked[1].name, asked[0].name, "the same song until it ends");
|
||||
const heard = [asked[0].name];
|
||||
for (let i = 0; i < trails.MUSIC_TRACKS.length; i++) {
|
||||
reply = "ended";
|
||||
g.tick(16);
|
||||
reply = "playing";
|
||||
g.tick(16);
|
||||
const next = asked.at(-1);
|
||||
assert.ok(next.restart, "the next song starts from the top");
|
||||
assert.notEqual(next.name, heard.at(-1), "and is another song");
|
||||
heard.push(next.name);
|
||||
}
|
||||
assert.deepEqual(heard.slice(0, trails.MUSIC_TRACKS.length).sort(), [...trails.MUSIC_TRACKS].sort(), "every song once before any plays again");
|
||||
});
|
||||
|
||||
test("Light Trails: a song the music could not play yet still starts from the top once it can", () => {
|
||||
const { canvas } = stubCanvas();
|
||||
const asked = [];
|
||||
let reply;
|
||||
const g = trails.default.create({ canvas, music: (name, intensity, options) => (asked.push(Boolean(options && options.restart)), reply) });
|
||||
g.resize(800, 600);
|
||||
g.start();
|
||||
g.cheat(true);
|
||||
g.tick(16);
|
||||
g.tick(16);
|
||||
reply = "playing";
|
||||
g.tick(16);
|
||||
g.tick(16);
|
||||
assert.deepEqual(asked, [true, true, true, false], "the restart is asked for until the music takes it");
|
||||
});
|
||||
|
||||
test("Light Trails: it asks for the deal's song while a round runs, silent before and after, and the next round opens on another", () => {
|
||||
const { canvas } = stubCanvas();
|
||||
const asked = [];
|
||||
const g = trails.default.create({ canvas, music: (name, level) => asked.push([name, level]) });
|
||||
g.resize(800, 600);
|
||||
g.tick(16);
|
||||
assert.equal(asked.length, 0, "silent before a round");
|
||||
g.start();
|
||||
g.tick(16);
|
||||
assert.equal(asked.length, 1, "asked once a tick");
|
||||
const [first] = asked[0];
|
||||
assert.ok(trails.MUSIC_TRACKS.includes(first), "a song the game has");
|
||||
g.round.lives = 1;
|
||||
for (let i = 0; i < 2000 && g.state === "running"; i++) g.tick(50);
|
||||
assert.equal(g.state, "over", "riding straight ends the round");
|
||||
const before = asked.length;
|
||||
g.tick(500);
|
||||
assert.equal(asked.length, before, "nothing asked for once the round is over");
|
||||
g.start();
|
||||
g.tick(16);
|
||||
assert.notEqual(asked.at(-1)[0], first, "the next round opens on another track");
|
||||
});
|
||||
|
||||
test("Light Trails game: the opening banner sits in the board from the start's first frame, held through the 3, 2, 1, and does not jump on the first tick", () => {
|
||||
const { canvas, shades } = bannerCanvas("rgba(0, 0, 0, 0.3)");
|
||||
const g = trails.default.create({ canvas });
|
||||
|
||||
@@ -470,7 +470,35 @@ test("git board view: each step's click goes out as the board offers it", () =>
|
||||
const [branch, onMain] = stepButtons(main);
|
||||
click(branch);
|
||||
click(onMain);
|
||||
assert.deepEqual(main.on.calls, [["openPanel", "create", { commit: true }], ["openPanel", "commit"]]);
|
||||
const mainFiles = [...commitTicks(STATES["nb-main-dirty"].git.changes)];
|
||||
assert.deepEqual(main.on.calls, [["openPanel", "create", { commit: true }], ["send", "commit", { files: mainFiles, ignore: [] }]]);
|
||||
|
||||
// The commit table is always on show below the step, so the step's Commit
|
||||
// sends what the table has ticked rather than "opening" a panel already open.
|
||||
const dirty = draw("cp-dirty", { tab: "changes" });
|
||||
const ticked = [...commitTicks(STATES["cp-dirty"].git.changes)];
|
||||
const top = stepButtons(dirty).find((c) => c.textContent.startsWith("Commit "));
|
||||
assert.equal(top.textContent, `Commit ${ticked.length} file${ticked.length === 1 ? "" : "s"}`);
|
||||
click(top);
|
||||
assert.deepEqual(dirty.on.calls, [["send", "commit", { files: ticked, ignore: [] }]]);
|
||||
|
||||
const unticked = draw("cp-dirty", { tab: "changes" });
|
||||
unticked.board.ticks.clear();
|
||||
const redrawn = drawGitBoard({
|
||||
git: STATES["cp-dirty"].git, board: unticked.board, now: NOW, mode: "idle", step: unticked.step,
|
||||
badges: tabBadges(STATES["cp-dirty"].git, { now: NOW, stepTab: unticked.step.tab }), notice: null, activity: null, hasCard: false, h: fakeH(), on: fakeOn(),
|
||||
});
|
||||
const none = controls(walk(redrawn.node).find((n) => n.classes.has("git-step"))).find((c) => c.textContent.startsWith("Commit "));
|
||||
assert.ok(none.disabled, "nothing ticked: the step's Commit is grayed, like the table's");
|
||||
|
||||
const one = draw("cp-dirty", { tab: "changes" });
|
||||
one.board.ticks = new Set([ticked[0]]);
|
||||
const again = drawGitBoard({
|
||||
git: STATES["cp-dirty"].git, board: one.board, now: NOW, mode: "idle", step: one.step,
|
||||
badges: tabBadges(STATES["cp-dirty"].git, { now: NOW, stepTab: one.step.tab }), notice: null, activity: null, hasCard: false, h: fakeH(), on: fakeOn(),
|
||||
});
|
||||
const card = walk(again.node).find((n) => n.classes.has("git-step"));
|
||||
assert.equal(walk(card).find((n) => n.classes.has("git-step-title")).textContent, "Commit 1 file", "the card's title follows the ticks too");
|
||||
|
||||
const away = draw("pc-conflict", { tab: "changes" });
|
||||
click(walk(away.node).find((n) => n.classes.has("git-hint")));
|
||||
@@ -576,7 +604,7 @@ test("git board view: a landed result splits the step strip into Just landed and
|
||||
assert.ok(!walk(r.node).some((n) => n.classes.has("git-result")), "no thin result line beside the zones");
|
||||
const commit = controls(rest).find((c) => c.textContent === "Commit other changes");
|
||||
click(commit);
|
||||
assert.deepEqual(r.on.calls[0], ["openPanel", "commit"], "the leftover offer runs the same op the primary would");
|
||||
assert.deepEqual(r.on.calls[0], ["send", "commit", { files: [...commitTicks(STATES["cp-dirty"].git.changes)], ignore: [] }], "the leftover offer runs the same op the primary would");
|
||||
|
||||
const plain = landed("cp-dirty", { id: "git-result", kind: "notice", title: "Committed 1eef797", body: "no op marker" });
|
||||
assert.ok(walk(plain.node).some((n) => n.classes.has("git-result")), "a notice with no op keeps the thin line");
|
||||
|
||||
@@ -536,7 +536,7 @@ test("models: the user's additions round-trip, XHigh and Max are refused, and th
|
||||
assert.equal((await post("/models", { nope: true })).status, 400);
|
||||
assert.equal((await get()).user.devin.length, 1, "a refused write must not touch what is saved");
|
||||
|
||||
// Codex has no curated list, but the launcher reads a user `codex` list all the same.
|
||||
// The launcher reads a user `codex` list too. The shipped file this test serves has no `codex` key, so that list is empty here.
|
||||
const codex = await post("/models", { models: { codex: [{ id: " gpt-5-codex ", label: "GPT-5 Codex" }, { id: "gpt-5-codex" }] } });
|
||||
assert.equal(codex.status, 200);
|
||||
assert.deepEqual((await get()).user, { claude: [], devin: [], codex: [{ id: "gpt-5-codex", label: "GPT-5 Codex" }] });
|
||||
@@ -547,6 +547,88 @@ test("models: the user's additions round-trip, XHigh and Max are refused, and th
|
||||
assert.deepEqual((await get()).user, { claude: [], devin: [], codex: [] });
|
||||
});
|
||||
|
||||
test("models: strengths come back shipped and user, round-trip, survive a models-only save, and bad rows name their field", async () => {
|
||||
fs.mkdirSync(path.join(MODELS_DIR, "bin"), { recursive: true });
|
||||
const shippedStrengths = { claude: { thrifty: { model: "sonnet", effort: "low" }, best: { model: "opus" } } };
|
||||
fs.writeFileSync(
|
||||
path.join(MODELS_DIR, "bin", "models.json"),
|
||||
JSON.stringify({ claude: [{ id: "opus", label: "Opus" }, { id: "sonnet", label: "Sonnet" }], strengths: shippedStrengths })
|
||||
);
|
||||
const get = async () => (await fetch(baseUrl + "/models", { headers: { cookie: cookieFor(baseUrl, token) } })).json();
|
||||
const userFile = () => JSON.parse(fs.readFileSync(path.join(MODELS_DIR, "models.json"), "utf8"));
|
||||
|
||||
const first = await get();
|
||||
assert.deepEqual(first.strengths, { shipped: shippedStrengths, user: {} }, "shipped rows come back, no user rows yet");
|
||||
assert.ok(!("strengths" in first.shipped) && !("strengths" in first.user), "strengths is never read as an agent's model list");
|
||||
|
||||
const mapping = { claude: { balanced: { model: " sonnet ", effort: "medium" }, best: { model: "opus" } }, codex: { thrifty: { model: "gpt-5-codex" } } };
|
||||
const saved = await post("/models", { models: { claude: [{ id: "mine" }] }, strengths: mapping });
|
||||
assert.equal(saved.status, 200);
|
||||
const want = { claude: { balanced: { model: "sonnet", effort: "medium" }, best: { model: "opus" } }, codex: { thrifty: { model: "gpt-5-codex" } } };
|
||||
assert.deepEqual((await get()).strengths.user, want);
|
||||
assert.deepEqual(userFile().strengths, want, "the launcher's file carries the mapping beside the lists");
|
||||
assert.equal(userFile().claude.length, 1);
|
||||
|
||||
// A save with only a Models list never wipes the mapping.
|
||||
assert.equal((await post("/models", { models: { claude: [{ id: "mine" }, { id: "other" }] } })).status, 200);
|
||||
assert.deepEqual((await get()).strengths.user, want);
|
||||
assert.equal((await get()).user.claude.length, 2);
|
||||
|
||||
// The agents' own lists and the reset keep it too; an explicit empty mapping clears it.
|
||||
assert.equal((await post("/models", { models: {} })).status, 200);
|
||||
assert.deepEqual((await get()).strengths.user, want);
|
||||
|
||||
const refused = [
|
||||
[{ claude: { thrifty: { model: "bad id!" } } }, /strengths\.claude\.thrifty\.model/],
|
||||
[{ claude: { cheap: { model: "sonnet" } } }, /strengths\.claude\.cheap/],
|
||||
[{ claude: { best: { model: "opus", effort: "max" } } }, /strengths\.claude\.best\.effort/],
|
||||
[{ nobody: { best: { model: "opus" } } }, /strengths\.nobody/],
|
||||
[{ claude: { best: "opus" } }, /strengths\.claude\.best/],
|
||||
[["claude"], /strengths/],
|
||||
];
|
||||
for (const [body, field] of refused) {
|
||||
const res = await post("/models", { models: {}, strengths: body });
|
||||
assert.equal(res.status, 400, JSON.stringify(body));
|
||||
assert.match((await res.json()).error, field);
|
||||
}
|
||||
assert.deepEqual((await get()).strengths.user, want, "a refused write must not touch what is saved");
|
||||
|
||||
assert.equal((await post("/models", { models: {}, strengths: {} })).status, 200);
|
||||
assert.deepEqual((await get()).strengths.user, {});
|
||||
assert.ok(!("strengths" in userFile()), "an empty mapping leaves no key behind");
|
||||
});
|
||||
|
||||
test("models: a saved mapping for an agent that is gone is skipped, and never hides or wipes the others", async (t) => {
|
||||
const userFile = path.join(MODELS_DIR, "models.json");
|
||||
t.after(() => fs.rmSync(userFile, { force: true }));
|
||||
fs.writeFileSync(
|
||||
userFile,
|
||||
JSON.stringify({ claude: [], strengths: { claude: { best: { model: "opus" } }, "deleted-agent": { best: { model: "x" } }, devin: { cheap: { model: "y" } } } })
|
||||
);
|
||||
const get = async () => (await fetch(baseUrl + "/models", { headers: { cookie: cookieFor(baseUrl, token) } })).json();
|
||||
assert.deepEqual((await get()).strengths.user, { claude: { best: { model: "opus" } } });
|
||||
assert.equal((await post("/models", { models: { claude: [{ id: "mine" }] } })).status, 200);
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(userFile, "utf8")).strengths, { claude: { best: { model: "opus" } } }, "the models-only save kept the good rows");
|
||||
});
|
||||
|
||||
test("models: one bad saved row never drops the other rows of its agent, like the app", async (t) => {
|
||||
const userFile = path.join(MODELS_DIR, "models.json");
|
||||
t.after(() => fs.rmSync(userFile, { force: true }));
|
||||
fs.writeFileSync(
|
||||
userFile,
|
||||
JSON.stringify({
|
||||
claude: [],
|
||||
strengths: { claude: { thrifty: { model: "haiku", effort: "max" }, balanced: { model: "bad id!" }, cheap: { model: "x" }, best: { model: "opus", effort: "high" } } },
|
||||
})
|
||||
);
|
||||
const get = async () => (await fetch(baseUrl + "/models", { headers: { cookie: cookieFor(baseUrl, token) } })).json();
|
||||
assert.deepEqual(
|
||||
(await get()).strengths.user,
|
||||
{ claude: { thrifty: { model: "haiku" }, best: { model: "opus", effort: "high" } } },
|
||||
"a bad effort is dropped and its row stays; a bad model or word drops only that row"
|
||||
);
|
||||
});
|
||||
|
||||
test("agents: no file is an empty list, a save is written whole and keeps unknown keys, and a bad save names its entry and field", async (t) => {
|
||||
const file = path.join(MODELS_DIR, "agents.json");
|
||||
t.after(() => fs.rmSync(file, { force: true }));
|
||||
|
||||
@@ -62,6 +62,9 @@ import {
|
||||
MAX_NOTE_IMAGES,
|
||||
noteAction,
|
||||
noteReplyLines,
|
||||
pruneStaged,
|
||||
suggestAction,
|
||||
suggestReplyLines,
|
||||
progressTotal,
|
||||
quietLimitMs,
|
||||
resumeCommand,
|
||||
@@ -515,6 +518,69 @@ test("a note with documents splits them into files, keeps attach order in its li
|
||||
]);
|
||||
});
|
||||
|
||||
test("a request for suggestions reads apart from a note, with its note and attachments", () => {
|
||||
assert.deepEqual(suggestReplyLines("Export format", "Which suits Excel?", []), ["Suggestions wanted on Export format: Which suits Excel?"]);
|
||||
assert.deepEqual(suggestReplyLines("Export format", "", []), ["Suggestions wanted on Export format: (no note)"]);
|
||||
assert.deepEqual(suggestReplyLines("Export format", "", undefined), ["Suggestions wanted on Export format: (no note)"]);
|
||||
assert.deepEqual(suggestReplyLines("Export format", "Line one\nLine two", []), [
|
||||
"Suggestions wanted on Export format: Line one\n Line two",
|
||||
]);
|
||||
const atts = [
|
||||
{ key: "k1", path: "C:\\x\\a.jpg", name: "shot.png", status: "ready" },
|
||||
{ key: "k2", kind: "file", path: "C:\\x\\b.pdf", name: "spec.pdf", status: "ready" },
|
||||
];
|
||||
assert.deepEqual(suggestReplyLines("Export format", "See these", atts), [
|
||||
"Suggestions wanted on Export format: See these",
|
||||
" Image: C:\\x\\a.jpg (shot.png)",
|
||||
" File: C:\\x\\b.pdf (spec.pdf)",
|
||||
]);
|
||||
assert.deepEqual(suggestAction("q1", "See these", atts), {
|
||||
i: "q1",
|
||||
type: "comment",
|
||||
text: "See these",
|
||||
images: [{ path: "C:\\x\\a.jpg", name: "shot.png" }],
|
||||
files: [{ path: "C:\\x\\b.pdf", name: "spec.pdf" }],
|
||||
suggest: true,
|
||||
});
|
||||
assert.deepEqual(suggestAction("q1", "", []), { i: "q1", type: "comment", text: "", suggest: true });
|
||||
});
|
||||
|
||||
test("pruneStaged drops only the picks a re-posted card no longer offers, without touching its inputs", () => {
|
||||
const opts = (...ks) => ks.map((k) => ({ k, text: k }));
|
||||
const items = [
|
||||
{ id: "c1", kind: "choice", options: opts("A", "B") },
|
||||
{ id: "c2", kind: "choice", options: opts("A") },
|
||||
{ id: "m1", kind: "multi", options: opts("1", "3") },
|
||||
{ id: "m2", kind: "multi", options: opts("1") },
|
||||
{ id: "f1", kind: "confirm" },
|
||||
{ id: "u1", kind: "choice", options: opts("A", "B") },
|
||||
];
|
||||
const staged = {
|
||||
c1: { type: "answer", kind: "choice", k: "C" },
|
||||
c2: { type: "answer", kind: "choice", k: "B", text: "or something else" },
|
||||
m1: { type: "answer", kind: "multi", ks: ["1", "2", "3"] },
|
||||
m2: { type: "answer", kind: "multi", ks: ["2"] },
|
||||
f1: { type: "answer", kind: "confirm", yes: true },
|
||||
u1: { type: "answer", kind: "choice", k: "B" },
|
||||
gone: { type: "answer", kind: "choice", k: "Z" },
|
||||
};
|
||||
const before = structuredClone(staged);
|
||||
const itemsBefore = structuredClone(items);
|
||||
const out = pruneStaged(items, staged);
|
||||
assert.deepEqual(out.dropped.sort(), ["c1", "c2", "m1", "m2"]);
|
||||
assert.equal("c1" in out.staged, false, "a choice left with nothing goes");
|
||||
assert.deepEqual(out.staged.c2, { type: "answer", kind: "choice", text: "or something else" }, "typed text keeps the entry");
|
||||
assert.deepEqual(out.staged.m1.ks, ["1", "3"], "a multi keeps the keys still offered");
|
||||
assert.equal("m2" in out.staged, false, "a multi left empty goes");
|
||||
assert.equal(out.staged.f1, staged.f1, "a confirm is left alone");
|
||||
assert.equal(out.staged.u1, staged.u1, "an unchanged card is left alone");
|
||||
assert.equal(out.staged.gone, staged.gone, "an id not among the items is left alone");
|
||||
assert.notEqual(out.staged, staged, "a new object comes back");
|
||||
assert.deepEqual(staged, before, "staged is not changed");
|
||||
assert.deepEqual(items, itemsBefore, "items are not changed");
|
||||
assert.deepEqual(pruneStaged(items, { u1: staged.u1 }), { staged: { u1: staged.u1 }, dropped: [] });
|
||||
});
|
||||
|
||||
test("document helpers: the extension allow-list, the picker's accept, sizes, and the kind of an old entry", () => {
|
||||
assert.equal(MAX_ATTACHMENTS, 5);
|
||||
assert.equal(MAX_DOC_BYTES, 10 * 1024 * 1024);
|
||||
@@ -2019,8 +2085,8 @@ test("workspace cursor never moves backwards, and only changes past it are pendi
|
||||
}
|
||||
});
|
||||
|
||||
test("subagents: only the thirteen opted-in workflows offer the switch", () => {
|
||||
for (const w of ["init", "init-update", "pathfinder", "plan", "revise-plan", "document", "implement", "implement-review", "quick-task", "review", "finalize", "xray", "diagnose"]) {
|
||||
test("subagents: only the fifteen opted-in workflows offer the switch", () => {
|
||||
for (const w of ["init", "init-update", "pathfinder", "plan", "revise-plan", "document", "implement", "implement-review", "quick-task", "review", "finalize", "xray", "diagnose", "pr-prep", "test"]) {
|
||||
assert.equal(offered(w), true, w);
|
||||
assert.ok(defaultInstruction(w).length > 0, `${w} has a default instruction`);
|
||||
}
|
||||
@@ -2028,7 +2094,7 @@ test("subagents: only the thirteen opted-in workflows offer the switch", () => {
|
||||
assert.equal(offered(w), false, String(w));
|
||||
assert.equal(defaultInstruction(w), "");
|
||||
}
|
||||
assert.equal(Object.keys(SUBAGENT_WORKFLOWS).length, 13);
|
||||
assert.equal(Object.keys(SUBAGENT_WORKFLOWS).length, 15);
|
||||
assert.deepEqual(defaultSetting("review"), { workflow: "review", on: true, instruction: null, max: 3, strength: "balanced" });
|
||||
assert.equal(defaultSetting("changelog").on, false, "a skill without the switch is never on");
|
||||
assert.equal(effectiveInstruction({ workflow: "review", instruction: " " }), defaultInstruction("review"));
|
||||
@@ -2318,13 +2384,14 @@ test("meter: the weights and labels built from the skill list are the ones writt
|
||||
"pathfinder-chart": 2, "pathfinder-question": 0, "pathfinder-research": 1,
|
||||
plan: 2, "revise-plan": 1, document: 2, "implement-phase": 2, "implement-review-phase": 3,
|
||||
review: 2, "quick-task": 1, init: 2, "init-update": 2, finalize: 1, handoff: 0, git: 1,
|
||||
"git-commits": 0, "git-conflict": 1, changelog: 1, xray: 1, diagnose: 1,
|
||||
"git-commits": 0, "git-conflict": 1, changelog: 1, xray: 1, diagnose: 1, "pr-prep": 1, test: 1,
|
||||
});
|
||||
assert.deepEqual({ ...LAUNCH_LABELS }, {
|
||||
plan: "Plan started", "revise-plan": "Revise plan started", document: "Document started",
|
||||
review: "Review started", "quick-task": "Quick task started", init: "Init started",
|
||||
"init-update": "Init update started", finalize: "Finalize started", git: "Git started",
|
||||
changelog: "Changelog started", xray: "X-ray started", diagnose: "Diagnose started",
|
||||
"pr-prep": "PR Prep started", test: "Test started",
|
||||
});
|
||||
assert.deepEqual({ ...RUN_LABELS }, {
|
||||
"pathfinder-chart": "Pathfinder map written", "pathfinder-question": "Pathfinder question settled",
|
||||
@@ -2334,6 +2401,7 @@ test("meter: the weights and labels built from the skill list are the ones writt
|
||||
"quick-task": "Quick task built", init: "Init run", "init-update": "Init update run",
|
||||
finalize: "Finalize run", handoff: "Handoff written", git: "Git run", "git-commits": "Commits in Git",
|
||||
"git-conflict": "Git conflict help", changelog: "Changelog run", xray: "X-ray run", diagnose: "Diagnose run",
|
||||
"pr-prep": "PR Prep run", test: "Test run",
|
||||
});
|
||||
for (const t of [WEIGHTS, LAUNCH_LABELS, RUN_LABELS]) assert.ok(Object.isFrozen(t));
|
||||
});
|
||||
|
||||
@@ -18,7 +18,7 @@ import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { applyPatch, blankState, validate, switchWorkflow } from "../src/web-console/patches.mjs";
|
||||
import { ROOT, CONSOLE_CLI, ENV, HOME, cli, readState, sessionUrl, payload } from "./web-console-test-helpers.mjs";
|
||||
import { ROOT, CONSOLE_CLI, ENV, HOME, MODELS_DIR, cli, readState, sessionUrl, payload } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const APP_VARS = ["PLAN2CODE_IN_APP", "PLAN2CODE_EMBED_ORIGIN", "PLAN2CODE_APP_ANNOUNCE", "PLAN2CODE_APP_TOKEN", "PLAN2CODE_CONSOLE_SID"];
|
||||
|
||||
@@ -472,10 +472,16 @@ test("loopEnd: a valid stopped with an evidence doc in the same patch is stored"
|
||||
assert.equal(replaced.next.loopEnd.line, "A later word replaces the earlier");
|
||||
});
|
||||
|
||||
test("loopEnd: ask is accepted in can, so a stopped loop can offer a question before anything runs", () => {
|
||||
const { problems, next } = tryPatch(loopState(), { loopEnd: goodEnd({ can: ["resume", "ask", "fix", "dashboard"] }) });
|
||||
assert.deepEqual(problems, []);
|
||||
assert.deepEqual(next.loopEnd.can, ["resume", "ask", "fix", "dashboard"]);
|
||||
});
|
||||
|
||||
test("loopEnd: an unknown evidence id, a push in can, and the other bad fields are refused, each named", () => {
|
||||
const cases = [
|
||||
["an unknown evidence id", goodEnd({ evidence: "nope" }), /loopEnd\.evidence must be the id of a doc on the page/],
|
||||
["a push in can", goodEnd({ can: ["resume", "push"] }), /loopEnd\.can must be an array with entries from resume, fix, finalize, dashboard/],
|
||||
["a push in can", goodEnd({ can: ["resume", "push"] }), /loopEnd\.can must be an array with entries from resume, ask, fix, finalize, dashboard/],
|
||||
["a bad kind", goodEnd({ kind: "paused" }), /loopEnd\.kind must be "stopped" or "finished"/],
|
||||
["a two-line line", goodEnd({ line: "one\ntwo" }), /loopEnd\.line must be one line/],
|
||||
["an absolute uncommitted path", goodEnd({ uncommitted: ["/etc/passwd"] }), /loopEnd\.uncommitted must be an array of relative paths/],
|
||||
@@ -772,7 +778,7 @@ test("loop-setup: GET /loop-setup lists the phases left for a spec and refuses a
|
||||
}
|
||||
|
||||
// Saving through the route, then reading it back in a new request.
|
||||
const save = await send({ review: true, fixMode: "smart", fix: ["critical"], commit: true, onQuestion: "stop", afterLast: "offer-finalize", quickCheck: "", notifyKind: "query", notifyUrl: "https://example.com/hook", notifyParam: "msg", retryOnce: true, silenceMinutes: 30 });
|
||||
const save = await send({ review: true, fixMode: "smart", fix: ["critical"], commit: true, onQuestion: "stop", afterLast: "offer-finalize", quickCheck: "", notifyKind: "query", notifyUrl: "https://example.com/hook", notifyParam: "msg", retryOnce: true, silenceMinutes: 30, phaseStrength: false, strengths: {} });
|
||||
assert.equal(save.status, 200, await save.clone().text());
|
||||
const after = await get("?spec=specs/demo");
|
||||
assert.equal(after.body.remembered, true);
|
||||
@@ -789,3 +795,170 @@ test("loop-setup: GET /loop-setup lists the phases left for a spec and refuses a
|
||||
cli(["stop", "--session", opened.json.sid, "--force"], { cwd, expectFail: true });
|
||||
}
|
||||
});
|
||||
|
||||
/* ------------------------------ phase strength: the setup's new fields */
|
||||
|
||||
const specWith = (project, name, phases) => {
|
||||
const dir = path.join(project, "specs", name);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const rows = phases.map(([mark, n, title]) => `- [${mark}] **Phase ${n}:** ${title} - [phase-${n}.md](phase-${n}.md)`);
|
||||
fs.writeFileSync(path.join(dir, "overview.md"), ["# Demo", "", "## Phase Checklist", "", ...rows, ""].join("\n"));
|
||||
};
|
||||
|
||||
test("loop-setup: the strength fields default off, and their bad values are named", () => {
|
||||
fs.rmSync(LOOP_SETUP_PATH, { force: true });
|
||||
const cases = [
|
||||
["phaseStrength as a string", { phaseStrength: "yes" }, /"phaseStrength" must be true or false/],
|
||||
["strengths as a list", { strengths: [] }, /"strengths" must be an object/],
|
||||
["a key outside specs/", { strengths: { "../x": [] } }, /must be a folder directly under specs\//],
|
||||
["a hidden spec folder", { strengths: { "specs/.hidden": [] } }, /must be a folder directly under specs\//],
|
||||
["a nested spec key", { strengths: { "specs/a/b": [] } }, /must be a folder directly under specs\//],
|
||||
["picks as an object", { strengths: { "specs/a": {} } }, /at most 100 phase picks/],
|
||||
["101 picks", { strengths: { "specs/a": Array.from({ length: 101 }, (_, i) => ({ n: i + 1, name: "p", strength: "best" })) } }, /at most 100 phase picks/],
|
||||
["n of 0", { strengths: { "specs/a": [{ n: 0, name: "p", strength: "best" }] } }, /positive whole number/],
|
||||
["n as text", { strengths: { "specs/a": [{ n: "2", name: "p", strength: "best" }] } }, /positive whole number/],
|
||||
["a repeated n", { strengths: { "specs/a": [{ n: 2, name: "p", strength: "best" }, { n: 2, name: "q", strength: "best" }] } }, /Phase 2 twice/],
|
||||
["a 201-character name", { strengths: { "specs/a": [{ n: 1, name: "x".repeat(201), strength: "best" }] } }, /at most 200 characters/],
|
||||
["an unknown word", { strengths: { "specs/a": [{ n: 1, name: "p", strength: "max" }] } }, /strength of thrifty, balanced, best/],
|
||||
];
|
||||
const got = inStore(
|
||||
(m, { project, list }) =>
|
||||
list.map(([what, change]) => {
|
||||
try {
|
||||
m.saveLoopSetup(project, { ...m.LOOP_DEFAULTS, fix: [...m.LOOP_DEFAULTS.fix], ...change });
|
||||
return { what, threw: false };
|
||||
} catch (e) {
|
||||
return { what, threw: true, message: e.message };
|
||||
}
|
||||
}),
|
||||
{ project: projectA, list: cases.map(([what, change]) => [what, change]) }
|
||||
);
|
||||
for (const [i, [what, , expected]] of cases.entries()) {
|
||||
assert.equal(got[i].threw, true, `${what} is refused`);
|
||||
assert.match(got[i].message, expected, what);
|
||||
}
|
||||
assert.equal(fs.existsSync(LOOP_SETUP_PATH), false, "a refused save writes nothing");
|
||||
const fresh = inStore((m, { project }) => m.readLoopSetup(project), { project: projectA });
|
||||
assert.equal(fresh.phaseStrength, false);
|
||||
assert.deepEqual(fresh.strengths, {});
|
||||
});
|
||||
|
||||
test("loop-setup: an entry saved before the strength fields reads as off with no picks", () => {
|
||||
fs.rmSync(LOOP_SETUP_PATH, { force: true });
|
||||
const project = path.join(HOME, "store-project-old");
|
||||
inStore((m, { p }) => (m.saveLoopSetup(p, { ...m.LOOP_DEFAULTS, fix: ["warning"] }), null), { p: project });
|
||||
const store = JSON.parse(fs.readFileSync(LOOP_SETUP_PATH, "utf8"));
|
||||
const [folded] = Object.keys(store.projects);
|
||||
delete store.projects[folded].phaseStrength;
|
||||
delete store.projects[folded].strengths;
|
||||
fs.writeFileSync(LOOP_SETUP_PATH, JSON.stringify(store));
|
||||
const got = inStore((m, { p }) => m.readLoopSetup(p), { p: project });
|
||||
assert.equal(got.remembered, true);
|
||||
assert.equal(got.phaseStrength, false);
|
||||
assert.deepEqual(got.strengths, {});
|
||||
assert.deepEqual(got.fix, ["warning"]);
|
||||
});
|
||||
|
||||
test("loop-setup: picks for a removed spec folder or a renamed phase are pruned on read and on save", () => {
|
||||
fs.rmSync(LOOP_SETUP_PATH, { force: true });
|
||||
const project = fs.mkdtempSync(path.join(HOME, "prune-"));
|
||||
specWith(project, "keep", [["x", 1, "Done"], [" ", 2, "Build it"], [" ", 3, "Ship it"]]);
|
||||
specWith(project, "gone", [[" ", 1, "Only"]]);
|
||||
const picks = {
|
||||
"specs/keep": [
|
||||
{ n: 2, name: "Build it", strength: "thrifty" },
|
||||
{ n: 3, name: "Ship it renamed", strength: "best" },
|
||||
{ n: 1, name: "Done", strength: "best" },
|
||||
],
|
||||
"specs/gone": [{ n: 1, name: "Only", strength: "best" }],
|
||||
"specs/never": [{ n: 1, name: "x", strength: "best" }],
|
||||
};
|
||||
const out = inStore(
|
||||
async (m, { project, picks }) => {
|
||||
const fs = await import("node:fs");
|
||||
const path = await import("node:path");
|
||||
const left = (spec) => {
|
||||
const text = fs.readFileSync(path.join(project, spec, "overview.md"), "utf8");
|
||||
return [...text.matchAll(/^- \[ \] \*\*Phase (\d+):\*\* (.+?) - /gm)].map((x) => ({ n: Number(x[1]), name: x[2] }));
|
||||
};
|
||||
fs.rmSync(path.join(project, "specs", "gone"), { recursive: true });
|
||||
const saved = m.saveLoopSetup(project, { ...m.LOOP_DEFAULTS, fix: [...m.LOOP_DEFAULTS.fix], phaseStrength: true, strengths: picks }, left);
|
||||
const onDisk = JSON.parse(fs.readFileSync(m.LOOP_SETUP_FILE, "utf8"));
|
||||
const raw = Object.values(onDisk.projects)[0].strengths;
|
||||
// A later read, with the overview changed again, drops the next pick too.
|
||||
fs.writeFileSync(path.join(project, "specs", "keep", "overview.md"), "# Demo\n\n## Phase Checklist\n\n- [ ] **Phase 3:** Ship it - [phase-3.md](phase-3.md)\n");
|
||||
const later = m.readLoopSetup(project, left);
|
||||
return { saved: saved.strengths, raw, later: later.strengths };
|
||||
},
|
||||
{ project, picks }
|
||||
);
|
||||
const kept = [{ n: 2, name: "Build it", strength: "thrifty" }];
|
||||
assert.deepEqual(out.saved, { "specs/keep": kept }, "the removed folder, the never-made one, the renamed phase and the finished phase are dropped");
|
||||
assert.deepEqual(out.raw, { "specs/keep": kept }, "the file holds the pruned copy");
|
||||
assert.deepEqual(out.later, {}, "a later read prunes what the overview no longer lists");
|
||||
});
|
||||
|
||||
test("loop-setup: the picks live only in loop-setup.json, never under specs/", () => {
|
||||
fs.rmSync(LOOP_SETUP_PATH, { force: true });
|
||||
const project = fs.mkdtempSync(path.join(HOME, "nowrite-"));
|
||||
specWith(project, "demo", [[" ", 1, "One"]]);
|
||||
const before = fs.readFileSync(path.join(project, "specs", "demo", "overview.md"), "utf8");
|
||||
inStore(
|
||||
(m, { project }) => (m.saveLoopSetup(project, { ...m.LOOP_DEFAULTS, fix: [...m.LOOP_DEFAULTS.fix], phaseStrength: true, strengths: { "specs/demo": [{ n: 1, name: "One", strength: "best" }] } }), null),
|
||||
{ project }
|
||||
);
|
||||
assert.ok(fs.existsSync(LOOP_SETUP_PATH));
|
||||
assert.deepEqual(fs.readdirSync(path.join(project, "specs", "demo")), ["overview.md"]);
|
||||
assert.equal(fs.readFileSync(path.join(project, "specs", "demo", "overview.md"), "utf8"), before);
|
||||
assert.deepEqual(fs.readdirSync(project), ["specs"], "nothing else appears in the project");
|
||||
});
|
||||
|
||||
test("GET /loop-setup?agent= answers the loop agent's resolved strengths and this spec's picks", async () => {
|
||||
fs.rmSync(LOOP_SETUP_PATH, { force: true });
|
||||
const cwd = tempProject("route-strength");
|
||||
specWith(cwd, "demo", [[" ", 1, "One"], [" ", 2, "Two"]]);
|
||||
// The installed copy of the shipped model menu, with its strengths, as install.js drops it.
|
||||
const shipped = path.join(MODELS_DIR, "bin", "models.json");
|
||||
const hadShipped = fs.existsSync(shipped) ? fs.readFileSync(shipped) : null;
|
||||
fs.mkdirSync(path.dirname(shipped), { recursive: true });
|
||||
fs.copyFileSync(path.join(ROOT, "src", "launcher", "models.json"), shipped);
|
||||
const opened = run(["open", "--workflow", "implement", "--no-open"], { cwd });
|
||||
assert.equal(opened.status, 0, opened.stderr);
|
||||
const { base, cookie } = sessionUrl(opened.json.url);
|
||||
const get = async (query) => {
|
||||
const res = await fetch(`${base}/loop-setup${query}`, { headers: { cookie, connection: "close" } });
|
||||
return { status: res.status, body: await res.json() };
|
||||
};
|
||||
try {
|
||||
const none = await get("?spec=specs/demo");
|
||||
assert.equal(none.body.resolved, null, "no agent asked, none answered");
|
||||
assert.deepEqual(none.body.picks, []);
|
||||
assert.equal(none.body.phaseStrength, false);
|
||||
|
||||
const claude = await get("?spec=specs/demo&agent=claude");
|
||||
assert.equal(claude.status, 200);
|
||||
assert.deepEqual(Object.keys(claude.body.resolved).sort(), ["balanced", "best", "thrifty"], "the shipped Claude Code rows");
|
||||
for (const word of ["thrifty", "balanced", "best"]) assert.equal(typeof claude.body.resolved[word].model, "string");
|
||||
|
||||
const codex = await get("?spec=specs/demo&agent=codex");
|
||||
assert.deepEqual(codex.body.resolved, {}, "codex has nothing mapped");
|
||||
|
||||
for (const agent of ["nobody", "..%2Fx", ""]) assert.equal((await get(`?spec=specs/demo&agent=${agent}`)).body.resolved, null, `agent=${agent}`);
|
||||
|
||||
// A save with picks reads back for its own spec; a pick for a phase that is not there is pruned.
|
||||
const entry = {
|
||||
review: true, fixMode: "smart", fix: ["critical"], commit: true, onQuestion: "guess", afterLast: "offer-finalize", quickCheck: "",
|
||||
notifyKind: "query", notifyUrl: "", notifyParam: "message", retryOnce: true, silenceMinutes: 20, phaseStrength: true,
|
||||
strengths: { "specs/demo": [{ n: 2, name: "Two", strength: "best" }, { n: 9, name: "Gone", strength: "best" }] },
|
||||
};
|
||||
const save = await fetch(`${base}/loop-setup`, { method: "POST", headers: { "content-type": "application/json", cookie, origin: base, connection: "close" }, body: JSON.stringify(entry) });
|
||||
assert.equal(save.status, 200, await save.clone().text());
|
||||
const back = await get("?spec=specs/demo&agent=claude");
|
||||
assert.equal(back.body.phaseStrength, true);
|
||||
assert.deepEqual(back.body.picks, [{ n: 2, name: "Two", strength: "best" }]);
|
||||
} finally {
|
||||
if (hadShipped) fs.writeFileSync(shipped, hadShipped);
|
||||
else fs.rmSync(shipped, { force: true });
|
||||
cli(["stop", "--session", opened.json.sid, "--force"], { cwd, expectFail: true });
|
||||
}
|
||||
});
|
||||
@@ -1266,7 +1266,8 @@ test("a game with music has its own Music slider, at its default until moved, ke
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING });
|
||||
const slider = s.page.locator("#activities-music-level");
|
||||
await openActivities(s, "snake");
|
||||
assert.equal(await s.page.locator("#activities-music").isVisible(), false, "Snake has no music, so no slider");
|
||||
assert.equal(await s.page.locator("#activities-music").isVisible(), true, "Snake has a slider");
|
||||
assert.equal(await boxValue(slider), "70", "at its default");
|
||||
await s.page.keyboard.press("Escape");
|
||||
await s.page.waitForFunction(() => !document.getElementById("activities-modal").open);
|
||||
await openActivities(s, "ghoul");
|
||||
@@ -2512,10 +2513,10 @@ test("Ghoul Rush plays in the real window: its board's shape and Planny big enou
|
||||
}, 5000);
|
||||
});
|
||||
|
||||
test("the server serves the activities' scripts, golf's seventeen, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring's two, Rapids Run's two, Hot Potato's two, Crossing Rush's two, Bounce Road's seven, Ghoul Rush's eighty-three, every game's sound effects and the shared pills included", () => {
|
||||
test("the server serves the activities' scripts, golf's seventeen, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring's two, Rapids Run's two, Hot Potato's two, Crossing Rush's two, Bounce Road's seven, Ghoul Rush's ninety-five, every game's sound effects and the shared pills included", () => {
|
||||
const server = fs.readFileSync(new URL("../src/web-console/static.mjs", import.meta.url), "utf8");
|
||||
const servable = server.slice(server.indexOf("const SERVABLE = new Set(["), server.indexOf("]);", server.indexOf("const SERVABLE = new Set([")));
|
||||
for (const file of ["activities.js", "tones.js", "music.js", "activities/snake.js", "screens/activities.js", "activities/golf.js", "activities/golf-holes.js", "activities/golf-draw.js", "activities/golf-decor.js", "activities/golf-kit.js", "activities/golf-paint.js", "activities/golf-looks.js", "activities/golf-course-pirate.js", "activities/golf-course-cave.js", "activities/golf-course-dino.js", "activities/golf-course-candy.js", "activities/golf-course-space.js", "activities/golf-course-frost.js", "activities/golf-look-dino.js", "activities/golf-look-candy.js", "activities/golf-look-space.js", "activities/golf-look-frost.js", "activities/trails.js", "activities/bugs.js", "activities/drive.js", "activities/stack.js", "activities/bumper.js", "activities/bumper-draw.js", "activities/rapids.js", "activities/rapids-draw.js", "activities/fuse.js", "activities/fuse-draw.js", "activities/hop.js", "activities/hop-draw.js", "activities/bounce.js", "activities/bounce-draw.js", "activities/bounce-roads.js", "activities/bounce-road.js", "activities/bounce-rivals.js", "activities/bounce-scenery.js", "activities/bounce-cars.js", "activities/ghoul-rush/ghoul.js", "activities/ghoul-rush/draw/ghoul-draw.js", "activities/ghoul-rush/core/ghoul-rooms.js", "activities/ghoul-rush/stages/wing/ghoul-bones.js", "activities/ghoul-rush/stages/wing/ghoul-bones-draw.js", "activities/ghoul-rush/stages/graveyard/ghoul-graveyard.js", "activities/ghoul-rush/stages/graveyard/ghoul-graveyard-draw.js", "activities/ghoul-rush/stages/grounds/ghoul-grounds.js", "activities/ghoul-rush/stages/grounds/ghoul-grounds-draw.js", "activities/ghoul-rush/stages/chapel/ghoul-chapel.js", "activities/ghoul-rush/stages/chapel/ghoul-chapel-draw.js", "activities/ghoul-rush/stages/sanatorium/ghoul-sanatorium.js", "activities/ghoul-rush/stages/sanatorium/ghoul-sanatorium-draw.js", "activities/ghoul-rush/stages/village/ghoul-village.js", "activities/ghoul-rush/stages/village/ghoul-village-draw.js", "activities/ghoul-rush/stages/village/ghoul-village-world.js", "activities/ghoul-rush/stages/village/ghoul-village-wolf.js", "activities/ghoul-rush/stages/mine/ghoul-mine.js", "activities/ghoul-rush/stages/mine/ghoul-mine-draw.js", "activities/ghoul-rush/stages/mine/ghoul-mine-world.js", "activities/ghoul-rush/stages/mine/ghoul-mine-tommy.js", "activities/ghoul-rush/rides/cart/ghoul-cart.js", "activities/ghoul-rush/rides/cart/ghoul-cart-draw.js", "activities/ghoul-rush/rides/sled/ghoul-sled.js", "activities/ghoul-rush/rides/sled/ghoul-sled-draw.js", "activities/ghoul-rush/rides/gurney/ghoul-gurney.js", "activities/ghoul-rush/rides/gurney/ghoul-gurney-draw.js", "activities/ghoul-rush/rides/banister/ghoul-banister.js", "activities/ghoul-rush/rides/banister/ghoul-banister-draw.js", "activities/ghoul-rush/rides/banister/ghoul-sfx-banister.js", "activities/ghoul-rush/rides/hearse/ghoul-hearse.js", "activities/ghoul-rush/rides/hearse/ghoul-hearse-draw.js", "activities/ghoul-rush/rides/wagon/ghoul-wagon.js", "activities/ghoul-rush/rides/wagon/ghoul-wagon-draw.js", "activities/ghoul-rush/rides/pew/ghoul-pew.js", "activities/ghoul-rush/rides/pew/ghoul-pew-draw.js", "activities/ghoul-rush/rides/pew/ghoul-pew-course.js", "activities/ghoul-rush/rides/pew/ghoul-pew-world.js", "activities/ghoul-rush/rides/mower/ghoul-mower.js", "activities/ghoul-rush/rides/mower/ghoul-mower-draw.js", "activities/ghoul-rush/rides/tray/ghoul-tray.js", "activities/ghoul-rush/rides/tray/ghoul-tray-draw.js", "activities/ghoul-rush/stages/carnival/ghoul-carnival.js", "activities/ghoul-rush/stages/carnival/ghoul-carnival-draw.js", "activities/ghoul-rush/stages/carnival/ghoul-carnival-world.js", "activities/ghoul-rush/stages/frozen/ghoul-frozen.js", "activities/ghoul-rush/stages/frozen/ghoul-frozen-draw.js", "activities/ghoul-rush/stages/frozen/ghoul-frozen-world.js", "activities/ghoul-rush/arms/ghoul-flare.js", "activities/ghoul-rush/stages/bog/ghoul-bog.js", "activities/ghoul-rush/stages/bog/ghoul-bog-draw.js", "activities/ghoul-rush/draw/ghoul-picker-draw.js", "activities/ghoul-rush/core/ghoul-powers.js", "activities/ghoul-rush/arms/ghoul-arms.js", "activities/ghoul-rush/arms/ghoul-arms-draw.js", "activities/ghoul-rush/arms/ghoul-rockets.js", "activities/ghoul-rush/arms/ghoul-rockets-draw.js", "activities/ghoul-rush/arms/ghoul-pans.js", "activities/ghoul-rush/arms/ghoul-sfx-arms.js", "activities/ghoul-rush/core/ghoul-run.js", "activities/ghoul-rush/core/ghoul-dice.js", "activities/ghoul-rush/core/ghoul-dice-draw.js", "activities/ghoul-rush/story/ghoul-gameover-draw.js", "activities/ghoul-rush/story/ghoul-intros.js", "activities/ghoul-rush/story/ghoul-intro-draw.js", "activities/ghoul-rush/story/ghoul-boss-intros.js", "activities/ghoul-rush/story/ghoul-bossintro-draw.js", "activities/ghoul-rush/story/ghoul-story.js", "activities/ghoul-rush/story/ghoul-story-draw.js", "activities/ghoul-rush/story/ghoul-sfx-story.js", "activities/ghoul-rush/core/ghoul-bonus.js", "activities/ghoul-rush/core/ghoul-bonus-drLine truncated
|
||||
for (const file of ["activities.js", "tones.js", "music.js", "activities/snake.js", "activities/snake-music.js", "screens/activities.js", "activities/golf.js", "activities/golf-holes.js", "activities/golf-draw.js", "activities/golf-decor.js", "activities/golf-kit.js", "activities/golf-paint.js", "activities/golf-looks.js", "activities/golf-course-pirate.js", "activities/golf-course-cave.js", "activities/golf-course-dino.js", "activities/golf-course-candy.js", "activities/golf-course-space.js", "activities/golf-course-frost.js", "activities/golf-look-dino.js", "activities/golf-look-candy.js", "activities/golf-look-space.js", "activities/golf-look-frost.js", "activities/trails.js", "activities/bugs.js", "activities/drive.js", "activities/stack.js", "activities/bumper.js", "activities/bumper-draw.js", "activities/rapids.js", "activities/rapids-draw.js", "activities/fuse.js", "activities/fuse-draw.js", "activities/hop.js", "activities/hop-draw.js", "activities/bounce.js", "activities/bounce-draw.js", "activities/bounce-roads.js", "activities/bounce-road.js", "activities/bounce-rivals.js", "activities/bounce-scenery.js", "activities/bounce-cars.js", "activities/ghoul-rush/ghoul.js", "activities/ghoul-rush/draw/ghoul-draw.js", "activities/ghoul-rush/core/ghoul-rooms.js", "activities/ghoul-rush/stages/wing/ghoul-bones.js", "activities/ghoul-rush/stages/wing/ghoul-bones-draw.js", "activities/ghoul-rush/stages/graveyard/ghoul-graveyard.js", "activities/ghoul-rush/stages/graveyard/ghoul-graveyard-draw.js", "activities/ghoul-rush/stages/grounds/ghoul-grounds.js", "activities/ghoul-rush/stages/grounds/ghoul-grounds-draw.js", "activities/ghoul-rush/stages/chapel/ghoul-chapel.js", "activities/ghoul-rush/stages/chapel/ghoul-chapel-draw.js", "activities/ghoul-rush/stages/sanatorium/ghoul-sanatorium.js", "activities/ghoul-rush/stages/sanatorium/ghoul-sanatorium-draw.js", "activities/ghoul-rush/stages/village/ghoul-village.js", "activities/ghoul-rush/stages/village/ghoul-village-draw.js", "activities/ghoul-rush/stages/village/ghoul-village-world.js", "activities/ghoul-rush/stages/village/ghoul-village-wolf.js", "activities/ghoul-rush/stages/mine/ghoul-mine.js", "activities/ghoul-rush/stages/mine/ghoul-mine-draw.js", "activities/ghoul-rush/stages/mine/ghoul-mine-world.js", "activities/ghoul-rush/stages/mine/ghoul-mine-tommy.js", "activities/ghoul-rush/rides/cart/ghoul-cart.js", "activities/ghoul-rush/rides/cart/ghoul-cart-draw.js", "activities/ghoul-rush/rides/sled/ghoul-sled.js", "activities/ghoul-rush/rides/sled/ghoul-sled-draw.js", "activities/ghoul-rush/rides/gurney/ghoul-gurney.js", "activities/ghoul-rush/rides/gurney/ghoul-gurney-draw.js", "activities/ghoul-rush/rides/banister/ghoul-banister.js", "activities/ghoul-rush/rides/banister/ghoul-banister-draw.js", "activities/ghoul-rush/rides/banister/ghoul-sfx-banister.js", "activities/ghoul-rush/rides/hearse/ghoul-hearse.js", "activities/ghoul-rush/rides/hearse/ghoul-hearse-draw.js", "activities/ghoul-rush/rides/wagon/ghoul-wagon.js", "activities/ghoul-rush/rides/wagon/ghoul-wagon-draw.js", "activities/ghoul-rush/rides/pew/ghoul-pew.js", "activities/ghoul-rush/rides/pew/ghoul-pew-draw.js", "activities/ghoul-rush/rides/pew/ghoul-pew-course.js", "activities/ghoul-rush/rides/pew/ghoul-pew-world.js", "activities/ghoul-rush/rides/mower/ghoul-mower.js", "activities/ghoul-rush/rides/mower/ghoul-mower-draw.js", "activities/ghoul-rush/rides/tray/ghoul-tray.js", "activities/ghoul-rush/rides/tray/ghoul-tray-draw.js", "activities/ghoul-rush/stages/carnival/ghoul-carnival.js", "activities/ghoul-rush/stages/carnival/ghoul-carnival-draw.js", "activities/ghoul-rush/stages/carnival/ghoul-carnival-world.js", "activities/ghoul-rush/stages/frozen/ghoul-frozen.js", "activities/ghoul-rush/stages/frozen/ghoul-frozen-draw.js", "activities/ghoul-rush/stages/frozen/ghoul-frozen-world.js", "activities/ghoul-rush/arms/ghoul-flare.js", "activities/ghoul-rush/stages/bog/ghoul-bog.js", "activities/ghoul-rush/stages/bog/ghoul-bog-draw.js", "activities/ghoul-rush/stages/marrow/ghoul-marrow.js", "activities/ghoul-rush/stages/marrow/ghoul-marrow-draw.js", "activities/ghoul-rush/rides/mat/ghoul-mat-room.js", "activities/ghoul-rush/rides/mat/ghoul-mat.js", "activities/ghoul-rush/rides/mat/ghoul-mat-draw.js", "activities/ghoul-rush/stages/marrow/ghoul-dollhouse-room.js", "activities/ghoul-rush/stages/marrow/ghoul-marrow-eye.js", "activities/ghoul-rush/stages/marrow/ghoul-marrow-eye-draw.js", "activities/ghoul-rush/rides/bonestair/ghoul-bonestair-room.js", "activities/ghoul-rush/rides/bonestair/ghoul-bonestair.js", "activities/ghoul-rush/rides/bonestair/ghoul-bonestair-draw.js", "activities/ghoul-rush/stages/marrow/ghoul-pit-room.js", "activities/ghoul-rush/stages/marrow/ghoul-marrow-heart.js", "activities/ghoul-rush/stages/marrow/ghoul-marrow-heart-draw.js", "activities/ghoul-rush/story/ghoul-ending.js", "activities/ghoul-rush/story/ghoul-ending-draw.js", "activities/ghoul-rush/draw/ghoul-picker-draw.js", "aLine truncated
|
||||
assert.ok(servable.includes(`"${file}"`), `SERVABLE includes ${file}`);
|
||||
}
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
// Page tests for the Ask tab: a Quick question and the agent's reply, the
|
||||
// starters, a retry after a failed send, a new conversation, a picture attached
|
||||
// to a note, and the Subagents tab. Run with:
|
||||
// to a note, the Subagents tab, and the Ask for suggestions chip. Run with:
|
||||
// node --test scripts/test-web-console-page-ask.mjs
|
||||
//
|
||||
// Each test drives the real console in a real Chrome or Edge through
|
||||
@@ -323,3 +323,167 @@ test("the Subagents tab shows a reported helper's strength line and none for a h
|
||||
assert.equal(await badges.first().locator(".sa-bars i.on").count(), 2);
|
||||
assert.equal(await rows.filter({ hasText: "Check the tests" }).locator(".sa-strength").count(), 0);
|
||||
});
|
||||
|
||||
// Ask for suggestions: the chip in the Notes on this panel.
|
||||
|
||||
const opt = (k, text) => ({ k, text, detail: `The ${text.toLowerCase()} option.` });
|
||||
|
||||
// The page's own staged answers, from the module app.js loaded.
|
||||
const stagedOn = (s) =>
|
||||
s.page.evaluate(async () => {
|
||||
const { page } = await import("/state.js");
|
||||
return page.local.staged;
|
||||
});
|
||||
|
||||
// Opens a question from the sidebar and waits for its card.
|
||||
async function goTo(s, id, title) {
|
||||
await s.page.locator("#sidebar").getByRole("button", { name: new RegExp(title) }).click();
|
||||
await itemCard(s.page, id).waitFor();
|
||||
await s.page.waitForFunction((want) => document.getElementById("aside").dataset.item === want, id);
|
||||
}
|
||||
|
||||
const chipOf = (s) => s.page.locator("#aside").getByRole("button", { name: "Ask Plan2Code for suggestions on this question" });
|
||||
|
||||
// What a person sees break: the chip on a card where there is nothing to pick,
|
||||
// on a settled record, or missing where they are unsure what to pick.
|
||||
test("the Ask for suggestions chip shows on open choice, multi and confirm cards only", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: {
|
||||
items: [
|
||||
{ id: "c1", kind: "choice", title: "Export format", body: "Which format?", options: [opt("A", "CSV"), opt("B", "JSON")] },
|
||||
{ id: "m1", kind: "multi", title: "Columns", body: "Which?", options: [opt("1", "Date"), opt("2", "User")] },
|
||||
{ id: "y1", kind: "confirm", title: "Keep going", body: "Carry on?" },
|
||||
{ id: "t1", kind: "text", title: "What to call it", body: "A name.", required: false },
|
||||
{ id: "d1", kind: "choice", title: "Old pick", body: "Which?", options: [opt("A", "CSV"), opt("B", "JSON")], status: "answered", answer: { k: "B" } },
|
||||
],
|
||||
agent: { status: "waiting" },
|
||||
},
|
||||
});
|
||||
for (const [id, title, shown] of [["c1", "Export format", 1], ["m1", "Columns", 1], ["y1", "Keep going", 1], ["t1", "What to call it", 0], ["d1", "Old pick", 0]]) {
|
||||
await goTo(s, id, title);
|
||||
assert.equal(await chipOf(s).count(), shown, `chip on ${id}`);
|
||||
if (shown) assert.equal(await textOf(chipOf(s)), "Ask for suggestions");
|
||||
}
|
||||
});
|
||||
|
||||
// What a person sees break: asking for suggestions sends or clears picks they
|
||||
// staged, locks the card, or keeps the note they typed in the box.
|
||||
test("Ask for suggestions sends one flagged note and leaves every staged pick staged", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: {
|
||||
items: [
|
||||
{ id: "c1", kind: "choice", title: "Export format", body: "Which format?", options: [opt("A", "CSV"), opt("B", "JSON")] },
|
||||
{ id: "c2", kind: "choice", title: "Where it goes", body: "Where?", options: [opt("A", "Email"), opt("B", "Slack")] },
|
||||
],
|
||||
agent: { status: "waiting" },
|
||||
},
|
||||
});
|
||||
await goTo(s, "c2", "Where it goes");
|
||||
await itemCard(s.page, "c2").getByLabel("Slack").check();
|
||||
await goTo(s, "c1", "Export format");
|
||||
await itemCard(s.page, "c1").getByLabel("JSON").check();
|
||||
await s.page.waitForFunction(async () => {
|
||||
const { page } = await import("/state.js");
|
||||
return page.local.staged.c1 && page.local.staged.c2;
|
||||
});
|
||||
await fillBox(s.page.locator("#thread-c1"), "I lean B");
|
||||
await chipOf(s).click();
|
||||
|
||||
const got = collect(s);
|
||||
assert.equal(got.actions.length, 1, `one action: ${JSON.stringify(got.actions)}`);
|
||||
const [action] = got.actions;
|
||||
assert.equal(action.i, "c1");
|
||||
assert.equal(action.type, "comment");
|
||||
assert.equal(action.suggest, true);
|
||||
assert.equal(action.text, "I lean B");
|
||||
assert.ok(got.reply.startsWith("Suggestions wanted on Export format: I lean B"), got.reply);
|
||||
|
||||
await s.page.waitForFunction(() => document.getElementById("suggest-c1")?.disabled);
|
||||
const staged = await stagedOn(s);
|
||||
assert.equal(staged.c1 && staged.c1.k, "B", "the pick on this card is still staged");
|
||||
assert.equal(staged.c2 && staged.c2.k, "B", "the pick on the other card is still staged");
|
||||
const card = itemCard(s.page, "c1");
|
||||
assert.match(await textOf(card), /Ready to send/i);
|
||||
assert.equal(await card.getByLabel("CSV").isEnabled(), true, "the card is still a live form");
|
||||
assert.equal(await boxValue(s.page.locator("#thread-c1")), "");
|
||||
await goTo(s, "c2", "Where it goes");
|
||||
assert.match(await textOf(itemCard(s.page, "c2")), /Ready to send/i);
|
||||
});
|
||||
|
||||
// What a person sees break: a request for suggestions that vanishes with no
|
||||
// sign it went, or a chip that never comes back once the agent has answered.
|
||||
test("a request for suggestions shows tagged and waiting, and the chip comes back once the agent replies", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: {
|
||||
items: [{ id: "c1", kind: "choice", title: "Export format", body: "Which format?", options: [opt("A", "CSV"), opt("B", "JSON")] }],
|
||||
agent: { status: "waiting" },
|
||||
},
|
||||
});
|
||||
await itemCard(s.page, "c1").waitFor();
|
||||
await chipOf(s).click();
|
||||
const got = collect(s);
|
||||
assert.ok(got.reply.startsWith("Suggestions wanted on Export format: (no note)"), got.reply);
|
||||
|
||||
const mine = s.page.locator("#aside .msg.you.pending");
|
||||
await mine.locator(".suggest-tag", { hasText: "Asked for suggestions" }).waitFor();
|
||||
assert.match(await textOf(mine), /Sent, waiting for Plan2Code/i);
|
||||
await s.page.waitForFunction(() => document.getElementById("suggest-c1")?.disabled);
|
||||
|
||||
s.post({ items: [{ id: "c1", thread: [{ who: "agent", text: "I would pick JSON: your scripts read it directly." }] }], agent: { status: "waiting" } });
|
||||
await s.page.locator("#aside .msg", { hasText: "I would pick JSON" }).waitFor();
|
||||
await s.page.waitForFunction(() => document.getElementById("suggest-c1") && !document.getElementById("suggest-c1").disabled);
|
||||
assert.equal(await s.page.locator("#aside .msg.you .suggest-tag").count(), 1, "the request keeps its tag once answered");
|
||||
});
|
||||
|
||||
// What a person sees break: a pick on an option the agent took away still
|
||||
// staged and sent, or the other picks on the card cleared with it.
|
||||
test("a re-post that removes a staged multi option clears only that pick and says so", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: {
|
||||
items: [{ id: "m1", kind: "multi", title: "Columns", body: "Which?", options: [opt("1", "Date"), opt("2", "User"), opt("3", "Action")] }],
|
||||
agent: { status: "waiting" },
|
||||
},
|
||||
});
|
||||
const card = itemCard(s.page, "m1");
|
||||
await card.getByLabel("Date").check();
|
||||
await card.getByLabel("Action").check();
|
||||
await s.page.waitForFunction(async () => {
|
||||
const { page } = await import("/state.js");
|
||||
return (page.local.staged.m1?.ks || []).length === 2;
|
||||
});
|
||||
|
||||
s.post({ items: [{ id: "m1", body: "Which, now that Action is gone?", options: [opt("1", "Date"), opt("2", "User")] }] });
|
||||
await s.page.locator("#banner", { hasText: "no longer matches the reworded question" }).waitFor();
|
||||
assert.match(await textOf(s.page.locator("#banner")), /A pick on Columns no longer matches/);
|
||||
assert.deepEqual((await stagedOn(s)).m1.ks, ["1"]);
|
||||
await itemCard(s.page, "m1").getByText("Which, now that Action is gone?").waitFor();
|
||||
assert.equal(await itemCard(s.page, "m1").getByLabel("Date").isChecked(), true);
|
||||
// A notice, not a fault: it clears by itself.
|
||||
await s.page.locator("#banner").waitFor({ state: "hidden", timeout: 20000 });
|
||||
});
|
||||
|
||||
// What a person sees break: a chip that sends past the Implementation Loop,
|
||||
// which answers for the agent while it drives.
|
||||
test("the Ask for suggestions chip stays away while the loop drives, even on a card waiting for the person", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "implement",
|
||||
open: ["--loop"],
|
||||
env: { PLAN2CODE_IN_APP: "1" },
|
||||
payload: {
|
||||
items: [{ id: "c1", kind: "choice", title: "Export format", body: "Which format?", options: [opt("A", "CSV"), opt("B", "JSON")] }],
|
||||
agent: { status: "waiting" },
|
||||
},
|
||||
});
|
||||
await itemCard(s.page, "c1").getByLabel("JSON").waitFor();
|
||||
await s.page.locator("#thread-c1").waitFor();
|
||||
assert.equal(await chipOf(s).count(), 0, "no chip while the loop drives");
|
||||
});
|
||||
@@ -137,15 +137,14 @@ const settles = (control, enabled) => until(async () => (await control.isEnabled
|
||||
const settlesUsable = (page, want) => until(async () => (await usable(page)) === want, 8000);
|
||||
const titled = (page, text) => page.waitForFunction((x) => document.getElementById("title").textContent.includes(x), text);
|
||||
|
||||
test("the commit dialog sends the ticked files as one __git action, with its reply sentence", async (t) => {
|
||||
test("the next step's Commit sends the files ticked in the table as one __git action, with its reply sentence", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: changesProject({ branch: "feature/x" }), payload: READY });
|
||||
const { page } = s;
|
||||
await page.getByRole("tablist").waitFor();
|
||||
await stepButton(page, "Commit 2 files").click();
|
||||
const panel = page.locator(".git-panel");
|
||||
await panel.getByRole("button", { name: "Close" }).waitFor();
|
||||
await stepButton(page, "Commit 2 files").waitFor();
|
||||
await tickBox(page, "notes.md").uncheck();
|
||||
await panel.getByRole("button", { name: "Commit 1 file" }).click();
|
||||
// The table is already on show below, so the step's button commits rather than opening it.
|
||||
await stepButton(page, "Commit 1 file").click();
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, "the agent collected the click");
|
||||
assert.deepEqual(got.actions, [{ i: "__git", type: "git", op: "commit", files: ["src/app.js"], ignore: [] }]);
|
||||
@@ -261,7 +260,7 @@ test("a commit with no branch to land on carries the ticked files into the new b
|
||||
await tickBox(page, "notes.md").uncheck();
|
||||
// The step is on the Branches tab, and its Commit button finds no branch to commit on.
|
||||
await tabButton(page, "Branches").click();
|
||||
await stepButton(page, "Commit 2 files").click();
|
||||
await stepButton(page, "Commit 1 file").click();
|
||||
const panel = page.locator(".git-panel");
|
||||
await panel.getByRole("heading", { name: "New branch for this commit" }).waitFor();
|
||||
const create = panel.getByRole("button", { name: "Create", exact: true });
|
||||
|
||||
@@ -5,7 +5,11 @@
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { pageSuite, openSession, tempProject, textOf } from "./page-test-helpers.mjs";
|
||||
import { MODELS_DIR } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
@@ -46,6 +50,7 @@ test("the setup lists each phase on its own line, in the agreed order of fields
|
||||
|
||||
const labels = await s.page.locator(".loop-label").allInnerTexts();
|
||||
assert.deepEqual(labels, [
|
||||
"Strength per phase",
|
||||
"Review",
|
||||
"Fix findings",
|
||||
"When a phase asks something",
|
||||
@@ -256,6 +261,27 @@ test("the finish card counts each kind of decision per phase and opens on the fu
|
||||
assert.deepEqual(seen.actions, ["Finalize", "Back to the dashboard"], "the way home is offered next to Finalize");
|
||||
});
|
||||
|
||||
test("a stopped loop offers Ask a question, which tells the app and wakes no loop", async (t) => {
|
||||
const s = await openSetup(t);
|
||||
await frameInFakeApp(s);
|
||||
const seen = await s.page.evaluate(async () => {
|
||||
const m = await import(new URL("screens/ending.js", document.baseURI).href);
|
||||
const card = m.renderLoopEnd({
|
||||
kind: "stopped",
|
||||
line: "Phase 5 stopped",
|
||||
phases: [{ n: 5, name: "Docs", commit: null, unfixed: 0, retries: 0 }],
|
||||
uncommitted: [],
|
||||
can: ["ask", "resume", "fix", "dashboard"],
|
||||
});
|
||||
const buttons = [...card.querySelectorAll(".loop-end-actions button")];
|
||||
const ask = buttons.find((b) => b.textContent === "Ask a question");
|
||||
if (ask) ask.click();
|
||||
return { labels: buttons.map((b) => b.textContent), told: window.__told.map((x) => x.plan2code) };
|
||||
});
|
||||
assert.deepEqual(seen.labels, ["Ask a question", "Resume the loop", "Fix it by hand", "Back to the dashboard"]);
|
||||
assert.deepEqual(seen.told, ["loop-ask"]);
|
||||
});
|
||||
|
||||
// A real loop session: `open --loop` under the app's signal stamps the lock.
|
||||
async function openLoopPage(t) {
|
||||
return openSession(await suite.browser(), {
|
||||
@@ -329,3 +355,172 @@ test("a loop phase still starting says the loop is starting it, and promises no
|
||||
await s.page.getByRole("heading", { name: "The loop is starting this phase" }).waitFor();
|
||||
assert.doesNotMatch(await textOf(s.page.locator("#main")), /pause for approvals/);
|
||||
});
|
||||
|
||||
/* ------------------------------------------- Strength per phase (the section) */
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const LAUNCH = { agent: "claude", agentLabel: "Claude Code", model: "opus", effort: "medium", permissionMode: "bypass", promptSupport: true, running: false };
|
||||
|
||||
// The installed copy of the shipped model menu, with its strengths, as install.js drops it.
|
||||
function installShippedModels() {
|
||||
const shipped = path.join(MODELS_DIR, "bin", "models.json");
|
||||
fs.mkdirSync(path.dirname(shipped), { recursive: true });
|
||||
fs.copyFileSync(path.join(ROOT, "src", "launcher", "models.json"), shipped);
|
||||
}
|
||||
|
||||
// The setup screen with the app's answer in: this launch choice, then the strengths read for it.
|
||||
async function openStrengthSetup(t, launch = LAUNCH) {
|
||||
installShippedModels();
|
||||
const s = await openSetup(t);
|
||||
await s.page.evaluate(async (facts) => {
|
||||
const { page, redraw } = await import(new URL("state.js", document.baseURI).href);
|
||||
page.loopFacts = facts;
|
||||
redraw();
|
||||
}, launch);
|
||||
return s;
|
||||
}
|
||||
|
||||
const strengthRows = (s) =>
|
||||
s.page.locator(".loop-strength-row").evaluateAll((rows) =>
|
||||
rows.map((r) => ({ phase: r.querySelector(".loop-strength-phase").textContent, pick: r.querySelector("select").value, model: r.querySelector(".loop-strength-model").textContent }))
|
||||
);
|
||||
|
||||
test("the strength section is first in the form and off by default", async (t) => {
|
||||
const s = await openStrengthSetup(t);
|
||||
const toggle = s.page.locator("#loop-phase-strength");
|
||||
await toggle.waitFor();
|
||||
assert.equal(await toggle.isChecked(), false);
|
||||
assert.equal(await s.page.locator(".loop-label").first().innerText(), "Strength per phase");
|
||||
assert.equal(await s.page.locator(".loop-strength-row").count(), 0, "no rows until the toggle is on");
|
||||
assert.equal(await s.page.locator("#loop-strength-all").count(), 0);
|
||||
});
|
||||
|
||||
test("turning it on shows one row per phase left with the model each pick becomes, and Set all to fills them", async (t) => {
|
||||
const s = await openStrengthSetup(t);
|
||||
await s.page.locator("#loop-phase-strength").check();
|
||||
await s.page.locator(".loop-strength-row").first().waitFor();
|
||||
assert.deepEqual(await strengthRows(s), [
|
||||
{ phase: "Phase 1: One", pick: "", model: "opus, medium" },
|
||||
{ phase: "Phase 2: Two", pick: "", model: "opus, medium" },
|
||||
], "untouched rows match the session and show the launch choice");
|
||||
|
||||
await s.page.locator("#loop-strength-1").selectOption("thrifty");
|
||||
assert.equal(await textOf(s.page.locator('[data-phase="1"] .loop-strength-model')), "sonnet, low");
|
||||
|
||||
assert.equal(await s.page.locator("#loop-strength-all").inputValue(), "-", "Set all to starts blank");
|
||||
await s.page.locator("#loop-strength-all").selectOption("best");
|
||||
assert.deepEqual((await strengthRows(s)).map((r) => [r.pick, r.model]), [["best", "opus, medium"], ["best", "opus, medium"]]);
|
||||
assert.equal(await s.page.locator("#loop-strength-all").inputValue(), "-", "and goes blank again: it is not a saved value");
|
||||
|
||||
await s.page.locator("#loop-strength-2").selectOption("balanced");
|
||||
assert.deepEqual((await strengthRows(s)).map((r) => [r.pick, r.model]), [["best", "opus, medium"], ["balanced", "sonnet, medium"]], "a row can change after Set all");
|
||||
|
||||
await s.page.locator("#loop-strength-all").selectOption("match");
|
||||
assert.deepEqual((await strengthRows(s)).map((r) => r.pick), ["", ""], "Match my session fills every row too");
|
||||
});
|
||||
|
||||
test("an agent with nothing mapped grays the section and links to Agents & models", async (t) => {
|
||||
const s = await openStrengthSetup(t, { ...LAUNCH, agent: "codex", agentLabel: "Codex" });
|
||||
const note = s.page.locator(".loop-strength-none");
|
||||
await note.waitFor();
|
||||
assert.match(await textOf(note), /This agent has no strengths mapped yet\./);
|
||||
assert.equal(await s.page.locator("#loop-phase-strength").isDisabled(), true);
|
||||
assert.equal(await s.page.locator(".loop-strength-row").count(), 0);
|
||||
await note.getByRole("button").click();
|
||||
await s.page.locator("#prefs-tab-agents[aria-selected='true']").waitFor();
|
||||
});
|
||||
|
||||
test("a saved pick that is not mapped holds Start with a line naming the row, and a change releases it", async (t) => {
|
||||
const s = await openStrengthSetup(t);
|
||||
await s.page.locator("#loop-phase-strength").check();
|
||||
await s.page.locator(".loop-strength-row").first().waitFor();
|
||||
// Thrifty is no longer mapped for this agent (an override went away); Phase 2 still holds it.
|
||||
await s.page.evaluate(async () => {
|
||||
const { page, redraw } = await import(new URL("state.js", document.baseURI).href);
|
||||
page.loopSetup.facts.resolved = { best: { model: "opus", effort: "medium" } };
|
||||
page.loopSetup.form.strengths["specs/ready"] = [{ n: 2, name: "Two", strength: "thrifty" }];
|
||||
redraw();
|
||||
});
|
||||
const why = s.page.locator(".loop-why");
|
||||
assert.equal(await textOf(why), "Pick a new strength for Phase 2: not mapped for this agent.");
|
||||
assert.equal(await s.page.locator("#loop-start").isDisabled(), true);
|
||||
const pick = s.page.locator("#loop-strength-2");
|
||||
assert.equal(await pick.inputValue(), "thrifty", "the saved word stays in the row");
|
||||
assert.equal(await pick.locator("option:checked").innerText(), "Thrifty (not mapped)");
|
||||
assert.equal(await pick.locator("option:checked").evaluate((o) => o.disabled), true);
|
||||
|
||||
await pick.selectOption("best");
|
||||
assert.equal(await s.page.locator(".loop-why").count(), 0, "the hold is gone");
|
||||
assert.equal(await s.page.locator("#loop-start").isDisabled(), false);
|
||||
});
|
||||
|
||||
test("startBlock names every unmapped row, ignores the picks while the toggle is off, and waits for the strengths", async (t) => {
|
||||
const s = await openSetup(t);
|
||||
const lines = await s.page.evaluate(async () => {
|
||||
const { startBlock } = await import(new URL("screens/loop-setup.js", document.baseURI).href);
|
||||
const phasesLeft = [{ n: 2, name: "A" }, { n: 3, name: "B" }, { n: 4, name: "C" }];
|
||||
const strengths = { "specs/x": [{ n: 2, name: "A", strength: "thrifty" }, { n: 3, name: "B", strength: "best" }, { n: 4, name: "C", strength: "thrifty" }] };
|
||||
const facts = (resolved) => ({ spec: "specs/x", phasesLeft, pending: 0, resolved });
|
||||
const form = (phaseStrength) => ({ commit: false, phaseStrength, strengths });
|
||||
const app = { permissionMode: "bypass", promptSupport: true };
|
||||
return {
|
||||
two: startBlock(form(true), facts({ best: { model: "m" } }), app),
|
||||
off: startBlock(form(false), facts({ best: { model: "m" } }), app),
|
||||
allMapped: startBlock(form(true), facts({ thrifty: { model: "s" }, best: { model: "m" } }), app),
|
||||
nothingMapped: startBlock(form(true), facts({}), app),
|
||||
loading: startBlock(form(true), facts(undefined), app),
|
||||
last: startBlock(form(true), { ...facts({ best: { model: "m" } }), phasesLeft: [] }, app),
|
||||
};
|
||||
});
|
||||
assert.equal(lines.two, "Pick a new strength for Phase 2, Phase 4: not mapped for this agent.");
|
||||
assert.equal(lines.off, "");
|
||||
assert.equal(lines.allMapped, "");
|
||||
assert.equal(lines.nothingMapped, "", "an agent with nothing mapped grays the section instead");
|
||||
assert.equal(lines.loading, "Asking the app...");
|
||||
assert.equal(lines.last, "Nothing left to build in this spec.", "the older checks keep their order");
|
||||
});
|
||||
|
||||
test("the toggle and the picks survive reopening the screen, and the toggle off sends nothing for the loop", async (t) => {
|
||||
const s = await openStrengthSetup(t);
|
||||
await s.page.locator("#loop-phase-strength").check();
|
||||
await s.page.locator("#loop-strength-1").selectOption("thrifty");
|
||||
await s.page.locator("#loop-strength-2").selectOption("best");
|
||||
|
||||
const save = () =>
|
||||
s.page.evaluate(async () => {
|
||||
const { page } = await import(new URL("state.js", document.baseURI).href);
|
||||
const { setupBody } = await import(new URL("screens/loop-setup.js", document.baseURI).href);
|
||||
const res = await fetch("/loop-setup", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(setupBody(page.loopSetup.form, page.loopSetup)) });
|
||||
return { status: res.status, body: await res.json() };
|
||||
});
|
||||
const saved = await save();
|
||||
assert.equal(saved.status, 200, JSON.stringify(saved.body));
|
||||
assert.equal(saved.body.setup.phaseStrength, true);
|
||||
assert.deepEqual(saved.body.setup.strengths, { "specs/ready": [{ n: 1, name: "One", strength: "thrifty" }, { n: 2, name: "Two", strength: "best" }] });
|
||||
|
||||
const reopen = async () => {
|
||||
await s.page.evaluate(async () => {
|
||||
const m = await import(new URL("screens/loop-setup.js", document.baseURI).href);
|
||||
const { page, redraw } = await import(new URL("state.js", document.baseURI).href);
|
||||
await m.openLoopSetup({ dir: "specs/ready" });
|
||||
redraw();
|
||||
});
|
||||
await s.page.locator("#loop-start").waitFor();
|
||||
};
|
||||
await reopen();
|
||||
await s.page.locator("#loop-strength-1").waitFor();
|
||||
assert.equal(await s.page.locator("#loop-phase-strength").isChecked(), true);
|
||||
assert.deepEqual((await strengthRows(s)).map((r) => [r.pick, r.model]), [["thrifty", "sonnet, low"], ["best", "opus, medium"]]);
|
||||
|
||||
// Off: the picks stay saved, the loop is told nothing.
|
||||
await s.page.locator("#loop-phase-strength").uncheck();
|
||||
const off = await save();
|
||||
assert.equal(off.body.setup.phaseStrength, false);
|
||||
assert.equal(off.body.setup.strengths["specs/ready"].length, 2, "the toggle hides the picks, it does not erase them");
|
||||
|
||||
// Back to Match my session for every row removes the key.
|
||||
await s.page.locator("#loop-phase-strength").check();
|
||||
await s.page.locator("#loop-strength-all").selectOption("match");
|
||||
const cleared = await save();
|
||||
assert.deepEqual(cleared.body.setup.strengths, {});
|
||||
});
|
||||
@@ -162,6 +162,199 @@ test("Agents & models: the table lists Claude, Devin and Codex, and a model id t
|
||||
assert.equal(await formField(s, "Model id").inputValue(), "gpt-test-codex-2");
|
||||
});
|
||||
|
||||
// The "Strengths in the loop" fold: Thrifty, Balanced and Best mapped to the
|
||||
// agent's own models. models.json under PLAN2CODE_MODELS_DIR is what Save writes.
|
||||
const MODELS_FILE = path.join(MODELS_DIR, "models.json");
|
||||
const strengthsFold = (s) => agentForm(s).locator("details.prefs-agents-strengths");
|
||||
const strengthRow = (s, word) => strengthsFold(s).locator(`.strength-row[data-word="${word}"]`);
|
||||
const savedStrengths = () => {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(MODELS_FILE, "utf8")).strengths ?? null;
|
||||
} catch {
|
||||
return null; // not written yet
|
||||
}
|
||||
};
|
||||
|
||||
// The shipped list the tests start with has no models at all; the fold needs some
|
||||
// (and Claude and Devin's shipped strengths), so a test writes them and puts the file back.
|
||||
const SHIPPED_FILE = path.join(MODELS_DIR, "bin", "models.json");
|
||||
function seedShippedModels(t) {
|
||||
fs.mkdirSync(path.dirname(SHIPPED_FILE), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
SHIPPED_FILE,
|
||||
JSON.stringify({
|
||||
claude: [{ id: "sonnet", label: "Sonnet" }, { id: "opus", label: "Opus" }],
|
||||
devin: [{ id: "swe-2-medium", label: "SWE 2 Medium" }, { id: "swe-2-high", label: "SWE 2 High" }, { id: "claude-opus-5-5-medium", label: "Opus 5.5 Medium" }],
|
||||
codex: [],
|
||||
strengths: {
|
||||
claude: { thrifty: { model: "sonnet", effort: "low" }, balanced: { model: "sonnet", effort: "medium" }, best: { model: "opus", effort: "medium" } },
|
||||
devin: { thrifty: { model: "swe-2-medium" }, balanced: { model: "swe-2-high" }, best: { model: "claude-opus-5-5-medium" } },
|
||||
},
|
||||
})
|
||||
);
|
||||
t.after(() => fs.rmSync(SHIPPED_FILE, { force: true }));
|
||||
}
|
||||
|
||||
// Save lands asynchronously and an earlier Saved mark may still be on screen, so wait on the file.
|
||||
async function savedStrengthsAre(expected) {
|
||||
for (let i = 0; i < 100; i++) {
|
||||
if (JSON.stringify(savedStrengths()) === JSON.stringify(expected)) return;
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
}
|
||||
assert.deepEqual(savedStrengths(), expected);
|
||||
}
|
||||
|
||||
async function openStrengths(s, name) {
|
||||
await s.page.getByRole("button", { name: `Edit ${name}` }).click();
|
||||
await formPane(s).waitFor();
|
||||
await strengthsFold(s).locator("summary").click();
|
||||
}
|
||||
|
||||
test("Agents & models: Claude's fold shows the shipped rows as default, and only a changed row is saved, until Reset", async (t) => {
|
||||
noSavedLooks(t);
|
||||
seedAgents(t);
|
||||
t.after(() => fs.rmSync(MODELS_FILE, { force: true }));
|
||||
seedShippedModels(t);
|
||||
fs.rmSync(MODELS_FILE, { force: true });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openAgentsTab(s);
|
||||
await openStrengths(s, "Claude");
|
||||
assert.equal(await strengthRow(s, "thrifty").locator('select[data-field="model"]').inputValue(), "sonnet");
|
||||
assert.equal(await strengthRow(s, "thrifty").locator('select[data-field="effort"]').inputValue(), "low");
|
||||
assert.equal(await strengthRow(s, "best").locator('select[data-field="model"]').inputValue(), "opus");
|
||||
assert.equal(await strengthsFold(s).locator(".strength-default").count(), 3, "all three rows are untouched defaults");
|
||||
assert.equal(await textOf(strengthRow(s, "balanced").locator(".strength-default")), "default");
|
||||
assert.equal(await strengthsFold(s).locator(".strength-reset").count(), 0, "nothing to reset yet");
|
||||
assert.equal(await textOf(strengthsFold(s).locator(".strength-offer")), "The loop will offer: Thrifty, Balanced, Best");
|
||||
|
||||
await strengthRow(s, "thrifty").locator('select[data-field="model"]').selectOption("opus");
|
||||
await agentForm(s).locator(".prefs-unsaved-badge").waitFor();
|
||||
assert.equal(await strengthRow(s, "thrifty").locator(".strength-reset").count(), 1, "a changed row has Reset");
|
||||
assert.equal(await strengthRow(s, "thrifty").locator(".strength-default").count(), 0);
|
||||
assert.equal(await strengthRow(s, "balanced").locator(".strength-reset").count(), 0, "the other rows stay default");
|
||||
assert.equal(fs.existsSync(MODELS_FILE), false, "nothing is saved before Save");
|
||||
|
||||
await formButton(s, "Save").click();
|
||||
await agentForm(s).locator(".prefs-saved").filter({ hasText: /^Saved. Restart plan2code/ }).waitFor();
|
||||
assert.deepEqual(savedStrengths(), { claude: { thrifty: { model: "opus", effort: "low" } } }, "only the changed row is written");
|
||||
|
||||
await strengthRow(s, "thrifty").locator(".strength-reset").click();
|
||||
assert.equal(await strengthRow(s, "thrifty").locator('select[data-field="model"]').inputValue(), "sonnet", "Reset restores the shipped row");
|
||||
assert.equal(await textOf(strengthRow(s, "thrifty").locator(".strength-default")), "default");
|
||||
await agentForm(s).locator(".prefs-unsaved-badge").waitFor();
|
||||
await formButton(s, "Save").click();
|
||||
await savedStrengthsAre(null); // with every row back at its default, no strengths are stored
|
||||
});
|
||||
|
||||
test("Agents & models: Codex has an effort select on each row and Devin does not", async (t) => {
|
||||
noSavedLooks(t);
|
||||
seedAgents(t);
|
||||
t.after(() => fs.rmSync(MODELS_FILE, { force: true }));
|
||||
seedShippedModels(t);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openAgentsTab(s);
|
||||
await openStrengths(s, "Codex");
|
||||
assert.equal(await textOf(strengthsFold(s).locator(".strength-empty")), "Add a model under Models first", "no models ship for Codex");
|
||||
await formButton(s, "Add a model").click();
|
||||
await formField(s, "Model id").fill("gpt-test-codex-1");
|
||||
assert.equal(await strengthsFold(s).locator('select[data-field="effort"]').count(), 3);
|
||||
assert.equal(await strengthRow(s, "thrifty").locator('select[data-field="model"]').inputValue(), "", "nothing ships for Codex, so the row is not mapped");
|
||||
assert.equal(await textOf(strengthsFold(s).locator(".strength-offer")), "The loop will not offer a strength for this agent until one is mapped.");
|
||||
await formButton(s, "Discard").click(); // the added model is unsaved: leaving would ask first
|
||||
await s.page.getByRole("button", { name: "Edit Devin" }).click();
|
||||
await strengthsFold(s).locator("summary").click();
|
||||
assert.equal(await strengthsFold(s).locator('select[data-field="model"]').count(), 3);
|
||||
assert.equal(await strengthsFold(s).locator('select[data-field="effort"]').count(), 0, "Devin takes no separate effort");
|
||||
});
|
||||
|
||||
test("Agents & models: a strength-only edit is unsaved until Save, Discard puts the shipped rows back, and Reset keeps focus on its row", async (t) => {
|
||||
noSavedLooks(t);
|
||||
seedAgents(t);
|
||||
t.after(() => fs.rmSync(MODELS_FILE, { force: true }));
|
||||
seedShippedModels(t);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openAgentsTab(s);
|
||||
await openStrengths(s, "Claude");
|
||||
assert.equal(await agentForm(s).locator(".prefs-unsaved-badge").isVisible(), false);
|
||||
await strengthRow(s, "best").locator('select[data-field="model"]').selectOption("sonnet");
|
||||
await agentForm(s).locator(".prefs-unsaved-badge").waitFor();
|
||||
await formButton(s, "Discard").click();
|
||||
assert.equal(await agentForm(s).locator(".prefs-unsaved-badge").isVisible(), false, "Discard clears the strength-only change");
|
||||
assert.equal(await strengthRow(s, "best").locator('select[data-field="model"]').inputValue(), "opus", "the shipped row is back");
|
||||
assert.equal(fs.existsSync(MODELS_FILE), false, "nothing was written");
|
||||
|
||||
await strengthRow(s, "best").locator('select[data-field="model"]').selectOption("sonnet");
|
||||
await strengthRow(s, "best").locator(".strength-reset").focus();
|
||||
await strengthRow(s, "best").locator(".strength-reset").click();
|
||||
assert.equal(
|
||||
await s.page.evaluate(() => document.activeElement?.closest("[data-word]")?.dataset.word),
|
||||
"best",
|
||||
"focus stays in the row the Reset was in"
|
||||
);
|
||||
});
|
||||
|
||||
test("Agents & models: a saved row whose model was removed reads not mapped while other models remain, and Save drops it", async (t) => {
|
||||
noSavedLooks(t);
|
||||
seedAgents(t);
|
||||
t.after(() => fs.rmSync(MODELS_FILE, { force: true }));
|
||||
seedShippedModels(t);
|
||||
fs.rmSync(MODELS_FILE, { force: true });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openAgentsTab(s);
|
||||
await s.page.click("#agents-add");
|
||||
await formPane(s).waitFor();
|
||||
await formField(s, "Name").fill("Gemini");
|
||||
await formField(s, "Command").fill("node");
|
||||
await agentForm(s).locator("details.agent-fold > summary", { hasText: /^Models$/ }).click();
|
||||
await formButton(s, "Add a model").click();
|
||||
await formField(s, "Model id").fill("model-a");
|
||||
await formButton(s, "Add a model").click();
|
||||
await formField(s, "Model id").nth(1).fill("model-b");
|
||||
await strengthsFold(s).locator("summary").click();
|
||||
await strengthRow(s, "thrifty").locator('select[data-field="model"]').selectOption("model-a");
|
||||
await strengthRow(s, "best").locator('select[data-field="model"]').selectOption("model-b");
|
||||
await formButton(s, "Save").click();
|
||||
await savedStrengthsAre({ gemini: { thrifty: { model: "model-a" }, best: { model: "model-b" } } });
|
||||
|
||||
await agentForm(s).locator(".agent-row.model").first().getByRole("button", { name: "Remove" }).click();
|
||||
assert.equal(await strengthRow(s, "thrifty").locator('select[data-field="model"]').inputValue(), "", "the removed model reads not mapped");
|
||||
assert.equal(await textOf(strengthsFold(s).locator(".strength-offer")), "The loop will offer: Best");
|
||||
await formButton(s, "Save").click();
|
||||
await savedStrengthsAre({ gemini: { best: { model: "model-b" } } });
|
||||
});
|
||||
|
||||
test("Agents & models: an added agent maps strengths only from its own Models, and a removed model reads not mapped", async (t) => {
|
||||
noSavedLooks(t);
|
||||
seedAgents(t);
|
||||
t.after(() => fs.rmSync(MODELS_FILE, { force: true }));
|
||||
seedShippedModels(t);
|
||||
fs.rmSync(MODELS_FILE, { force: true });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openAgentsTab(s);
|
||||
await s.page.click("#agents-add");
|
||||
await formPane(s).waitFor();
|
||||
await formField(s, "Name").fill("Copilot");
|
||||
await formField(s, "Command").fill("node");
|
||||
await strengthsFold(s).locator("summary").click();
|
||||
assert.equal(await textOf(strengthsFold(s).locator(".strength-empty")), "Add a model under Models first");
|
||||
assert.equal(await strengthsFold(s).locator("select").count(), 0, "no selects without a model");
|
||||
|
||||
await agentForm(s).locator("details.agent-fold > summary", { hasText: /^Models$/ }).click();
|
||||
await formButton(s, "Add a model").click();
|
||||
await formField(s, "Model id").fill("gpt-test-1");
|
||||
assert.equal(await strengthsFold(s).locator(".strength-empty").count(), 0, "the fold follows the Models list as it changes");
|
||||
await strengthRow(s, "thrifty").locator('select[data-field="model"]').selectOption("gpt-test-1");
|
||||
assert.equal(await strengthRow(s, "thrifty").locator('select[data-field="effort"]').count(), 0, "an added agent has no effort select");
|
||||
await formButton(s, "Save").click();
|
||||
await agentForm(s).locator(".prefs-saved").waitFor();
|
||||
assert.deepEqual(savedStrengths(), { copilot: { thrifty: { model: "gpt-test-1" } } }, "saved under the new agent's id");
|
||||
|
||||
await agentForm(s).locator(".agent-row.model").first().getByRole("button", { name: "Remove" }).click();
|
||||
assert.equal(await textOf(strengthsFold(s).locator(".strength-empty")), "Add a model under Models first");
|
||||
await formButton(s, "Save").click();
|
||||
await savedStrengthsAre(null);
|
||||
});
|
||||
|
||||
test("Agents & models: a person adds an agent, tests its command, sees it after a reload, and deletes it", async (t) => {
|
||||
noSavedLooks(t);
|
||||
seedAgents(t);
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
// Web console tests, the Send button: public/send-state.js decides whether
|
||||
// Send is available and what its button says, from the shared page state. It
|
||||
// only defines, so it imports here under plain Node and each case sets `page`
|
||||
// directly.
|
||||
// Run with: node --test scripts/test-web-console-send-state.mjs
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { page, fresh } from "../src/web-console/public/state.js";
|
||||
import { WORKING_GRACE_MS } from "../src/web-console/public/selectors.js";
|
||||
import { sendState, suggestState } from "../src/web-console/public/send-state.js";
|
||||
|
||||
const MIN = 60 * 1000;
|
||||
const ago = (ms) => new Date(Date.now() - ms).toISOString();
|
||||
const question = (id = "q1", extra = {}) => ({ id, kind: "choice", title: "Export format", status: "open", required: true, ...extra });
|
||||
|
||||
// A waiting agent seen just now, one open question, nothing staged.
|
||||
function setup({ agent = { status: "waiting" }, items = [question()], ...S } = {}) {
|
||||
page.S = { workflow: "test", agent, items, ...S };
|
||||
page.local = fresh();
|
||||
page.gone = false;
|
||||
page.pendingResult = false;
|
||||
page.agentLastSeen = ago(0);
|
||||
page.chatFrame = null;
|
||||
}
|
||||
|
||||
const working = (sinceMs, extra = {}) => ({ status: "working", since: ago(sinceMs), ...extra });
|
||||
|
||||
test("send state: a finished session is closed, and says paused when its headline does", () => {
|
||||
setup({ finish: { headline: "Phase 3 is done" } });
|
||||
page.local.staged.q1 = { k: "A" };
|
||||
assert.deepEqual(sendState(), { disabled: true, why: "This session is finished.", short: "Session finished" });
|
||||
setup({ finish: { headline: "Paused at Step 2" } });
|
||||
assert.deepEqual(sendState(), { disabled: true, why: "This session is paused.", short: "Session paused" });
|
||||
});
|
||||
|
||||
test("send state: a finish wins over a dropped connection", () => {
|
||||
setup({ finish: { headline: "Done" } });
|
||||
page.gone = true;
|
||||
assert.equal(sendState().short, "Session finished");
|
||||
});
|
||||
|
||||
test("send state: offline reads Not connected, whatever is staged", () => {
|
||||
setup();
|
||||
page.local.staged.q1 = { k: "A" };
|
||||
page.gone = true;
|
||||
assert.deepEqual(sendState(), { disabled: true, why: "Not connected right now.", short: "Not connected" });
|
||||
});
|
||||
|
||||
test("send state: the loop driving locks Send until a question it does not handle waits", () => {
|
||||
setup({ loop: { driving: true }, items: [question("q1", { handledBy: "loop" })] });
|
||||
page.local.staged.q1 = { k: "A" };
|
||||
assert.deepEqual(sendState(), { disabled: true, why: "The loop is building. Cards unlock when it needs you.", short: "The loop is building" });
|
||||
|
||||
setup({ loop: { driving: true }, items: [question("q2")] });
|
||||
page.local.staged.q2 = { k: "A" };
|
||||
assert.deepEqual(sendState(), { disabled: false, why: "" }, "a question for the person unlocks it");
|
||||
|
||||
setup({ loop: { driving: true }, loopEnd: { at: ago(0) }, items: [question("q1", { handledBy: "loop" })] });
|
||||
page.local.staged.q1 = { k: "A" };
|
||||
assert.deepEqual(sendState(), { disabled: false, why: "" }, "a posted loopEnd lets go of the page");
|
||||
});
|
||||
|
||||
test("send state: a send still being collected stays disabled, and says so once nobody comes for it", () => {
|
||||
setup();
|
||||
page.local.staged.q1 = { k: "A" };
|
||||
page.pendingResult = true;
|
||||
assert.deepEqual(sendState(), { disabled: true, why: "Your last answers are on their way. One moment.", short: "" });
|
||||
|
||||
page.agentLastSeen = ago(2 * MIN);
|
||||
assert.deepEqual(sendState(), {
|
||||
disabled: true,
|
||||
why: "Saved, and waiting for Plan2Code to come back for them.",
|
||||
short: "Saved, not picked up",
|
||||
});
|
||||
});
|
||||
|
||||
test("send state: while the agent works, an answer or a note to an open question can still go", () => {
|
||||
setup({ agent: working(MIN) });
|
||||
page.local.staged.q1 = { k: "A" };
|
||||
const open = { disabled: false, why: "Plan2Code is still working. Your answers wait for it to look.", short: "Still working · it reads this next" };
|
||||
assert.deepEqual(sendState(), open);
|
||||
|
||||
setup({ agent: working(MIN) });
|
||||
page.local.drafts["thread-q1"] = "Prefer CSV for Excel.";
|
||||
assert.deepEqual(sendState(), open, "a typed note counts as much as a staged answer");
|
||||
});
|
||||
|
||||
test("send state: a question already sent is not the person's turn while the agent works", () => {
|
||||
setup({ agent: working(MIN) });
|
||||
page.local.staged.q1 = { k: "A" };
|
||||
page.local.sent.q1 = true;
|
||||
assert.deepEqual(sendState(), { disabled: true, why: "Wait for Plan2Code to finish.", short: "" });
|
||||
});
|
||||
|
||||
test("send state: past the working grace, something staged can be pushed through", () => {
|
||||
setup({ agent: working(WORKING_GRACE_MS + MIN), items: [] });
|
||||
page.local.staged.q1 = { k: "A" };
|
||||
assert.deepEqual(sendState(), { disabled: false, why: "Plan2Code has been busy a while. You can send anyway.", short: "Busy · send anyway" });
|
||||
});
|
||||
|
||||
test("send state: past the working grace with nothing staged, open questions say a note unlocks Send", () => {
|
||||
setup({ agent: working(WORKING_GRACE_MS + MIN), items: [question("q1", { submitted: { at: ago(MIN) } })] });
|
||||
assert.deepEqual(sendState(), {
|
||||
disabled: true,
|
||||
why: "Plan2Code has been busy a while. Answer something or add a note, and you can send anyway.",
|
||||
short: "Busy · a note unlocks Send",
|
||||
});
|
||||
|
||||
setup({ agent: working(WORKING_GRACE_MS + MIN), items: [] });
|
||||
assert.deepEqual(sendState(), { disabled: true, why: "Plan2Code has been busy a while.", short: "Busy a while" });
|
||||
});
|
||||
|
||||
test("send state: quietMinutes stretches the working grace", () => {
|
||||
setup({ agent: working(10 * MIN, { quietMinutes: 30 }), items: [] });
|
||||
page.local.staged.q1 = { k: "A" };
|
||||
assert.deepEqual(sendState(), { disabled: true, why: "Wait for Plan2Code to finish.", short: "" });
|
||||
|
||||
setup({ agent: working(31 * MIN, { quietMinutes: 30 }), items: [] });
|
||||
page.local.staged.q1 = { k: "A" };
|
||||
assert.equal(sendState().short, "Busy · send anyway", "past the stretched grace the hatch opens");
|
||||
});
|
||||
|
||||
test("send state: inside the working grace Send waits, and reads Gone quiet once the agent is adrift", () => {
|
||||
setup({ agent: working(MIN), items: [] });
|
||||
assert.deepEqual(sendState(), { disabled: true, why: "Wait for Plan2Code to finish.", short: "" });
|
||||
|
||||
setup({ agent: working(4 * MIN), items: [] });
|
||||
page.agentLastSeen = ago(4 * MIN);
|
||||
assert.deepEqual(sendState(), { disabled: true, why: "Wait for Plan2Code to finish.", short: "Gone quiet" });
|
||||
});
|
||||
|
||||
test("send state: an idle page enables Send only once something is staged or typed", () => {
|
||||
setup();
|
||||
assert.deepEqual(sendState(), { disabled: true, why: "" });
|
||||
|
||||
page.local.staged.q1 = { k: "A" };
|
||||
assert.deepEqual(sendState(), { disabled: false, why: "" });
|
||||
|
||||
setup();
|
||||
page.local.drafts["thread-q1"] = " ";
|
||||
assert.deepEqual(sendState(), { disabled: true, why: "" }, "a blank note is nothing to send");
|
||||
});
|
||||
|
||||
test("send state: a note waits while its picture uploads, and goes once it is ready", () => {
|
||||
setup();
|
||||
page.local.drafts["thread-q1"] = "See the screenshot.";
|
||||
page.local.images.q1 = [{ key: "a", status: "uploading" }];
|
||||
assert.deepEqual(sendState(), { disabled: true, why: "" }, "a held note is not sent");
|
||||
|
||||
page.local.images.q1 = [{ key: "a", status: "ready", url: "/uploads/a.jpg" }];
|
||||
assert.deepEqual(sendState(), { disabled: false, why: "" });
|
||||
});
|
||||
|
||||
test("send state: told there is something to send, an idle page enables it with nothing staged", () => {
|
||||
setup();
|
||||
assert.deepEqual(sendState(), { disabled: true, why: "" }, "left out, it reads what is staged");
|
||||
assert.deepEqual(sendState(true), { disabled: false, why: "" });
|
||||
assert.deepEqual(sendState(false), { disabled: true, why: "" });
|
||||
});
|
||||
|
||||
test("suggest state: the chip follows Send, and waits while its own request does", () => {
|
||||
const ready = { disabled: false, why: "Ask Plan2Code what it would pick here, and why." };
|
||||
setup();
|
||||
assert.deepEqual(suggestState(question()), ready, "nothing staged is needed: the request is the payload");
|
||||
|
||||
setup({ finish: { headline: "Phase 3 is done" } });
|
||||
assert.deepEqual(suggestState(question()), { disabled: true, why: "This session is finished." });
|
||||
|
||||
setup();
|
||||
page.pendingResult = true;
|
||||
assert.deepEqual(suggestState(question()), { disabled: true, why: "Your last answers are on their way. One moment." });
|
||||
|
||||
const at = ago(MIN);
|
||||
const asked = question("q1", { sentNote: { at, text: "", suggest: true }, thread: [{ who: "user", at, text: "", suggest: true }] });
|
||||
setup({ items: [asked] });
|
||||
assert.deepEqual(suggestState(asked), { disabled: true, why: "Plan2Code has your request for suggestions on this one." });
|
||||
|
||||
const plain = question("q1", { sentNote: { at, text: "Hm" }, thread: [{ who: "user", at, text: "Hm" }] });
|
||||
setup({ items: [plain] });
|
||||
assert.deepEqual(suggestState(plain), ready, "a plain note waiting does not hold the chip");
|
||||
|
||||
const replied = { ...asked, thread: [...asked.thread, { who: "agent", at: ago(0), text: "I would pick CSV." }] };
|
||||
setup({ items: [replied] });
|
||||
assert.deepEqual(suggestState(replied), ready, "the agent's reply frees it");
|
||||
});
|
||||
@@ -1281,6 +1281,30 @@ test("a send records its note and attachments on the item, so the page can show
|
||||
assert.equal(cli(["wait", "--session", sid, "--seconds", "10"]).status, 0);
|
||||
});
|
||||
|
||||
test("a request for suggestions is recorded with its flag and threaded even with no note; a non-boolean flag is dropped", async () => {
|
||||
const readState = () => JSON.parse(fs.readFileSync(path.join(HOME, "sessions", sid, "state.json"), "utf8"));
|
||||
const userCount = () => readState().items.find((i) => i.id === "q1").thread.filter((m) => m.who === "user").length;
|
||||
|
||||
let before = userCount();
|
||||
const ok = await post("/submit", { actions: [{ i: "q1", type: "comment", text: "", suggest: true }], reply: "Suggestions wanted on q1: (no note)" });
|
||||
assert.equal(ok.status, 200);
|
||||
let q1 = readState().items.find((i) => i.id === "q1");
|
||||
assert.equal(q1.sentNote.suggest, true);
|
||||
const mine = q1.thread.filter((m) => m.who === "user").at(-1);
|
||||
assert.equal(userCount(), before + 1, "an empty request still goes into the thread");
|
||||
assert.equal(mine.who, "user");
|
||||
assert.equal(mine.suggest, true);
|
||||
assert.equal(mine.at, q1.sentNote.at);
|
||||
assert.equal(cli(["wait", "--session", sid, "--seconds", "10"]).status, 0);
|
||||
|
||||
before = userCount();
|
||||
assert.equal((await post("/submit", { actions: [{ i: "q1", type: "comment", text: "", suggest: "yes" }], reply: "z" })).status, 200);
|
||||
q1 = readState().items.find((i) => i.id === "q1");
|
||||
assert.equal("suggest" in q1.sentNote, false, "only true is kept");
|
||||
assert.equal(userCount(), before, "a plain empty comment still adds no thread entry");
|
||||
assert.equal(cli(["wait", "--session", sid, "--seconds", "10"]).status, 0);
|
||||
});
|
||||
|
||||
test("what the person attached is not scanned for markers either", () => {
|
||||
const statePath = path.join(HOME, "sessions", sid, "state.json");
|
||||
const state = JSON.parse(fs.readFileSync(statePath, "utf8"));
|
||||
|
||||
@@ -399,7 +399,7 @@ test("Implement's card launches Implement + Review when Review is ticked", () =>
|
||||
assert.equal(launchVariant(quick, true), quick, "a card with no Review box is unchanged");
|
||||
});
|
||||
|
||||
test("helper-strength.md ships in the thirteen skills that start helpers, and in no other", () => {
|
||||
test("helper-strength.md ships in the fifteen skills that start helpers, and in no other", () => {
|
||||
// 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") {
|
||||
execFileSync(process.execPath, [path.join(ROOT, "install.js"), "--build-skills"], { stdio: "ignore" });
|
||||
@@ -417,8 +417,10 @@ test("helper-strength.md ships in the thirteen skills that start helpers, and in
|
||||
"plan2code-diagnose",
|
||||
"plan2code-init",
|
||||
"plan2code-init-update",
|
||||
"plan2code-pr-prep",
|
||||
"plan2code-quick-task",
|
||||
"plan2code-review",
|
||||
"plan2code-test",
|
||||
"plan2code-xray",
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -536,3 +536,12 @@ test("prefs: Help and the readme name every tab and section, and the dialog's un
|
||||
assert.ok(!new RegExp(`class="[^"]*\\b${cls}\\b[^"]*"`).test(html), `index.html has no .${cls} left`);
|
||||
}
|
||||
});
|
||||
|
||||
test("Diagnose's opening cards: only What is wrong is required", () => {
|
||||
const notes = fs.readFileSync(path.join(ROOT, "src", "web-console", "notes", "diagnose.md"), "utf8");
|
||||
const batch = JSON.parse(notes.match(/```jsonc\n(.*)\n```/)[1]);
|
||||
const required = Object.fromEntries(batch.items.map((item) => [item.id, item.required !== false]));
|
||||
assert.deepEqual(required, { bug: true, expected: false, "see-it": false });
|
||||
const prompt = fs.readFileSync(path.join(ROOT, "src", "plan2code-diagnose.md"), "utf8");
|
||||
assert.match(prompt, /the last two `"required":false`/, "the prompt says the last two cards are optional");
|
||||
});
|
||||
@@ -275,6 +275,30 @@ const CARDS = {
|
||||
built: { on: true },
|
||||
unrecognized: { on: true },
|
||||
},
|
||||
"plan2code-pr-prep": {
|
||||
"none": { on: true },
|
||||
diagnosed: { on: true },
|
||||
fixed: { on: true },
|
||||
exploring: { on: true },
|
||||
mapped: { on: true },
|
||||
planned: { on: true },
|
||||
documented: { on: true },
|
||||
building: { on: true },
|
||||
built: { on: true },
|
||||
unrecognized: { on: true },
|
||||
},
|
||||
"plan2code-test": {
|
||||
"none": { on: true },
|
||||
diagnosed: { on: true },
|
||||
fixed: { on: true },
|
||||
exploring: { on: true },
|
||||
mapped: { on: true },
|
||||
planned: { on: true },
|
||||
documented: { on: true },
|
||||
building: { on: true },
|
||||
built: { on: true },
|
||||
unrecognized: { on: true },
|
||||
},
|
||||
"plan2code-changelog": {
|
||||
"none": { on: true },
|
||||
diagnosed: { on: true },
|
||||
@@ -418,6 +442,27 @@ test("the scan: every state it can return is in the table, and a fixture reaches
|
||||
assert.deepEqual(scanProblems(FIXTURES, known), ["the scan returns unrecognized, which spec-states.js lacks"]);
|
||||
});
|
||||
|
||||
test("the scan: a PR-READINESS report changes no spec's state, and alone it stays unrecognized", () => {
|
||||
const scanOf = (fixtures) => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-spec-readiness-"));
|
||||
try {
|
||||
for (const [name, files] of Object.entries(fixtures))
|
||||
for (const [rel, text] of Object.entries(files)) {
|
||||
const file = path.join(root, "specs", name, rel);
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
fs.writeFileSync(file, text);
|
||||
}
|
||||
return Object.fromEntries(scanProject(root).specs.map((sp) => [sp.name, [sp.state, sp.detail]]));
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
};
|
||||
const REPORT = { "PR-READINESS-20261103.md": "# PR readiness\n\n**Verdict:** Ready\n\n- [x] Unit tests\n- [ ] Lint (trimmed)\n" };
|
||||
const withReport = Object.fromEntries(Object.entries(FIXTURES).map(([name, files]) => [name, { ...files, ...REPORT }]));
|
||||
assert.deepEqual(scanOf(withReport), scanOf(FIXTURES));
|
||||
assert.equal(scanOf({ only: REPORT }).only[0], "unrecognized");
|
||||
});
|
||||
|
||||
test("the scan: an assumed task counts as done and is named, and numbered task lines count", () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-spec-assumed-"));
|
||||
const specs = {
|
||||
|
||||
@@ -481,7 +481,7 @@ test("every console workflow has its notes, and its skill's Interface reads them
|
||||
init: "init", "init-update": "init", pathfinder: "pathfinder", plan: "plan", "revise-plan": "revise-plan",
|
||||
document: "document", implement: "implement", "implement-review": "implement", "quick-task": "quick-task",
|
||||
review: "review", finalize: "finalize", handoff: "handoff", changelog: "changelog", git: "git", xray: "xray",
|
||||
diagnose: "diagnose",
|
||||
diagnose: "diagnose", "pr-prep": "pr-prep", test: "test",
|
||||
};
|
||||
const skills = fs.readdirSync(path.join(ROOT, "src")).filter((f) => /^plan2code(-.*)?\.md$/.test(f));
|
||||
for (const f of skills) {
|
||||
@@ -750,7 +750,7 @@ test("long task lines, long words, a narrow board and a narrow Ask pane never wi
|
||||
|
||||
test("over the git board a note box grows with its text, and the no-repo note only points above when a card is there", () => {
|
||||
const css = joinedCss();
|
||||
assert.match(css, /\.git-cards > \.card textarea \{ field-sizing: content; max-height: 50vh; \}/);
|
||||
assert.match(css, /\.git-cards > \.card \.md-host \{ min-height: 0; max-height: 50vh; \}/);
|
||||
const view = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "git-board-view.js"), "utf8");
|
||||
const fn = view.slice(view.indexOf("export function drawGitBoard("), view.indexOf("function header("));
|
||||
assert.ok(fn.includes("ctx.hasCard"), "the note checks for a card first");
|
||||
|
||||
@@ -46,6 +46,7 @@ test("state: the rest of the shared state starts as app.js always started it", (
|
||||
meterFrame: null,
|
||||
updateFrame: null,
|
||||
inApp: false,
|
||||
terminalCollapsed: false,
|
||||
loop: null,
|
||||
loopSetup: null,
|
||||
loopFacts: null,
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
// Tests for src/web-console/strengths.mjs against the shared cases in
|
||||
// scripts/fixtures/strength-cases.json (the Rust twin in models.rs loads the
|
||||
// same file). Run with: node --test scripts/test-web-console-strengths.mjs
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { STRENGTH_ORDER, nextStrength, resolveStrengths } from "../src/web-console/strengths.mjs";
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const FIXTURE = JSON.parse(fs.readFileSync(path.join(ROOT, "scripts", "fixtures", "strength-cases.json"), "utf8"));
|
||||
|
||||
test("the fixture is schema 1 and covers every kind of case", () => {
|
||||
assert.equal(FIXTURE.schema, 1);
|
||||
assert.ok(FIXTURE.cases.length >= 10);
|
||||
const names = FIXTURE.cases.map((c) => c.name);
|
||||
assert.equal(new Set(names).size, names.length, "case names are unique");
|
||||
});
|
||||
|
||||
for (const c of FIXTURE.cases) {
|
||||
test(`resolveStrengths: ${c.name}`, () => {
|
||||
const resolved = resolveStrengths({ shipped: c.shipped, user: c.user, models: c.models, hasEffort: c.hasEffort });
|
||||
assert.deepEqual(resolved, c.expect.resolved);
|
||||
});
|
||||
|
||||
test(`nextStrength: ${c.name}`, () => {
|
||||
for (const word of STRENGTH_ORDER) {
|
||||
assert.equal(nextStrength(c.expect.resolved, word), c.expect.next[word], `next after ${word}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test("nextStrength: an unknown word or a missing mapping has no next", () => {
|
||||
assert.equal(nextStrength({ best: { model: "x" } }, "cheap"), null);
|
||||
assert.equal(nextStrength(null, "thrifty"), null);
|
||||
assert.equal(nextStrength(undefined, "balanced"), null);
|
||||
});
|
||||
|
||||
test("resolveStrengths: called with nothing at all resolves nothing", () => {
|
||||
assert.deepEqual(resolveStrengths(), {});
|
||||
assert.deepEqual(resolveStrengths({}), {});
|
||||
});
|
||||
@@ -9,10 +9,15 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { defaultInstruction, offered, onLines, STRENGTH_LINES, STRENGTHS } from "../src/web-console/public/subagents.js";
|
||||
import { readSubagentCursor } from "../src/web-console/settings.mjs";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { readSubagentCursor, readSubagentSetting } from "../src/web-console/settings.mjs";
|
||||
import { foldKey } from "../src/web-console/workspace.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
HOME,
|
||||
ENV,
|
||||
CONSOLE_CLI,
|
||||
safeJson,
|
||||
cli,
|
||||
sessionUrl,
|
||||
readState,
|
||||
@@ -510,3 +515,63 @@ test("subagents: a change arrives as reply lines only, carrying state, strength
|
||||
cli(["stop", "--session", s.sid, "--force"]);
|
||||
}
|
||||
});
|
||||
|
||||
/* ------------------------------------- a loop phase's helpers follow its strength */
|
||||
|
||||
const loopOpen = (cwd, env, workflow = "implement", extraArgs = ["--loop"]) => {
|
||||
const clean = { ...process.env, ...ENV };
|
||||
for (const key of ["PLAN2CODE_IN_APP", "PLAN2CODE_EMBED_ORIGIN", "PLAN2CODE_APP_ANNOUNCE", "PLAN2CODE_APP_TOKEN", "PLAN2CODE_CONSOLE_SID", "PLAN2CODE_LOOP_STRENGTH"]) delete clean[key];
|
||||
const res = spawnSync(process.execPath, [CONSOLE_CLI, "open", "--workflow", workflow, ...extraArgs, "--no-open"], { env: { ...clean, ...env }, encoding: "utf8", cwd });
|
||||
assert.equal(res.status, 0, res.stderr);
|
||||
return safeJson(res.stdout);
|
||||
};
|
||||
|
||||
test("subagents: open --loop on a phase strength tells the agent that strength, leaves the stored setting alone and off stays off", () => {
|
||||
const cwd = fs.mkdtempSync(path.join(HOME, "sub-loop-"));
|
||||
const stored = (entry) => fs.writeFileSync(SUBAGENTS_STORE, JSON.stringify({ [foldKey(cwd)]: { implement: entry } }));
|
||||
const sessions = [];
|
||||
try {
|
||||
stored({ on: true, instruction: null, max: 3, strength: "balanced" });
|
||||
const before = fs.readFileSync(SUBAGENTS_STORE, "utf8");
|
||||
const thrifty = loopOpen(cwd, { PLAN2CODE_IN_APP: "1", PLAN2CODE_LOOP_STRENGTH: "thrifty" });
|
||||
sessions.push(thrifty.sid);
|
||||
assert.deepEqual(subagentLines(thrifty.reply), ["Subagents: on, thrifty strength, at most 3 helpers at once (a console setting, not typed by the person)."]);
|
||||
assert.deepEqual(readState(thrifty.session).loop, { driving: true, strength: "thrifty" });
|
||||
assert.equal(fs.readFileSync(SUBAGENTS_STORE, "utf8"), before, "the stored setting is not rewritten");
|
||||
|
||||
// The next phase in the same session runs on another strength, then none.
|
||||
const best = loopOpen(cwd, { PLAN2CODE_IN_APP: "1", PLAN2CODE_LOOP_STRENGTH: "best" }, "implement", ["--resume", thrifty.sid, "--loop"]);
|
||||
assert.deepEqual(subagentLines(best.reply).map((l) => l.replace(/ \(a console.*/, "")), ["Subagents: on, best strength, at most 3 helpers at once"]);
|
||||
assert.equal(fs.readFileSync(SUBAGENTS_STORE, "utf8"), before);
|
||||
|
||||
// A phase with no strength after a strength phase hears the stored one.
|
||||
const none = loopOpen(cwd, { PLAN2CODE_IN_APP: "1" }, "implement", ["--resume", thrifty.sid, "--loop"]);
|
||||
assert.deepEqual(subagentLines(none.reply).map((l) => l.replace(/ \(a console.*/, "")), ["Subagents: on, balanced strength, at most 3 helpers at once"]);
|
||||
assert.deepEqual(readState(thrifty.session).loop, { driving: true });
|
||||
|
||||
// Off stays off, whatever the phase's strength.
|
||||
stored({ on: false, instruction: null, max: 3, strength: "balanced" });
|
||||
const off = loopOpen(cwd, { PLAN2CODE_IN_APP: "1", PLAN2CODE_LOOP_STRENGTH: "thrifty" }, "implement", ["--resume", thrifty.sid, "--loop"]);
|
||||
assert.ok(!subagentLines(off.reply).some((l) => /on,/.test(l)), JSON.stringify(off.reply));
|
||||
assert.equal(readSubagentSetting(thrifty.session).on, false);
|
||||
} finally {
|
||||
for (const sid of sessions) cli(["stop", "--session", sid, "--force"], { expectFail: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("subagents: open without --loop ignores PLAN2CODE_LOOP_STRENGTH, and a word that is not a strength is dropped", () => {
|
||||
const cwd = fs.mkdtempSync(path.join(HOME, "sub-noloop-"));
|
||||
fs.writeFileSync(SUBAGENTS_STORE, JSON.stringify({ [foldKey(cwd)]: { implement: { on: true, instruction: null, max: 3, strength: "balanced" } } }));
|
||||
const sessions = [];
|
||||
try {
|
||||
const plain = loopOpen(cwd, { PLAN2CODE_LOOP_STRENGTH: "thrifty" }, "implement", []);
|
||||
sessions.push(plain.sid);
|
||||
assert.deepEqual(subagentLines(plain.reply).map((l) => l.replace(/ \(a console.*/, "")), ["Subagents: on, balanced strength, at most 3 helpers at once"]);
|
||||
assert.equal("loop" in readState(plain.session), false);
|
||||
const odd = loopOpen(cwd, { PLAN2CODE_IN_APP: "1", PLAN2CODE_LOOP_STRENGTH: "session" });
|
||||
sessions.push(odd.sid);
|
||||
assert.deepEqual(readState(odd.session).loop, { driving: true });
|
||||
} finally {
|
||||
for (const sid of sessions) cli(["stop", "--session", sid, "--force"], { expectFail: true });
|
||||
}
|
||||
});
|
||||
@@ -8,11 +8,16 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { HUM_TABLES, TONE_TABLES, hum, humNames, hushTones, tone, toneNames } from "../src/web-console/public/tones.js";
|
||||
import { HUM_TABLES, LOUDER_MAX, TONE_TABLES, hum, humNames, hushTones, tone, toneNames } from "../src/web-console/public/tones.js";
|
||||
import { looks } from "../src/web-console/public/looks.js";
|
||||
import { compileTrack, hushMusic, music, musicNames, noteFreq } from "../src/web-console/public/music.js";
|
||||
import { MUSIC_TABLES } from "../src/web-console/public/tones.js";
|
||||
import { SONG_PEAK, compileTrack, hushMusic, music, musicNames, noteFreq, songNames } from "../src/web-console/public/music.js";
|
||||
import { MUSIC_TABLES, SONG_TABLES } from "../src/web-console/public/tones.js";
|
||||
import { SERVABLE } from "../src/web-console/static.mjs";
|
||||
import { REGIONS, ROAD_MUSIC } from "../src/web-console/public/activities/drive.js";
|
||||
import { MUSIC_TRACKS } from "../src/web-console/public/activities/snake.js";
|
||||
import snakeSfx from "../src/web-console/public/activities/snake-sfx.js";
|
||||
import { MUSIC_TRACKS as TRAILS_TRACKS } from "../src/web-console/public/activities/trails.js";
|
||||
import trailsSfx from "../src/web-console/public/activities/trails-sfx.js";
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const GAMES = path.join(ROOT, "src/web-console/public/activities");
|
||||
@@ -164,6 +169,35 @@ test("a hum starts once, follows each call without starting more, and goes quiet
|
||||
}
|
||||
});
|
||||
|
||||
test("a game's `louder` lifts a tone and a hum past their usual loudness, never past LOUDER_MAX", () => {
|
||||
const saved = { sound: looks.sound, ctor: globalThis.AudioContext };
|
||||
const { Ctx, made } = AUDIO;
|
||||
globalThis.AudioContext = Ctx;
|
||||
try {
|
||||
looks.sound = true;
|
||||
hushTones();
|
||||
const tonePeak = (louder) => {
|
||||
const mark = made.gains.length;
|
||||
tone("coin", 1, 1, louder);
|
||||
return Math.max(...made.gains.slice(mark).flatMap((g) => g.gain.ramps.map((r) => r.v)));
|
||||
};
|
||||
const base = tonePeak(undefined);
|
||||
assert.ok(Math.abs(tonePeak(1.4) - base * 1.4) < 1e-9, "a tone 1.4 times as loud");
|
||||
assert.ok(Math.abs(tonePeak(9) - base * LOUDER_MAX) < 1e-9, "capped at LOUDER_MAX");
|
||||
const humLevel = (id, louder) => {
|
||||
const mark = made.gains.length;
|
||||
hum(id, "wind", 1, 1, louder);
|
||||
return made.gains.slice(mark).flatMap((g) => g.gain.ramps).filter((r) => r.kind === "target").at(-1).v;
|
||||
};
|
||||
const plain = humLevel("plain", undefined);
|
||||
assert.ok(Math.abs(humLevel("lifted", 1.4) - plain * 1.4) < 1e-9, "a hum 1.4 times as loud");
|
||||
} finally {
|
||||
hushTones();
|
||||
looks.sound = saved.sound;
|
||||
globalThis.AudioContext = saved.ctor;
|
||||
}
|
||||
});
|
||||
|
||||
test("every tone or hum a game's source names is one the engine has", () => {
|
||||
const tones = new Set(toneNames());
|
||||
const hums = new Set(humNames());
|
||||
@@ -213,6 +247,16 @@ test("music: a track that does not read is turned away", () => {
|
||||
assert.equal(arp.patterns.A.lines.a[0].len, 3, "held for three steps");
|
||||
});
|
||||
|
||||
test("music: a track in another meter sets its bar, and a pattern that is not whole bars is turned away", () => {
|
||||
const steps = (n) => Array(n).fill(".").join(" ");
|
||||
const ok = { bpm: 120, bar: 12, voices: { a: { wave: "pulse" } }, patterns: { A: { a: steps(24) } }, order: ["A"] };
|
||||
assert.equal(compileTrack(ok).length, 24, "two bars of 6/8");
|
||||
assert.throws(() => compileTrack({ ...ok, patterns: { A: { a: steps(16) } } }), /whole bars/);
|
||||
assert.throws(() => compileTrack({ ...ok, bar: 2 }), /bar/);
|
||||
assert.throws(() => compileTrack({ ...ok, bar: 100 }), /bar/);
|
||||
assert.equal(compileTrack({ ...ok, bar: undefined, patterns: { A: { a: steps(16) } } }).length, 16, "no bar: sixteen steps, as before");
|
||||
});
|
||||
|
||||
test("music: a track plays notes while asked for, quiets when hushed, and stays silent while Play sounds is off", () => {
|
||||
const saved = { sound: looks.sound, ctor: globalThis.AudioContext };
|
||||
const { Ctx, made } = AUDIO;
|
||||
@@ -335,6 +379,119 @@ test("music: the volume scales the track's level, a change glides there, and a v
|
||||
}
|
||||
});
|
||||
|
||||
test("music: Snake lists exactly the tracks it has, each a real track that no other game defines", () => {
|
||||
const tracks = new Set(musicNames());
|
||||
assert.deepEqual([...MUSIC_TRACKS].sort(), Object.keys(snakeSfx.music).sort(), "the game lists the tracks its sound file has");
|
||||
for (const name of MUSIC_TRACKS) {
|
||||
assert.ok(tracks.has(name), `track "${name}" exists`);
|
||||
assert.equal(MUSIC_TABLES.filter((t) => Object.hasOwn(t, name)).length, 1, `${name} is defined once`);
|
||||
}
|
||||
});
|
||||
|
||||
test("music: Light Trails lists exactly the songs it has, each an mp3 on disk the server serves, and no chiptune tracks", () => {
|
||||
const songs = new Set(songNames());
|
||||
assert.equal(trailsSfx.music, undefined, "its music is the songs, not note data");
|
||||
assert.deepEqual([...TRAILS_TRACKS].sort(), Object.keys(trailsSfx.songs).sort(), "the game lists the songs its sound file has");
|
||||
for (const name of TRAILS_TRACKS) {
|
||||
assert.ok(songs.has(name), `song "${name}" exists`);
|
||||
assert.equal(SONG_TABLES.filter((t) => Object.hasOwn(t, name)).length, 1, `${name} is defined once`);
|
||||
assert.ok(!musicNames().includes(name), `${name} is not also a chiptune track`);
|
||||
const file = trailsSfx.songs[name];
|
||||
assert.ok(SERVABLE.has(file), `${file} is servable`);
|
||||
assert.ok(fs.statSync(path.join(ROOT, "src/web-console/public", file)).size > 0, `${file} is on disk`);
|
||||
}
|
||||
});
|
||||
|
||||
// A stand-in <audio>: records what music.js asks of it.
|
||||
class FakeAudio {
|
||||
static made = [];
|
||||
constructor(src) {
|
||||
Object.assign(this, { src, volume: 1, paused: true, ended: false, currentTime: 0, plays: 0, loads: 0 });
|
||||
FakeAudio.made.push(this);
|
||||
}
|
||||
play() {
|
||||
this.paused = false;
|
||||
this.plays += 1;
|
||||
return Promise.resolve();
|
||||
}
|
||||
pause() {
|
||||
this.paused = true;
|
||||
}
|
||||
load() {
|
||||
Object.assign(this, { paused: true, ended: false, currentTime: 0, loads: this.loads + 1 });
|
||||
}
|
||||
}
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
async function withSongs(fn) {
|
||||
const saved = { sound: looks.sound, Audio: globalThis.Audio };
|
||||
globalThis.Audio = FakeAudio;
|
||||
looks.sound = true;
|
||||
hushMusic();
|
||||
try {
|
||||
await fn();
|
||||
} finally {
|
||||
hushMusic();
|
||||
looks.sound = saved.sound;
|
||||
globalThis.Audio = saved.Audio;
|
||||
}
|
||||
}
|
||||
|
||||
test("music: a song plays from its file, fades in toward its level, says when it has ended, and starts from the top again when asked", () =>
|
||||
withSongs(async () => {
|
||||
const [name] = TRAILS_TRACKS;
|
||||
assert.equal(music(name, 1, 1, { restart: true }), "playing");
|
||||
const el = FakeAudio.made.find((a) => a.src === `/${trailsSfx.songs[name]}`);
|
||||
assert.ok(el, "an element for the song's file");
|
||||
assert.ok(!el.paused && el.plays === 1, "it plays");
|
||||
for (let i = 0; i < 20; i++) {
|
||||
music(name, 1, 1);
|
||||
await sleep(30);
|
||||
}
|
||||
assert.ok(Math.abs(el.volume - SONG_PEAK) < 1e-9, "glided up to its level");
|
||||
assert.equal(el.plays, 1, "asked for again, it is not started again");
|
||||
el.currentTime = 100;
|
||||
el.ended = true;
|
||||
el.paused = true;
|
||||
assert.equal(music(name, 1, 1), "ended", "a song played through says so");
|
||||
assert.equal(el.plays, 1, "and is not looped");
|
||||
assert.equal(music(name, 1, 1, { restart: true }), "playing", "a restart plays it again");
|
||||
assert.equal(el.loads, 1, "from the top");
|
||||
assert.equal(el.currentTime, 0);
|
||||
}));
|
||||
|
||||
test("music: a song no longer asked for fades out and pauses where it was, and another song replaces it at once", () =>
|
||||
withSongs(async () => {
|
||||
const [first, second] = TRAILS_TRACKS;
|
||||
music(first, 1, 0.5);
|
||||
const el = FakeAudio.made.findLast((a) => a.src === `/${trailsSfx.songs[first]}`);
|
||||
const loads = el.loads;
|
||||
await sleep(800);
|
||||
assert.ok(el.paused, "paused once it stops being asked for");
|
||||
assert.equal(el.volume, 0, "faded to silence");
|
||||
assert.equal(el.loads, loads, "kept where it was, so it picks up again mid-song");
|
||||
music(first, 1, 0.5);
|
||||
assert.ok(!el.paused, "asked for again, it plays on");
|
||||
music(second, 1, 0.5);
|
||||
assert.ok(el.paused, "another song stops it");
|
||||
assert.ok(!FakeAudio.made.at(-1).paused, "and plays");
|
||||
hushMusic();
|
||||
assert.ok(FakeAudio.made.every((a) => a.paused), "a hush pauses every song");
|
||||
}));
|
||||
|
||||
test("music: a song plays nothing while Play sounds is off, at a volume of 0, or with no audio", () =>
|
||||
withSongs(async () => {
|
||||
const [name] = TRAILS_TRACKS;
|
||||
looks.sound = false;
|
||||
assert.equal(music(name, 1, 1), undefined);
|
||||
looks.sound = true;
|
||||
assert.equal(music(name, 1, 0), undefined);
|
||||
globalThis.Audio = undefined;
|
||||
assert.equal(music(name, 1, 1), undefined);
|
||||
assert.ok(FakeAudio.made.filter((a) => a.src === `/${trailsSfx.songs[name]}`).every((a) => a.paused), "nothing plays");
|
||||
}));
|
||||
|
||||
test("music: every Sunset Drive road has a song, and every song is a real track", () => {
|
||||
const tracks = new Set(musicNames());
|
||||
assert.deepEqual(Object.keys(ROAD_MUSIC).sort(), Object.keys(REGIONS).sort(), "a song for every road");
|
||||
|
||||
@@ -104,8 +104,9 @@
|
||||
"kind": "template",
|
||||
"command": "opencode",
|
||||
"prompt": "Use the plan2code skill",
|
||||
"args": ["--prompt", "{prompt}"],
|
||||
"bypassArgs": ["--auto"]
|
||||
"args": ["{model}", "--prompt", "{prompt}"],
|
||||
"bypassArgs": ["--auto"],
|
||||
"modelArgs": ["--model", "{model}"]
|
||||
},
|
||||
{
|
||||
"id": "gemini",
|
||||
@@ -113,8 +114,9 @@
|
||||
"kind": "template",
|
||||
"command": "gemini",
|
||||
"prompt": "Use the plan2code skill",
|
||||
"args": ["{prompt}"],
|
||||
"args": ["{model}", "{prompt}"],
|
||||
"bypassArgs": ["--approval-mode=yolo"],
|
||||
"modelArgs": ["--model", "{model}"],
|
||||
"note": "For unpaid tier and Google One accounts Gemini CLI was replaced by Antigravity CLI on June 18, 2026; whether gemini still runs depends on the account."
|
||||
},
|
||||
{
|
||||
@@ -123,7 +125,8 @@
|
||||
"kind": "template",
|
||||
"command": "pi",
|
||||
"prompt": "/skill:plan2code",
|
||||
"args": ["{prompt}"]
|
||||
"args": ["{model}", "{prompt}"],
|
||||
"modelArgs": ["--model", "{model}"]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"_note": "Curated model menu for the plan2code launcher. Maintained by the Plan2Code authors; every install overwrites this file. Users add models in User Preferences (kept in ~/.plan2code/models.json). Devin entries are explicit ids at Low, Medium and High effort only, verified against `devin models list`. Codex has no curated entries yet (its docs name none to verify): the launcher skips the model question for it. Pass --model <name> to choose one.",
|
||||
"_note": "Curated model menu for the plan2code launcher. Maintained by the Plan2Code authors; every install overwrites this file. Users add models in User Preferences (kept in ~/.plan2code/models.json). Devin entries are explicit ids at Low, Medium and High effort only, verified against `devin models list`. Codex entries are the models its docs name as current. The strengths key maps the loop's Thrifty, Balanced and Best to a model (and effort) per agent; users override it in User Preferences. Pass --model <name> to choose any other.",
|
||||
"claude": [
|
||||
{
|
||||
"id": "default",
|
||||
@@ -138,7 +138,63 @@
|
||||
{
|
||||
"id": "gpt-6-astra-high",
|
||||
"label": "GPT-6 Astra High Thinking"
|
||||
},
|
||||
{
|
||||
"id": "gpt-5-6-sol-low",
|
||||
"label": "GPT-5.6 Sol Low Thinking"
|
||||
},
|
||||
{
|
||||
"id": "gpt-5-6-sol-medium",
|
||||
"label": "GPT-5.6 Sol Medium Thinking"
|
||||
},
|
||||
{
|
||||
"id": "gpt-5-6-sol-high",
|
||||
"label": "GPT-5.6 Sol High Thinking"
|
||||
}
|
||||
],
|
||||
"codex": []
|
||||
"codex": [
|
||||
{
|
||||
"id": "gpt-6-astra",
|
||||
"label": "GPT-6 Astra"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6.1-sol",
|
||||
"label": "GPT-6.1 Sol"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6.1-terra",
|
||||
"label": "GPT-6.1 Terra"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6-luna",
|
||||
"label": "GPT-6 Luna"
|
||||
}
|
||||
],
|
||||
"strengths": {
|
||||
"claude": {
|
||||
"thrifty": {
|
||||
"model": "sonnet",
|
||||
"effort": "low"
|
||||
},
|
||||
"balanced": {
|
||||
"model": "sonnet",
|
||||
"effort": "medium"
|
||||
},
|
||||
"best": {
|
||||
"model": "opus",
|
||||
"effort": "medium"
|
||||
}
|
||||
},
|
||||
"devin": {
|
||||
"thrifty": {
|
||||
"model": "swe-2-medium"
|
||||
},
|
||||
"balanced": {
|
||||
"model": "swe-2-high"
|
||||
},
|
||||
"best": {
|
||||
"model": "claude-opus-5-5-medium"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -59,7 +59,7 @@ Keep with you: every question, confidence score, decision and sign-off, Phases 3
|
||||
|
||||
Before Phase 1, run `node "<S>/specs.mjs" list` from the project root (`<S>`: `scripts/` beside this SKILL.md, `~/.agents/skills/plan2code-1-plan/scripts/` globally). It reads gitignored `specs/` (Glob silently finds nothing there) and gives each spec's `planDrafts` with its **Status:** line (`-prev` copies are `archived`; ignore them). Route on that status:
|
||||
- Status "Phase 3 Complete - Resume at Phase 4": Resume at Phase 4
|
||||
- Status "Escalated from Quick Task - Resume at Phase 2": Acknowledge, verify requirements, skip to Phase 2
|
||||
- Status "Escalated from Quick Task - Resume at Phase 2" or "Escalated from Test - Resume at Phase 2": Acknowledge, verify requirements, skip to Phase 2
|
||||
- Status "Draft" or "Complete": Ask user how to proceed
|
||||
- Before going on with any existing draft (a Pathfinder handoff, a Quick Task escalation, a Draft or Complete one), read its 2.4: `| Status | Deferred to Plan |`, empty or `Not discussed` means ask the Phase 1 testing question now and write the answer into 2.4; a cadence with no `Full Suite` row means ask only the full-suite part.
|
||||
- A spec folder holding a `DIAGNOSIS-*.md` (Diagnose's write-up of a bug): read it first, as the Phase 1 brief (the bug, its cause, the suggested fix); that folder's name is the feature name (do not ask for one), so the PLAN-DRAFT lands beside the diagnosis
|
||||
|
||||
@@ -57,7 +57,7 @@ Keep with you: the reproduction, any bisect, the cause judgment and every questi
|
||||
|
||||
### Step 1: The Bug
|
||||
|
||||
A typed argument is the report; ask only for what it leaves out. Otherwise ask in one batch (console: three `text` cards, the first with a placeholder example of a real report, no `"templates"`):
|
||||
A typed argument is the report; ask only for what it leaves out. Otherwise ask in one batch (console: three `text` cards, the first with a placeholder example of a real report, the last two `"required":false`, no `"templates"`):
|
||||
|
||||
> "1. **What is wrong?** The bug, in a sentence or two.
|
||||
> 2. **Expected vs actual:** what should happen, and what happens instead.
|
||||
|
||||
@@ -828,18 +828,14 @@ function classifyError({ file }) {
|
||||
}
|
||||
|
||||
async function prUrlCmd({ root, branch, base }) {
|
||||
const s = repoState(root);
|
||||
const b = (branch || "").trim() || s.branch;
|
||||
if (!b) fail(EXIT.REFUSED, "detached", "HEAD is detached, so there is no branch to open a pull request for.", "Switch to a branch, or pass --branch.");
|
||||
const row = localBranch(s, b);
|
||||
if (!row) fail(EXIT.INVALID, "unknown-branch", `There is no local branch named "${b}".`, "Pick a branch from the list.");
|
||||
const into = (base || "").trim() || s.def.name;
|
||||
if (!into) fail(EXIT.INVALID, "no-base", "There is no default branch to open the pull request against.", "Pass --base <branch>.");
|
||||
// A pull request from a branch into itself is no pull request (a push to main).
|
||||
if (into === b) fail(EXIT.INVALID, "is-base", `${b} is the branch pull requests go into, so there is nothing to open.`, "Post no link for this push.");
|
||||
const remote = row.upstream && !row.gone ? R.readRemotes(root, await prHosts()).find((r) => r.name === row.upstreamRemote) : null;
|
||||
if (!remote) fail(EXIT.INVALID, "not-pushed", `${b} is not on a remote yet.`, "Publish it first (plan publish).");
|
||||
out({ ok: true, url: R.prUrl(remote, { base: into, head: b }), host: remote.host, kind: remote.kind, needsKind: !!remote.host && !remote.kind });
|
||||
let link;
|
||||
try {
|
||||
link = R.prLink(root, { branch, base, prHosts: await prHosts() });
|
||||
} catch (e) {
|
||||
if (!R.PR_LINK_CODES.has(e?.code)) throw e;
|
||||
fail(e.code === "detached" ? EXIT.REFUSED : EXIT.INVALID, e.code, e.message, e.next);
|
||||
}
|
||||
out({ ok: true, url: link.url, host: link.host, kind: link.kind, needsKind: link.needsKind });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ main */
|
||||
|
||||
@@ -103,7 +103,7 @@ In the terminal the same stops are asked in prose, with the diff printed.
|
||||
## Terminal
|
||||
|
||||
- **No instruction:** print the status from `state` (branch, ahead/behind, changed files) and ask what to do, `next` first.
|
||||
- **After an action:** show the new state and one line naming the likely next step, then stop. A follow-up reply runs it; there is no "what next?" loop.
|
||||
- **After an action:** show the new state and one line naming the likely next step, then stop. A follow-up reply runs it; there is no "what next?" loop. After a push or publish (or when the branch is pushed with nothing left to commit), that next step may be `/plan2code-pr-prep`: run the checks and write the PR description.
|
||||
- **Several actions in one instruction** (`commit and push`): state the plan in one line, run each step in order, ask each ask-first confirm at its own step with the same `confirm` text the board shows, and stop at the first failure with git's error and `classify-error`'s `next`.
|
||||
- **An unclear instruction:** offer the two or three likely readings through the question tool, the state-based guess first. Never run on a guess.
|
||||
- Print the pull-request link from `pr-url` after a push or publish (`needsKind` → ask the host's kind once and say it is remembered).
|
||||
|
||||
@@ -24,6 +24,7 @@ The FIRST thing you do, before anything else in this file — before the Awarene
|
||||
- `node "<S>/agents-md.mjs" filename "<Section Name>"`: a new section file's name, link line and header.
|
||||
- `node "<S>/agent-files.mjs" detect` / `apply <id> ...`: Step 7.
|
||||
- `node "<S>/commit-msg.mjs" --subject "<subject>"`: the Session End commit.
|
||||
- `node "<S>/test-map.mjs" read` / `write --rows <file>` and `node "<S>/test-commands.mjs" discover`: the `## Test map` (Testing, Step 4); the rows file goes in the session folder or the OS temp folder, never the project.
|
||||
|
||||
---
|
||||
|
||||
@@ -138,7 +139,7 @@ Present the user with update options:
|
||||
> - **1. Commands** - Build, test, run, lint, how to run and view the app, or other CLI commands
|
||||
> - **2. Architecture** - How components interact, data flow, key patterns
|
||||
> - **3. Gotchas/Pitfalls** - Traps to avoid, non-obvious behaviors
|
||||
> - **4. Testing** - Test patterns, how to run specific tests, the test map and quick checks, fixtures
|
||||
> - **4. Testing** - Test patterns, how to run specific tests, the `## Test map` table and quick checks, fixtures
|
||||
> - **5. Environment/Config** - Setup quirks, env variables, configuration
|
||||
> - **6. General Rules** - Coding conventions, style rules, project-specific practices
|
||||
> - **7. Failure Log** - Record a mistake or correction in the Failure log
|
||||
@@ -160,7 +161,7 @@ Present the user with update options:
|
||||
| Commands | Purpose? Flags? Prerequisites? How to run and view the app? |
|
||||
| Architecture | Components? Interactions? Pattern? |
|
||||
| Gotchas | What was unexpected? Workaround? |
|
||||
| Testing | Commands? Test map and quick checks stale? Fixtures? Mocking? |
|
||||
| Testing | Commands? Test map `Paths` still match real files and `Run` commands still exist (`test-map.mjs read` problems, `test-commands.mjs discover`)? Quick checks stale? Fixtures? Mocking? No map but tests exist: offer to create one, written only on a yes through `test-map.mjs write`. |
|
||||
| Environment | Local/CI/deploy? Env vars/files? |
|
||||
| Rules | Project-wide or specific? Why? |
|
||||
| Failure Log | What went wrong? Correct behavior (imperative, one line)? Merge into an entry on the same topic if one exists; over 17 entries, propose what to prune (rule 7). |
|
||||
|
||||
@@ -26,7 +26,7 @@ The FIRST thing you do, before anything else in this file — before exploring t
|
||||
|
||||
## Content
|
||||
|
||||
1. **Commands**: Build, lint, test, run single test (and beside it a short **Test map**: `area -> tests or command` lines saying which tests cover which areas, plus a note of which checks are quick; omit it when the project has no tests), other common development tasks, and how to start the app and where to view it (URL or command), when it has one
|
||||
1. **Commands**: Build, lint, test, run single test (and beside it a note of which checks are quick), other common development tasks, and how to start the app and where to view it (URL or command), when it has one. Then the **`## Test map`** section: run `node "<S>/test-commands.mjs" discover` and `node "<S>/test-map.mjs" read`. When test commands are found and no map exists, propose a `## Test map` table (`| Area | Paths | Run | Shared |`, one row per area with its own run command, `Shared: yes` for helper, fixture and config areas) for the person to approve, and write it only on a yes with `test-map.mjs write --rows <file>` (the rows file in the session folder or the OS temp folder, never the project). In a progressive `AGENTS.md`, the heading holds one link to `.agents-docs/AGENTS-test-map.md` and the table goes there. Omit the map when the project has no tests.
|
||||
2. **Architecture**: High-level "big picture" structure requiring multi-file context to understand
|
||||
3. **How to Use This File**: A short paragraph explaining that sections below contain brief summaries and agents should follow the markdown links to `.agents-docs/` for full details — only read what's relevant to the current task.
|
||||
4. **Failure Log**: running list of mistakes and/or corrections that went wrong via the AI Agent at least once.
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
#!/usr/bin/env node
|
||||
// pr-prep.mjs: the facts only PR Prep needs.
|
||||
//
|
||||
// Where the repository's pull-request template is and which headings it asks
|
||||
// for, the create-a-pull-request link (through git-repo.mjs, the same code the
|
||||
// git skill uses, so the two never disagree), and which spec folder belongs to
|
||||
// the branch, for the save offer. It only reads: it never commits, pushes or
|
||||
// writes a file.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { EXIT, consoleModule, fail, gitRepo, out, parseArgs, readText, run } from "./common.mjs";
|
||||
|
||||
const USAGE = `
|
||||
pr-prep.mjs: read-only facts for PR Prep. JSON on stdout.
|
||||
|
||||
node pr-prep.mjs template [--root <dir>]
|
||||
The pull-request template, looked for in this order (names compared
|
||||
case-insensitively): .github/pull_request_template.md,
|
||||
.github/PULL_REQUEST_TEMPLATE.md, PULL_REQUEST_TEMPLATE.md,
|
||||
docs/pull_request_template.md, then the first .md in
|
||||
.github/PULL_REQUEST_TEMPLATE/, docs/PULL_REQUEST_TEMPLATE/ and
|
||||
.gitlab/merge_request_templates/.
|
||||
Prints { ok, found, path, headings, hasTesting, others }.
|
||||
headings the template's # to ### headings in order, text only,
|
||||
outside code fences
|
||||
hasTesting a heading is about testing (test, verify, how it was
|
||||
checked, QA)
|
||||
others every further template found, to mention to the person
|
||||
|
||||
node pr-prep.mjs pr-url [--branch <b>] [--base <b>] [--root <dir>]
|
||||
The create-a-pull-request link for --branch (the current branch) into
|
||||
--base (the default branch). Prints { ok, pushed: true, url, host, kind,
|
||||
needsKind, branch, base, ahead }; needsKind: the host is unknown and has
|
||||
no saved answer, so url is null. url is also null for a remote no link
|
||||
can be built for (a path or ssh alias, or a host saved as none). A
|
||||
branch not on a remote yet prints
|
||||
{ ok, pushed: false, branch, next } with exit 0.
|
||||
|
||||
node pr-prep.mjs spec [--branch <b>] [--base <b>] [--root <dir>]
|
||||
The branch's spec folder, for the save offer. Prints { ok, branch,
|
||||
match, candidates, how }.
|
||||
how branch: a folder in specs/ (then specs--completed/) whose name
|
||||
is a whole dash-separated run of the branch name
|
||||
recent: no name matched; the one folder with a file changed
|
||||
since the branch left --base (default main, else master)
|
||||
ask: several folders fit; candidates lists them
|
||||
none: nothing fits; match is null
|
||||
|
||||
Exit: 0 ok · 1 crash · 2 bad arguments · 3 not a git repository (pr-url,
|
||||
spec) or an unreadable template (template) · 4 no such branch, no base,
|
||||
or the branch is the base (pr-url) · 5 detached HEAD (pr-url) or git
|
||||
missing or too old (pr-url, spec).
|
||||
`;
|
||||
|
||||
/* ------------------------------------------------------------- template */
|
||||
|
||||
const TEMPLATE_FILES = [
|
||||
".github/pull_request_template.md",
|
||||
".github/PULL_REQUEST_TEMPLATE.md",
|
||||
"PULL_REQUEST_TEMPLATE.md",
|
||||
"docs/pull_request_template.md",
|
||||
];
|
||||
const TEMPLATE_DIRS = [".github/PULL_REQUEST_TEMPLATE", "docs/PULL_REQUEST_TEMPLATE", ".gitlab/merge_request_templates"];
|
||||
const TESTING = /test|testing|verif|how .*checked|qa/i;
|
||||
|
||||
function entries(dir) {
|
||||
try {
|
||||
return fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** `relPath` under root with every segment matched case-insensitively (an exact match first); the real relative path, or null. */
|
||||
function findCI(root, relPath, want) {
|
||||
let at = "";
|
||||
const parts = relPath.split("/");
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const list = entries(path.join(root, at));
|
||||
const last = i === parts.length - 1;
|
||||
const fits = (e) => (last ? (want === "dir" ? e.isDirectory() : e.isFile()) : e.isDirectory());
|
||||
const hit = list.find((e) => e.name === parts[i] && fits(e)) || list.find((e) => e.name.toLowerCase() === parts[i].toLowerCase() && fits(e));
|
||||
if (!hit) return null;
|
||||
at = at ? `${at}/${hit.name}` : hit.name;
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
function headingsOf(text) {
|
||||
const headings = [];
|
||||
let fence = null;
|
||||
for (const line of text.split(/\r?\n/)) {
|
||||
const f = line.match(/^\s{0,3}(`{3,}|~{3,})/);
|
||||
if (f) {
|
||||
if (!fence) fence = f[1][0];
|
||||
else if (f[1][0] === fence) fence = null;
|
||||
continue;
|
||||
}
|
||||
if (fence) continue;
|
||||
const m = line.match(/^\s{0,3}#{1,3}\s+(.*?)\s*#*\s*$/);
|
||||
if (m && m[1]) headings.push(m[1]);
|
||||
}
|
||||
return headings;
|
||||
}
|
||||
|
||||
function template({ root }) {
|
||||
const found = [];
|
||||
for (const f of TEMPLATE_FILES) {
|
||||
const hit = findCI(root, f, "file");
|
||||
if (hit && !found.includes(hit)) found.push(hit);
|
||||
}
|
||||
for (const d of TEMPLATE_DIRS) {
|
||||
const dir = findCI(root, d, "dir");
|
||||
if (!dir) continue;
|
||||
const mds = entries(path.join(root, dir))
|
||||
.filter((e) => e.isFile() && /\.md$/i.test(e.name))
|
||||
.map((e) => `${dir}/${e.name}`)
|
||||
.sort((a, b) => a.localeCompare(b));
|
||||
for (const m of mds) if (!found.includes(m)) found.push(m);
|
||||
}
|
||||
if (!found.length) return out({ ok: true, found: false, path: null, headings: [], hasTesting: false, others: [] });
|
||||
const text = readText(path.join(root, found[0]));
|
||||
if (text === null) fail(EXIT.NOT_FOUND, "unreadable-template", `Cannot read ${found[0]}.`, "Check the file's permissions, or write the description without the template.");
|
||||
const headings = headingsOf(text);
|
||||
out({ ok: true, found: true, path: found[0], headings, hasTesting: headings.some((h) => TESTING.test(h)), others: found.slice(1) });
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- the repo */
|
||||
|
||||
let R;
|
||||
|
||||
function repoRoot(root) {
|
||||
const floor = R.gitFloor();
|
||||
if (!floor.ok) fail(EXIT.REFUSED, "git-too-old", floor.message, "Install or update git (2.23 or newer), then try again.");
|
||||
const top = R.git(["rev-parse", "--show-toplevel"], root);
|
||||
if (!top.ok || !top.out) fail(EXIT.NOT_FOUND, "not-a-repo", `${root} is not inside a git repository.`, "Run PR Prep from inside the project's git repository.");
|
||||
return path.resolve(top.out);
|
||||
}
|
||||
|
||||
async function prUrlCmd({ root, branch, base }) {
|
||||
const repo = repoRoot(root);
|
||||
let link;
|
||||
try {
|
||||
link = R.prLink(repo, { branch, base, prHosts: (await consoleModule("settings.mjs")).readPrHosts() });
|
||||
} catch (e) {
|
||||
if (!R.PR_LINK_CODES.has(e?.code)) throw e;
|
||||
if (e.code === "not-pushed") {
|
||||
return out({ ok: true, pushed: false, branch: e.branch, next: "Say the branch is not pushed yet, and offer to hand over to the git skill (/plan2code-git), which asks before it pushes." });
|
||||
}
|
||||
fail(e.code === "detached" ? EXIT.REFUSED : EXIT.INVALID, e.code, e.message, e.next);
|
||||
}
|
||||
out({ ok: true, pushed: true, ...link });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------- spec */
|
||||
|
||||
const SPEC_DIRS = ["specs", "specs--completed"];
|
||||
const PREFIX = /^(feature|fix|bugfix|chore|hotfix)\//i;
|
||||
|
||||
/** The branch name as one kebab-case run, with a leading feature/, fix/ ... or <user>/ segment dropped. */
|
||||
function branchKebab(branch) {
|
||||
let b = branch.replace(PREFIX, "");
|
||||
if (b === branch && b.includes("/")) b = b.slice(b.indexOf("/") + 1).replace(PREFIX, "");
|
||||
return b.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
||||
}
|
||||
|
||||
function specFolders(repo) {
|
||||
const all = [];
|
||||
for (const d of SPEC_DIRS) {
|
||||
const names = entries(path.join(repo, d)).filter((e) => e.isDirectory()).map((e) => e.name).sort((a, b) => a.localeCompare(b));
|
||||
for (const name of names) all.push({ dir: d, name, path: `${d}/${name}` });
|
||||
}
|
||||
return all;
|
||||
}
|
||||
|
||||
function newestMtime(dir, depth = 4) {
|
||||
let newest = 0;
|
||||
for (const e of entries(dir)) {
|
||||
const p = path.join(dir, e.name);
|
||||
if (e.isFile()) {
|
||||
try {
|
||||
newest = Math.max(newest, fs.statSync(p).mtimeMs);
|
||||
} catch {}
|
||||
} else if (e.isDirectory() && depth > 1) newest = Math.max(newest, newestMtime(p, depth - 1));
|
||||
}
|
||||
return newest;
|
||||
}
|
||||
|
||||
function pickBase(repo, wanted) {
|
||||
const candidates = wanted ? [wanted, `origin/${wanted}`] : ["main", "origin/main", "master", "origin/master"];
|
||||
return candidates.find((ref) => R.git(["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], repo).ok) || null;
|
||||
}
|
||||
|
||||
/** When `branch` (HEAD when it is not a local branch) left its base, in ms; null when there is no base or no shared commit. */
|
||||
function branchStart(repo, base, branch) {
|
||||
const ref = pickBase(repo, base);
|
||||
if (!ref) return null;
|
||||
const local = branch && `refs/heads/${branch}`;
|
||||
const tip = local && R.git(["rev-parse", "--verify", "--quiet", `${local}^{commit}`], repo).ok ? local : "HEAD";
|
||||
const mb = R.git(["merge-base", tip, ref], repo);
|
||||
if (!mb.ok || !mb.out) return null;
|
||||
const t = R.git(["show", "-s", "--format=%ct", mb.out], repo);
|
||||
return t.ok && /^\d+$/.test(t.out) ? Number(t.out) * 1000 : null;
|
||||
}
|
||||
|
||||
function spec({ root, branch, base }) {
|
||||
const repo = repoRoot(root);
|
||||
let b = (branch || "").trim();
|
||||
if (!b) {
|
||||
const head = R.git(["symbolic-ref", "-q", "--short", "HEAD"], repo);
|
||||
b = head.ok ? head.out : "";
|
||||
}
|
||||
const folders = specFolders(repo);
|
||||
const verdict = (hits, how) =>
|
||||
hits.length === 1 ? { match: hits[0].path, candidates: [], how } : { match: null, candidates: hits.map((h) => h.path), how: "ask" };
|
||||
|
||||
const kebab = b ? branchKebab(b) : "";
|
||||
if (kebab) {
|
||||
const named = folders.filter((f) => `-${kebab}-`.includes(`-${f.name.toLowerCase()}-`));
|
||||
const open = named.filter((f) => f.dir === "specs");
|
||||
const hits = open.length ? open : named;
|
||||
if (hits.length) return out({ ok: true, branch: b || null, ...verdict(hits, "branch") });
|
||||
}
|
||||
|
||||
const since = branchStart(repo, base, b);
|
||||
const recent = since === null ? [] : folders.filter((f) => newestMtime(path.join(repo, f.path)) > since);
|
||||
if (recent.length) return out({ ok: true, branch: b || null, ...verdict(recent, "recent") });
|
||||
out({ ok: true, branch: b || null, match: null, candidates: [], how: "none" });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ main */
|
||||
|
||||
const COMMANDS = { template, "pr-url": prUrlCmd, spec };
|
||||
|
||||
async function main(argv) {
|
||||
const args = parseArgs(argv, { values: ["root", "branch", "base"] });
|
||||
const [cmd, ...extra] = args._;
|
||||
const names = Object.keys(COMMANDS).join(", ");
|
||||
if (!cmd) fail(EXIT.USAGE, "missing-command", `A subcommand is required: ${names}.`, "Run with --help for usage.");
|
||||
if (!Object.hasOwn(COMMANDS, cmd)) fail(EXIT.USAGE, "unknown-command", `Unknown subcommand "${cmd}".`, `Use one of: ${names}.`);
|
||||
if (extra.length) fail(EXIT.USAGE, "stray-argument", `Unexpected argument(s): ${extra.join(" ")}.`, "Run with --help for usage.");
|
||||
args.root = path.resolve(args.root || ".");
|
||||
if (cmd !== "template") R = await gitRepo();
|
||||
return COMMANDS[cmd](args);
|
||||
}
|
||||
|
||||
// Run as a script; imported, do nothing.
|
||||
const isMain = (() => {
|
||||
try {
|
||||
return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
})();
|
||||
if (isMain) run(USAGE, main);
|
||||
@@ -0,0 +1,143 @@
|
||||
# ✅ PR PREP MODE
|
||||
|
||||
Start all PR PREP MODE responses with '✅ [PR PREP]'
|
||||
|
||||
## Role
|
||||
|
||||
Gets a branch ready for review. Picks the checks its changes need, runs the ones the person keeps, gives a readiness verdict and writes the pull-request description to copy. **Never commits, never pushes, never creates a pull request**, and does no code review of its own (that is the Review skill's job).
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file, before reading the branch: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow pr-prep` before reading (<D>: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-pr-prep/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/pr-prep.md. Every question, the check plan, the report and the description go through it. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context.
|
||||
|
||||
## Project Context
|
||||
|
||||
Read `./AGENTS.md` when it exists: its commands, its `## Test map` and anything it says about slow suites. PR Prep still works without one: the scripts find the project's commands from its config files, and nothing here needs Plan2Code's specs.
|
||||
|
||||
## Scripts
|
||||
|
||||
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-pr-prep/scripts/` globally). Run from the project root. Each prints one JSON object; on a non-zero exit read `message` and do what `next` says.
|
||||
|
||||
- `node "<S>/review-scope.mjs" [--base <branch>]`: the branch's changes against main (or master): `files` (each with `status`: a list of one or more of `committed`, `staged`, `unstaged`, `untracked`), `counts`, `mix` (`docs`, `code`, `mixed`), `empty`, `commits`.
|
||||
- `node "<S>/test-map.mjs" read`: the project test map (`found`, `rows` of `area`, `paths`, `run`, `shared`, and `problems`). `write --rows <file.json>` saves one, only on a yes.
|
||||
- `node "<S>/test-commands.mjs" discover`: the project's commands from its config files: `suite` (the whole-suite command or null), `runners` (`cmd`, `cwd`, `covers`), `checks` (`kind` lint, types or build, with `cmd`), `builtin` (the language's own runner, only when there is no suite and no runner).
|
||||
- `node "<S>/test-match.mjs" covers --stdin`: pipe review-scope's JSON in. `matched` (test map rows with their `run` and `files`), `unmatched` (`file`, `tests`, `method`), `sharedHits` (`file`, `why`).
|
||||
- `node "<S>/run-check.mjs" --cmd <c> --cwd <d> --timeout <s> --log <file>`: runs one check and prints `outcome` (`passed`, `failed`, `timeout`, `not-started` with a `reason`), `exit`, `seconds` and `tail`.
|
||||
- `node "<S>/pr-prep.mjs" template`: the repo's pull-request template: `found`, `path`, `headings`, `hasTesting`, `others`.
|
||||
- `node "<S>/pr-prep.mjs" pr-url`: the create-a-PR link: `pushed: true` with `url` (`needsKind: true` means the host is unknown and `url` is null), or `pushed: false` for a branch not on a remote yet.
|
||||
- `node "<S>/pr-prep.mjs" spec`: the branch's spec folder for the save offer: `match`, `candidates`, `how` (`branch`, `recent`, `ask`, `none`).
|
||||
|
||||
## References
|
||||
|
||||
- `references/test-runs.md`: how to pick tests for files no map row covers, and what counts as shared ground.
|
||||
- `references/helper-strength.md`: helper strength and effort.
|
||||
|
||||
## Rules
|
||||
|
||||
- Follow `./AGENTS.md` when it exists.
|
||||
- **Never** run `git commit`, `git push`, `git add` or anything that opens a pull request, and never ask a forge CLI (`gh`, `glab`) to. Read-only git is fine. The person copies the description from the page.
|
||||
- **Nothing runs before the person sends the trimmed plan.** A command found by a script is shown before it runs.
|
||||
- **Never install anything**: no runner, no package, no service.
|
||||
- **Record honestly.** A check that did not run is never reported as passed, and nothing unrun is ever Ready.
|
||||
- No code review and no fixes: a failing check is reported, not repaired.
|
||||
- Plain words: name the check, the file and the command.
|
||||
|
||||
## Helpers
|
||||
|
||||
When your tool can start helpers (subagents) and they are not switched off for this run (on the web console a `Subagents:` block says which, console-subagents.md): helpers may read the files behind leftover changes (Step 3) and draft the Changes by area section (Step 8). Keep the check plan, the runs, the verdict and every question with you. Light strength, low effort, per references/helper-strength.md. No helpers? Do the same work yourself.
|
||||
|
||||
## Process
|
||||
|
||||
### Step 1: Changes
|
||||
|
||||
Run `review-scope.mjs`. `empty: true` → say there is nothing on this branch to prepare, and end. A `no-base` exit → ask which branch is the trunk and rerun with `--base`.
|
||||
|
||||
Files whose `status` includes `staged`, `unstaged` or `untracked` are uncommitted. When there are any, list them up front on one card and ask: **Include them in this run** or **Commit first**. Commit first → say the git skill commits them (`/plan2code-git`, or its dashboard card), then come back to PR Prep; end the run. Remember which was picked: the report says whether uncommitted work was included.
|
||||
|
||||
### Step 2: Commands
|
||||
|
||||
Run `test-map.mjs read`. With a map (`found: true`), its rows are the project's checks; mention any `problems` in one line.
|
||||
|
||||
With no map, run `test-commands.mjs discover`. List every command it found with the folders each covers (`suite`, each of `runners` with its `cwd` and `covers`, each of `checks`), and confirm them on one card before anything runs. A correction from the person replaces what the script found. No suite or runner but a `builtin` → offer it on that card as the test candidate, beside any `checks` (`cmd`, for its `language`), run only on a yes; it runs whatever tests already exist and installs nothing. Nothing found at all → ask how the project runs its tests, or go on with the checks you can see and say so.
|
||||
|
||||
### Step 3: Check plan
|
||||
|
||||
Pipe review-scope's JSON to `test-match.mjs covers --stdin`. With a map, run `discover` once now too, for its `suite` and `checks`. Build the plan:
|
||||
|
||||
1. **Matched rows:** every `matched` row is its own check, running its own `run`, with the files it covers as its reason.
|
||||
2. **Unmatched files:** pick checks for each `unmatched` file following `references/test-runs.md`, using its `tests` and `method` when present; mark these "picked by the agent" so the person knows they were judged. A file with no test anywhere stays a note for Step 6.
|
||||
3. **Shared ground:** any `sharedHits` entry with `why: "row"`, or a `config`, `test-helper` or `fixture` hint you judge to be real shared ground (or a widely imported module you spot), plans the full suite: the `suite` command when `discover` found one, else every map row's `run` as separate checks. Name the file and why it reaches wide.
|
||||
4. **Project checks:** add every `checks` entry from `discover` (lint, types, build) unless review-scope's `mix` is `docs`.
|
||||
5. Every check carries a one-line reason. Drop exact duplicates (the same command in the same folder), keeping both reasons.
|
||||
6. **More than one runner** (several `runners`, or map rows run by different tools): group the plan by runner, and keep the grouping in the report.
|
||||
|
||||
### Step 4: Trim
|
||||
|
||||
Show the whole plan with every check on offer; the person keeps what to run and drops what to skip. On the console that is one card with an "All of them" quick pick, since a card cannot open ticked; in the terminal, the numbered list, run in full unless they name checks to skip. Nothing runs before they send. A dropped check is a trimmed check: a plain note in the verdict, never a failure.
|
||||
|
||||
### Step 5: Run
|
||||
|
||||
Run each kept check, one at a time:
|
||||
|
||||
```
|
||||
node "<S>/run-check.mjs" --cmd "<command>" --cwd <folder> --timeout <seconds> --log <session folder>/checks/<n>.log
|
||||
```
|
||||
|
||||
The timeout is 600 seconds by default, longer when the person or `AGENTS.md` says a suite is slow. On the console the log goes in the `session` folder `open` printed; in the terminal, the OS temp folder. Before each check post one `activity` line ("Check 2 of 5: the launcher tests") with `quietMinutes` sized to its timeout. Record each outcome with its `seconds`, `exit` and `tail`.
|
||||
|
||||
### Step 6: Verdict
|
||||
|
||||
- **Ready:** every planned check ran and passed.
|
||||
- **Ready with notes:** every check that ran passed, but something did not run or is not covered. Each trimmed check is a plain note. Each `timeout` or `not-started` check is a louder note with its `reason` and the end of its `tail` (a missing command, runner or service is not a failed check). Each changed source file no check covers is a note naming the file and suggesting `/plan2code-test` to write tests for it.
|
||||
- **Not ready:** any check `failed`. Name it and quote the end of its `tail`.
|
||||
|
||||
Nothing unrun is ever Ready. Say whether uncommitted work was included in the run.
|
||||
|
||||
### Step 7: Report
|
||||
|
||||
On the console, a report doc: the verdict first, then the checks grouped by runner, each with its outcome, seconds and reason, then the notes. In the terminal, the same as a short table.
|
||||
|
||||
### Step 8: PR description
|
||||
|
||||
Run `pr-prep.mjs template` and `pr-prep.mjs spec` (the branch's spec folder: `match`, `candidates`, `how`; Step 10 reuses this answer).
|
||||
|
||||
- **With a template** (`found: true`): fill every heading in `headings`, in order, keeping the template's own words. When `hasTesting` is false, add a `## How it was checked` section. Mention `others` in one line (the person may want a different template).
|
||||
- **Without one:** five sections: `## Summary` (what the branch does, two or three sentences), `## Why` (the reason, with the spec folder when `spec` gave a `match`, or an issue link when one is known), `## Changes by area` (review-scope's files grouped by test map area, or by top folder), `## How it was checked` (drawn from the report: which checks ran and passed, what was trimmed or could not run), `## Risks` (what could break, what a reviewer should look at).
|
||||
|
||||
Post it as its own doc holding one fenced block (` ```markdown `), so the page's copy button copies the raw Markdown. In the terminal, print the same fenced block.
|
||||
|
||||
### Step 9: Link
|
||||
|
||||
Run `pr-prep.mjs pr-url`.
|
||||
|
||||
- `pushed: true`: put the create-a-PR `url` under the description. `url` null (`needsKind: true` for an unknown host, or a remote no link can be built for): say the link cannot be built for this host here; with `needsKind`, add that the git skill (`/plan2code-git`) asks what kind of host it is once and remembers it for next time.
|
||||
- `pushed: false`: say the branch is not pushed yet and offer to hand over to the git skill (`/plan2code-git`), which asks before it pushes. PR Prep never pushes.
|
||||
- Any other failure: say why in one line (detached HEAD, the branch is the default branch) and leave the link out.
|
||||
|
||||
### Step 10: Save offer
|
||||
|
||||
Use Step 8's `spec` answer.
|
||||
|
||||
- `match`: offer to save the report and the description as `<match>/PR-READINESS-<YYYYMMDD>.md`. A file of that name already there → say it will be replaced before asking. Save only on a yes.
|
||||
- `ask`: ask which of `candidates` (or none), then offer as above.
|
||||
- `none`: save nothing and say nothing about saving.
|
||||
|
||||
### Step 11: Test map offer
|
||||
|
||||
When the run had no map, or found commands or areas the map lacks, offer to write or update it (one table under `## Test map` in `AGENTS.md`, columns `Area`, `Paths`, `Run`, `Shared`). On a yes, write the rows to a JSON file in the session folder (or the OS temp folder) and run `test-map.mjs write --rows <file>`. Never without a yes. No `AGENTS.md` (`write` refuses with `no-agents-md`) → offer Init (`/plan2code-init`) instead.
|
||||
|
||||
## Session End
|
||||
|
||||
Work summary: the verdict, the checks that ran (passed, failed, timed out, could not start), the trimmed ones, whether uncommitted work was included, the description shown, the link or that the branch is not pushed, and any file written.
|
||||
|
||||
**Next step**, as the closing line: "Optional next (NEW conversation): `/plan2code-review` for a code review before you open the PR." Add `/plan2code-test` when untested files were noted.
|
||||
|
||||
On the console, post `finish` with the verdict in `headline`, `command` `/plan2code-review`, and `"dashboard": true`; mention `/plan2code-test` in `body` when untested files were noted.
|
||||
|
||||
```
|
||||
⋅
|
||||
╭───╮
|
||||
╲│ ★ │╱
|
||||
│ ◡ │ Ready for review!
|
||||
╰┬─┬╯
|
||||
```
|
||||
@@ -0,0 +1,188 @@
|
||||
#!/usr/bin/env node
|
||||
// coverage.mjs: coverage output read into per-file numbers, for the Test skill.
|
||||
//
|
||||
// Reads what a project's own coverage tool already wrote: an lcov file (Node's
|
||||
// test runner with the lcov reporter, Jest, Vitest, pytest-cov's lcov export)
|
||||
// or the text `go tool cover -func` prints. It never runs a tool and never
|
||||
// writes a file; the skill runs the coverage command first, on a yes.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { EXIT, fail, out, parseArgs, run } from "./common.mjs";
|
||||
|
||||
const USAGE = `
|
||||
coverage.mjs: per-file coverage from a coverage tool's output. JSON on stdout.
|
||||
|
||||
node coverage.mjs read --lcov <file> [--root <dir>]
|
||||
node coverage.mjs read --go-func <file> [--root <dir>]
|
||||
Prints { ok, format, files: [{ file, lines, hit, pct }], total },
|
||||
files sorted by path, pct with one decimal.
|
||||
lcov SF: / DA:<line>,<hits> / LF: / LH: / end_of_record records.
|
||||
lines is LF (or the DA count when LF is missing), hit is LH
|
||||
(or the DA lines with hits above 0). Paths are made relative
|
||||
to --root (default: the current folder) with forward slashes;
|
||||
an absolute path outside the root is kept as given. total
|
||||
sums every file.
|
||||
go-func "<import path>/<file>.go:<line>: <func> <pct>%" lines,
|
||||
grouped by file: pct is the mean of the file's functions,
|
||||
lines and hit are null. The module path of the go.mod that
|
||||
owns each file (any under --root, four folders deep) is
|
||||
swapped for that go.mod's folder, so files read as project
|
||||
paths, a nested module's included. The "total:" line
|
||||
is not a file: it is reported as total.
|
||||
A file with no lines has pct null.
|
||||
|
||||
Exit: 0 ok · 1 crash · 2 bad arguments · 3 no such file · 4 not lcov or
|
||||
go tool cover -func output.
|
||||
`;
|
||||
|
||||
const pct1 = (n) => Math.round(n * 10) / 10;
|
||||
const slash = (p) => p.replace(/\\/g, "/");
|
||||
const isAbs = (p) => p.startsWith("/") || /^[A-Za-z]:\//.test(p);
|
||||
|
||||
/** A path made relative to root when it lies under it; anything else as given (relative paths with forward slashes). */
|
||||
function relTo(root, file) {
|
||||
const f = slash(file.trim());
|
||||
if (!isAbs(f)) return f.replace(/^\.\//, "");
|
||||
const r = slash(root).replace(/\/+$/, "");
|
||||
const drive = /^[A-Za-z]:\//.test(f);
|
||||
const under = drive ? f.toLowerCase().startsWith(`${r.toLowerCase()}/`) : f.startsWith(`${r}/`);
|
||||
return under ? f.slice(r.length + 1) : file.trim();
|
||||
}
|
||||
|
||||
function byPath(a, b) {
|
||||
return a.file < b.file ? -1 : a.file > b.file ? 1 : 0;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ lcov */
|
||||
|
||||
function readLcov(text, root) {
|
||||
if (!/^SF:/m.test(text)) return null;
|
||||
const files = [];
|
||||
let cur = null;
|
||||
const close = () => {
|
||||
if (!cur) return;
|
||||
const lines = cur.lf ?? cur.da.length;
|
||||
const hit = cur.lh ?? cur.da.filter((h) => h > 0).length;
|
||||
files.push({ file: relTo(root, cur.sf), lines, hit, pct: lines ? pct1((hit / lines) * 100) : null });
|
||||
cur = null;
|
||||
};
|
||||
for (const raw of text.split(/\r?\n/)) {
|
||||
const line = raw.trim();
|
||||
if (line.startsWith("SF:")) {
|
||||
close();
|
||||
cur = { sf: line.slice(3), da: [], lf: null, lh: null };
|
||||
} else if (!cur) continue;
|
||||
else if (line.startsWith("DA:")) {
|
||||
const hits = Number(line.slice(3).split(",")[1]);
|
||||
cur.da.push(Number.isFinite(hits) ? hits : 0);
|
||||
} else if (line.startsWith("LF:")) cur.lf = Number(line.slice(3)) || 0;
|
||||
else if (line.startsWith("LH:")) cur.lh = Number(line.slice(3)) || 0;
|
||||
else if (line === "end_of_record") close();
|
||||
}
|
||||
close();
|
||||
files.sort(byPath);
|
||||
const lines = files.reduce((s, f) => s + f.lines, 0);
|
||||
const hit = files.reduce((s, f) => s + f.hit, 0);
|
||||
return { files, total: { lines, hit, pct: lines ? pct1((hit / lines) * 100) : null } };
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- go-func */
|
||||
|
||||
const GO_LINE = /^(.+\.go):\d+:\s+\S+\s+([\d.]+)%\s*$/;
|
||||
const GO_TOTAL = /^total:\s+(?:\(statements\)\s+)?([\d.]+)%\s*$/;
|
||||
|
||||
const GO_SKIP = new Set([".git", "node_modules", "vendor", "testdata"]);
|
||||
|
||||
// Every Go module under root (four folders deep, as discover walks), longest
|
||||
// module path first, so a nested module (tools/go.mod) owns its own files.
|
||||
function goModules(root) {
|
||||
const found = [];
|
||||
const walk = (dir, depth) => {
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(path.join(root, dir), { withFileTypes: true });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
for (const e of entries) {
|
||||
if (e.isFile() && e.name === "go.mod") {
|
||||
try {
|
||||
const m = fs.readFileSync(path.join(root, dir, e.name), "utf8").match(/^\s*module\s+(\S+)/m);
|
||||
if (m) found.push({ dir, mod: m[1].replace(/^"|"$/g, "") });
|
||||
} catch {}
|
||||
} else if (e.isDirectory() && depth < 4 && !GO_SKIP.has(e.name) && !e.name.startsWith(".")) {
|
||||
walk(dir ? `${dir}/${e.name}` : e.name, depth + 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
walk("", 0);
|
||||
return found.sort((a, b) => b.mod.length - a.mod.length);
|
||||
}
|
||||
|
||||
function readGoFunc(text, root) {
|
||||
const lines = text.split(/\r?\n/).map((l) => l.trim());
|
||||
if (!lines.some((l) => GO_LINE.test(l))) return null;
|
||||
const mods = goModules(root);
|
||||
const groups = new Map();
|
||||
let total = null;
|
||||
for (const line of lines) {
|
||||
const t = line.match(GO_TOTAL);
|
||||
if (t) {
|
||||
total = { lines: null, hit: null, pct: pct1(Number(t[1])) };
|
||||
continue;
|
||||
}
|
||||
const m = line.match(GO_LINE);
|
||||
if (!m) continue;
|
||||
let file = slash(m[1]);
|
||||
const own = mods.find((g) => file.startsWith(`${g.mod}/`));
|
||||
if (own) file = `${own.dir ? `${own.dir}/` : ""}${file.slice(own.mod.length + 1)}`;
|
||||
else file = relTo(root, m[1]);
|
||||
(groups.get(file) || groups.set(file, []).get(file)).push(Number(m[2]));
|
||||
}
|
||||
const files = [...groups].map(([file, pcts]) => ({ file, lines: null, hit: null, pct: pct1(pcts.reduce((s, p) => s + p, 0) / pcts.length) }));
|
||||
files.sort(byPath);
|
||||
return { files, total };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ main */
|
||||
|
||||
async function main(argv) {
|
||||
const args = parseArgs(argv, { values: ["lcov", "go-func", "root"] });
|
||||
const [cmd, ...extra] = args._;
|
||||
if (!cmd) fail(EXIT.USAGE, "missing-command", "A subcommand is required: read.", "Run with --help for usage.");
|
||||
if (cmd !== "read") fail(EXIT.USAGE, "unknown-command", `Unknown subcommand "${cmd}".`, "Use: read.");
|
||||
if (extra.length) fail(EXIT.USAGE, "stray-argument", `Unexpected argument(s): ${extra.join(" ")}.`, "Run with --help for usage.");
|
||||
if (!args.lcov === !args["go-func"]) fail(EXIT.USAGE, "one-format", "Give exactly one of --lcov <file> or --go-func <file>.", "Run with --help for usage.");
|
||||
const format = args.lcov ? "lcov" : "go-func";
|
||||
const file = args.lcov || args["go-func"];
|
||||
const rootArg = args.root || process.cwd();
|
||||
const root = isAbs(slash(rootArg)) ? rootArg : path.resolve(rootArg);
|
||||
let text;
|
||||
try {
|
||||
text = fs.readFileSync(file, "utf8");
|
||||
} catch {
|
||||
fail(EXIT.NOT_FOUND, "no-file", `Cannot read ${file}.`, "Run the coverage command first, then pass the file it wrote.");
|
||||
}
|
||||
const read = format === "lcov" ? readLcov(text, root) : readGoFunc(text, root);
|
||||
if (!read) {
|
||||
fail(
|
||||
EXIT.INVALID,
|
||||
"unreadable-format",
|
||||
`${file} is not ${format === "lcov" ? "lcov output (no SF: lines)" : "go tool cover -func output (no .go: lines)"}.`,
|
||||
"Check the coverage command's reporter writes lcov, or pass go tool cover -func output with --go-func."
|
||||
);
|
||||
}
|
||||
out({ ok: true, format, ...read });
|
||||
}
|
||||
|
||||
// Run as a script; imported, do nothing.
|
||||
const isMain = (() => {
|
||||
try {
|
||||
return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
})();
|
||||
if (isMain) run(USAGE, main);
|
||||
@@ -0,0 +1,201 @@
|
||||
# 🧪 TEST MODE
|
||||
|
||||
Start all TEST MODE responses with '🧪 [TEST]'
|
||||
|
||||
## Role
|
||||
|
||||
Finds code no test covers and writes the missing tests. Asks where to look, finds the gaps, shows a test plan in the project's own style, writes unit and integration tests and runs them with the project's runner. **Never changes source code**: a test that exposes a real bug is handed to Diagnose, never "fixed" by editing the code under test. **Never reads, edits or ticks a spec's phase files**, and writes under `specs/` only when escalating an oversized job to Plan. No browser or end-to-end tests.
|
||||
|
||||
## Interface
|
||||
|
||||
The FIRST thing you do, before anything else in this file, before reading the code: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow test` before reading (<D>: references/web-console/ beside this SKILL.md (~/.agents/skills/plan2code-test/references/web-console/ globally) or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/test.md. Every question, the plan and the results go through it. Switchable anytime. If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open: resume it (console-launches.md), then Project Context.
|
||||
|
||||
## Project Context
|
||||
|
||||
Read `./AGENTS.md` when it exists: its commands, its `## Test map` and anything it says about tests, helpers or slow suites. Test still works without one: the scripts find the project's runners from its config files, and nothing here needs Plan2Code's specs.
|
||||
|
||||
## Scripts
|
||||
|
||||
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-test/scripts/` globally). Run from the project root. Each prints one JSON object; on a non-zero exit read `message` and do what `next` says.
|
||||
|
||||
- `node "<S>/test-map.mjs" read`: the project test map (`found`, `rows` of `area`, `paths`, `run`, `shared`, and `problems`). `write --rows <file.json>` saves one, only on a yes.
|
||||
- `node "<S>/test-commands.mjs" discover`: the project's commands from its config files: `suite`, `runners` (`cmd`, `cwd`, `covers`), `checks`, `coverage` (`runner`, `cmd`, some with an `<out>` placeholder, `cwd`, `reads`: `lcov` or `go-func`), `builtin` (the language's own runner, only when there is no suite and no runner).
|
||||
- `node "<S>/test-match.mjs" gaps --scope branch|path|all [--path <p>]`: source files no test covers (`file`, `area`, `runner`, `commits90d`, `lastTouched`), ranked newest first, then by recent commits; `capped` when it stopped at 2,000 files.
|
||||
- `node "<S>/test-match.mjs" nearest --file <f>`: up to three existing test files to read for the project's style.
|
||||
- `node "<S>/run-check.mjs" --cmd <c> --cwd <d> --timeout <s> --log <file>`: runs one command and prints `outcome` (`passed`, `failed`, `timeout`, `not-started` with a `reason`), `exit`, `seconds` and `tail`.
|
||||
- `node "<S>/coverage.mjs" read --lcov <file> | --go-func <file>`: coverage output as per-file `lines`, `hit` and `pct`, plus `total`.
|
||||
- `node "<S>/review-scope.mjs" [--base <branch>]`: the branch's changed files, when you need the list itself (`gaps --scope branch` already reads it).
|
||||
|
||||
## References
|
||||
|
||||
- `references/test-runs.md`: which tests cover a file, and what counts as shared ground.
|
||||
- `references/building-habits.md`: how to write and run tests, and what to do when one fails unexpectedly.
|
||||
- `references/helper-strength.md`: helper strength and effort.
|
||||
|
||||
## Rules
|
||||
|
||||
- Follow `./AGENTS.md` when it exists.
|
||||
- **Never change source code.** Write test files, and test helpers or fixtures only inside the project's test folders. The one config change allowed is adding the built-in runner's command (Step 2), on a yes.
|
||||
- **Never read, edit or tick a spec's phase files.** Write under `specs/` only for an escalation PLAN-DRAFT.
|
||||
- **Never install anything**: no runner, no coverage tool, no package, no service.
|
||||
- **Nothing runs before the person confirms it.** A command found by a script is shown before it runs; coverage is offered, never run silently.
|
||||
- Unit and integration tests only: no browser, end-to-end or load tests.
|
||||
- Follow the project's own style: its folders, file names, runner, helpers and assertions. Never add a test framework.
|
||||
- **Record honestly.** Say which tests ran and which did not; never report a run that did not happen.
|
||||
- Never run `git commit`, `git push` or `git add`: the person commits the new tests.
|
||||
- Plain words: name the file, the runner and the command.
|
||||
|
||||
## Helpers
|
||||
|
||||
When your tool can start helpers (subagents) and they are not switched off for this run (on the web console a `Subagents:` block says which, console-subagents.md): helpers may read the nearest tests and runner configs per runner group (Step 4). Keep the gaps, the plan, the style block, every question and the writing of tests with you. Light strength, low effort, per references/helper-strength.md. No helpers? Do the same work yourself.
|
||||
|
||||
## Process
|
||||
|
||||
### Step 1: Scope
|
||||
|
||||
Every run, ask where to look, on one card:
|
||||
|
||||
1. **The branch's changes**: files changed on this branch (`--scope branch`).
|
||||
2. **A named area**: a folder or file the person names; ask for it as a follow-up (`--scope path --path <p>`).
|
||||
3. **The whole project** (`--scope all`).
|
||||
|
||||
### Step 2: Runner
|
||||
|
||||
Run `test-map.mjs read` and `test-commands.mjs discover`. With a map (`found: true`), its rows are the project's runners; mention any `problems` in one line.
|
||||
|
||||
- **No map:** list every command `discover` found with the folders each covers (`suite`, each of `runners` with its `cwd` and `covers`), and confirm them on one card before anything runs. A correction from the person replaces what the script found.
|
||||
- **No runner at all, `builtin` set:** offer that runner, naming it and the command it would add (for Node, a `"test": "node --test"` script in `package.json`; for Python `python -m unittest`). Go ahead only on a yes; on a yes add that one command and nothing else.
|
||||
- **No runner and no `builtin`:** stop. Say the project has no test runner and none built into its language, so there is nothing to write tests for here; end the run.
|
||||
|
||||
### Step 3: Gaps
|
||||
|
||||
Run `test-match.mjs gaps --scope <branch|path|all>` (with `--path <p>` for a named area). `capped: true` → say only the first 2,000 source files were read.
|
||||
|
||||
**Coverage, only when the project already has it.** When `discover` lists a `coverage` entry for a runner in scope, offer it on one card naming the command and what it covers. Never run it without a yes.
|
||||
|
||||
- **Yes:** when `cmd` has an `<out>` placeholder (already quoted), replace just `<out>` with a file in the session folder (`open` printed it; in the terminal, the OS temp folder). Run it with `run-check.mjs` in its `cwd`, with a `--log` file. Then read the output with `coverage.mjs read`, per `reads`: `--lcov <out>` when the command wrote to `<out>`, else `--lcov <cwd>/coverage/lcov.info` (Jest's and Vitest's default); `--go-func <log>` for Go, whose `go tool cover -func` table is printed into the run's log. Files at 0% or under 50% that matching called covered become extra gaps, method `coverage`. A coverage run that fails or times out, or a `coverage.mjs read` that fails (exit 3 or 4, as for .NET's Cobertura output): say so in one line, and matching alone continues.
|
||||
- **No:** matching alone continues, and the plan says coverage was skipped.
|
||||
|
||||
Every gap carries the method that found it (`matching` or `coverage`), ranked as `gaps` ranks them; coverage gaps follow the matching ones, lowest percent first. No gaps at all → say every source file in scope has a test, offer the test map (Step 8) when the run had none, and end.
|
||||
|
||||
### Step 3b: Size check
|
||||
|
||||
Count the source files to cover, the new test files the plan would add, and the runners involved. When any one passes its limit, post one card naming the counts:
|
||||
|
||||
> This is a big job for one run:
|
||||
> - Source files: [X]/8
|
||||
> - New test files: [X]/8
|
||||
> - Runners: [X]/2
|
||||
>
|
||||
> 1. **Continue**: a lighter plan this run only, the top 8 gaps by rank
|
||||
> 2. **Escalate**: write a PLAN-DRAFT and plan it properly
|
||||
|
||||
**Continue:** keep the top 8 gaps by rank; name the rest as left for a later run.
|
||||
|
||||
**Escalate:**
|
||||
1. Ask for a kebab-case name (e.g. `billing-tests`).
|
||||
2. Write `specs/<name>/PLAN-DRAFT-<YYYYMMDD>.md`:
|
||||
|
||||
```markdown
|
||||
# PLAN-DRAFT: [Name]
|
||||
|
||||
**Status:** Escalated from Test - Resume at Phase 2
|
||||
**Created:** [YYYYMMDD]
|
||||
**Source:** Test escalation
|
||||
|
||||
## 1. Executive Summary
|
||||
Write the missing tests for [scope]: [N] source files with no test, across [runners].
|
||||
|
||||
## 2. Requirements (Gathered)
|
||||
|
||||
### Functional Requirements
|
||||
- FR-1: Tests for `[file]` ([method], [area], [runner])
|
||||
- FR-2: ...
|
||||
|
||||
### Non-Functional Requirements
|
||||
- NFR-1: Tests follow the project's own style; no source changes; nothing installed
|
||||
|
||||
### Testing Strategy
|
||||
[The "How this project writes tests" notes gathered so far, per runner]
|
||||
|
||||
## 3. Scope Assessment
|
||||
| Indicator | Value | Threshold |
|
||||
|-----------|-------|-----------|
|
||||
| Source files | X | 8 |
|
||||
| New test files | X | 8 |
|
||||
| Runners | X | 2 |
|
||||
|
||||
**Escalation reason:** [the limits passed]
|
||||
|
||||
## 4. Context Gathered
|
||||
[Commands confirmed, coverage run or skipped, nearest tests read]
|
||||
|
||||
---
|
||||
**Next:** New conversation with `/plan2code-1-plan --web`, attach this file.
|
||||
Resume at Phase 2 (System Context).
|
||||
```
|
||||
|
||||
3. Say: "Created `specs/<name>/PLAN-DRAFT-<date>.md`. Start a new conversation with `/plan2code-1-plan --web` to continue." End the run (Session End, escalated).
|
||||
|
||||
### Step 4: Style
|
||||
|
||||
For each runner in the plan: run `test-match.mjs nearest --file <gap>` for its gaps, read those tests (two or three per runner is enough) and the runner's config. Note:
|
||||
|
||||
- **Folder:** where tests live (beside the source, a `test/` or `tests/` folder, `__tests__/`).
|
||||
- **File naming:** `x.test.js`, `test_x.py`, `x_test.go` and the like.
|
||||
- **Runner and command:** the command that runs one file or folder.
|
||||
- **Helpers reused:** fixtures, factories, setup files, mocks the project already has.
|
||||
- **Assertion style:** `assert`, `expect`, table-driven cases, the describe/it shape.
|
||||
|
||||
No test exists near a gap: use the closest tests for that runner anywhere in the project, and say so.
|
||||
|
||||
### Step 5: Plan
|
||||
|
||||
The plan opens with a **How this project writes tests** block per runner (the five notes above). Then, per runner group, each gap with its method, the test file to add or extend, and the cases, each marked unit or integration. Every gap follows its own area's runner.
|
||||
|
||||
Show it for approval; the person approves or corrects the style and the plan together. A correction to the style changes every test in that group. Nothing is written before they approve.
|
||||
|
||||
### Step 6: Write and run
|
||||
|
||||
Write the tests following `references/building-habits.md`, one runner group at a time, matching the approved style. Reuse the project's helpers; add a new helper only inside the test folders, and only when two or more new tests need it.
|
||||
|
||||
Run each group's new tests with `run-check.mjs`: the map row's `run`, or the runner command narrowed to the new files when the runner allows it (the whole group's command when it does not). The timeout is 600 seconds by default, longer when `AGENTS.md` says a suite is slow. On the console the log goes in `<session>/runs/<n>.log`; in the terminal, the OS temp folder. Before each run post one `activity` line ("Running the new launcher tests").
|
||||
|
||||
A new test that fails: read the failure.
|
||||
- **The test is wrong** (a wrong expectation, a missing setup, a typo): fix the test and run again.
|
||||
- **The source is wrong** (the test asks for what the code clearly means to do, and the code does not): Step 7.
|
||||
- `timeout` or `not-started`: say so with its `reason` and the end of its `tail`; never call it passed.
|
||||
|
||||
Never weaken, skip or delete a test to make it pass.
|
||||
|
||||
### Step 7: Real bug
|
||||
|
||||
A new test that fails because the source is wrong is never "fixed" by changing the source. Ask, per bug:
|
||||
|
||||
> `[test file]` › `[case]` fails because `[source file]` [does X instead of Y]. Keep it as the reproduction and hand it to Diagnose, or remove it?
|
||||
|
||||
- **Keep:** leave the failing test in place; name the file and the failing case in the finish, with `/plan2code-diagnose` as the next step.
|
||||
- **Remove:** delete that case (or the file when it held only that case) and say so.
|
||||
|
||||
### Step 8: Test map offer
|
||||
|
||||
When the run had no map, or found runners or areas the map lacks, offer to write or update it (one table under `## Test map` in `AGENTS.md`, columns `Area`, `Paths`, `Run`, `Shared`). On a yes, write the rows to a JSON file in the session folder (or the OS temp folder) and run `test-map.mjs write --rows <file>`. Never without a yes. No `AGENTS.md` (`write` refuses with `no-agents-md`) → offer Init (`/plan2code-init`) instead.
|
||||
|
||||
## Session End
|
||||
|
||||
Work summary: the scope, how gaps were found (matching, and coverage run or skipped), the tests added (file, cases, unit or integration), each run's outcome, any bug kept for Diagnose, any gap left for later, and any file written outside the tests (the built-in runner's command, the test map, a PLAN-DRAFT).
|
||||
|
||||
**Next step**, as the closing line:
|
||||
- A bug was kept: "NEXT STEP (NEW conversation): `/plan2code-diagnose` with `[test file]` › `[case]` as the reproduction."
|
||||
- Escalated: "NEXT STEP (NEW conversation): `/plan2code-1-plan --web` with `specs/<name>/PLAN-DRAFT-<date>.md`."
|
||||
- Otherwise: "Commit the new tests with `/plan2code-git`."
|
||||
|
||||
On the console, post `finish` with the tests added and their results in `headline`, `"dashboard": true`, and `command` `/plan2code-diagnose` when a bug was kept (`/plan2code-1-plan` when escalated), else no `command`. No `commit` field: `body` says to commit the new tests with `/plan2code-git`.
|
||||
|
||||
```
|
||||
⋅
|
||||
╭───╮
|
||||
╲│ ★ │╱
|
||||
│ ◡ │ Tests written!
|
||||
╰┬─┬╯
|
||||
```
|
||||
@@ -67,6 +67,8 @@ Ground truth for menu notes and Ask-tab answers. For anything beyond this table,
|
||||
| git | git status, branches, diffs, `AGENTS.md` | commits, branches; optional `.gitignore`, push, publish; no spec writes |
|
||||
| xray | the codebase, `git` history, `gh` when present | an answer; `ARCHITECTURE-BRIEF-<date>.md` or `XRAY-<area>-<date>.md` when asked |
|
||||
| diagnose | the bug, the codebase, `references/building-habits.md` | `DIAGNOSIS-<date>.md`; no code changes |
|
||||
| pr-prep | git diff and status, the `AGENTS.md` test map, the project's config files, the PR template | the page report and description; `PR-READINESS-<date>.md` on a yes; the `AGENTS.md` test map on a yes; no commits, no push |
|
||||
| test | the codebase, the `AGENTS.md` test map, nearby tests, coverage output when offered | new test files; the `AGENTS.md` test map on a yes; `PLAN-DRAFT-<date>.md` when escalated; no source changes |
|
||||
|
||||
## A pick arrives
|
||||
|
||||
@@ -102,6 +104,7 @@ If `skill` is not in the table below, say so on the page and stay the dashboard.
|
||||
| plan2code-quick-task | quick-task | | plan2code-handoff | handoff |
|
||||
| plan2code-git | git | | plan2code-changelog | changelog |
|
||||
| plan2code-xray | xray | | plan2code-diagnose | diagnose |
|
||||
| plan2code-pr-prep | pr-prep | | plan2code-test | test |
|
||||
|
||||
## A pick-up arrives
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# Choosing what to run
|
||||
> Read by Document, Implement, Implement + Review, Quick Task, Review and Finalize before they write, run or offer tests. Never invoked as a skill.
|
||||
> Read by Document, Implement, Implement + Review, Quick Task, Review, Finalize, PR Prep and Test before they write, run or offer tests. Never invoked as a skill.
|
||||
|
||||
## Three tiers
|
||||
|
||||
@@ -11,8 +11,8 @@
|
||||
|
||||
In this order:
|
||||
|
||||
1. `AGENTS.md`'s test map and its "run single test" command.
|
||||
2. Otherwise match by name, folder and imports of the changed files.
|
||||
1. `AGENTS.md`'s `## Test map` table (`Area`, `Paths`, `Run`, `Shared`; it may sit behind one link to `.agents-docs/AGENTS-test-map.md`), read with `test-map.mjs read` when the skill ships it, plus the "run single test" command.
|
||||
2. Otherwise match by name, folder and imports of the changed files; `test-match.mjs` does this when the skill ships it.
|
||||
|
||||
A runner's own related-tests flag may be used when `AGENTS.md` records it. It is never required.
|
||||
|
||||
@@ -22,7 +22,7 @@ Lint, a type check, a size check: run them at phase end only when the project or
|
||||
|
||||
## Shared ground
|
||||
|
||||
A test helper or fixture, build or test config, a widely imported module, a shared type or schema. Touching any of these is the moment to offer a wider run: say what was touched and why it reaches wide, and let the person choose.
|
||||
A test helper or fixture, build or test config, a widely imported module, a shared type or schema. A test map row marked `Shared: yes` is shared ground by definition. Touching any of these is the moment to offer a wider run: say what was touched and why it reaches wide, and let the person choose.
|
||||
|
||||
## Ask when unsure
|
||||
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
// glob.mjs: the small glob subset the test map uses, as RegExps.
|
||||
//
|
||||
// A library, no CLI. The test map's Paths cells hold globs, and every script
|
||||
// that reads them (test-map.mjs, test-match.mjs) matches them the same way:
|
||||
//
|
||||
// ** any number of path segments, including none
|
||||
// * any characters except /
|
||||
// ? one character except /
|
||||
// {a,b} alternation, no nesting
|
||||
//
|
||||
// Everything else is literal. unsupported() names anything outside the subset
|
||||
// so the test map can report it instead of matching it wrongly. Paths are
|
||||
// forward-slash normalized; on Windows both sides are lower-cased, as file
|
||||
// names there are case-insensitive.
|
||||
|
||||
const FOLD = process.platform === "win32";
|
||||
const fold = (s) => (FOLD ? s.toLowerCase() : s);
|
||||
|
||||
/** Backslashes to /, a leading ./ dropped. */
|
||||
export function toPosix(p) {
|
||||
return String(p).replace(/\\/g, "/").replace(/^(\.\/)+/, "");
|
||||
}
|
||||
|
||||
/** A reason string for a glob outside the subset, or null when it is supported. */
|
||||
export function unsupported(glob) {
|
||||
const g = String(glob);
|
||||
if (!g.trim()) return "empty glob";
|
||||
if (/[[\]]/.test(g)) return "character classes ([...]) are not supported";
|
||||
if (g.startsWith("!")) return "negation (!) is not supported";
|
||||
if (g.includes("***")) return "*** is not a glob; use ** for any folders";
|
||||
let depth = 0;
|
||||
for (const ch of g) {
|
||||
if (ch === "{") {
|
||||
if (++depth > 1) return "nested braces are not supported";
|
||||
} else if (ch === "}") {
|
||||
if (--depth < 0) return "a } has no matching {";
|
||||
}
|
||||
}
|
||||
if (depth !== 0) return "a { has no matching }";
|
||||
return null;
|
||||
}
|
||||
|
||||
const escape = (s) => s.replace(/[.+^$()|\\/]/g, "\\$&");
|
||||
|
||||
// One alternative's text (no braces) to RegExp source.
|
||||
function plain(text) {
|
||||
let src = "";
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const ch = text[i];
|
||||
if (ch === "*") {
|
||||
if (text[i + 1] === "*") {
|
||||
const before = i === 0 || text[i - 1] === "/";
|
||||
const after = i + 2 === text.length || text[i + 2] === "/";
|
||||
if (before && after) {
|
||||
if (text[i + 2] === "/") {
|
||||
src += "(?:[^/]*/)*"; // **/ : any folders, including none
|
||||
i += 2;
|
||||
} else if (i > 0) {
|
||||
src = src.replace(/\\\/$/, "") + "(?:/.*)?"; // /** at the end: the folder and everything in it
|
||||
i += 1;
|
||||
} else {
|
||||
src += ".*"; // a lone **
|
||||
i += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
i += 1; // ** inside a segment reads as *
|
||||
}
|
||||
src += "[^/]*";
|
||||
} else if (ch === "?") src += "[^/]";
|
||||
else src += escape(ch);
|
||||
}
|
||||
return src;
|
||||
}
|
||||
|
||||
/** The glob as an anchored RegExp. Throws on a glob unsupported() rejects. */
|
||||
export function globToRegExp(glob) {
|
||||
const why = unsupported(glob);
|
||||
if (why) throw new Error(`Unsupported glob "${glob}": ${why}`);
|
||||
const g = fold(toPosix(glob));
|
||||
let src = "";
|
||||
let i = 0;
|
||||
while (i < g.length) {
|
||||
const open = g.indexOf("{", i);
|
||||
if (open === -1) {
|
||||
src += g.slice(i);
|
||||
break;
|
||||
}
|
||||
src += g.slice(i, open);
|
||||
const close = g.indexOf("}", open);
|
||||
src += `\u0000${g.slice(open + 1, close)}\u0001`;
|
||||
i = close + 1;
|
||||
}
|
||||
// Brace groups are marked with \0 ... \1 so the text around them converts
|
||||
// as one piece (a ** next to a brace still sees its neighbors).
|
||||
const parts = src.split(/(\u0000[^\u0001]*\u0001)/);
|
||||
let out = "";
|
||||
for (const part of parts) {
|
||||
if (part.startsWith("\u0000")) out += `(?:${part.slice(1, -1).split(",").map(plain).join("|")})`;
|
||||
else out += plain(part);
|
||||
}
|
||||
return new RegExp(`^${out}$`);
|
||||
}
|
||||
|
||||
// Compiled globs, by glob text (null for an unsupported one): a map's few
|
||||
// globs are tested against every file in a run.
|
||||
const compiled = new Map();
|
||||
|
||||
/** Does the path match the glob? Unsupported globs match nothing. */
|
||||
export function matchGlob(glob, p) {
|
||||
if (!compiled.has(glob)) compiled.set(glob, unsupported(glob) ? null : globToRegExp(glob));
|
||||
const re = compiled.get(glob);
|
||||
return re !== null && re.test(fold(toPosix(p)));
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
#!/usr/bin/env node
|
||||
// run-check.mjs: run one check command with a timeout and classify the result.
|
||||
//
|
||||
// Agent shells differ in their timeouts, none kill a Windows process tree, and
|
||||
// telling "the command is not there" from "the command failed" needs the exit
|
||||
// code and the spawn error. So one check runs here: passed, failed, timeout or
|
||||
// not-started, with the output's last lines. The full output goes only to
|
||||
// --log; nothing else is written.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { spawn, execFileSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { EXIT, fail, out, parseArgs, run, isDir } from "./common.mjs";
|
||||
|
||||
const USAGE = `
|
||||
run-check.mjs: run one command and classify its outcome. JSON on stdout.
|
||||
|
||||
node run-check.mjs --cmd <command> [--cwd <dir>] [--timeout <seconds>] [--log <file>]
|
||||
Runs the command through the shell in --cwd (relative to the current
|
||||
folder; default "."), stops it and every process it started after
|
||||
--timeout seconds (default 600, at most 86400), and prints
|
||||
{ ok, cmd, cwd, outcome, exit, signal, seconds, tail, log }.
|
||||
outcome passed (exit 0) · failed (any other exit) · timeout ·
|
||||
not-started (with reason: spawn-error, command-not-found,
|
||||
cwd-missing, log-unwritable)
|
||||
tail the output's last 60 lines, stdout and stderr interleaved,
|
||||
each cut at 400 characters
|
||||
log the file holding the full output, when --log was given
|
||||
|
||||
Exit: 0 whenever an outcome was classified · 2 bad arguments.
|
||||
`;
|
||||
|
||||
// One day: a longer timer overflows Node's 32-bit limit and fires at once.
|
||||
const MAX_TIMEOUT = 86400;
|
||||
const TAIL_LINES = 60;
|
||||
const LINE_CAP = 400;
|
||||
const NOT_RECOGNIZED = /is not recognized as an internal or external command/;
|
||||
|
||||
function killTree(child) {
|
||||
if (process.platform === "win32") {
|
||||
try {
|
||||
execFileSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
||||
} catch {}
|
||||
} else {
|
||||
try {
|
||||
process.kill(-child.pid, "SIGKILL");
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
function tailOf(text) {
|
||||
const lines = text.split(/\r?\n/);
|
||||
if (lines.length && lines[lines.length - 1] === "") lines.pop();
|
||||
return lines.slice(-TAIL_LINES).map((l) => (l.length > LINE_CAP ? l.slice(0, LINE_CAP) : l));
|
||||
}
|
||||
|
||||
export function runCheck({ cmd, cwd, timeout, log }) {
|
||||
const shownCwd = cwd || ".";
|
||||
const abs = path.resolve(shownCwd);
|
||||
const logFile = log ? path.resolve(log) : null;
|
||||
const base = { ok: true, cmd, cwd: shownCwd };
|
||||
if (!isDir(abs)) {
|
||||
return Promise.resolve({ ...base, outcome: "not-started", reason: "cwd-missing", exit: null, signal: null, seconds: 0, tail: [], log: null });
|
||||
}
|
||||
return new Promise((resolve) => {
|
||||
const started = Date.now();
|
||||
let output = "";
|
||||
let stderrHead = "";
|
||||
let spawnError = null;
|
||||
let timedOut = false;
|
||||
let done = false;
|
||||
let logStream = null;
|
||||
let logFailed = false;
|
||||
if (logFile) {
|
||||
// Opened before the run, so a log that cannot be written stops the
|
||||
// check up front instead of crashing it halfway with no JSON.
|
||||
let fd;
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(logFile), { recursive: true });
|
||||
fd = fs.openSync(logFile, "w");
|
||||
} catch {
|
||||
resolve({ ...base, outcome: "not-started", reason: "log-unwritable", exit: null, signal: null, seconds: 0, tail: [], log: null });
|
||||
return;
|
||||
}
|
||||
logStream = fs.createWriteStream(null, { fd });
|
||||
logStream.on("error", () => {
|
||||
logFailed = true;
|
||||
});
|
||||
}
|
||||
const child = spawn(cmd, { cwd: abs, shell: true, windowsHide: true, detached: process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"] });
|
||||
const take = (chunk, isErr) => {
|
||||
const s = chunk.toString("utf8");
|
||||
output += s;
|
||||
// Keep only what the tail can still need, plus the start of stderr for
|
||||
// the Windows "not recognized" check.
|
||||
if (output.length > 1_000_000) output = output.slice(-TAIL_LINES * LINE_CAP * 4);
|
||||
if (isErr && stderrHead.length < 65536) stderrHead += s;
|
||||
if (logStream && !logFailed) logStream.write(chunk);
|
||||
};
|
||||
child.stdout.on("data", (c) => take(c, false));
|
||||
child.stderr.on("data", (c) => take(c, true));
|
||||
|
||||
const finish = (code, signal) => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
clearTimeout(timer);
|
||||
clearTimeout(grace);
|
||||
// A process the kill missed must not keep this one alive through its pipes.
|
||||
child.stdout.destroy();
|
||||
child.stderr.destroy();
|
||||
child.unref();
|
||||
const seconds = Math.round((Date.now() - started) / 100) / 10;
|
||||
let outcome;
|
||||
let reason;
|
||||
if (spawnError) [outcome, reason] = ["not-started", "spawn-error"];
|
||||
else if (timedOut) outcome = "timeout";
|
||||
else if (code === 0) outcome = "passed";
|
||||
else if (code === 127 || code === 9009 || NOT_RECOGNIZED.test(stderrHead)) [outcome, reason] = ["not-started", "command-not-found"];
|
||||
else outcome = "failed";
|
||||
const result = { ...base, outcome, ...(reason ? { reason } : {}), exit: typeof code === "number" ? code : null, signal: signal || null, seconds, tail: tailOf(output), log: logFailed ? null : logFile };
|
||||
// An errored stream never finishes, so it is not waited on.
|
||||
if (logStream && !logFailed) logStream.end(() => resolve(result));
|
||||
else resolve(result);
|
||||
};
|
||||
|
||||
let grace = null;
|
||||
const timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
killTree(child);
|
||||
// Wait for close, but never more than 5 seconds after the kill.
|
||||
grace = setTimeout(() => finish(null, "SIGKILL"), 5000);
|
||||
}, timeout * 1000);
|
||||
|
||||
child.on("error", (err) => {
|
||||
spawnError = err;
|
||||
// close may not follow a spawn error; give it a moment, then report.
|
||||
setTimeout(() => finish(null, null), 200);
|
||||
});
|
||||
child.on("close", (code, signal) => finish(code, signal));
|
||||
});
|
||||
}
|
||||
|
||||
async function main(argv) {
|
||||
const args = parseArgs(argv, { values: ["cmd", "cwd", "timeout", "log"] });
|
||||
if (args._.length) fail(EXIT.USAGE, "unexpected-argument", `Unexpected argument "${args._[0]}".`, "Pass the command with --cmd \"<command>\".");
|
||||
if (!args.cmd || !args.cmd.trim()) fail(EXIT.USAGE, "missing-cmd", "run-check needs --cmd <command>.", "Run with --help for usage.");
|
||||
const timeout = args.timeout === undefined ? 600 : Number(args.timeout);
|
||||
if (!Number.isFinite(timeout) || timeout <= 0 || timeout > MAX_TIMEOUT) {
|
||||
fail(EXIT.USAGE, "bad-timeout", `--timeout must be a number of seconds above 0 and at most ${MAX_TIMEOUT}, not "${args.timeout}".`, "Pass --timeout <seconds>.");
|
||||
}
|
||||
out(await runCheck({ cmd: args.cmd, cwd: args.cwd, timeout, log: args.log }));
|
||||
}
|
||||
|
||||
// Run as a script; imported, do nothing.
|
||||
const isMain = (() => {
|
||||
try {
|
||||
return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
})();
|
||||
if (isMain) run(USAGE, main);
|
||||
@@ -828,7 +828,7 @@ async function cmdCheck(args) {
|
||||
checkReport("check", { spec: spec.rel, checked: names.map(at) }, problems);
|
||||
}
|
||||
|
||||
const DRAFT_STATUSES = ["Draft", "Phase 3 Complete - Resume at Phase 4", "Escalated from Quick Task - Resume at Phase 2", "Complete"];
|
||||
const DRAFT_STATUSES = ["Draft", "Phase 3 Complete - Resume at Phase 4", "Escalated from Quick Task - Resume at Phase 2", "Escalated from Test - Resume at Phase 2", "Complete"];
|
||||
// The headings Document reads out of a Complete draft.
|
||||
const DRAFT_SECTIONS = [
|
||||
{ name: "## 1. Executive Summary", re: /^##\s+1\.\s+Executive Summary\b/im },
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
#!/usr/bin/env node
|
||||
// test-commands.mjs: find a project's test and check commands from its config.
|
||||
//
|
||||
// Reads package.json, workspace files and runner configs (go.mod, Cargo.toml,
|
||||
// pyproject.toml, *.csproj, Makefile, ...) and reports the whole-suite
|
||||
// command, one runner per folder, lint/type/build checks, the coverage
|
||||
// commands the project can already run, and the built-in runner to offer when
|
||||
// it has none. It only reads files: it never runs a command, installs anything
|
||||
// or touches the network. Which of these to run stays the agent's call, and
|
||||
// every command is shown to the person before it runs.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { EXIT, fail, out, parseArgs, run, readText, isDir } from "./common.mjs";
|
||||
import { matchGlob } from "./glob.mjs";
|
||||
|
||||
const USAGE = `
|
||||
test-commands.mjs: a project's test and check commands. JSON on stdout.
|
||||
|
||||
node test-commands.mjs discover [--root <dir>]
|
||||
{ ok, suite, runners, checks, coverage, builtin }
|
||||
suite { cmd, why } the whole-suite command, or null
|
||||
runners [{ cmd, cwd, covers[] }] one per folder with its own runner
|
||||
(workspaces, go.mod, Cargo.toml, Python configs, .NET, Makefile);
|
||||
the root folder's is cwd "." and covers "**"
|
||||
checks [{ kind, cmd }] kind is lint, types or build
|
||||
coverage [{ runner, cmd, cwd, reads }] only for tools already present;
|
||||
<out> in cmd (already in quotes, so a path with spaces
|
||||
works) is a placeholder for the output file; reads is
|
||||
lcov or go-func
|
||||
builtin { language, cmd, others? } the language's own runner (node or
|
||||
python; Go and Rust always show as runners), only when there
|
||||
is no suite and no runner; otherwise null
|
||||
|
||||
Only reads files. Exit: 0 ok · 2 bad arguments · 3 no such folder.
|
||||
`;
|
||||
|
||||
const SKIP = new Set(["node_modules", ".git", "vendor", "dist", "build", "target", ".venv"]);
|
||||
const MAX_DEPTH = 4;
|
||||
const PLACEHOLDER = /no test specified/;
|
||||
const LANG_EXT = {
|
||||
node: [".js", ".mjs", ".cjs", ".jsx", ".ts", ".mts", ".cts", ".tsx"],
|
||||
python: [".py"],
|
||||
go: [".go"],
|
||||
rust: [".rs"],
|
||||
};
|
||||
// Node and Python only: a go.mod or a Cargo.toml always gives a runner above.
|
||||
const BUILTIN = { node: "node --test", python: "python -m unittest" };
|
||||
|
||||
function readJson(file) {
|
||||
const text = readText(file);
|
||||
if (text === null) return null;
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Every folder to depth 4 (forward-slash, "." for the root) with its file names, and source counts. */
|
||||
function walk(root) {
|
||||
const dirs = new Map();
|
||||
const counts = { node: 0, python: 0, go: 0, rust: 0 };
|
||||
const extLang = new Map(Object.entries(LANG_EXT).flatMap(([lang, exts]) => exts.map((e) => [e, lang])));
|
||||
const visit = (abs, rel, depth) => {
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(abs, { withFileTypes: true });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const files = [];
|
||||
dirs.set(rel, files);
|
||||
for (const e of entries) {
|
||||
if (e.isDirectory()) {
|
||||
if (depth < MAX_DEPTH && !SKIP.has(e.name)) visit(path.join(abs, e.name), rel === "." ? e.name : `${rel}/${e.name}`, depth + 1);
|
||||
} else if (e.isFile()) {
|
||||
files.push(e.name);
|
||||
const lang = extLang.get(path.extname(e.name).toLowerCase());
|
||||
if (lang) counts[lang]++;
|
||||
}
|
||||
}
|
||||
};
|
||||
visit(root, ".", 0);
|
||||
return { dirs, counts };
|
||||
}
|
||||
|
||||
/** The package manager the lockfile names. */
|
||||
function packageManager(files) {
|
||||
if (files.includes("pnpm-lock.yaml")) return "pnpm";
|
||||
if (files.includes("yarn.lock")) return "yarn";
|
||||
if (files.includes("bun.lockb") || files.includes("bun.lock")) return "bun";
|
||||
return "npm";
|
||||
}
|
||||
|
||||
const realTest = (pkg) => {
|
||||
const t = pkg && pkg.scripts && pkg.scripts.test;
|
||||
return typeof t === "string" && t.trim() && !PLACEHOLDER.test(t) ? t : null;
|
||||
};
|
||||
const deps = (pkg) => ({ ...(pkg && pkg.dependencies), ...(pkg && pkg.devDependencies), ...(pkg && pkg.peerDependencies), ...(pkg && pkg.optionalDependencies) });
|
||||
const hasMakeTest = (text) => text !== null && /^test\s*:/m.test(text);
|
||||
const covers = (cwd) => (cwd === "." ? ["**"] : [`${cwd}/**`]);
|
||||
const ancestors = (rel) => {
|
||||
const list = rel === "." ? [] : ["."];
|
||||
const parts = rel === "." ? [] : rel.split("/");
|
||||
for (let i = 1; i < parts.length; i++) list.push(parts.slice(0, i).join("/"));
|
||||
return list;
|
||||
};
|
||||
|
||||
/** Workspace folders from package.json workspaces and pnpm-workspace.yaml, matched against the folders on disk. */
|
||||
function workspaceFolders(root, pkg, dirs) {
|
||||
let globs = [];
|
||||
const ws = pkg && pkg.workspaces;
|
||||
if (Array.isArray(ws)) globs = ws;
|
||||
else if (ws && Array.isArray(ws.packages)) globs = ws.packages;
|
||||
const pnpm = readText(path.join(root, "pnpm-workspace.yaml"));
|
||||
if (pnpm !== null) {
|
||||
let inPackages = false;
|
||||
for (const line of pnpm.split(/\r?\n/)) {
|
||||
const inline = line.match(/^packages\s*:\s*\[([^\]]*)\]/);
|
||||
if (inline) {
|
||||
globs.push(...inline[1].split(",").map((g) => g.trim().replace(/^['"]|['"]$/g, "")));
|
||||
inPackages = false;
|
||||
} else if (/^packages\s*:/.test(line)) inPackages = true;
|
||||
else if (/^\S/.test(line)) inPackages = false;
|
||||
else if (inPackages) {
|
||||
const m = line.match(/^\s*-\s*['"]?([^'"#]+?)['"]?\s*(?:#.*)?$/);
|
||||
if (m) globs.push(m[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
globs = globs.filter((g) => typeof g === "string" && g.trim()).map((g) => g.trim().replace(/\/+$/, ""));
|
||||
const include = globs.filter((g) => !g.startsWith("!"));
|
||||
const exclude = globs.filter((g) => g.startsWith("!")).map((g) => g.slice(1));
|
||||
return [...dirs.keys()].filter((d) => d !== "." && include.some((g) => matchGlob(g, d)) && !exclude.some((g) => matchGlob(g, d))).sort();
|
||||
}
|
||||
|
||||
/** pytest is configured or listed in this folder's Python files. */
|
||||
function usesPytest(abs, files) {
|
||||
if (files.includes("pytest.ini")) return true;
|
||||
const pyproject = readText(path.join(abs, "pyproject.toml"));
|
||||
if (pyproject !== null && (/\[tool\.pytest/.test(pyproject) || /\bpytest\b/i.test(pyproject))) return true;
|
||||
const setup = readText(path.join(abs, "setup.cfg"));
|
||||
if (setup !== null && /\bpytest\b/i.test(setup)) return true;
|
||||
const tox = readText(path.join(abs, "tox.ini"));
|
||||
if (tox !== null && /\bpytest\b/i.test(tox)) return true;
|
||||
return files.some((f) => /^requirements.*\.txt$/i.test(f) && /^\s*pytest\b/im.test(readText(path.join(abs, f)) || ""));
|
||||
}
|
||||
|
||||
/** The Python files of this folder or a folder above it mention pytest-cov. */
|
||||
function usesPytestCov(root, cwd, dirs) {
|
||||
return [cwd, ...ancestors(cwd)].some((d) => {
|
||||
const files = dirs.get(d) || [];
|
||||
return ["pyproject.toml", "setup.cfg", "tox.ini", ...files.filter((f) => /^requirements.*\.txt$/i.test(f))]
|
||||
.some((f) => files.includes(f) && /pytest-cov/i.test(readText(path.join(root, d, f)) || ""));
|
||||
});
|
||||
}
|
||||
|
||||
export function discover(root) {
|
||||
const { dirs, counts } = walk(root);
|
||||
const rootFiles = dirs.get(".") || [];
|
||||
const pkg = readJson(path.join(root, "package.json"));
|
||||
const pm = packageManager(rootFiles);
|
||||
const runners = [];
|
||||
const coverage = [];
|
||||
const checks = [];
|
||||
const add = (list, item) => {
|
||||
if (!list.some((x) => x.cmd === item.cmd && x.cwd === item.cwd)) list.push(item);
|
||||
};
|
||||
|
||||
let suite = null;
|
||||
if (realTest(pkg)) suite = { cmd: `${pm} test`, why: "package.json scripts.test" };
|
||||
else if (hasMakeTest(readText(path.join(root, "Makefile")))) suite = { cmd: "make test", why: "Makefile test target" };
|
||||
|
||||
if (pkg && pkg.scripts) {
|
||||
const s = pkg.scripts;
|
||||
if (s.lint) checks.push({ kind: "lint", cmd: `${pm} run lint` });
|
||||
const types = ["typecheck", "type-check", "types", "tsc"].find((n) => s[n]);
|
||||
if (types) checks.push({ kind: "types", cmd: `${pm} run ${types}` });
|
||||
else if (rootFiles.includes("tsconfig.json")) checks.push({ kind: "types", cmd: "npx tsc --noEmit" });
|
||||
if (s.build) checks.push({ kind: "build", cmd: `${pm} run build` });
|
||||
} else if (rootFiles.includes("tsconfig.json")) checks.push({ kind: "types", cmd: "npx tsc --noEmit" });
|
||||
|
||||
// Node: the root package and each workspace with a test script.
|
||||
const nodeFolders = [{ cwd: ".", pkg }, ...workspaceFolders(root, pkg, dirs).map((cwd) => ({ cwd, pkg: readJson(path.join(root, cwd, "package.json")) }))];
|
||||
for (const { cwd, pkg: p } of nodeFolders) {
|
||||
const test = realTest(p);
|
||||
if (!test) continue;
|
||||
add(runners, { cmd: `${pm} test`, cwd, covers: covers(cwd) });
|
||||
const d = deps(p);
|
||||
if (/\bnode\s+--test\b/.test(test)) {
|
||||
add(coverage, { runner: "node", cmd: "node --test --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=\"<out>\"", cwd, reads: "lcov" });
|
||||
}
|
||||
if (d.jest || /\bjest\b/.test(test)) add(coverage, { runner: "jest", cmd: "npx jest --coverage --coverageReporters=lcov", cwd, reads: "lcov" });
|
||||
if (Object.keys(d).some((k) => k.startsWith("@vitest/coverage-"))) add(coverage, { runner: "vitest", cmd: "npx vitest run --coverage --coverage.reporter=lcov", cwd, reads: "lcov" });
|
||||
}
|
||||
|
||||
// Nested runner configs, walked in folder order.
|
||||
const cargoWorkspaces = new Set();
|
||||
const solutions = new Set();
|
||||
for (const [cwd, files] of [...dirs].sort(([a], [b]) => (a === "." ? -1 : b === "." ? 1 : a.localeCompare(b)))) {
|
||||
const abs = path.join(root, cwd);
|
||||
const before = runners.length;
|
||||
if (files.includes("go.mod")) {
|
||||
add(runners, { cmd: "go test ./...", cwd, covers: covers(cwd) });
|
||||
add(coverage, { runner: "go", cmd: "go test -coverprofile=\"<out>\" ./... && go tool cover -func=\"<out>\"", cwd, reads: "go-func" });
|
||||
}
|
||||
if (files.includes("Cargo.toml")) {
|
||||
const cargo = readText(path.join(abs, "Cargo.toml")) || "";
|
||||
const isWorkspace = /^\[workspace\]/m.test(cargo);
|
||||
// A member of a Cargo workspace already runs from the workspace root.
|
||||
const inWorkspace = ancestors(cwd).some((a) => cargoWorkspaces.has(a));
|
||||
if (isWorkspace) cargoWorkspaces.add(cwd);
|
||||
if (!inWorkspace && (isWorkspace || /^\[package\]/m.test(cargo))) add(runners, { cmd: "cargo test", cwd, covers: covers(cwd) });
|
||||
}
|
||||
if (["pyproject.toml", "setup.cfg", "pytest.ini", "tox.ini"].some((f) => files.includes(f))) {
|
||||
if (usesPytest(abs, files)) {
|
||||
add(runners, { cmd: "python -m pytest", cwd, covers: covers(cwd) });
|
||||
if (usesPytestCov(root, cwd, dirs)) add(coverage, { runner: "pytest", cmd: "python -m pytest --cov --cov-report=lcov:\"<out>\"", cwd, reads: "lcov" });
|
||||
} else add(runners, { cmd: "python -m unittest", cwd, covers: covers(cwd) });
|
||||
}
|
||||
const dotnet = files.some((f) => /\.(csproj|sln)$/i.test(f));
|
||||
// Projects under a solution already run from the solution's folder.
|
||||
if (dotnet && !ancestors(cwd).some((a) => solutions.has(a))) {
|
||||
if (files.some((f) => /\.sln$/i.test(f))) solutions.add(cwd);
|
||||
add(runners, { cmd: "dotnet test", cwd, covers: covers(cwd) });
|
||||
const prefix = cwd === "." ? "" : `${cwd}/`;
|
||||
const coverlet = [...dirs].some(([d, fs2]) => (cwd === "." || d === cwd || d.startsWith(prefix)) && fs2.some((f) => /\.csproj$/i.test(f) && /coverlet\.collector/i.test(readText(path.join(root, d, f)) || "")));
|
||||
if (coverlet) add(coverage, { runner: "dotnet", cmd: 'dotnet test --collect:"XPlat Code Coverage"', cwd, reads: "lcov" });
|
||||
}
|
||||
// make test is the folder's runner only when nothing else runs there.
|
||||
const hasNode = runners.slice(0, before).some((r) => r.cwd === cwd);
|
||||
if (runners.length === before && !hasNode && files.includes("Makefile") && hasMakeTest(readText(path.join(abs, "Makefile")))) {
|
||||
add(runners, { cmd: "make test", cwd, covers: covers(cwd) });
|
||||
}
|
||||
}
|
||||
|
||||
let builtin = null;
|
||||
if (!suite && !runners.length) {
|
||||
const present = [];
|
||||
if (pkg || rootFiles.includes("package.json")) present.push("node");
|
||||
if (counts.python) present.push("python");
|
||||
if (present.length) {
|
||||
present.sort((a, b) => counts[b] - counts[a]);
|
||||
const [first, ...rest] = present;
|
||||
builtin = { language: first, cmd: BUILTIN[first] };
|
||||
if (rest.length) builtin.others = rest.map((language) => ({ language, cmd: BUILTIN[language] }));
|
||||
}
|
||||
}
|
||||
|
||||
return { ok: true, suite, runners, checks, coverage, builtin };
|
||||
}
|
||||
|
||||
async function main(argv) {
|
||||
const args = parseArgs(argv, { values: ["root"] });
|
||||
const cmd = args._[0];
|
||||
if (cmd !== "discover") fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", "Commands: discover. Run with --help.");
|
||||
const root = path.resolve(args.root || ".");
|
||||
if (!isDir(root)) fail(EXIT.NOT_FOUND, "no-root", `No folder at ${root}.`, "Pass the project folder with --root, or run from the project root.");
|
||||
out(discover(root));
|
||||
}
|
||||
|
||||
// Run as a script; imported, do nothing.
|
||||
const isMain = (() => {
|
||||
try {
|
||||
return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
})();
|
||||
if (isMain) run(USAGE, main);
|
||||
@@ -0,0 +1,331 @@
|
||||
#!/usr/bin/env node
|
||||
// test-map.mjs: read and write the project test map.
|
||||
//
|
||||
// The test map is one Markdown table under a `## Test map` heading in
|
||||
// AGENTS.md, or in .agents-docs/AGENTS-test-map.md behind one link from that
|
||||
// section: `| Area | Paths | Run | Shared |`. It tells pr-prep and test which
|
||||
// checks cover which files. Parsing it, validating its globs and rewriting it
|
||||
// without touching any other line are mechanical, so they live here; what goes
|
||||
// in the rows is the agent's call.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { EXIT, fail, out, parseArgs, run, readText, writeIfChanged, eol } from "./common.mjs";
|
||||
import { toPosix, unsupported } from "./glob.mjs";
|
||||
|
||||
const USAGE = `
|
||||
test-map.mjs: the project test map (## Test map in AGENTS.md). JSON on stdout.
|
||||
|
||||
node test-map.mjs read [--root <dir>]
|
||||
The table's rows: { area, paths[], run, shared }, read from AGENTS.md
|
||||
or from the one .agents-docs/ file its Test map section links to.
|
||||
found is false when AGENTS.md has no ## Test map heading. problems lists
|
||||
what could not be read (a missing column, an unsupported glob, a Shared
|
||||
value that is not yes or no, a link outside .agents-docs/).
|
||||
|
||||
node test-map.mjs write --rows <file.json> [--dry-run] [--root <dir>]
|
||||
Write the table from a JSON array of { area, paths: [..], run, shared }.
|
||||
An existing table is replaced in place, a heading with no table gets
|
||||
one, and no heading appends a ## Test map section to AGENTS.md. Every
|
||||
line outside the table stays byte-identical.
|
||||
|
||||
Globs: ** (any folders), * and ? (within one folder), {a,b}. Anything else is
|
||||
a problem and matches nothing.
|
||||
|
||||
Exit: 0 ok (check "found") · 2 bad arguments · 3 no AGENTS.md, or no --rows
|
||||
file · 4 invalid rows · 5 refused: the section links outside .agents-docs/.
|
||||
`;
|
||||
|
||||
const HEADING = /^## +test map\s*$/i;
|
||||
const FENCE = /^\s*(```|~~~)/;
|
||||
const COLUMNS = ["area", "paths", "run", "shared"];
|
||||
|
||||
/** Split text into lines, keeping track of which sit inside a code fence. */
|
||||
function linesOf(text) {
|
||||
const lines = text.split(/\r?\n/);
|
||||
let inFence = false;
|
||||
const fenced = lines.map((l) => {
|
||||
if (FENCE.test(l)) {
|
||||
inFence = !inFence;
|
||||
return true;
|
||||
}
|
||||
return inFence;
|
||||
});
|
||||
return { lines, fenced };
|
||||
}
|
||||
|
||||
/** The Test map section: heading line index and body [start, end) line range. */
|
||||
function findSection(lines, fenced) {
|
||||
const at = lines.findIndex((l, i) => !fenced[i] && HEADING.test(l));
|
||||
if (at === -1) return null;
|
||||
let end = lines.length;
|
||||
for (let i = at + 1; i < lines.length; i++) {
|
||||
if (!fenced[i] && /^#{1,2} /.test(lines[i])) {
|
||||
end = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { heading: at, start: at + 1, end };
|
||||
}
|
||||
|
||||
const isRow = (l) => /^\s*\|/.test(l);
|
||||
const isSeparator = (l) => /^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)*\|?\s*$/.test(l);
|
||||
|
||||
/** The first table between start and end, outside fences: [start, end) or null. */
|
||||
function findTable(lines, fenced, start, end) {
|
||||
for (let i = start; i < end - 1; i++) {
|
||||
if (fenced[i] || !isRow(lines[i]) || !isSeparator(lines[i + 1])) continue;
|
||||
let j = i + 2;
|
||||
while (j < end && !fenced[j] && isRow(lines[j])) j++;
|
||||
return { start: i, end: j };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Cells of one table row; `\|` stays inside its cell as `|`. */
|
||||
function cellsOf(line) {
|
||||
let s = line.trim();
|
||||
if (s.startsWith("|")) s = s.slice(1);
|
||||
if (s.endsWith("|") && !s.endsWith("\\|")) s = s.slice(0, -1);
|
||||
const cells = [];
|
||||
let cur = "";
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
if (s[i] === "\\" && s[i + 1] === "|") {
|
||||
cur += "|";
|
||||
i++;
|
||||
} else if (s[i] === "|") {
|
||||
cells.push(cur.trim());
|
||||
cur = "";
|
||||
} else cur += s[i];
|
||||
}
|
||||
cells.push(cur.trim());
|
||||
return cells;
|
||||
}
|
||||
|
||||
const unquote = (s) => (s.length >= 2 && s.startsWith("`") && s.endsWith("`") ? s.slice(1, -1).trim() : s);
|
||||
|
||||
/** A Paths cell split on commas outside braces and backticks. */
|
||||
function splitPaths(cell) {
|
||||
const parts = [];
|
||||
let cur = "";
|
||||
let depth = 0;
|
||||
let tick = false;
|
||||
for (const ch of cell) {
|
||||
if (ch === "`") tick = !tick;
|
||||
else if (!tick && ch === "{") depth++;
|
||||
else if (!tick && ch === "}") depth = Math.max(0, depth - 1);
|
||||
if (ch === "," && depth === 0 && !tick) {
|
||||
parts.push(cur);
|
||||
cur = "";
|
||||
} else cur += ch;
|
||||
}
|
||||
parts.push(cur);
|
||||
return parts.map((p) => unquote(p.trim())).filter(Boolean);
|
||||
}
|
||||
|
||||
/** Rows and problems from the table's lines. */
|
||||
function parseTable(lines, table) {
|
||||
const problems = [];
|
||||
const header = cellsOf(lines[table.start]).map((c) => c.toLowerCase());
|
||||
const index = Object.fromEntries(COLUMNS.map((c) => [c, header.indexOf(c)]));
|
||||
const missing = COLUMNS.filter((c) => index[c] === -1);
|
||||
if (missing.length) {
|
||||
const names = missing.map((c) => c[0].toUpperCase() + c.slice(1));
|
||||
return { rows: [], problems: [`The test map table has no ${names.join(", ")} column${names.length > 1 ? "s" : ""}; no rows were read`] };
|
||||
}
|
||||
const rows = [];
|
||||
for (let i = table.start + 2; i < table.end; i++) {
|
||||
const cells = cellsOf(lines[i]);
|
||||
if (cells.every((c) => !c)) continue;
|
||||
const n = rows.length + 1;
|
||||
const area = cells[index.area] || "";
|
||||
const label = `Row ${n}${area ? ` (${area})` : ""}`;
|
||||
const paths = [];
|
||||
for (const glob of splitPaths(cells[index.paths] || "")) {
|
||||
const why = unsupported(glob);
|
||||
if (why) problems.push(`${label}: path "${glob}" was dropped: ${why}`);
|
||||
else paths.push(toPosix(glob));
|
||||
}
|
||||
const sharedCell = (cells[index.shared] || "").trim();
|
||||
const yes = /^yes$/i.test(sharedCell);
|
||||
if (!yes && !/^no$/i.test(sharedCell)) problems.push(`${label}: Shared is "${sharedCell}", not yes or no; read as no`);
|
||||
rows.push({ area, paths, run: unquote(cells[index.run] || ""), shared: yes });
|
||||
}
|
||||
return { rows, problems };
|
||||
}
|
||||
|
||||
/**
|
||||
* The section body's link into .agents-docs/ (`docs`, the path under it);
|
||||
* with none, `outside` holds the first other relative .md link.
|
||||
*/
|
||||
function linkIn(lines, fenced, start, end) {
|
||||
let outside = null;
|
||||
for (let i = start; i < end; i++) {
|
||||
if (fenced[i]) continue;
|
||||
for (const m of lines[i].matchAll(/\]\(([^)\s]+)\)/g)) {
|
||||
const target = m[1].replace(/#.*$/, "");
|
||||
if (/^[a-z][a-z0-9+.-]*:/i.test(target) || !/\.md$/i.test(target)) continue;
|
||||
const norm = path.posix.normalize(toPosix(target));
|
||||
if (/^\.agents-docs\/.+\.md$/i.test(norm)) return { docs: norm };
|
||||
outside ??= target;
|
||||
}
|
||||
}
|
||||
return outside === null ? null : { outside };
|
||||
}
|
||||
|
||||
/**
|
||||
* The test map of the project at `root`. Never throws for a missing map:
|
||||
* `agentsMd` false means there is no AGENTS.md, `found` false no heading.
|
||||
* `file` is the absolute path the table lives in (or would be written to).
|
||||
*/
|
||||
export function readTestMap(root) {
|
||||
const agentsFile = path.join(root, "AGENTS.md");
|
||||
const text = readText(agentsFile);
|
||||
if (text === null) return { agentsMd: false, found: false, source: null, rows: [], problems: [] };
|
||||
const { lines, fenced } = linesOf(text);
|
||||
const section = findSection(lines, fenced);
|
||||
if (!section) return { agentsMd: true, found: false, source: null, rows: [], problems: [] };
|
||||
const link = linkIn(lines, fenced, section.start, section.end);
|
||||
if (link && link.outside) {
|
||||
return { agentsMd: true, found: true, source: "AGENTS.md", rows: [], linkOutside: link.outside, problems: [`The Test map section links to ${link.outside}, outside .agents-docs/; no table was read`] };
|
||||
}
|
||||
if (link && link.docs) {
|
||||
const file = path.join(root, link.docs);
|
||||
const linked = readText(file);
|
||||
if (linked === null) return { agentsMd: true, found: true, source: link.docs, file, rows: [], problems: [`The Test map section links to ${link.docs}, which does not exist`] };
|
||||
const l = linesOf(linked);
|
||||
const table = findTable(l.lines, l.fenced, 0, l.lines.length);
|
||||
if (!table) return { agentsMd: true, found: true, source: link.docs, file, rows: [], problems: [`${link.docs} has no table`] };
|
||||
return { agentsMd: true, found: true, source: link.docs, file, ...parseTable(l.lines, table) };
|
||||
}
|
||||
const table = findTable(lines, fenced, section.start, section.end);
|
||||
if (!table) return { agentsMd: true, found: true, source: "AGENTS.md", file: agentsFile, rows: [], problems: ["The Test map section has no table"] };
|
||||
return { agentsMd: true, found: true, source: "AGENTS.md", file: agentsFile, ...parseTable(lines, table) };
|
||||
}
|
||||
|
||||
const cell = (s) => String(s).replace(/\|/g, "\\|");
|
||||
|
||||
/** The table's lines for `rows`. */
|
||||
export function renderTable(rows) {
|
||||
return [
|
||||
"| Area | Paths | Run | Shared |",
|
||||
"|---|---|---|---|",
|
||||
...rows.map((r) => `| ${cell(r.area)} | ${r.paths.map((p) => `\`${cell(p)}\``).join(", ")} | \`${cell(r.run)}\` | ${r.shared ? "yes" : "no"} |`),
|
||||
];
|
||||
}
|
||||
|
||||
function validRows(data) {
|
||||
if (!Array.isArray(data)) fail(EXIT.INVALID, "invalid-rows", "The rows file must hold a JSON array of { area, paths, run, shared }.", "Fix the rows file and run write again.");
|
||||
return data.map((r, i) => {
|
||||
const bad = (what) => fail(EXIT.INVALID, "invalid-rows", `Row ${i} ${what}.`, "Fix the rows file and run write again.", { row: i });
|
||||
if (!r || typeof r !== "object") bad("is not an object");
|
||||
if (typeof r.area !== "string" || !r.area.trim()) bad("has no area");
|
||||
if (typeof r.run !== "string" || !r.run.trim()) bad("has no run command");
|
||||
if (!Array.isArray(r.paths) || !r.paths.length || r.paths.some((p) => typeof p !== "string" || !p.trim())) bad("has no paths");
|
||||
// A backtick or line break would break the table; an unsupported glob
|
||||
// would be written, then dropped by the next read.
|
||||
if ([r.area, r.run, ...r.paths].some((s) => /[`\r\n]/.test(s))) bad("has a backtick or line break in a cell");
|
||||
for (const p of r.paths) {
|
||||
const why = unsupported(p.trim());
|
||||
if (why) bad(`has an unsupported glob "${p.trim()}": ${why}`);
|
||||
}
|
||||
return { area: r.area.trim(), paths: r.paths.map((p) => toPosix(p.trim())), run: r.run.trim(), shared: r.shared === true };
|
||||
});
|
||||
}
|
||||
|
||||
// Insert `table` into `lines` at index `at`, with a blank line before it and
|
||||
// one after it unless one is already there.
|
||||
function insertAt(lines, at, table) {
|
||||
const after = at < lines.length && lines[at] !== "" ? [""] : [];
|
||||
return [...lines.slice(0, at), "", ...table, ...after, ...lines.slice(at)];
|
||||
}
|
||||
|
||||
/** The new text of a file whose Test map section (or whole body) gets `table`. */
|
||||
function placeIn(text, table, { linked }) {
|
||||
const nl = eol(text);
|
||||
const { lines, fenced } = linesOf(text);
|
||||
if (linked) {
|
||||
const t = findTable(lines, fenced, 0, lines.length);
|
||||
if (t) return [...lines.slice(0, t.start), ...table, ...lines.slice(t.end)].join(nl);
|
||||
const trimmed = text.replace(/(\r?\n)*$/, "");
|
||||
return `${trimmed}${nl}${nl}${table.join(nl)}${nl}`;
|
||||
}
|
||||
const section = findSection(lines, fenced);
|
||||
if (!section) {
|
||||
const lead = text === "" || text.endsWith("\n") ? "" : nl;
|
||||
return `${text}${lead}${nl}## Test map${nl}${nl}${table.join(nl)}${nl}`;
|
||||
}
|
||||
const t = findTable(lines, fenced, section.start, section.end);
|
||||
if (t) return [...lines.slice(0, t.start), ...table, ...lines.slice(t.end)].join(nl);
|
||||
// After the heading's first paragraph, or right under the heading.
|
||||
let i = section.start;
|
||||
while (i < section.end && lines[i].trim() === "") i++;
|
||||
let at = section.start;
|
||||
if (i < section.end && !fenced[i] && !/^#{1,6}(\s|$)/.test(lines[i])) {
|
||||
while (i < section.end && lines[i].trim() !== "") i++;
|
||||
at = i;
|
||||
}
|
||||
return insertAt(lines, at, table).join(nl);
|
||||
}
|
||||
|
||||
function write(root, rowsFile, dryRun) {
|
||||
const raw = readText(path.resolve(rowsFile));
|
||||
if (raw === null) fail(EXIT.NOT_FOUND, "no-rows-file", `No rows file at ${rowsFile}.`, "Write the rows as a JSON array to a file and pass its path to --rows.");
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(raw);
|
||||
} catch (err) {
|
||||
fail(EXIT.INVALID, "invalid-rows", `The rows file is not JSON: ${err.message}`, "Fix the rows file and run write again.");
|
||||
}
|
||||
const rows = validRows(data);
|
||||
const map = readTestMap(root);
|
||||
if (!map.agentsMd) fail(EXIT.NOT_FOUND, "no-agents-md", `No AGENTS.md in ${root}.`, "Create AGENTS.md first (Init), then write the test map.");
|
||||
if (map.linkOutside) fail(EXIT.REFUSED, "link-outside", `The Test map section links to ${map.linkOutside}, outside .agents-docs/.`, "Point the link at .agents-docs/AGENTS-test-map.md, or remove it, then write again.");
|
||||
const table = renderTable(rows);
|
||||
const linked = map.source && map.source !== "AGENTS.md";
|
||||
let file;
|
||||
let next;
|
||||
if (linked) {
|
||||
file = map.file;
|
||||
const current = readText(file);
|
||||
next =
|
||||
current === null
|
||||
? ["# Test map", "", `> Part of [AGENTS.md](${"../".repeat(map.source.split("/").length - 1)}AGENTS.md): which checks cover which files.`, "", ...table, ""].join(eol(readText(path.join(root, "AGENTS.md")) || "\n"))
|
||||
: placeIn(current, table, { linked: true });
|
||||
} else {
|
||||
file = path.join(root, "AGENTS.md");
|
||||
next = placeIn(readText(file), table, { linked: false });
|
||||
}
|
||||
const source = linked ? map.source : "AGENTS.md";
|
||||
const written = dryRun ? false : writeIfChanged(file, next);
|
||||
return { ok: true, written, source, dryRun: !!dryRun };
|
||||
}
|
||||
|
||||
async function main(argv) {
|
||||
const args = parseArgs(argv, { values: ["root", "rows"], booleans: ["dry-run"] });
|
||||
const root = path.resolve(args.root || ".");
|
||||
const cmd = args._[0];
|
||||
if (cmd === "read") {
|
||||
const map = readTestMap(root);
|
||||
if (!map.agentsMd) fail(EXIT.NOT_FOUND, "no-agents-md", `No AGENTS.md in ${root}.`, "There is no test map to read; offer to create AGENTS.md (Init).");
|
||||
out({ ok: true, found: map.found, source: map.source, rows: map.rows, problems: map.problems });
|
||||
return;
|
||||
}
|
||||
if (cmd === "write") {
|
||||
if (!args.rows) fail(EXIT.USAGE, "missing-rows", "write needs --rows <file.json>.", "Run with --help for usage.");
|
||||
out(write(root, args.rows, args["dry-run"]));
|
||||
return;
|
||||
}
|
||||
fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", "Commands: read, write. Run with --help.");
|
||||
}
|
||||
|
||||
// Run as a script; imported (by test-match.mjs), do nothing.
|
||||
const isMain = (() => {
|
||||
try {
|
||||
return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
})();
|
||||
if (isMain) run(USAGE, main);
|
||||
@@ -0,0 +1,581 @@
|
||||
#!/usr/bin/env node
|
||||
// test-match.mjs: files to tests, in both directions.
|
||||
//
|
||||
// pr-prep asks which checks cover a branch's changed files; test asks which
|
||||
// source files no test covers, and which existing tests to read for style.
|
||||
// Both answers come from the same rules, in the same order: the project's
|
||||
// test map first, then name, folder and import matching. Anything these rules
|
||||
// cannot settle (a path alias, a bare package name) is left unmatched for the
|
||||
// agent to judge, never guessed.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { EXIT, HERE, fail, out, parseArgs, run, readText, isDir, now } from "./common.mjs";
|
||||
import { toPosix, matchGlob } from "./glob.mjs";
|
||||
import { readTestMap } from "./test-map.mjs";
|
||||
|
||||
const USAGE = `
|
||||
test-match.mjs: match files to tests, both ways. JSON on stdout.
|
||||
|
||||
node test-match.mjs covers (--files <a,b,...> | --stdin) [--root <dir>]
|
||||
Changed files to the checks that cover them. --stdin takes
|
||||
review-scope.mjs JSON (files[].path). matched: test map rows that cover
|
||||
at least one file, in table order. unmatched: { file, tests, method }
|
||||
for every file no row covers; tests and method come from the name,
|
||||
folder and import rules (method null when nothing was found).
|
||||
sharedHits: { file, why }: why is "row" (a Shared: yes row) or a hint
|
||||
for the agent to judge ("config", "test-helper", "fixture").
|
||||
|
||||
node test-match.mjs gaps --scope branch|all|path [--path <p>] [--base <b>] [--root <dir>]
|
||||
Source files no test covers: { file, area, runner, commits90d,
|
||||
lastTouched }, newest first, then by commits in the last 90 days.
|
||||
branch: the files review-scope.mjs reports; all: every tracked file;
|
||||
path: every file under --path. Capped at 2,000 source files (capped).
|
||||
|
||||
node test-match.mjs nearest --file <f> [--root <dir>]
|
||||
Up to 3 existing test files to read for the project's test style.
|
||||
|
||||
Exit: 0 ok · 2 bad arguments · 3 not a git repository, or review-scope.mjs
|
||||
not beside this script (gaps --scope branch).
|
||||
`;
|
||||
|
||||
/* ------------------------------------------------------------- files */
|
||||
|
||||
const SKIP_DIRS = new Set(["node_modules", ".git", "dist", "build", "vendor", "target", ".venv"]);
|
||||
const TEST_DIRS = new Set(["test", "tests", "__tests__", "spec"]);
|
||||
const CODE_EXT = new Set(["js", "mjs", "cjs", "ts", "tsx", "jsx", "py", "go", "rs", "java", "kt", "cs", "rb", "php", "swift"]);
|
||||
const SOURCE_SKIP = new Set(["node_modules", "vendor", "dist", "build", "target", ".venv", "specs", "specs--completed"]);
|
||||
const CAP = 2000;
|
||||
|
||||
const fold = (s) => (process.platform === "win32" ? s.toLowerCase() : s);
|
||||
const extOf = (p) => (path.posix.extname(p).slice(1) || "").toLowerCase();
|
||||
const baseOf = (p) => path.posix.basename(p);
|
||||
const dirOf = (p) => {
|
||||
const d = path.posix.dirname(p);
|
||||
return d === "." ? "" : d;
|
||||
};
|
||||
const segs = (d) => (d ? d.split("/") : []);
|
||||
|
||||
function git(root, args) {
|
||||
try {
|
||||
return execFileSync("git", ["-c", "core.quotePath=false", ...args], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 256 * 1024 * 1024 });
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const inGit = (root) => git(root, ["rev-parse", "--show-toplevel"]) !== null;
|
||||
|
||||
function walk(root) {
|
||||
const found = [];
|
||||
const visit = (dir, relDir) => {
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
for (const e of entries) {
|
||||
const r = relDir ? `${relDir}/${e.name}` : e.name;
|
||||
if (e.isDirectory()) {
|
||||
if (!SKIP_DIRS.has(e.name)) visit(path.join(dir, e.name), r);
|
||||
} else if (e.isFile()) found.push(r);
|
||||
}
|
||||
};
|
||||
visit(root, "");
|
||||
return found;
|
||||
}
|
||||
|
||||
// Every file in the project, once per run: tracked plus untracked files git
|
||||
// does not ignore, or a walk outside git. Paths relative to root.
|
||||
const fileLists = new Map();
|
||||
function allFiles(root) {
|
||||
if (!fileLists.has(root)) {
|
||||
let list;
|
||||
if (inGit(root)) {
|
||||
const tracked = (git(root, ["ls-files"]) || "").split("\n");
|
||||
const untracked = (git(root, ["ls-files", "--others", "--exclude-standard"]) || "").split("\n");
|
||||
list = [...new Set([...tracked, ...untracked].filter(Boolean))].filter((f) => fs.existsSync(path.join(root, f)));
|
||||
} else list = walk(root);
|
||||
fileLists.set(root, list.map(toPosix).sort());
|
||||
}
|
||||
return fileLists.get(root);
|
||||
}
|
||||
|
||||
/** Is this path a test file by name or by folder? */
|
||||
export function isTestFile(p) {
|
||||
const file = toPosix(p);
|
||||
const base = baseOf(file);
|
||||
if (/\.(test|spec)\.[^./]+$/i.test(base)) return true;
|
||||
if (/^test_.+\.py$/i.test(base) || /_test\.py$/i.test(base) || /_test\.go$/i.test(base)) return true;
|
||||
if (/Tests?\.(java|kt|cs)$/.test(base)) return true;
|
||||
return segs(dirOf(file)).some((s) => TEST_DIRS.has(s));
|
||||
}
|
||||
|
||||
/** The project's test files with a code extension. */
|
||||
export function listTestFiles(root) {
|
||||
return allFiles(root).filter((f) => isTestFile(f) && (CODE_EXT.has(extOf(f)) || JS_EXT.has(extOf(f))));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- name and folder */
|
||||
|
||||
// A file's name without its extension and without test markers:
|
||||
// foo.test.js, test_foo.py, foo_test.go and FooTests.cs all give "foo"/"Foo".
|
||||
function stemOf(p) {
|
||||
const base = baseOf(p);
|
||||
const dot = base.lastIndexOf(".");
|
||||
let stem = dot > 0 ? base.slice(0, dot) : base;
|
||||
stem = stem.replace(/\.(test|spec)$/i, "");
|
||||
if (/^test_/i.test(stem) && extOf(p) === "py") stem = stem.slice(5);
|
||||
stem = stem.replace(/_test$/i, "");
|
||||
if (/^(java|kt|cs)$/.test(extOf(p))) stem = stem.replace(/Tests?$/, "");
|
||||
return stem;
|
||||
}
|
||||
|
||||
function nameMatch(source, test) {
|
||||
const ext = extOf(source);
|
||||
const stem = stemOf(source);
|
||||
const base = baseOf(test);
|
||||
const tdot = base.lastIndexOf(".");
|
||||
const tname = tdot > 0 ? base.slice(0, tdot) : base;
|
||||
const same = (a, b) => fold(a) === fold(b);
|
||||
if (ext === "py") return extOf(test) === "py" && (same(tname, `test_${stem}`) || same(tname, `${stem}_test`));
|
||||
if (ext === "go") return same(test, `${dirOf(source) ? `${dirOf(source)}/` : ""}${stem}_test.go`);
|
||||
if (ext === "cs" || ext === "java" || ext === "kt") return extOf(test) === ext && (same(tname, `${stem}Tests`) || same(tname, `${stem}Test`));
|
||||
const text = extOf(test);
|
||||
if (JS_EXT.has(ext) ? !JS_EXT.has(text) : text !== ext) return false;
|
||||
return same(tname, `${stem}.test`) || same(tname, `${stem}.spec`);
|
||||
}
|
||||
|
||||
// Does the test file sit in a test folder that mirrors the source file's
|
||||
// folder? src/a/b.js mirrors to src/a/__tests__/, tests/a/, test/src/a/ and
|
||||
// the like: the part of the path before the test folder must be an ancestor of
|
||||
// the source, and the part after it the rest of the source's folder (with a
|
||||
// leading src/ or lib/ optional).
|
||||
function mirrors(source, test) {
|
||||
const sd = segs(dirOf(source)).map(fold);
|
||||
const td = segs(dirOf(test)).map(fold);
|
||||
const k = td.findIndex((s) => TEST_DIRS.has(s));
|
||||
if (k === -1) return false;
|
||||
const prefix = td.slice(0, k);
|
||||
const rest = td.slice(k + 1);
|
||||
if (prefix.some((s, i) => sd[i] !== s)) return false;
|
||||
const remaining = sd.slice(prefix.length);
|
||||
const eq = (a, b) => a.length === b.length && a.every((s, i) => s === b[i]);
|
||||
if (eq(remaining, rest)) return true;
|
||||
return (remaining[0] === "src" || remaining[0] === "lib") && eq(remaining.slice(1), rest);
|
||||
}
|
||||
|
||||
const folderMatch = (source, test) => mirrors(source, test) && fold(stemOf(source)) === fold(stemOf(test));
|
||||
|
||||
/* --------------------------------------------------------------- imports */
|
||||
|
||||
const JS_EXT = new Set(["js", "mjs", "cjs", "ts", "tsx", "jsx", "mts", "cts"]);
|
||||
const JS_TRY = ["", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx"];
|
||||
const JS_PATTERNS = [
|
||||
/\bimport\s+(?:[\w*{}\s,$]+?\s+from\s+)?["']([^"'\n]+)["']/g,
|
||||
/\bexport\s+[\w*{}\s,$]+?\s+from\s+["']([^"'\n]+)["']/g,
|
||||
/\brequire\s*\(\s*["']([^"'\n]+)["']\s*\)/g,
|
||||
/\bimport\s*\(\s*["']([^"'\n]+)["']\s*\)/g,
|
||||
];
|
||||
|
||||
const isFile = (p) => {
|
||||
try {
|
||||
return fs.statSync(p).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// Repo-relative path for `p` (already posix, relative to root), or null when
|
||||
// it climbs out of the project.
|
||||
const inside = (p) => {
|
||||
const n = path.posix.normalize(p);
|
||||
return n === ".." || n.startsWith("../") || path.posix.isAbsolute(n) ? null : n;
|
||||
};
|
||||
|
||||
function resolveJs(root, test, spec) {
|
||||
if (!spec.startsWith("./") && !spec.startsWith("../")) return [];
|
||||
const target = inside(path.posix.join(dirOf(test) || ".", spec));
|
||||
if (!target) return [];
|
||||
for (const ext of JS_TRY) if (isFile(path.join(root, target + ext))) return [target + ext];
|
||||
for (const ext of JS_TRY.slice(1)) if (isFile(path.join(root, `${target}/index${ext}`))) return [`${target}/index${ext}`];
|
||||
return [];
|
||||
}
|
||||
|
||||
function resolvePyModule(root, bases, dotted) {
|
||||
const rel = dotted.split(".").filter(Boolean).join("/");
|
||||
if (!rel) return [];
|
||||
for (const base of bases) {
|
||||
const p = inside(base ? `${base}/${rel}` : rel);
|
||||
if (!p) continue;
|
||||
if (isFile(path.join(root, `${p}.py`))) return [`${p}.py`];
|
||||
if (isFile(path.join(root, `${p}/__init__.py`))) return [`${p}/__init__.py`];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function pythonImports(root, test, text) {
|
||||
const found = [];
|
||||
const own = dirOf(test);
|
||||
for (const m of text.matchAll(/^[ \t]*import[ \t]+([\w.]+(?:[ \t]*,[ \t]*[\w.]+)*)/gm)) {
|
||||
for (const name of m[1].split(",")) found.push(...resolvePyModule(root, ["", own], name.trim()));
|
||||
}
|
||||
for (const m of text.matchAll(/^[ \t]*from[ \t]+(\.*)([\w.]*)[ \t]+import[ \t]+\(?([\w\s,]+)/gm)) {
|
||||
const dots = m[1].length;
|
||||
const mod = m[2];
|
||||
const names = m[3].split(",").map((s) => s.trim().split(/\s+/)[0]).filter(Boolean);
|
||||
let bases;
|
||||
if (dots) {
|
||||
let base = own;
|
||||
for (let i = 1; i < dots; i++) base = dirOf(base);
|
||||
bases = [base];
|
||||
} else bases = ["", own];
|
||||
if (mod) found.push(...resolvePyModule(root, bases, mod));
|
||||
for (const n of names) found.push(...resolvePyModule(root, bases, mod ? `${mod}.${n}` : n));
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
// The module path and folder of the go.mod nearest to `file`, walking up.
|
||||
const goMods = new Map();
|
||||
function goModFor(root, file) {
|
||||
let dir = dirOf(file);
|
||||
for (;;) {
|
||||
const key = `${root}\0${dir}`;
|
||||
if (!goMods.has(key)) {
|
||||
const text = readText(path.join(root, dir, "go.mod"));
|
||||
const m = text && text.match(/^module\s+(\S+)/m);
|
||||
goMods.set(key, m ? { module: m[1], dir } : null);
|
||||
}
|
||||
if (goMods.get(key)) return goMods.get(key);
|
||||
if (!dir) return null;
|
||||
dir = dirOf(dir);
|
||||
}
|
||||
}
|
||||
|
||||
// Go imports name packages: the result is folders, prefixed "dir:".
|
||||
function goImports(root, test, text) {
|
||||
const mod = goModFor(root, test);
|
||||
if (!mod) return [];
|
||||
const specs = [];
|
||||
for (const m of text.matchAll(/^\s*import\s+(?:[\w.]+\s+)?"([^"]+)"/gm)) specs.push(m[1]);
|
||||
for (const m of text.matchAll(/^\s*import\s*\(([\s\S]*?)\)/gm)) {
|
||||
for (const l of m[1].matchAll(/(?:^|\n)\s*(?:[\w.]+\s+)?"([^"]+)"/g)) specs.push(l[1]);
|
||||
}
|
||||
const found = [];
|
||||
for (const s of specs) {
|
||||
if (s !== mod.module && !s.startsWith(`${mod.module}/`)) continue;
|
||||
const sub = s.slice(mod.module.length).replace(/^\//, "");
|
||||
const dir = inside([mod.dir, sub].filter(Boolean).join("/") || ".");
|
||||
if (dir) found.push(`dir:${dir === "." ? "" : dir}`);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
// Source path (or "dir:<folder>" for Go) to the test files that import it,
|
||||
// built once per root from every test file.
|
||||
const importIndexes = new Map();
|
||||
function importIndex(root, testFiles) {
|
||||
if (importIndexes.has(root)) return importIndexes.get(root);
|
||||
const index = new Map();
|
||||
const add = (target, test) => {
|
||||
const k = fold(target);
|
||||
if (!index.has(k)) index.set(k, new Set());
|
||||
index.get(k).add(test);
|
||||
};
|
||||
for (const test of testFiles) {
|
||||
const ext = extOf(test);
|
||||
if (!JS_EXT.has(ext) && ext !== "py" && ext !== "go") continue;
|
||||
const text = readText(path.join(root, test));
|
||||
if (text === null || text.length > 2 * 1024 * 1024) continue;
|
||||
if (JS_EXT.has(ext)) {
|
||||
for (const re of JS_PATTERNS) for (const m of text.matchAll(re)) for (const t of resolveJs(root, test, m[1])) add(t, test);
|
||||
} else if (ext === "py") for (const t of pythonImports(root, test, text)) add(t, test);
|
||||
else for (const t of goImports(root, test, text)) add(t, test);
|
||||
}
|
||||
importIndexes.set(root, index);
|
||||
return index;
|
||||
}
|
||||
|
||||
/**
|
||||
* The tests that cover `file` after the test map: by name, then by mirrored
|
||||
* folder, then by imports. `{ tests, method }`, method null when none did.
|
||||
*/
|
||||
export function findTests(root, file, testFiles = listTestFiles(root)) {
|
||||
const f = toPosix(file);
|
||||
const others = testFiles.filter((t) => fold(t) !== fold(f));
|
||||
const byName = others.filter((t) => nameMatch(f, t));
|
||||
if (byName.length) return { tests: byName, method: "name" };
|
||||
const byFolder = others.filter((t) => folderMatch(f, t));
|
||||
if (byFolder.length) return { tests: byFolder, method: "folder" };
|
||||
const index = importIndex(root, testFiles);
|
||||
const hits = new Set([...(index.get(fold(f)) || [])]);
|
||||
if (extOf(f) === "go" && !isTestFile(f)) for (const t of index.get(fold(`dir:${dirOf(f)}`)) || []) hits.add(t);
|
||||
hits.delete(f);
|
||||
if (hits.size) return { tests: [...hits].sort(), method: "imports" };
|
||||
return { tests: [], method: null };
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- covers */
|
||||
|
||||
const CONFIG_NAMES = new Set(["package.json", "package-lock.json", "pnpm-lock.yaml", "yarn.lock", "jsconfig.json", "pytest.ini", "pyproject.toml", "setup.cfg", "tox.ini", "go.mod", "go.sum", "cargo.toml", "makefile", "directory.build.props"]);
|
||||
|
||||
/** A shared-ground hint for a file the agent should judge, or null. */
|
||||
export function hintFor(file) {
|
||||
const f = toPosix(file);
|
||||
const base = baseOf(f);
|
||||
const lower = base.toLowerCase();
|
||||
const dirs = segs(dirOf(f));
|
||||
if (CONFIG_NAMES.has(lower) || /^tsconfig.*\.json$/i.test(base) || /\.config\.(js|cjs|mjs|ts)$/i.test(base) || /^\.babelrc/i.test(base) || /\.csproj$/i.test(base)) return "config";
|
||||
if (dirs.some((d) => ["fixtures", "__fixtures__", "testdata"].includes(d))) return "fixture";
|
||||
if (dirs.some((d) => ["helpers", "test-utils", "testutils", "support"].includes(d))) return "test-helper";
|
||||
if (/helpers/i.test(base) && /\.(js|mjs|ts|py|go)$/i.test(base) && dirs.some((d) => TEST_DIRS.has(d))) return "test-helper";
|
||||
return null;
|
||||
}
|
||||
|
||||
const rowMatches = (row, file) => row.paths.some((g) => matchGlob(g, file));
|
||||
|
||||
function covers(root, files) {
|
||||
const map = readTestMap(root);
|
||||
const rows = map.found ? map.rows : [];
|
||||
const matched = rows.map((r) => ({ area: r.area, run: r.run, shared: r.shared, files: [] }));
|
||||
const unmatched = [];
|
||||
const sharedHits = [];
|
||||
let testFiles;
|
||||
for (const file of files) {
|
||||
let hit = false;
|
||||
let sharedRow = false;
|
||||
rows.forEach((r, i) => {
|
||||
if (!rowMatches(r, file)) return;
|
||||
hit = true;
|
||||
matched[i].files.push(file);
|
||||
if (r.shared) sharedRow = true;
|
||||
});
|
||||
if (!hit) {
|
||||
testFiles ||= listTestFiles(root);
|
||||
const { tests, method } = findTests(root, file, testFiles);
|
||||
unmatched.push({ file, tests, method });
|
||||
}
|
||||
const why = sharedRow ? "row" : hintFor(file);
|
||||
if (why) sharedHits.push({ file, why });
|
||||
}
|
||||
return { ok: true, mapFound: map.found, matched: matched.filter((m) => m.files.length), unmatched, sharedHits };
|
||||
}
|
||||
|
||||
function readStdin() {
|
||||
try {
|
||||
return fs.readFileSync(0, "utf8");
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ gaps */
|
||||
|
||||
/**
|
||||
* The branch's changed files, relative to root, from review-scope.mjs, which
|
||||
* every skill that ships this script ships beside it. One list, never a copy
|
||||
* of its git commands that could drift from it.
|
||||
*/
|
||||
export function branchFiles(root, base) {
|
||||
const top = git(root, ["rev-parse", "--show-toplevel"]);
|
||||
if (top === null) fail(EXIT.NOT_FOUND, "not-a-repo", `${root} is not inside a git repository.`, "Use --scope all or --scope path, or ask which files to look at.");
|
||||
const prefix = (git(root, ["rev-parse", "--show-prefix"]) || "").trim();
|
||||
const scope = path.join(HERE, "review-scope.mjs");
|
||||
if (!fs.existsSync(scope)) fail(EXIT.NOT_FOUND, "review-scope-missing", "review-scope.mjs is not beside test-match.mjs.", "Reinstall the skill, or use --scope all or --scope path.");
|
||||
let stdout;
|
||||
try {
|
||||
stdout = execFileSync(process.execPath, [scope, "--root", root, ...(base ? ["--base", base] : [])], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 });
|
||||
} catch (err) {
|
||||
stdout = err.stdout;
|
||||
}
|
||||
let json;
|
||||
try {
|
||||
json = JSON.parse(stdout);
|
||||
} catch {
|
||||
fail(EXIT.CRASH, "review-scope-failed", "review-scope.mjs printed no JSON.", "Run review-scope.mjs on its own to see why.");
|
||||
}
|
||||
if (!json.ok) fail(EXIT.NOT_FOUND, json.error, json.message, json.next);
|
||||
const list = json.files.map((f) => f.path);
|
||||
return [...new Set(list.map(toPosix))]
|
||||
.filter((f) => f.startsWith(prefix))
|
||||
.map((f) => f.slice(prefix.length))
|
||||
.filter((f) => fs.existsSync(path.join(root, f)));
|
||||
}
|
||||
|
||||
function isSource(file) {
|
||||
const f = toPosix(file);
|
||||
if (!CODE_EXT.has(extOf(f)) || /\.d\.ts$/i.test(f) || isTestFile(f)) return false;
|
||||
return !segs(dirOf(f)).some((s) => SOURCE_SKIP.has(s));
|
||||
}
|
||||
|
||||
// Commits in the last 90 days per file, and the newest commit time, from one
|
||||
// git log read. Paths relative to root.
|
||||
function churn(root) {
|
||||
const prefix = (git(root, ["rev-parse", "--show-prefix"]) || "").trim();
|
||||
const since = new Date(now().getTime() - 90 * 24 * 3600 * 1000).toISOString();
|
||||
const text = git(root, ["log", `--since=${since}`, "--name-only", "--format=%x00%ct"]) || "";
|
||||
const stats = new Map();
|
||||
for (const chunk of text.split("\0")) {
|
||||
const lines = chunk.split("\n");
|
||||
const ts = Number(lines[0]);
|
||||
if (!ts) continue;
|
||||
for (const raw of new Set(lines.slice(1).filter(Boolean))) {
|
||||
if (!raw.startsWith(prefix)) continue;
|
||||
const f = raw.slice(prefix.length);
|
||||
const s = stats.get(f) || { commits: 0, newest: 0 };
|
||||
s.commits++;
|
||||
s.newest = Math.max(s.newest, ts);
|
||||
stats.set(f, s);
|
||||
}
|
||||
}
|
||||
return stats;
|
||||
}
|
||||
|
||||
function gaps(root, { scope, sub, base }) {
|
||||
const repo = inGit(root);
|
||||
let files;
|
||||
if (scope === "branch") files = branchFiles(root, base);
|
||||
else {
|
||||
files = allFiles(root);
|
||||
if (scope === "path") {
|
||||
const p = path.posix.normalize(toPosix(sub)).replace(/\/+$/, "");
|
||||
// The project root (".") is every file.
|
||||
if (p !== "." && p !== "") files = files.filter((f) => fold(f) === fold(p) || fold(f).startsWith(`${fold(p)}/`));
|
||||
}
|
||||
}
|
||||
let sources = [...new Set(files)].filter(isSource).sort();
|
||||
const capped = sources.length > CAP;
|
||||
if (capped) sources = sources.slice(0, CAP);
|
||||
const map = readTestMap(root);
|
||||
const rows = map.found ? map.rows : [];
|
||||
const testFiles = listTestFiles(root);
|
||||
const stats = repo ? churn(root) : null;
|
||||
const list = [];
|
||||
let covered = 0;
|
||||
for (const file of sources) {
|
||||
// Any matching row with a run command covers the file, as in covers, so
|
||||
// a gap's area is set only by a row that names it without one.
|
||||
const row = rows.find((r) => rowMatches(r, file));
|
||||
if (rows.some((r) => r.run && rowMatches(r, file)) || findTests(root, file, testFiles).tests.length) {
|
||||
covered++;
|
||||
continue;
|
||||
}
|
||||
const s = stats && stats.get(file);
|
||||
list.push({
|
||||
file,
|
||||
area: row ? row.area : null,
|
||||
runner: row && row.run ? row.run : null,
|
||||
commits90d: stats ? (s ? s.commits : 0) : null,
|
||||
lastTouched: s ? new Date(s.newest * 1000).toISOString().slice(0, 10) : null,
|
||||
});
|
||||
}
|
||||
list.sort((a, b) => {
|
||||
if (a.lastTouched !== b.lastTouched) {
|
||||
if (a.lastTouched === null) return 1;
|
||||
if (b.lastTouched === null) return -1;
|
||||
return a.lastTouched < b.lastTouched ? 1 : -1;
|
||||
}
|
||||
if ((b.commits90d || 0) !== (a.commits90d || 0)) return (b.commits90d || 0) - (a.commits90d || 0);
|
||||
return a.file < b.file ? -1 : a.file > b.file ? 1 : 0;
|
||||
});
|
||||
return { ok: true, scope, gaps: list, scanned: sources.length, covered, capped };
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- nearest */
|
||||
|
||||
// Path tokens in a Run command that name a file or folder in the project.
|
||||
function runPaths(root, cmd) {
|
||||
return (cmd || "")
|
||||
.split(/\s+/)
|
||||
.map((t) => toPosix(t.replace(/^["']|["']$/g, "")).replace(/\/+$/, ""))
|
||||
.filter((t) => t && !t.startsWith("-") && inside(t) && fs.existsSync(path.join(root, t)));
|
||||
}
|
||||
|
||||
function nearest(root, file) {
|
||||
const f = toPosix(file);
|
||||
const testFiles = listTestFiles(root).filter((t) => fold(t) !== fold(f));
|
||||
const picked = [];
|
||||
const take = (list) => {
|
||||
for (const t of list) {
|
||||
if (picked.length >= 3) return;
|
||||
if (!picked.includes(t)) picked.push(t);
|
||||
}
|
||||
};
|
||||
take(findTests(root, f, testFiles).tests);
|
||||
take(testFiles.filter((t) => fold(dirOf(t)) === fold(dirOf(f))));
|
||||
take(testFiles.filter((t) => mirrors(f, t)));
|
||||
if (picked.length < 3) {
|
||||
const map = readTestMap(root);
|
||||
const row = map.found ? map.rows.find((r) => rowMatches(r, f)) : null;
|
||||
if (row) {
|
||||
for (const p of runPaths(root, row.run)) {
|
||||
take(isDir(path.join(root, p)) ? testFiles.filter((t) => t.startsWith(`${p}/`)) : testFiles.filter((t) => t === p));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (picked.length < 3) {
|
||||
const mine = segs(dirOf(f));
|
||||
const shared = (t) => {
|
||||
const ts = segs(dirOf(t));
|
||||
let n = 0;
|
||||
while (n < mine.length && n < ts.length && fold(mine[n]) === fold(ts[n])) n++;
|
||||
return n;
|
||||
};
|
||||
// Same language first: a Python test teaches nothing about a JS file's style.
|
||||
const lang = (p) => (JS_EXT.has(extOf(p)) ? "js" : extOf(p));
|
||||
const other = (t) => (lang(t) === lang(f) ? 0 : 1);
|
||||
take([...testFiles].sort((a, b) => other(a) - other(b) || shared(b) - shared(a) || (a < b ? -1 : a > b ? 1 : 0)));
|
||||
}
|
||||
return { ok: true, file: f, tests: picked };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ main */
|
||||
|
||||
const listArg = (s) => String(s).split(",").map((x) => toPosix(x.trim())).filter(Boolean);
|
||||
|
||||
async function main(argv) {
|
||||
const args = parseArgs(argv, { values: ["root", "files", "scope", "path", "base", "file"], booleans: ["stdin"] });
|
||||
const root = path.resolve(args.root || ".");
|
||||
const cmd = args._[0];
|
||||
if (cmd === "covers") {
|
||||
let files;
|
||||
if (args.files) files = listArg(args.files);
|
||||
else if (args.stdin) {
|
||||
let json;
|
||||
try {
|
||||
json = JSON.parse(readStdin());
|
||||
} catch {
|
||||
fail(EXIT.USAGE, "bad-stdin", "--stdin needs review-scope.mjs JSON.", "Pipe review-scope.mjs output in, or pass --files.");
|
||||
}
|
||||
if (!json || !Array.isArray(json.files)) fail(EXIT.USAGE, "bad-stdin", "The JSON on stdin has no files list.", "Pipe review-scope.mjs output in, or pass --files.");
|
||||
files = json.files.filter((f) => f && typeof f.path === "string" && f.path).map((f) => toPosix(f.path)).filter(Boolean);
|
||||
} else fail(EXIT.USAGE, "missing-files", "covers needs --files <a,b,...> or --stdin.", "Run with --help for usage.");
|
||||
out(covers(root, [...new Set(files)]));
|
||||
return;
|
||||
}
|
||||
if (cmd === "gaps") {
|
||||
if (!["branch", "all", "path"].includes(args.scope)) fail(EXIT.USAGE, "bad-scope", "gaps needs --scope branch, all or path.", "Run with --help for usage.");
|
||||
if (args.scope === "path" && !args.path) fail(EXIT.USAGE, "missing-path", "--scope path needs --path <p>.", "Run with --help for usage.");
|
||||
out(gaps(root, { scope: args.scope, sub: args.path, base: args.base }));
|
||||
return;
|
||||
}
|
||||
if (cmd === "nearest") {
|
||||
if (!args.file) fail(EXIT.USAGE, "missing-file", "nearest needs --file <f>.", "Run with --help for usage.");
|
||||
out(nearest(root, args.file));
|
||||
return;
|
||||
}
|
||||
fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", "Commands: covers, gaps, nearest. Run with --help.");
|
||||
}
|
||||
|
||||
const isMain = (() => {
|
||||
try {
|
||||
return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
})();
|
||||
if (isMain) run(USAGE, main);
|
||||
@@ -48,10 +48,11 @@ import {
|
||||
workspaceForAgent,
|
||||
writeWorkspaceCursor,
|
||||
} from "./workspace.mjs";
|
||||
import { readPrHosts, resetSubagentCursor } from "./settings.mjs";
|
||||
import { readPrHosts, resetSubagentCursor, subagentStoreEntry } from "./settings.mjs";
|
||||
import { resetPointers } from "./pointers.mjs";
|
||||
import { WORKFLOWS, isWorkflow } from "./public/skills.js";
|
||||
import { startsClean } from "./public/hops.js";
|
||||
import { STRENGTH_ORDER } from "./strengths.mjs";
|
||||
import { snapshot } from "./git-repo.mjs";
|
||||
import { announcePage, currentSession, inAppSignal } from "./in-app.mjs";
|
||||
import { findAgent } from "./agent-lookup.mjs";
|
||||
@@ -107,6 +108,14 @@ const EMBED_API = 1;
|
||||
// The only workflows a loop drives (open --loop).
|
||||
const LOOP_WORKFLOWS = ["implement", "implement-review"];
|
||||
|
||||
// What the loop locks a session with: `driving`, and, when the app started this
|
||||
// phase on a strength, its word (PLAN2CODE_LOOP_STRENGTH), which the server's
|
||||
// Subagents sync reads so the phase's helpers follow it.
|
||||
function loopLock() {
|
||||
const strength = process.env.PLAN2CODE_LOOP_STRENGTH;
|
||||
return STRENGTH_ORDER.includes(strength) ? { driving: true, strength } : { driving: true };
|
||||
}
|
||||
|
||||
export async function cmdOpen() {
|
||||
trace("open: start");
|
||||
// A workflow the console does not know is refused first, before the pointer,
|
||||
@@ -256,7 +265,7 @@ export async function cmdOpen() {
|
||||
// without it (Fix it by hand, from a stop screen) is an ordinary,
|
||||
// unlocked session. `loopExpect` goes with the lock: the app restamps it
|
||||
// on its next look, so a stale setup never judges a new run.
|
||||
if (loopMode) s.loop = { driving: true };
|
||||
if (loopMode) s.loop = loopLock();
|
||||
else {
|
||||
delete s.loop;
|
||||
delete s.loopExpect;
|
||||
@@ -288,7 +297,7 @@ export async function cmdOpen() {
|
||||
// Only a freshly opened dashboard plays Planny's wake-up.
|
||||
if (args.workflow === "dashboard") state.wake = true;
|
||||
// Locked from the first frame, before the state is first written.
|
||||
if (loopMode) state.loop = { driving: true };
|
||||
if (loopMode) state.loop = loopLock();
|
||||
// The setup session's hand-over data (forCli + the token /handover
|
||||
// checks), created with the state so the first write already has it.
|
||||
if (args.workflow === "setup") {
|
||||
@@ -450,7 +459,11 @@ export async function cmdOpen() {
|
||||
// A standing instruction the new agent is owed, as a `reply` holding only
|
||||
// its lines; no key when nothing is owed.
|
||||
const subagentsOwed = () => {
|
||||
awaitSubagentSync(dir, state.workflow);
|
||||
// In a loop the setting must carry this phase's strength, or the stored one
|
||||
// when the phase has none, before the first block is built: a resume leaves
|
||||
// the earlier phase's strength in the setting until the server syncs.
|
||||
const expected = loopMode ? (state.loop && state.loop.strength) || subagentStoreEntry(worktree, state.workflow).strength : undefined;
|
||||
awaitSubagentSync(dir, state.workflow, expected);
|
||||
const [out, cursor] = withSubagents(dir, { reply: "" });
|
||||
return [cursor ? out : {}, cursor];
|
||||
};
|
||||
|
||||
@@ -553,12 +553,14 @@ export function advanceWorkspace(dir, changes) {
|
||||
// an older server, which never writes one: a short look, not the full wait.
|
||||
const SUBAGENT_SYNC_WAIT_MS = 1500;
|
||||
const SUBAGENT_SYNC_MISSING_MS = 250;
|
||||
export function awaitSubagentSync(dir, workflow) {
|
||||
export function awaitSubagentSync(dir, workflow, strength) {
|
||||
if (!offered(workflow)) return;
|
||||
const start = Date.now();
|
||||
for (;;) {
|
||||
const setting = readSubagentSetting(dir);
|
||||
if (setting && setting.workflow === workflow) return;
|
||||
// A loop phase's strength rides on the session's state: the setting must
|
||||
// carry it before the first block is built, or the agent hears the stored one.
|
||||
if (setting && setting.workflow === workflow && (!strength || setting.strength === strength)) return;
|
||||
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
|
||||
if (Date.now() - start >= budget) return;
|
||||
sleepSync(25);
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
Read only if a `run` was refused; your workflow notes give the exact `run` to post.
|
||||
|
||||
The meter is advice and never blocks. The console scores these launches itself when their session opens (post nothing for them): Plan, Revise plan, Document, Review, Quick task, Init, Init update, Finalize, Git, Changelog, X-ray, Diagnose. It also counts answers: every 2 cards answered in a send add a point; notes, Quick questions and buttons do not count.
|
||||
The meter is advice and never blocks. The console scores these launches itself when their session opens (post nothing for them): Plan, Revise plan, Document, Review, Quick task, Init, Init update, Finalize, Git, Changelog, X-ray, Diagnose, PR Prep, Test. It also counts answers: every 2 cards answered in a send add a point; notes, Quick questions and buttons do not count.
|
||||
|
||||
Per-unit work is yours: `{"run":{"event":"implement-phase","id":"phase-2","tasks":9}}`, one `run` per post, never reaching the page state.
|
||||
|
||||
- `event`: `pathfinder-chart`, `pathfinder-question` (scores nothing now), `pathfinder-research`, `plan`, `revise-plan`, `document`, `implement-phase`, `implement-review-phase`, `review`, `quick-task`, `init`, `init-update`, `finalize`, `handoff`, `git`, `changelog`, `xray`, `diagnose`, `git-commits`, `git-conflict`. An unknown event is exit 3. Post only the events your notes name: a launch the console scores already has its points.
|
||||
- `event`: `pathfinder-chart`, `pathfinder-question` (scores nothing now), `pathfinder-research`, `plan`, `revise-plan`, `document`, `implement-phase`, `implement-review-phase`, `review`, `quick-task`, `init`, `init-update`, `finalize`, `handoff`, `git`, `changelog`, `xray`, `diagnose`, `pr-prep`, `test`, `git-commits`, `git-conflict`. An unknown event is exit 3. Post only the events your notes name: a launch the console scores already has its points.
|
||||
- `id`: the unit (a question's slug, `phase-N`, `map`), non-empty. The same id in the same skill run is ignored.
|
||||
- `tasks`: only with `implement-phase` and `implement-review-phase`; the tasks completed (`[x]`, not blocked), a whole number 1 to 999. A phase scores one point per 3 tasks rounded up (Implement + Review one more for the review); without it, a flat 2 (or 3). It takes over the count from `headline.cleared`, never adding to it.
|
||||
- `commits`: only with `git-commits`; commits made, 1 to 999, one point per 2 rounded down.
|
||||