Harden the shared console install, launcher, Loop staging, spec state and prompts

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-08 13:48:28 -08:00
1 parent 120c259d9c
commit 3ee96834bf
130 files changed
+5988 -1434

No files matched your search

@@ -0,0 +1,64 @@
# Architecture: Activities (the games)
> Part of [AGENTS.md](../AGENTS.md) and the [Architecture index](./AGENTS-architecture.md): project guidance for AI coding agents.
One row per file of every game but Ghoul Rush (which has its own files: [core](./AGENTS-architecture-ghoul-core.md), [stages](./AGENTS-architecture-ghoul-stages.md), [rides](./AGENTS-architecture-ghoul-rides.md)), then the rules every game follows.
| File | Role |
|---|---|
| `public/activities.js` | the list of activities (`ACTIVITIES`: each game's id, title, picker card line `blurb` and module path) an optional `courses` list (Mini golf's six course ids, which open a course dashboard), `bestKey(id, course?)`, the flat looks.json key for its best score (`activityBestSnake`, one per golf course `activityBestGolfPirate` to `activityBestGolfFrost`, `activityBestTrails`, `activityBestBugs`, `activityBestDrive`, `activityBestStack`, `activityBestBumper`, `activityBestRapids`, `activityBestFuse`, `activityBestHop`, `activityBestBounce`, `activityBestGhoul`, `activityBestFlock`); lists Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, `bestKeys(entry)`, every best key a game keeps, and documents the game contract including the course parts (`courses` and `preview()` on the export, `setCourse()` and `course` on the game), the optional `pointer(type, x, y)`, `release(name)` (a game key let go) and `lowerIsBetter`; data only, imported by the page and by Node |
| `public/activities/snake.js` | Snake: its rules as plain exported functions and the game contract (`create({ canvas, tone, onScore })` returning `start`, `pause`, `resume`, `key`, `tick`, `resize`, `score`, `state`); it never runs a timer or listens for keys, so the Activities window drives it; 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 |
| `public/activities/bumper.js` | Bumper Ring: its rules and physics as plain exported functions (`newRound`, `newHeat`, `advance` on a fixed 4 ms sub-step over `round.input`, which `key()` and `release()` set, `push` (accel toward the held direction, capped at the top speed that way, drag easing a car to the floor's own speed), `collide` (circle bounce with restitution `BOUNCE`; the faster car rams and gives `SHOVE_BONUS` more, takes that much less back; under `IMPACT_SPEED` it is a lean, no bounce and no shove, so a pushing match goes to the stronger push), `dash`, `edgeGap` and `outOfRing` (a car is out when its center is past the edge or over an open hole; round or, in the Hall of Mirrors, square), `shrinkAt` and `nextShrinkIn` (whole for `SHRINK_START_MS`, `SHRINK_STEP` a step to `MIN_RING`, then after `SUDDEN_MS` sudden death to `LAST_RING`, under one car's radius, so every heat ends), `aim` (a rival's push, dash and target per personality, with panic near the edge and a sharpness-scaled chance to misjudge), `applyPower`, `spawnPad`, `creditKo` (the last toucher within `CREDIT_MS`, your hit carried through a rival counting as yours, and a rival you rammed into another keeping your credit, the carry lasting `CAROM_MS` from your hit; the combo, the double and the bait bonus), `rivalPower` and `arenaFor` (each built once per arena, since the rules ask every slice), `holeState`), the `ARENAS` (rivals, sharpness, shrink pace, then endless Finals past the ninth), the `RIVALS` personalities and the `POWERS` pads, and the game contract with `release()`; a rival winds a dash up for `WINDUP_MS` (shorter when sharper) before it goes, which is the player's moment to step aside; a big hit holds the action for `HIT_STOP_MS`; memo is the furthest arena reached, which can pass 9; a read-only `round` getter for the tests only. Hand-tuned from the brief's starting numbers (the changes are listed under "As built" in `game-ideas/bumper-ring.md`), aiming for heats of 20 to 60 s from arena 2 on |
| `public/activities/bumper-draw.js` | Bumper Ring's drawing: `drawScene(ctx, view)` from a plain view `bumper.js` builds (the round, the board geometry, the effects, the pill numbers), each arena's ring in its fixed palette (`themeFor`), the floor (ice, oil, holes, bumpers, the magnet, the warning bands), the cars (Planny upright at the wheel of a car in `--accent`, star eye and stick arms; rivals with a face each), the pills (laid out by `hudLayout`, which starts a row below rather than run into the ring's countdown or off the board), banners and the start and end strip, and `readColors(canvas)`; decides nothing |
| `public/activities/rapids.js` | Rapids Run: its rules as plain exported functions over a round on a river scrolling down a 64 unit wide field, 84 units of it on the board (`newRound(seed)`, `newRiver(seed)`, `buildStretch(river, n, random)` (a stretch's rows from its own seed, each row a center, width and island width: a calm opening, then drifts, narrows and islands, every bank slanting at most `SLOPE` a unit, every channel at least `MIN_CHANNEL` wide, then a `BASIN_W` basin on a boss stretch and the narrowing to the `DAM_W` dam; and its plan of foes, buoys and crates, none in the first `SAFE_START` (where you start again) or by the dam), `ensureRiver`, `riverAt` (a row's banks and island eased from the row before's, so they slant as drawn), `channelsAt`, `channelAt`, `isWater`, `onLand` (the hull sampled at seven points), `placeAt` (the start of a stretch, its dam whole and its plan loaded afresh), `advance` in 4 ms slices over `round.input`, which `key()` and `release()` set: steering eased in, the whirlpools' tug, the speed held (up, down or neither, times the stretch's `pace`), the battery drained (`DRAIN` a second cruising, more at speed), distance points, the guns (`FIRE_MS`, Spread's fan), shots against foes, the boss, the dam and buoys, the foes (skiffs and darters drift and turn at the banks, a darter swerves into your lane, gulls take off as you near and swoop across, sentries fire at you), the boss (`spawnBoss` holds the river and the battery; its volleys by kind), bolts, pickups (a buoy `BUOY_CHARGE`, the magnet's pull, crates), crashes (`lose`: a shield takes any crash but a flat battery and slides you off a bank; blinking for `GRACE_MS` after a restart), skims (`SKIM_POINTS` each `SKIM_MS` closer than `SKIM_GAP` at speed), the dam (`hitDam`, then past it the next stretch, with `FLAWLESS_POINTS` times it for no life lost), `hurtFoe` (the combo, up to `MAX_COMBO`), `hurtBoss` (a life back and a crate), `applyPower`, `stretchFor` (built once a stretch; past the eighth, Night Water 2, 3 and on), `underBanner`, `screenY`, `seeded`), the `FOES`, `BOSSES`, `POWERS` and `STRETCHES`, and the game contract with `release()` (held arrows steer, speed and slow, held space fires; a pause lets go of every key); memo is the furthest dam blasted, which can pass 8; a read-only `round` getter for the tests only. Tuned by a scratch sim: a careful bot clears a stretch in 20 to 35 seconds, and the battery runs flat for one that grabs too few buoys |
| `public/activities/rapids-draw.js` | Rapids Run's drawing: `drawScene(ctx, view)` from one view object `rapids.js` refills each frame, in field units: the strip above the field in the page's colors with the pills (laid out by `hudLayout`, which starts a second row rather than run off the board and centers its rows in the strip), the river a look at a time (`LOOKS`: meadow, autumn, canyon, marsh, dusk and night, each in fixed colors, the look changing at each dam): banded banks, the water between them with shore lines and flow streaks carried downstream by the view's clock, pointed islands, trees or rocks; the dam ahead (hazard stripes, a crack for every share knocked out, a trickle once it is close to going) and the broken one behind; charge buoys, crates with their glyphs, whirlpools, skiffs, darters, mines, bank sentries aiming at you and gull drones with their shadows; the mini-boss and its health bar; Planny's jet-skimmer in your highlight with a white trim (so a blue highlight still shows on blue water), his wake, jets, arms to the bars (up when a dam or a boss goes), his box and his star eye in your highlight, bobbing with the star spinning after a crash; shots, bolts, sparks, rings, floating words (kept on the field by `labelSpot`), the combo's big number, the battery gauge beside the field (green, amber, then red and blinking under the low mark), banners, and the start and end strip with the big final score and a dot per named stretch whose dam you have blasted; `readColors(canvas)`, `lookColor`, `inkOn`, `contrast`; decides nothing |
| `public/activities/flock.js` | Flock Dash: its rules as plain exported functions over a round scrolling right to left over a 96 by 54 unit field (`newRound(seed)`, `steer` (the leader eased up and down inside the `BAND_MIN` to `BAND_MAX` band at the left), `recordPath`, `placeFlock`, `screenX`, `collect` and `spawnStrays` (a stray joins the flock, the combo up to `MAX_COMBO` within `COMBO_MS`), `buildStage(seed, n)` (a stage's hazards by distance from its own seed, a clear `SAFE_START` and `SAFE_END`, and `clearGap` keeping a way through), `moveHazards`, `hazardHits`, `snapAt` (a snap drops the birds behind the one hit, `scattered` for `SCATTER_MS` so they can be picked up again), `hitLeader` (a life, or a shield; `GRACE_MS` after), `reachPortal` (the jet stream portal, the V of `V_POINTS` a bird when the flock has `min`, `FLAWLESS_POINTS` for no snap or life lost, and the final portal that sways), `applyPower` (crates: tailwind, shield up to `MAX_SHIELDS`, magnet), `banner`, `bannerRow`, `underBanner`, `advance` in `SLICE_MS` slices, `teaser`, `seeded`, `dealMusic`), the `STAGES` table (eight stages, each with its speed, length, stray gap, portal `min`, hazard weights and gap; the place to tune the difficulty), the `HAZARDS` (balloon, gust, stream, cluster, storm, kite, each from its own stage) and `POWERS`, and the game contract with `release()` (held arrows steer, a pause lets go of every key); the round also carries `events` (what the draw and the sounds react to) and `warned` (one gust or storm warning each); memo is the furthest stage reached. The flock is a recorded path with running arc length: follower k sits `k * SPACING` behind the leader along it, so it copies every turn at any speed. `MUSIC_TRACKS` names the five songs, dealt afresh each round |
| `public/activities/flock-draw.js` | Flock Dash's drawing: `drawScene(ctx, view)` and `hudLayout` from one view object `flock.js` refills each frame, in field units: the sunset sky (`SKIES`, one palette per stage: the sun sinking, clouds, a rim light from stage 6 and stars on the last), the hazards (balloons and bunches, the head-wind's warning band and gust, slipstreams, thunderheads with their flash and bolt, kites on their strings), the strays and scattered birds, the flock, Planny as the lead bird with a star for an eye, crates and the magnet ring, the tailwind streaks, the portal and the V, the pills (laid out by `hudLayout`, which shrinks them to fit the board), banners, and the end strip with the final score, the best and the teaser; `readColors(canvas)`; decides nothing |
| `public/activities/fuse.js` | Hot Potato: its rules as plain exported functions over a round on a 104 by 70 arena (`newRound`, `newMatch(round, venue)`, which lights each bomb on a rival, never you, in a match's first fuse, `advance` in 8 ms slices over `round.input`, which `key()` and `release()` set, `move` (speed eased toward the held direction at `GRIP`, a dash holding its line, belts and ice from the floor), `dash` (a holder's dash is a numbered lunge), `tag` (a holder touching a runner with no bomb passes it, never inside `NO_TAGBACK_MS` of the bomb changing hands, nor back to the one who just passed it within `TAGBACK_MS` while three or more are left, `tagBack`, with `tagSafe` saying who is safe that way for the drawing; a fuse under `PASS_FLOOR_MS`, `NO_TAGBACK_MS` plus `PASS_REACT_MS`, is raised to it on any pass, once a fuse for each runner (`bomb.lifted`); your pass scores, a hot one under `HOT_MS` as passed steps the streak), `burn` (Freeze takes its share first), `blast` (the holder out, everyone near knocked back, the match over when that was you or one is left), `nextFuse` (a survivor with no bomb, the next shorter fuse from `fuseFor`, never more bombs than one for every two left), `think` (a holder chases by its own flood-fill path, weighted toward a boxed-in or dashless target; a runner without a bomb scores candidate spots by the holders' path distance against its own and flees to the best; personalities bend both), `applyPower`, `spawnPickup`, `speedOf`, `clearLine`, `rivalPower` and `venueFor` (each built once per venue), `rivalColors(you)`), the `VENUES`, `LAYOUTS`, `RIVALS` and `POWERS`, and the game contract with `release()` (`key(name, repeat)` never dashes on a repeat); a rival holder winds up (`WINDUP_MS`, shorter when sharp) or, a Trickster, feints (`FAKE_MS`) before a lunge, and a runner a lunge comes at dodges once a lunge at its venue's odds after its reaction time; the fuse ticks quicker and higher as it burns down, on one clock however many bombs burn (yours, else the shortest); a bomb whose fuse has run out passes to nobody; memo is the furthest venue reached, which can pass 9; a read-only `round` getter for the tests only. Tuned by a scratch sim (see "As built" in `game-ideas/hot-potato.md`) |
| `public/activities/fuse-draw.js` | Hot Potato's drawing: `drawScene(ctx, view)` from one view object `fuse.js` refills each frame, in arena units: the strip above the arena in the page's colors with the pills (laid out by `hudLayout`, which starts a second row rather than run into the fuse and centers its rows in the strip), each venue's floor in its fixed palette (`themeFor`, `venueColor`), ice, running belts, the Rooftop's open edge, the things to run round, pickups, the runners (Planny on his feet with his star eye and stick arms, flailing while he holds a bomb, and still Planny when charred; arms and feet on the floor in `limbInk(level)`, the ink that stands out from that venue's tiles; rivals with a mark per personality; a white ring with a dark edge at the feet of a runner safe from a tag-back; the charred waddle to the nearest wall and the fall from the roof), the bomb over its holder (a red ball with a `<<<` band, growing and glowing as it burns, flashing white while it cannot be passed, its fuse a shortening curl with a spark, the last seconds in big numbers (under the holder's feet when there is no room above, `countY`), a hop across on a pass), blast clouds, the Blackout's dark worked out once a frame in cells, the red edge pulse in a fuse's last second, banners and the start and end strip with the big final score, and `readColors(canvas)`; decides nothing |
| `public/activities/hop.js` | Crossing Rush: its rules as plain exported functions over a round on a strip `COLS` (11) cells wide of 30 to 40 lanes, `VIEW_ROWS` (14) on the board at once (`newRound`, `newHeat(round, zone)`, which builds the heat's lanes from the round's seed, kept when a heat runs again, `buildLanes(zone, seed)` (groups of road, highway, ice, river, turtle, rapids or rail lanes with a grass row between each two, the zone's new thing first; the same seed builds the same lanes), `advance` in 8 ms slices (lanes flow, riders drift with their log, rivals choose, everyone is checked where they stand before any hop moves on, then hops and flights; hoppers home in the same slice finish by the moment each landed, a dead heat to you), `hop(round, hopper, dir)` (one cell, two with a Spring; a hopper counts in the cell it leaves for the first half and the one it lands on for the second; an icy lane slides it a cell more), `laneAt`, `occupied(round, row, col, atMs)` (a car or a train on it, or in a river no float or the edge, `atMs` ahead through `shiftAt`, which follows a lane's flips, surges and a Horn exactly), `sendBack` (to the last grass row, `safeBelow`, crediting a shove within `SHOVE_CREDIT_MS`), `shove(round, from, to)` (a cell the way `from` faces, only on a hopper `inReach` and never on one past the half of its hop home, once every `SHOVE_MS`), `plan(round, hopper, random, power)` (a look ahead of `LOOKAHEAD` to `LOOKAHEAD_SHARP` hops over the lanes as they will move, each hop followed by the hopper's wait where it lands; never a hop where it would be hit or fall in at full sharpness; a sloppy rival now and then hops on regardless), `applyPower`, `zoneFor` and `rivalPower` (each built once per zone), `rivalColors(you)`, `standings`), the `ZONES`, `RIVALS` and `POWERS`, and the game contract with `release()` (`key(name, repeat)` hops once a press: never on a repeat, never again until the arrow is let go, never with the press that plays on, and with one hop queued behind the one in the air; a pause drops what is held and the queue); rivals wait `REACT_MS` down to a sharp rival's after each landing, a Bruiser shoves anyone beside it into a lane, a Tagalong follows a row behind you and shoves near the top, and a rival that lets a shove go weighs the next one only after `SHOVE_LOOK_MS`; memo is the furthest zone reached, which can pass 9; a read-only `round` getter for the tests only. Tuned by a scratch sim (see "As built" in `game-ideas/crossing-rush.md`) |
| `public/activities/hop-draw.js` | Crossing Rush's drawing: `drawScene(ctx, view)` from one view object `hop.js` refills each frame, in board units: the strip above the field in the page's colors with the pills (laid out by `hudLayout`, which starts a second row rather than run into your place and centers its rows in the strip), the lanes in fixed colors (`LANES`, `lookOf`; pavement, grass with tufts, bushes and rocks, the checkered finish, roads with dashes and surge chevrons, icy roads, rivers with ripples and Rapids arrows, tracks with a signal that flashes while a train is coming), cars, vans, trucks, logs, turtles that sink and dive, the train, pickups, the hoppers (Planny on his stick feet with his star eye in every state: stretching mid-hop, spinning as he flies back, cheering, slumped when beaten; rival critters with a Hopper's ears, a Daredevil's goggles, a Bruiser's brow and a Tagalong's beak; arms and feet, and each rival's body edge, in `limbInk(look)`, the ink that stands out from that lane), a Shield's ring and a Spring's coil, staggered stars, arrows at the edge for hoppers out of view, the Night Market's dark (soft lights cut from a layer the size of the field with one gradient made with the layer, or in steps with no second canvas), the race bar in the page's colors, banners, and the start and end strip with the big final score; every word kept on the field by `labelSpot`, and `readColors(canvas)`, `zoneColor`; decides nothing |
| `public/activities/bounce.js` | Bounce Road: the cars, the hazards against them, the scoring and the round, as plain exported functions over a round on a road scrolling up a 72 unit wide field, 90 units of it on the board (it re-exports every rule of `bounce-road.js` and `bounce-rivals.js`, so the suite imports one module): `newRound(seed, random)`, `advance` in 4 ms slices over `round.input`, which `key()` and `release()` set (a jump press first, then your `move`, the rivals' `think` and `move`, the pads (a boost strip pushes you to `NITRO_TOP` for `BOOST_MS` even off the throttle, and the brake cuts it; a ramp launches any car crossing its lip quick enough `RAMP_AIR` the usual jump; a slick eases the steering at `SLICK_EASE` and makes a knock last for `SLICK_MS`), the bumps (`collide`: boxes pushed apart along the shallower overlap, side on a knock split by mass and harder for the car that did not steer in, end on speed passed forward, into a `HEAVY` truck's back at `CRASH_CLOSE` a crash; with Mega wheels a touch flattens; a close shave, `NEAR_GAP` or less between the boxes at speed and no touch, scores once), the barriers (a cone or a tire knocked flying slows you to `CONE_SLOW`; a block, pot or bucket nose first is a crash, from the side a push out), the hazards placed by the round's clock (a train hits a car on its track, a ball knocks a car by `BALL_KICK`, a sprinkler's jet pushes at `SPRAY_PUSH`, a drop falls `DROP_FALL_MS` after you come within `DROP_TRIGGER`, aimed at your line, and lies there after, a gust pushes at `WIND_PUSH`), then the ground (water or a hole under your middle a life, a flowerbed nose first a crash, a rival off the road out and yours within `CREDIT_MS`)), `jump`, `land` (on a car: flattened for its `points` times the chain up to `MAX_CHAIN`, a truck's roof `HAUL_POINTS`, the Monster a stomp, `STOMP_POINTS`, and on its last of `BOSS_HP` `BOSS_POINTS` times the lap and a life; on the road the chain ends, and the holes, trains, balls and barriers flown over and a ramp's big air score), `stunt` (a stunt's points times `comboOf(streak)`: every `COMBO_STEP` stunts within `STREAK_MS` of each other one more, up to `MAX_COMBO`), `lose` (a Bubble throws you clear instead), `applyPower`, `underBanner(round, y, cam)` (a rival, a coming train, a ball or a thing still falling in the strip) and `BANNER_Y`, `rivalColors(you)`), the `POWERS` (Spring, Bubble, Nitro, Mega wheels) and the game contract with `release()` (`key(name, repeat)`: held arrows drive and steer, space jumps once a press, never on a repeat or with the press that plays on, and a press up to `JUMP_BUFFER_MS` before a landing jumps on it; a pause lets go of every key and drops a press). A stage line scores `STAGE_POINTS` times the stage, `TIME_POINTS` a second under its par and, flawless, `FLAWLESS_POINTS` and a life back up to `MAX_LIVES`. Memo is the furthest stage reached, which can pass 10. A read-only `round` getter is for the tests only. Tuned by scratch bots: a careful bot clears all ten stages with no rivals on every seed tried (23 to 42 s a stage), and a bot with 150 ms reactions and 80 ms jump timing error reaches a median of stage 5 with the rivals out, stage 10 without |
| `public/activities/bounce-draw.js` | Bounce Road's drawing: `drawScene(ctx, view)` from one view object `bounce.js` refills each frame, in field units: the strip above the field in the page's colors with the pills (laid out by `hudLayout`: stage, lives, Spring, Bubble, Nitro and Mega with their timers, the chain and the combo with its timer; a pill that would run off the board starts a second row), the road a chunk of `CHUNK_ROWS` rows at a time, drawn off screen once per road and scale, a few kept and copied each frame (rows from `bounce-scenery.js`), the layers over it (`bounce-scenery.js`), the landing rings (yours in your highlight, a rival's in red, the Monster's its own size), the cars through `bounce-cars.js` (every shadow first, upright, then every body with its tumble: Planny in your highlight with his box in the page's panel color and his star eye, arms to the wheel, up in the air or cheering, down at the end; each rival kind in its own style and color, the Cop's siren while it chases, the Monster's dents and a star per life left above it, headlights at Night Lights), sparks, rings, the dark of Night Lights, the chain's big number, the stage bar beside the field, banners, and the start and end strip with the big final score and a dot per stage reached; every word kept on the field by `labelSpot`, and `readColors(canvas)`, `limbInk`, `inkOn`; decides nothing |
| `public/activities/bounce-cars.js` | Bounce Road's cars, drawing only and no imports: `drawCarBody(ctx, style, opts)` draws one top-down toy car about the origin, nose up, filling `w` by `h` field units exactly (tires on the box's corners), in one of `CAR_STYLES` (`STYLE_NAMES`: Planny's convertible with his star eye and arms to the wheel, hatch, sedan, coupe, muscle, pickup, van, box truck, police, racer, taxi, jeep, monster) with flat-fill shading worked out from `color` and `accent` (`shade`, `rgbOf`), and options for roll (`tilt`), a jump (`air`: it draws the shadow and the lift itself), a pancake (`squash`), night beams, a siren bar, damage, a boost flame and brake lights, all moving parts on `opts.clock`; `drawCarShadow` and `shadow: false` for a shadows-first pass in screen space; `carLength(style, w)` for a style's natural length and `carReach(style, opts)` (with `MARGINS`) for what reaches outside the box |
| `public/activities/bounce-scenery.js` | Bounce Road's scenery, drawing only: each stage's look in fixed colors (`LOOKS`: patio slabs, lawn stripes, kitchen tiles, garden, sand, a toy room's rug, a pond with lily pads, roof shingles, the night lawn with lamps and the Monster's dirt; `lookOf`, `stageColor`, `contrast`, `better`), `drawRow` (one row of the road in three passes over a chunk: the yard, the road's surface, the details: edges slanting from row to row, rivers, plank bridges with jagged broken ends, cracks, flowerbeds, rails across a crossing, cracked road over a pit, checkered stage lines, verge decor), and the layers drawn fresh each frame from the round's clock: `drawTimed` (a drawbridge lifting with its red lights, a swaying bridge where it is now, crumbled road gone to the pit), `drawPads` (running boost chevrons, ramps, slicks), `drawBlocks` (cones, toy blocks, pots, buckets, acorns and tires, knocked ones tumbling off), `drawStars`, `drawSigns` (a mark per hazard), `drawItems`, `drawHazardsLow` (crossing lights, the train, a rolling ball, a falling thing's growing shadow, a sprinkler's head), `drawHazardsHigh` (the jet, gust streaks, the thing still falling), `drawNight` and `drawFireflies`; decides nothing |
| `public/activities/bounce-road.js` | Bounce Road's road, rules only: the jump math every hole is sized by (`airMs(v)`, `reach(v)`, `LONGEST_JUMP`, `JUMP_FAIR`, `TOP_SPEED`, `MAX_SPEED`), `stageFor(n)` (built once a stage: the ten of `bounce-roads.js`, then laps from `LAP_FROM`, quicker, keener, busier, the Monster at every Monster Mash) and `stageName`, `newRoad(seed)` and `buildStage(road, n, random)` (a stage's rows from its own seed, by the stage's piece weights: straights, cracks, rivers on bridges with one or two broken spans or a drawbridge, splits round flowerbeds, ramps before a crack with stars beyond, cone or block chicanes, crumbling road, train crossings, swaying bridges, boost strips, slicks, balls, sprinklers, drops and gusts; every hole after a `RUNUP` with a sign and no longer than `MAX_HOLE`, the bridge between two breaks long enough to land `LONGEST_JUMP` on), `ensureRoad`, `groundAt(road, x, d, t)` (a row's edges eased from the row before's; a drawbridge water while lifted, a swaying bridge shifted, crumbled road a hole), `rowGone`, `spanAt`, `holesIn`, `firstAt`, `plainRow`, `safeSpot` (no hole, water, timed part or rails for `RESPAWN_RUN` ahead), and where each timed thing is at a moment: `swayOff`, `drawLift`, `crumbleAt` (falling away `CRUMBLE_DELAY` after you reach it, at `CRUMBLE_SPEED`, under a fair speed), `trainAt` (on, and lit `TRAIN_WARN_MS` before), `ballX`, `sprayAt`, `gustAt`; plus `seeded`, `GROUND`, `MARK`, `SPAN` |
| `public/activities/bounce-rivals.js` | Bounce Road's rivals, rules only: `RIVALS` (the Zigzag, Brick, Frog, Nudge, Hauler, Sneak, Bruiser, Racer, Cop and Monster: box, mass, speed, points, how readily each dodges, how often each comes, its car style and whether it comes from behind), `makeCar`, `think(round, car, ms, random)` (each kind's choice of speed and line: the Zigzag's weave, into your path when you follow; the Brick holding your lane and brake-checking from in front, then resting `BRAKE_REST_MS` or more; the Frog's hops toward you; the Nudge's chase and up to 1 + 2 times the stage's `sharp` swipes; the Hauler drifting to block; the Sneak dropping up to `SNEAK_DROPS` cones while you follow; the Bruiser slamming you within `BRUISER_RANGE`; the Racer passing then fleeing; the Cop sitting on your roomier side and leaning in to push you to the near edge for `COP_MS`, never on a bridge or by the water (`nearWater`), nor the Bruiser; the Monster keeping `BOSS_AHEAD` in front, hopping every `BOSS_HOP_MS` to come down where you will be and dropping tires; every rival rubber-banded to stay near you, swerving from under your landing as sharply as its stage allows, keeping to the narrowest road just ahead and the band a swaying bridge always covers, holding a slower car's speed, and hopping any hole, drawbridge, barrier or coming train, or flying off a ramp), `spawnRival`, `pickKind` (one of each special kind at a time), `HEAVY`, `RIVAL_MIN_SPEED` |
| `public/activities/bounce-roads.js` | Bounce Road's ten stages as data (no imports): `FIELD_W`, `FIELD_H`, `ROW`, `MAX_HOLE`, `LAP_FROM`, and per stage its length, par time, road widths, piece weights (straights, holes, rivers, splits, ramps, chicanes, crumbling road, trains, swaying bridges, boost strips, slicks, balls, sprinklers, drops, gusts), crack and broken span lengths, bridge widths and shares of broken, double and drawbridge spans, flowerbed sizes, barrier and drop kinds, the rivals' count, kinds, pace and sharpness, power-ups, stars, and whether the Monster comes |
| `public/activities/pills.js` | The pills every game but Mini golf draws along its top (no imports): `drawPill(ctx, x, y, w, h, text, color, fill, textY)` on one opaque dark backing, `PILL`, the same in light and dark and over any scene, a timer's share still left tinted at `PILL_TINT`, and the text in `pillInk(color, tinted)`: the pill's own color when it reads at `PILL_CONTRAST` (4.5:1) on the backing (and on the tint while a timer runs), else the least step toward white that does, so warnings stay red; lives are the one solid pill: a pill in the `LIVES` color is drawn on `LIVES_BACK` in white (`LIVES_INK`), its text from `livesText(n)` (a heart per life up to five, `♥ xN` past that, `♡` at none); `pillTint` and `pillContrast` for the unit suite |
| `public/activities/golf.js` | Mini golf: six eighteen-hole courses, one round at a time; its rules and physics as plain exported functions (`newRound(courseId)`, `holesOf`, `coursePar`, `strike`, `advance` on a fixed 4 ms sub-step, `nextHole`, `total`, `toPar`, `predictPath` for the spyglass, `moverAt`, `gateShut`, plus ice that barely slows the ball and wells that pull it in or push it away), the `POWERUPS` held for the next putt (`round.held`, then `round.active` for that putt), the arcade swing (`startSwing`, `setPower`, `meterAt`, `meterZone`, `swingShot`: a ping-pong power meter, slow at the bottom and fast at the top, with a MAX band that boosts and an overswing band that shanks; a shot clock in `advance()` that starts the meter after `SHOT_CLOCK_MS` and dribbles the ball after `METER_TRIPS` trips; all on the round's own clock), the pop-up gags, and the game contract with `pointer()` (the aim follows the pointer, a press swings, a press held on a roll fast-forwards), `release()` (held arrows turn the aim, held space fast-forwards) and `lowerIsBetter`, `courses` (the dashboard's cards), `preview(canvas, id, w, h)` (a course's card art) and `setCourse(id)`; deterministic (no `Math.random()`), a read-only `round` getter for the unit suite only |
| `public/activities/golf-draw.js` | Mini golf's drawing: `drawCourse(ctx, view)` from a plain view `golf.js` builds, each hole in its theme's fixed palette (`pirate`, `cave` with its darkness and glows, or a newer course's look from `golf-looks.js`, asked first for its grounds, water, tunnels, gates and wells), ice, the scorecard and banners in the course's voice, a bare view for the dashboard's card art, `knownGround`/`knownLiquid` for the unit suite, and `readColors(canvas)`, which reads the `--golf-*` properties `styles/activities.css` mixes from the tokens for the ball, pills and scorecard; decides nothing |
| `public/activities/golf-decor.js` | Mini golf's scenery and props for Pirate Cove and the Caves of Doom: each `decor` kind (sharks, ships, parrots, bats, torches, eyes, a dragon) on its layer, the looks of bumpers, movers and spinners, and the power-up icons, each asking the hole's course look first (`decorKinds(theme)` lists a theme's scenery); drawing only, moving with the round's clock |
| `public/activities/golf-holes.js` | Mini golf's courses: `COURSES`, the six eighteen-hole courses in dashboard order (Pirate Cove, Caves of Doom, Dino Valley, Candy Carnival, Cosmic Glow, Frosty Peaks), `courseById`, `HOLE_COUNT`, `FRONT_NINE`, `COURSE_W`, `COURSE_H` |
| `public/activities/golf-kit.js` | Mini golf's course kit, data only: `COURSE_W`, `COURSE_H`, the helpers course files build holes with (`pt`, `rect`, `wall`, `bump`, `pad`, `deco`), `hole(def, defaults)` (what a hole holds: theme, quip, ground, liquid, tee, cup, outline, walls, bumpers, sand, ice, water, slopes, wells, bridges, spinners, tunnels, movers, gates, powerups, decor) and `course()`, which freezes a course with its name, card line, cover hole and voice |
| `public/activities/golf-course-pirate.js` | Mini golf's Pirate Cove course: its eighteen holes and its `voice` (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only |
| `public/activities/golf-course-cave.js` | Mini golf's the Caves of Doom course: its eighteen holes and its `voice` (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only |
| `public/activities/golf-course-dino.js` | Mini golf's Dino Valley course: its eighteen holes and its `voice` (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only |
| `public/activities/golf-course-candy.js` | Mini golf's Candy Carnival course: its eighteen holes and its `voice` (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only |
| `public/activities/golf-course-space.js` | Mini golf's Cosmic Glow course: its eighteen holes and its `voice` (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only |
| `public/activities/golf-course-frost.js` | Mini golf's Frosty Peaks course: its eighteen holes and its `voice` (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only |
| `public/activities/golf-looks.js` | Mini golf's course looks by theme id, and the look contract (palette, liquids, grounds, rough, tunnel, lights, and the looks of bumpers, movers, spinners, gates, wells and scenery) |
| `public/activities/golf-look-dino.js` | How Dino Valley is drawn: its palette, ground, water, props and scenery; drawing only, moving with the round's clock |
| `public/activities/golf-look-candy.js` | How Candy Carnival is drawn: its palette, ground, water, props and scenery; drawing only, moving with the round's clock |
| `public/activities/golf-look-space.js` | How Cosmic Glow is drawn: its palette, ground, water, props and scenery; drawing only, moving with the round's clock |
| `public/activities/golf-look-frost.js` | How Frosty Peaks is drawn: its palette, ground, water, props and scenery; drawing only, moving with the round's clock |
| `public/activities/golf-paint.js` | Mini golf's shared canvas helpers (`polygon`, `circle`, `ellipse`, `radial`, `fill`, `stroke`, `line`, `label`, `turned`, `t`, `scatter`, `bounds`), no imports, so the drawing files and the looks share them without import loops |
| `public/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-music.js` | Snake's ten music tracks as data (no imports): `SNAKE_MUSIC`, `{ bpm, rush, voices, patterns, order }` each, named `snake<Place>` and listed in `MUSIC_TRACKS` in `snake.js`. A round deals them in a fresh order, one to each level, so a run hears a different track at every level and none twice. They were picked on the pages in `prototypes/music/snake` (rhythm-first folk and world tunes led by something plucked or reedy, mostly dark or modal), and their bars are not all sixteen steps: 6/8 is 12, 7/8 is 14, ten beats is 20, twelve beats is 24, each pattern a whole number of its bars; merged by `snake-sfx.js` |
| `public/activities/light-trails/1.mp3` to `5.mp3` | Light Trails' five background songs, named `trailsSong1` to `trailsSong5` under `songs` in `trails-sfx.js` and listed in `SERVABLE`; re-encoded for size with ffmpeg (80 kbps stereo MP3 at 44.1 kHz, loudness-normalized to -16 LUFS with `loudnorm`, metadata stripped), about 7.6 MB together, and copied into every skill with the rest of the console. The server leaves them out of its start-up cache warm |
| `public/activities/flock-dash/1.mp3` to `5.mp3` | Flock Dash's five background songs, named `flockSong1` to `flockSong5` under `songs` in `flock-sfx.js` and listed in `SERVABLE`; re-encoded for size with ffmpeg the way Light Trails' were (80 kbps stereo MP3 at 44.1 kHz, loudness-normalized to -16 LUFS with `loudnorm`, metadata stripped), about 6.4 MB together, and copied into every skill with the rest of the console. The server leaves them out of its start-up cache warm; `flock.js` deals all five in a fresh order each round with `dealMusic()`, plays each in full one after another and deals again after the last, never opening on the song that just ended |
| `public/screens/activities.js` | Activities: `#btn-activities` (the die right of the megaphone), `#activities-modal`, the one frame timer (`requestAnimationFrame`, swappable with `setTickSource()` for the page tests), the keys (arrows, W/A/S/D, space, P, Esc; stopped at the dialog so none reach the page behind; `CHEAT_CODE`, typed on a game's board, turns on endless lives through the game's `cheat(on)` until the round starts over, and `dropCheats()` turns it off on leaving for the picker or closing; `STAGE_CODE`, the same arrows then S, calls the game's `stageSelect()` where it has one, Ghoul Rush's practice stage select) and `pauseAll()`, which a new question, a finish, a hidden page, a window blur and a close all go through and which never resumes a game (it also sends a pointer game a cancel, dropping a drag). Canvas pointer events (down, move, up, cancel, with pointer capture) go to a game with `pointer()`, and key releases to a game with `release()`; a press on a paused board resumes without starting a drag. While paused, any game key or a board click resumes, except while a round is `held`: a question or finish that pauses a round on an open window holds it, the banner adds `#activities-unpause` (**Unpause game**) beside **Go to it**, and only that button plays on (`play()` refuses a held round), since a key or click already on its way used to dismiss the banner unread. Go to it, or closing the window any other way, lets the hold go, and a banner with nothing left to say drops it. Every start and play-on first counts down 3, 2, 1 (`COUNT_FROM`, 700 ms a number, `setCountdownMs()` for the page tests, which set 0 unless they test it): the game is already `running`, the frame timer just does not tick it, and game keys, overlay clicks and board presses wait, while P and Esc still pause. With two or more games listed the window opens on the picker (`view`: `"picker"` or `"game"`, `applyView()`): a card button per game (`drawPicker()`, covers in `COVERS` drawn as SVG with `cv-*` token classes, since the page's policy refuses a style attribute) with its blurb, best and a **Last played** or **Round paused** tag, arrows walking the cards (`moveFocus()`), and `#activities-back` (**All games**) back to it. One game at a time: `pick()` drops the last game from `games` when another is picked, and `openActivities()` goes straight back into a paused round. The last pick is kept as `lastActivity` and gets the focus; `lowerIsBetter` games keep the lowest round as the best; the header shows the current game's best (`paintTitle()`). `renderActivities()` in the render pass compares `myTurn()` and `finish()` with the last render and shows the banner with **Go to it**. Loads a game with `import()` when it is picked and keeps it until another is picked; `setActivityList()` lets a test list a stub second game, which brings up the picker |
| `public/styles/activities.css` | the Activities rules: the die in the top bar, the Notebook-sized dialog, the board and its state overlay, the your-turn banner in the highlight color, the picker and the notes |
**Building an Activities game:** the rules every game follows, so a new one plays like the rest.
- **Lives are prominent.** A game with lives draws them as the lives pill: `livesText(round.lives)` in the `LIVES` color from `pills.js`, placed right after the level/stage pill, which `drawPill()` draws solid pink with a heart per life. Never a plain `♥ N` on the dark backing: that was hard to read at a glance. The unit suite checks every game with lives for it.
- **Every game with lives takes the endless-lives code.** Typing up, down, up, down, left, right, left, right, B, A, space on the board gives endless lives until the round starts over or the person leaves the game (`CHEAT_CODE` in `screens/activities.js`, which calls the game's `cheat(true)` and `cheat(false)` on leaving for the picker or closing). A game with lives answers `cheat(on)` by setting `round.infinite`, never takes a life while it is set (`if (!round.infinite) round.lives -= 1`), lets `start()` make a new round without it, and shows `livesText(Infinity)` ("♥ x∞") in its lives pill. `scripts/test-web-console-activities.mjs` checks every listed game whose round has `lives`.
- **Banners never get in the way.** A banner over the board (`"Hit!"`, a new level, a power-up) is placed on the frame it first shows, on the part of the board away from the player, and fades to `BANNER_SEE_THROUGH` (0.12) over `BANNER_FADE_MS` while the player, or anything the player must react to (a diving bug, a bomb, a rival, a hazard, the road over a hill), is in its strip; Snake's `bannerRow()` and `underBanner()` are the model. Give the banner object a `see` field, multiply the draw's alpha by it, and export the strip check (`underBanner`) for the unit suite.
- **The window owns pausing.** A game never resumes itself; `screens/activities.js` decides when a key or click plays on, including the hold on a question or finish (see the row above), so a game needs nothing of its own for it. Full screen is the window's too (`setFull()`: the button, `F`, and a turn or finish putting it back; `fitFull()` sizes the game to the whole screen (black bars where its shape leaves room) and docks the overlaid panel in a bar that holds it, `data-dock="side"` or `"below"`, or floats it, `"float"`, shrunk to the score while a round plays and the pointer is still; and tells the desktop app `activities-full`); a game only sees a bigger `resize()`, so a new game needs nothing for it, as long as its `resize()` sets the canvas's CSS size.
- **Every moment has a sound, and moving things hum.** A game plays a one-shot through the `tone` it is handed for each event worth hearing (a hit, a pickup, a level, a new best, game over) and keeps continuous things (an engine, a motor, wind, water, a fuse, a monster close by) going with `hum(id, name, level, pitch)` from its `tick`, pitch following speed. Never a one-shot every frame: a repeating cue is throttled by a timer in the round. Its own sounds live in `activities/<id>-sfx.js`, named with the game id; the shared kit is in `tones.js`. `create()` defaults `tone` and `hum` to no-ops, since the suites make games with neither, and a sound never changes the game's state.
- **Its logic tests pin the dice.** A game rolls `Math.random` for roads, spawns and layouts, and an unlucky roll once failed a test on CI at random (Ghoul Rush's Eye, Bounce Road twice). Import `./seed-random.mjs` FIRST in every `scripts/test-web-console-activities*.mjs` file: it seeds `Math.random` (set `PLAN2CODE_TEST_SEED` to try another roll), so a test sees the same world on every run.
@@ -0,0 +1,67 @@
# Architecture: web console design points
> Part of [AGENTS.md](../AGENTS.md) and the [Architecture index](./AGENTS-architecture.md): project guidance for AI coding agents.
Key design points:
- **First-run Welcome.** The first dashboard a person sees (after the wake-up finishes) opens `#welcome-modal`. Any close (button, Esc, backdrop) saves `looks.welcomeSeen: true` to `looks.json`, which survives "Back to default". Help's first tab has a **Show the welcome again** link (`data-action="welcome"`). Logic: `maybeWelcome()` / `openWelcome()` in `screens/help-dialog.js`.
- **Top-bar icons.** `#btn-looks` (gear) opens `#looks-modal`, titled User Preferences (see User Preferences below). `#btn-feedback` (megaphone) is a plain link to `https://github.com/jparkerweb/plan2code/issues/new/choose`, backed by `.github/ISSUE_TEMPLATE/bug.yml` and `idea.yml` (`config.yml` sets `blank_issues_enabled: false`). `DEFAULT_ACCENT` in `palette.js` is `ocean`.
- **Version in Help.** `GET /version` reads `version.json` beside `server.mjs`, falling back to `../../version.json` for a run from `src/` (the `/version` route in `routes.mjs`). `renderHelpVersion()` in `screens/help-dialog.js` fills `#help-version`. `computeExpectedSkills()` in `install.js` injects the root `version.json` into every `references/web-console/`, so a version bump changes every skill.
- **User Preferences is four tabs in a side list.** Appearance (Theme, Card width, Highlight color, Role), Agents & models, System (Cleanup, and Desktop app inside the app only) and Sounds & activities (Sounds, Activities), a sideways strip below 720 px. The tabs are the static `<section class="prefs-panel">` panels in `#looks-modal`, each fieldset in exactly one (its `data-section`, listed in `PREFS_TABS`), wired by the shared `public/tabs.js` (`wireTabs()`, the same helper Help uses: `helpKeyTarget()` re-exports its `tabKeyTarget()`). `public/prefs.js` is the pure part: `PREFS_TABS`, `prefsOpenTab()` (the gear and the dashboard's Set up preferences both open Appearance; nothing is remembered between opens) and `prefsResetScope()` (Back to default resets only the shown tab's looks keys, and is hidden on Agents & models and System). `screens/prefs-dialog.js` owns `openPrefs(tab)`, the one way in, the Saved mark and the unsaved prompt; `screens/looks.js` keeps the look and sound controls, which save to `looks.json` as they change; `screens/agents-view.js` mounts the Agents & models tab, a master-detail split over today's `models.json` and `agents.json` (formats unchanged) whose per-agent form has its own Save and Discard: Save sends the last saved list with only that form's draft swapped in, so another form's half-typed edit is never written. The split's components live under `screens/agents/` (data, list editor, summary, form); the mount owns all state and every fetch and hands them one `ctx`.
- **Models in User Preferences.** `GET` / `POST /models` in `routes.mjs` read the shipped `~/.plan2code/bin/models.json` and read/write the user's `~/.plan2code/models.json` (`SHIPPED_MODELS_FILE` / `USER_MODELS_FILE` in `files.mjs`), edited from each built-in agent's form on the Agents & models tab. `PLAN2CODE_MODELS_DIR` relocates both for tests. The launcher reads the same two files for its model menu.
- **The wait is bounded.** `wait --seconds 240` exits `0` (answers), `10` (still waiting, `message: "Waiting on your answer in the web console"` to relay), `20` (server gone, resume it) or `30` (canceled). The agent loops. Nothing blocks for the whole time a person takes.
- **A turn is one command, and the CLI does the bookkeeping.** Agent speed is model round trips and typed tokens, not the console (`bench-web-console.mjs --roundtrip`: Send→agent ~70 ms, post→page ~180 ms), so the CLI absorbs every step with one right answer: `consume()` marks the agent `working` when it hands over a submit (`markWorking()`), and `wait` hands the turn back (`markWaiting()`) when it starts with an open question, a finish, or on the dashboard or git board; `post --wait <N>` posts and waits in one process; `settle: true | [ids]` (`settleItems()` in `patches.mjs`) records the latest send's cards as answered from their `submitted`; a new or reopened question with no stated status sets `waiting` and waiting drops `quietMinutes` (`settleAgent()`); a doc whose content changed with no `version` moves up one (`mergeDocs()`); a chat reply with no `id` is `r<re>`; doc blocks with `file` (and `select: "tasks"`, doc-level `refresh: true`) are read from the worktree by `resolveDocFiles()` before the merge, refusing paths outside it; and a hop (`__launch`, `__dashboard`, `__commit`, `__pickup`) comes with `resume` (the exact `open --resume` command) and `skillFile` (`hopFor()`), a pick-up also with `handoffFile`. The wait loop's health check runs beside the 50 ms polling instead of blocking it, and is aborted on exit. `help <topic>` prints any contract file; `help topics` lists them. `token` defaults to the option key in the page's `tokenFor()`, and nothing reads `fallbackText`, so the contract no longer asks for either.
- **The CLI hands the agent its terminal line.** `open`, `post` and `wait` (exits `0` and `10`) print `terminalLine: "→ Look at the web console: <url>"` (`terminalLine()` in `sessions.mjs`), and `console.md` asks the agent to end every terminal message with the latest one verbatim, so the tool builds the line rather than the model. In `wait` it is added to the printed result only; the collected `result.json` on disk never carries it. `open` also prints `swept: { sessions, scratch, handoffs }` when it found anything to clean.
- **State fields written by `open`, not the agent.** Every `open` (fresh or resume) records `state.worktree` and `state.branch` from `repoRoots()` — the branch is read off `<gitdir>/HEAD` on the walk that already finds the gitdir (`""` on a detached HEAD or outside git; env-relocated repos ask git, as before) — and the page shows them in the footer as the workspace label (`footerLabel()`: `folder · branch`, or `folder + N folders · branch` once folders are added, stepping down through narrower tiers); a click opens the Workspace dialog. `state.wake = true` is set only by a fresh `open --workflow dashboard` and deleted by every resume (server restart, launch, Back to the dashboard); the page also keeps a per-sid `sessionStorage` guard so a reload never replays it.
- **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `routes.mjs`, which paints `data-width` on first load; `styles/tokens.css` maps `data-width` onto the single `--card-width` variable that every column rule uses.
- **`GET /agents-doc` is the other route that reads a project file** (the dashboard's AGENTS.md tab, right after Dashboard, shown while the project has an `AGENTS.md`). A dashboard session only; it serves `AGENTS.md` or one markdown file directly under `.agents-docs/` (`?file=`, default `AGENTS.md`; `readAgentsDoc()` in `sessions.mjs` allows exactly those two shapes and `realpath`s the file inside the root), as `text/markdown` with `no-store`, or a `204` for anything else. The page links `.agents-docs/` files in place through `md()`'s `link` option (`renderAgentsDoc()` in `screens/docs.js`).
- **`GET /overview` reads a project file too.** It serves `<spec>/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or with `?file=map` / `?file=draft` the spec's `pathfinder/map.md` / live `PLAN-DRAFT-*.md` (the dashboard's Map and Plan draft tabs, shown only while the spec has no overview; `readSpecFile()` picks the file and names it in `x-spec-file`), or an empty `204` when there is no such file (normal for most specs, and no failed request in the browser console). A dashboard session honors `?spec=` only when it equals a `dir` in `state.scan.specs`; every other workflow uses `state.specDir` and ignores the query. The root is `state.worktree` (fallback `state.project`), and `readSpecFile()` (which `readOverview()` wraps) resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all get the same 204, as do an unscanned `?spec=` and an unknown `?file=`.
- **Month-old sessions are deleted whole.** `open` lists `staleSessions()` (directories matching the session-id pattern whose `state.json` mtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) and `staleScratch()` (top-level regular `.json` / `.mjs` files in the console folder older than 30 days, never `looks.json` or `console-dir` — `PROTECTED_CONSOLE_FILES` — never a directory or symlink) before it prints, and removes them after; `removeSessions()` / `removeScratch()` re-check every name against the session-id pattern / the scratch-name rule before deleting — not the age, the skipped sid or the file type, which the `stale*` listing already decided, so never hand them names that did not come from it. `console.md` tells agents to write temporary payload files into the session's own folder so they go with it.
- **User Preferences → System → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes, folder? }], bytes }` (`folder` on `notepad:` items only), ids `session:<sid>` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:<name>` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:<name>` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `install.json`, `models.json`, `handoffs`, `notepads`, `app`, `app.json`, `agents.json`), `notepad:<key>` (a month-old notepad, whole; see Notebook below) and `completed:<name>` (each folder or link directly under the session worktree's `specs--completed/` whose newest mtime is older than the session age, 30 days; loose files there stay; the server passes `project: sessionWorktree() || PROJECT`, and without a `project` the archive is never scanned). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `<file>.<pid>.tmp`, which live for milliseconds. `root:` is only scanned when the console home is `<PLAN2CODE_MODELS_DIR or ~/.plan2code>/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed, refused, refusal }`. So Cleanup is the one place the server deletes in a project, and it keeps a completed spec git could not give back: `completedSpecs()` marks each `completed:` item `tracked` only when `git ls-files` lists it and `git ls-files --others` lists nothing inside (outside a repository, or gitignored as `specs--completed/` is by default, it is untracked), and `removeCleanup()` refuses an untracked one into `refused`, with `refusal` the line the page's status shows. Nothing records a backup copy, so tracked by git is the only way through. The page always shows the list before **Delete these**.
- **The console's path is stated, not searched for.** Each Interface line names `references/web-console/` beside the SKILL.md and the `~/.plan2code/console/console-dir` fallback; the prompts with room (all but pathfinder, plan, document and finalize, which sit near the char limit) also name the canonical global install path `~/.agents/skills/<skill>/references/web-console/` (the skills CLI's real store; every agent dir links into it), and every `console.mjs open` writes `HERE` to `~/.plan2code/console/console-dir` (only `open`, so a `help` or dev run from `src/` never repoints it) so a later session can read the path from a fixed place. Without these the agent hunts the skill install dirs on every session.
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<D>/console.mjs" open --workflow <w>` BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `screens/starting.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `styles/poses.css`; each `SKILLS` entry's `pose` in `skills.js` is the list (`START_POSES`/`startPose()` in `answers.js` read it), and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (`.waiting-pane`, agent working with an `activity` and nothing to ask). `posePane()` keeps the pane on screen across renders when the pose is unchanged — `renderMain()` holds any `:scope > [data-pose]` child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.
- **The dashboard scan knows whether the folder is a git repository.** `scanProject()` returns `{ hasAgents, isGit, pending, specs }`; `isGit` comes from `insideGitRepo()`, the same filesystem walk `findRoots()` does (no `git` process, linked worktrees and submodules count, a set `GIT_DIR` / `GIT_WORK_TREE` / `GIT_COMMON_DIR` counts as a repo). The Git card is never grayed, since a clean tree still has branches to switch, pull and push. When `isGit` is `false` the card shows `GIT_INIT_NOTE` ("Not a git repository yet: it offers to start one") as its detail line; a scan with no `isGit` counts as a repo. In a repo, `pending` is `pendingFiles()` in `sessions.mjs`, which calls `countPending()` in `git-repo.mjs`: one bounded `git status --porcelain -z` under `GIT_OPTIONAL_LOCKS=0` (`null` when git cannot say) counting modified, staged, deleted and untracked paths. Above `0` the detail line is `pendingNote(n)` ("3 files to commit"); `0` and `null` show no note. A finish with `commit: true` puts a **Commit it now** button on the finished screen (`commitOffer()`, `renderCommitOffer()`); its `__commit` press makes the agent resume as `git` in the same session and run the commit flow above the board. `open --resume` treats any switch into `git` (this press, or Changelog's "Commit this now?") as a hop, like a dashboard launch: `switchWorkflow()` blanks the page, finish and the last run's `state.git` included, and `draft.json` goes. Without that, the old finish outlived the switch, and the page sat on the old ending above the new questions and the board. A confirm item may carry `files: [{ path, state }]`, drawn as a collapsed table by `filesTable()`. Subagents is **on** by default for the twelve opted-in skills (`defaultSetting()`); a saved Off stays off.
- **The start path is timed, and `open` is built around it.** Measure with `node scripts/bench-web-console.mjs` (`--browser-delay 900` for a real Chrome launch, `--roundtrip` for Send→agent and post→page, `PLAN2CODE_CONSOLE_TRACE=1` on `open` for a step timeline). Four things make it fast, and each is load-bearing:
- **No git process.** `repoRoots()` in `sessions.mjs` finds the common dir and worktree top by walking to `.git` (following `gitdir:` and `commondir` files) — each `git rev-parse` cost 150ms+ on Windows. It asks git only when `GIT_DIR`/`GIT_WORK_TREE`/`GIT_COMMON_DIR` relocate the repo, and uses the native realpath so an 8.3 short name keys the same project git would.
- **The socket handover.** `open` spawns the server first, then binds the loopback port itself (the first `listen()` blocks ~50ms on Windows, overlapped with the server's boot), launches the browser on that URL immediately (Chrome via `start` takes ~900ms to its first request, the longest step of all), and hands the listening socket to the server over IPC (`bindLoopback()`/`handOff()` in `sessions.mjs`, `--handoff` in `server.mjs`). Requests queue in the socket until the server takes it; one `open` already accepted is passed across as a socket and acknowledged (`conn-held`) before the channel is closed. No channel, or no socket within 3s, and the server binds its own port; `open` then opens the real URL.
- **The first paint needs no fetch.** `routes.mjs` (`renderIndex()`) renders `index.html` with the session's title, badge and saved theme (`data-theme`, `data-looks-accent`, matched by accent rules generated from `palette.js` and appended to the joined stylesheet by `static.mjs`) and the whole first state as an inline `<script type="application/json" id="boot">` (every `<` escaped; data blocks are not executed, so the CSP is unchanged). `modulepreload` hints fetch every module in parallel, the page draws in the same task as the script runs, and `/events?have=<key>` skips the opening frame when the page already holds that exact state. The chimes load on first use, not at start-up.
- **Reads are stat-gated.** `fileStamp()` (mtime:size:ino) decides whether `state.json`, `result.json` and `looks.json` changed before anything reads or parses them — per request, per heartbeat and in the 1s poll; the parsed state is cached (`readState()` returns it; `/submit` clones before editing). `wait` stats `result.json` every 50ms instead of parsing it every 400ms. Static assets are held in memory for the server's life and revalidate by ETag.
- **The Workspace and the session meter live beside `state.json`, one writer each, and outlive every hop.** Three session files, none of which `switchWorkflow()` ever touches, so both survive dashboard → skill → dashboard (a new console session starts with a count of 0, and with the folders remembered for its folder and spec, below):
| File | Writer | Holds |
|---|---|---|
| `workspace.json` | the server (`workspace.mjs`) | the folders (`id`, `path`, `name`, `description`, `original`, `nested`), `version`, the `changes` log, `missing` ids, and `remote` (`remoteWarning()` in `sessions.mjs`, computed by the server at boot) |
| `ledger.ndjson` | `console.mjs` | append-only, one JSON line per entry. Meter events: `launch` (every fresh `open` and every resume into another workflow), `run` (a post's `run`, id scoped by launch, with `tasks` when a built phase reports one) and `answer` (one per item the person answered in a collected send, written by `ledgerAnswers()`, id `<launch>:answer:<send stamp>:<item>`). Also `folder-issue` reports |
| `workspace-cursor.json` | `console.mjs` | the last workspace `version` handed to the agent; advanced after the print, never backwards |
The page changes the workspace only through five routes: `GET /workspace` (`?check=1` re-stats every folder first), `POST /workspace/add` (path resolved against `state.worktree`, `~` expanded, case-insensitive duplicate check on win32/darwin; `not-a-folder`, `duplicate`, `bad-name`, `name-taken` + `suggest`), `POST /workspace/edit`, `POST /workspace/remove` (the original folder refuses) and `POST /workspace/browse` (one picker at a time, 409 `busy`; 404 `no-picker` when `remote` is set or no picker exists; `PLAN2CODE_PICKER_ECHO` stands in for the dialog in tests). `stateFrame()` carries `workspace` (folders, `missing`, `remote`, the current launch's folder `issues`) and `meter` (`meterView()` over the ledger), and both files are on the 1s poll; it also carries an optional `update` once the boot-time release check (`update-check.mjs`) finds a newer release. The agent hears of the workspace through `open` output (`workspace: { folders, missing? }`, which also seeds the cursor) and then each change once, as `workspace: [...]` plus `Workspace: …` reply lines on `wait` exit 0 or `chat`; a change alone never ends a `wait` slice (`pendingWorkspace` on exit 10). `post` and `open --file` lift `run` and `folderIssue` out of the patch into the ledger, never into `state.json`; an unknown event or a malformed issue is exit 3. **Remembered workspaces.** `workspace.mjs` keeps `~/.plan2code/console/workspaces.json` (`WORKSPACES_FILE`, under `PLAN2CODE_CONSOLE_HOME` in tests): `projects[<case-folded worktree>] = { path, project, specs: { "specs/<name>": … } }`, each entry `{ original: { name, description }, folders: [{ path, name, description, nested? }], at }`. `rememberedWorkspace()` answers spec, else project, else nothing; `initialWorkspace(worktree, entry)` builds from it, both in the server's first `workspaceNow()` and in `open`'s read-only `workspaceOnOpen()`, so they agree. `workspace.json` carries `scope` (the spec key or `""`). Every user change (`bumpWorkspace`, not `missing`/`found`) calls `rememberWorkspace()`. `setScope()` swaps the list, logging `removed`/`added`/`renamed`/`described` changes so the cursor stays truthful; `POST /workspace/scope { spec }` (the dashboard picker, on selection and before a launch) seeds an unsaved spec from the project's list, and `followSpecDir()` (state poll, boot) moves the scope to a posted `specDir`, saving the current list as an unsaved spec's. Two writers, each a read-modify-write of one key: the server and `console.mjs forget --spec` (Finalize Step 6). The contract is in `console-workspace.md` and `console-meter.md`, and `building.md` (per-phase `run`), so the skill prompts stay unchanged.
- **The Subagents switch is a standing instruction, injected only on change.** The page's icon button (`#btn-subagents`, after Write a brief) and `#subagents-modal` show only when the frame's `subagents` block says `offered && supported`. `offered` comes from `public/subagents.js`; `supported` means the latest `{ "type": "open" }` line in `events.ndjson` carries `caps: ["subagents"]` (`latestOpenCaps()`), so an older skill copy's `open` hides the button. Four places hold it, one writer each:
| File | Writer | Holds |
|---|---|---|
| `~/.plan2code/console/subagents.json` | `server.mjs` | per project folder → workflow: `{ on, instruction, max }`, `instruction: null` being the shipped default; on `PROTECTED_CONSOLE_FILES` |
| `<session>/subagents-setting.json` | the server (`settings.mjs`) | `{ workflow, on, instruction, max, revision }`: synced from the store at boot and on any workflow change (`serverSubagents().sync` in `settings.mjs`), `revision` bumped only by a real change |
| `<session>/subagents-cursor.json` | `console.mjs` | `{ revision, state }`, the last block handed over; `open` resets it, and it moves only after the print |
| `state.json` → `helpers` | `console.mjs post` | the helpers the agent reports, merged by `id`, checked by `checkHelpers()` plus the prose scan; dropped by `switchWorkflow()` on a dashboard hop |
`POST /subagents` (origin-checked; `400` `not-offered` / `bad` / `too-long` / `max`) saves the store and bumps the session setting. `consume()`, `cmdChat()`, `deliverChat()` and `open` append `blockFor()`'s lines last in `reply` and the `subagents` field; a change alone never ends a `wait` slice. The page's Subagents tab (before Ask) draws `state.helpers` through `helperRows()`. Helpers never reach the meter ledger. Contract: `console-subagents.md`.
- **The filesystem is the transport.** Sessions live in `~/.plan2code/console/sessions/<sid>/`, deliberately not under `specs/`, so the console cannot trip the metrics scraper or any marker parser, and survives `git clean`. A result written after the agent dies is picked up by the next session.
- **Attachments on notes and quick questions live in `<sid>/uploads/`**, never in the project: images as `<uuid>.jpg`, documents as `<uuid>.<ext>` with `ext` from `DOC_TYPES` in `answers.js` (text, code, PDF). The browser re-encodes images to JPEG and sends raw bytes to `POST /upload` as `image/jpeg`; documents go as-is as `application/octet-stream`, the extension taken by `docExt()` from the uncut `x-p2c-name`. `readRaw(req, limit, cb)` in `routes.mjs` caps images at `MAX_BODY` (4 MB) and documents at `MAX_DOC_BYTES` (10 MB), and drains rather than destroys so the client gets its 413. Images need the `FF D8 FF` magic; documents pass `checkDocument()` in `sessions.mjs` (`%PDF-` for PDF, strict UTF-8 with no NUL for text), else 415. The server names the file with `crypto.randomUUID()`. `GET /uploads/<id>.<ext>` serves images as `image/jpeg` and documents under a fixed type (`application/pdf`, else `text/plain`) with `nosniff` and, on text, CSP `sandbox` (a sandboxed PDF cannot open in the viewer), so a browser can show but never run one; `recordSubmitted()` writes every send's note onto its item as `sentNote { at, text, images, files, 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.
- **Back to the dashboard is the same kind of post-finish request.** A finish with `finish.dashboard: true` shows the button; a press arrives as `{ "i": "__dashboard", "type": "dashboard" }`, and the agent runs `open --resume <sid> --no-open --workflow dashboard` then posts `"finish": null` with a fresh `menu`. The agent waits ~10 minutes after the finish for it (alongside `__review` / `__done` on a quick task); after that the page swaps the button for the `/plan2code` command. `finish.command` is optional — without one the page shows the "All done" line — and `validate()` rejects a `<placeholder>` command and a non-boolean `dashboard`. The session-level actions are therefore `__brief`, `__stop`, `__launch`, `__review`, `__done` and `__dashboard`; a new post-finish button should copy this precedent.
- **Continue here, Update CHANGELOG first and Ask prompt blocks.** Three small additions on the same pattern. **Continue here** is page-only: `continueOffer(fin)` (`public/answers.js`) reads `finish.command`, and when it starts with a Plan2Code skill (and the finish is not a pause) `screens/ending.js` draws a button beside the Next step block, hidden when the session meter is red; the press is the dashboard's own `{ "i": "__launch", ... }` through `sendAfterBuild("launch", offer)`, so the agent writes nothing new (`startsClean()` cleans the page for the hop, except out of Git and into Review; a same-skill next step keeps the workflow, so the agent posts `"finish": null`). **Update CHANGELOG first** is `finish.changelog: true`, accepted by `validate()` only on `quick-task` and `finalize` (a paused finish is exempt from that check and the page ignores the flag), and it belongs with `commit: true`; the press is `__changelog`, a `HOP_ACTIONS` entry in `cmd-post-wait.mjs` that resumes as `changelog`, whose "Commit this now?" yes carries on to Git. **Ask prompt blocks** are contract only (`console-chat.md` → Prompts to carry away): the page already draws a Copy button on every fenced block.
- **`__dashboard` also arrives mid-workflow.** A left-pointing triangle (`#btn-home`, filled with `--accent`) sits left of Stop session on every non-dashboard page. Its state comes from the pure `homeButtonState()` in `answers.js`: hidden on the dashboard, on a finish and during a stop, and otherwise gated by the same `turnGate()` Stop now uses (the person's turn, unless the agent has gone adrift). The confirm (`#home-modal`) reuses `stopWarning()`, and the submit carries the staged answers plus `__dashboard`, with `HOME_REPLY`. With no finish on the page, the agent treats it as a stop that lands on the menu: it saves its place as for `__stop`, then resumes as the dashboard with `"finish": null` + `menu`, with no finish and no stop in between (console-stop.md → "Back to the dashboard, mid-workflow"; building.md for builds). `local.homeward` drives Planny's "Saving your place and opening the dashboard…" line until the through-the-dashboard reset clears it.
- **Handoffs live outside every repo, in `~/.plan2code/handoffs/`, and the console owns them** (`handoffs.mjs`; the console ships in every skill, so the Stop flow, the Handoff skill and the dashboard all reach it through `console.mjs`). `handoff new --workflow <w> --skill <s> [--spec specs/<x>] [--title <t>] [--from-stop]` claims one for this checkout and prints `{ ok, id, path, meta }` (exit 2 bad usage, 3 a bad value). Off the dashboard the Stop modal offers **Stop with a handoff** (`#stop-handoff`, suggested) above **Just stop and save** (`#stop-go`); the first sends `__stop` with `handoff: true` and `STOP_HANDOFF_REPLY`, and `wait` adds `handoffSkill` (the built Handoff skill's `SKILL.md`, `handoffFor()`); console-stop.md gives the order (answers, save, `handoff new --from-stop`, write, paused finish naming the file, `stop`). On a dashboard, `cmdOpen()` adds `scan.handoffs` (`listHandoffs(worktree)`) and `scan.handoffsDir` after `scanProject()`, which stays handoff-free because `specs.mjs list` shares it. The picker draws them as dashed `.spec-chip.is-handoff` chips after the specs (`specSel = "handoff:<id>"`); a picked one replaces the skill cards with `renderHandoffPreview()`: **Pick it up here**, **Read it all** (`GET /handoff?id=`, served only for an id in the dashboard's own `state.scan.handoffs`), **Copy for a new conversation** (`handoffCopyText()`) and **Delete** (`openHandoffDelete()`, one step). Pick it up sends `{ "i": "__pickup", "type": "pickup", "handoff": <id> }`; `HOP_ACTIONS.pickup` (`pickupHop()`) reads the stored `.json` only, never the page, and falls back to Quick Task with `fallback: true` when the record, its skill or its spec is gone, or the Handoff skill wrote it (resuming that skill would only write another handoff); `markPickedUp()` stamps `usedAt` as the hop is printed, so the next scan drops the chip. Delete sends `__delete` with `handoff` in place of `spec`, and the agent runs `delete-handoff --handoff <id>` (`removeHandoff()`, exit 3 on a refusal, nothing touched). `open` sweeps handoffs untouched for 30 days (`staleHandoffs()`, the `.json`'s mtime, else the `.md`'s), picked up or not, and reports them in `swept.handoffs`; Cleanup never lists the folder (`KEPT_PLAN2CODE_ENTRIES`).
- **Notebook: the person's, one per folder, in `~/.plan2code/notepads/`, in named tabs, and the agent's only when the person sends a tab.** `notepads.mjs` is the store's one owner (`PLAN2CODE_NOTEPADS_DIR` moves it for tests). The folder is the session's worktree, else its project (`notepadRoot()` in `routes.mjs`), keyed `<folder-name>-<12 hex>` by `notepadKey()` (the hash over `foldKey()`, so case-only path differences match on Windows and macOS, and two worktrees get two notepads). **Layout:** `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order: [id], last, tabs: { id: { name, created, sent? } } }`, the index and the only place order and the last tab live) and, per tab, `tabs/<id>/note.md` with `tabs/<id>/images/<uuid>.jpg` and `<uuid>.thumb.jpg`; a tab id is 12 hex. Every write takes the folder's `notepad.lock`; a read never creates a file, so only the person's edits age a notepad. A delete removes the tab from the index first, then its folder, and the next write sweeps away a tab folder the index no longer names (a delete that crashed half way). **Migration:** the first shape (`v: 1`, one `note.md` and `images/` at the top) reads as one virtual tab, Notes, with the fixed id `LEGACY_TAB_ID`, and a read writes nothing; the first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, so a crash in the middle is finished by the next write and never loses a file. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders. **Routes:** twelve, placed after `/upload` in `ROUTES` (the shape test pins the order): `GET /notepad[?tab=<id>]` (`{ tabs, last, tab: { id, text, savedAt, images } }`, with the tab's `text`, `savedAt` and `images` repeated at the top), `POST /notepad/text?tab=` (`{ text }`, 1 MB, 413 `too-long`), `POST /notepad/image?tab=` and `POST /notepad/thumb?id=<uuid>&tab=` (raw `image/jpeg` the page re-encoded with `reencode()`, 4 MB, 200 pictures per tab: 415 `not-jpeg`, 413 `too-large`, 409 `too-many`), `POST /notepad/image/delete?tab=` (`{ id }`), `POST /notepad/tab` (`{ name }`), `/notepad/tab/rename` (`{ id, name }`), `/notepad/tab/delete` (`{ id }`), `/notepad/tab/order` (`{ order }`, every id once) `/notepad/tab/last` (`{ id }`) and `/notepad/tab/sent` (`{ id, workflow, spec? }`, `markTabSent()`: sets `sent: { workflow, spec?, at }` on the tab, replacing an earlier one; `workflow` one of `pathfinder`, `plan`, `quick-task`, `revise-plan`, `spec` matching `^specs/[A-Za-z0-9._-]+$`, else 400 `bad-sent`), and `GET /notepad/images/<tab>/<uuid>[.thumb].jpg` (matched on the raw request line like `/uploads/`, served through `imagePath()`'s realpath containment, `no-store`). A text or picture request with no `?tab` means the last tab used (and makes Notes when there is none), so an unchanged client keeps working. The eleven POSTs are origin-checked, and every refusal is a `NotepadError` turned into `{ error }` (`bad-name`, `duplicate-name`, `too-many-tabs`, `no-such-tab` beside the picture and text codes). None of them writes to the session folder or `events.ndjson`, and `console.mjs` and the `cmd-*.mjs` files never import `notepads.mjs` (a source test pins it; `sessions.mjs` loads it lazily for Cleanup only, listing and removing whole notepads), so nothing in a notepad reaches `state.json` or anything `wait` prints except a tab the person sends (see **Send to a skill**). **The editor, and the CSP.** CodeMirror 6 replaced OverType 2.6.1 after a spike (typing at 200 KB measured about 24 ms a key against about 99 ms, and real heading sizes): `public/vendor/codemirror.esm.js` is one minified file (about 500 KB) made by the dev-only `scripts/vendor-codemirror.mjs` from `scripts/vendor-codemirror-lock.json`, never installed in the repo, and loaded by a dynamic import only when the Notebook first opens. CodeMirror writes its rules as a `<style>` element, which `style-src 'self'` refuses, so the editor lives in the open shadow root of `.notepad-cm-host` where it adopts them as a constructed stylesheet, and its own look is `public/notepad-editor.css`, a `<link>` inside the root. Custom properties inherit across the boundary, so both themes work; page tests reach the editor with Playwright's CSS locators (they pierce open shadow roots) and read its text from `EditorView.findFromDOM()`, since lines the cursor is not on draw without their Markdown marks. CodeMirror's own rules win a tie in specificity (they are adopted after the linked sheet), so `notepad-editor.css` writes `div.cm-editor .cm-scroller` for the few it overrides. `scripts/test-web-console-page-notepad.mjs` fails on any `securitypolicyviolation` with the notepad open. **Upgrading CodeMirror:** change a version in `scripts/vendor-codemirror.mjs`, run `node scripts/vendor-codemirror.mjs --update-lock` (npm and network; it installs in a temp folder), update the sha256 in the files-table row, then run the two notepad test files. **Tabs on the page:** `screens/notLine truncated
- **A Bug fixed spec deletes in one step.** Its chip shows a visible **Delete** (`.spec-chip-del-label`) instead of the hover ✕, `openDeleteConfirm()` gives it a fixed-bug warning and a **Delete it** button, and `deleteStep()` sends `__delete` on the first press, with no name to type. `chipDetail()` drops the scan's repeated "bug fixed" detail under the label.
- **The Quick question chat is a second, append-only channel beside the card slot.** The page's **Ask** tab (always last, every workflow, still there after a finish) posts to `POST /chat` (a message, or `{ reset: true }` for New conversation) and `POST /chat/decision` (Approve / Decline on an edit the agent proposed). The server is the only writer of `<sid>/chat.ndjson` (one JSON line per `message` / `decision` / `reset`, each with a `seq`; `appendChat()` in `inbox.mjs`); `console.mjs` is the only writer of `<sid>/chat-cursor.json` (the last seq handed over, advanced only after printing) and of the agent's replies in `state.json` → `chat.replies` (merged by `id`, checked by `validateChat()`: real `re`, proposal paths outside the running `specs/<idea>/`). The server never writes chat into `state.json` — `post` read-modify-writes it under `withStateLock()` — and `stateFrame()` merges inbox and replies into the frame's `chat` block (`conversation`, `messages`, `typed`, `limit`, `offline`) in memory. `/chat` never checks `pendingResult()`, so neither channel can block the other. `wait` keeps its exit codes 0/10/20/30: exit 0 gains `chat` (or is `type: "chat"` with no actions), and the instant `console.mjs chat` answers 0/10/20 without touching `result.json`, which builds run after every task. Guards: 10 typed messages per conversation (`409 limit`), 4,000 characters (`400 too-long`), own uploads only, of the right kind (`400 image`, `400 file`), `409 offline` when `chatOffline()` says no agent is there, `409 stale` for an old conversation. A hop through the dashboard keeps the conversation: `switchWorkflow()` carries `chat.replies` across and the page keeps its Ask state, so only New conversation appends a `reset` after the opening one. A lone reset never ends a `wait` slice (`deliverableChat()`); it rides along with the next message.
- **`validate()` in `patches.mjs` enforces four workflow rules mechanically**: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait.
- **The palette is written twice for dark, and that duplication is the mechanism.** `@media (prefers-color-scheme: dark) :root:not([data-theme="light"])` follows the system; `:root[data-theme="dark"]` is the explicit choice from the colors panel. Drop the `:not()` and a system-dark browser overrides someone who asked for light. A chosen accent is applied as an inline custom property on `:root` (CSSOM, which the CSP allows), and the default is applied by REMOVING that override so the stylesheet's own per-theme values win. The server's `data-looks-accent` stand-in only lasts until `applyLooks()` runs, which removes it first thing — left on, its rule would beat "Back to default".
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 21 panels and their icon sheet are hand-written HTML and SVG in `<template id="help-content">` in `index.html` (after `#start-poses`), cloned into `#help-panels` the first time **?** is pressed (except the dashboard topic's card list: `buildHelp()` fills its `.help-cards` from `SKILL_CATALOG` and `CATALOG_GROUPS` at that moment, in the dashboard's order), so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `screens/help-dialog.js` the wiring (tab buttons, roving focus, `renderAbout()` for the live connection line on tab 1, `lightDismiss()`, and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a `style=` attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a `data-fact` span a test checks against the constant it comes from.
- **Stuck sessions are explained twice, in Help and on the status line.** `stuck` ("When something looks stuck") is the second tab in `HELP_TABS`; its panel opens with a `help-callout` ("Check this first": Plan2Code often waits for a permission in the terminal, which the page cannot see) and four You see / Likely cause / Do this rows before the diagram. The quiet and Not running status lines carry a "What to check" button (`openHelpOn("stuck")`) inside the existing `role="status"` element, so it exists only while the symptom shows. Every finished and paused screen gets a "Before you close this" panel from `renderCloseGuide()` in `renderHandoff()` (Safe to close, Start fresh, Carry on). Tests in `scripts/test-web-console-source.mjs` check the tab order, the callout and rows, and the `renderCloseGuide` call.
- **Markdown is rendered to DOM nodes, never to an HTML string** (`public/render.js`), so agent-authored text that quotes a hostile source cannot execute. Only `marked.lexer()` is used.
Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --build-skills`, `parse-check.mjs`, `check-skill-table.mjs`, then one `node --test` over the skill-script tests (`test-skill-scripts.mjs`, `test-script-*.mjs`, `test-git-repo.mjs`), `test-launcher.mjs`, `test-getting-started.mjs` and the web console's `test-web-console-*.mjs`, so they run in parallel, one process each. The console tests are split by area (`-session`, `-lifecycle`, `-logic`, `-server`, `-chat`, `-chat-stress`, `-workspace`, `-subagents`, `-concurrency`, `-source`, `-shape`, `-git`, `-git-board`, `-qa`, `-speed`, `-hardening`, `-embed`, `-handoffs`, `-in-app`, `-loop`, `-notepad`, `-pointers`, `-skills`, `-spec-states`, `-state`, `-tones`), plus the `-page-*` browser suites and the per-game `-activities*` suites. Their shared setup is `scripts/web-console-test-helpers.mjs`: importing it gives the file its own console home (so `workspaces.json`, `subagents.json`, `looks.json` and sessions never collide across files) and registers the `stop --all` cleanup. `-session` and `-lifecycle` each run an ordered chain of tests on one session of their own; everything else opens a session per test. A new test goes in the file for its area, after the tests it depends on. The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill.
**Adding a file under `public/`:** a page module needs `SERVABLE` in `static.mjs` and a `<link rel="modulepreload">` in `index.html`. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a module missing from it 404s and the page dies at import with no useful error (the import-fetch test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after `app.js` and slows the first paint. A screen goes in `public/screens/`, imports only `state.js` and the pure modules (never another screen), and is imported by `screens/core.js`; the import guard in `scripts/test-web-console-shape.mjs` fails naming a screen that breaks either rule. A stylesheet goes in `public/styles/` and on `CSS_ORDER` in `static.mjs`, never on `SERVABLE`; the joined-stylesheet test fails when the folder and the list disagree. Every new file also needs its row in the files tables (the server and contract in [the console file](./AGENTS-architecture-console.md), a `public/` file in [the page file](./AGENTS-architecture-console-page.md), a game file in [Activities](./AGENTS-architecture-activities.md) or the Ghoul Rush files), which the docs-table test (same file) checks.
@@ -0,0 +1,87 @@
# Architecture: web console page files
> Part of [AGENTS.md](../AGENTS.md) and the [Architecture index](./AGENTS-architecture.md): project guidance for AI coding agents.
One row per file under `src/web-console/public/` (the games and their sound are in [Activities](./AGENTS-architecture-activities.md)). The server and contract files are in [the server file](./AGENTS-architecture-console.md).
| File | Role |
|---|---|
| `public/` (other files) | `index.html`, `favicon.svg` (Planny peeking up from the tab bar, served as `image/svg+xml`) with `favicon.png` (the same icon at 192 px, served as `image/png`) as the fallback, `vendor/marked.esm.js`, the chimes (`start-skill.mp3`, `bootup.mp3`, `start-stop.mp3`, `next.mp3`, `insert.mp3`, `sleeping.mp3`; which moment plays which is `SOUND_EVENTS` in `palette.js`, one switch per event saved in `looks.json`), and a `package.json` that only says `"type": "module"`, so Node (the server and the tests import the pure modules) parses them as ES modules without a reparse warning. The stylesheet is the files in `public/styles/`, joined by the server into the one `/app.css` the page asks for |
| `public/md-field.js` | A Markdown answer field on CodeMirror 6: every multiline box the person types into renders its Markdown live. |
| `public/md-field.css` | The frame a Markdown field wears inside its shadow root, linked beside `notepad-editor.css`. |
| `public/app.js` | the page's entry and the only page file that starts anything: the start-up block. `index.html` loads it; it imports `screens/core.js` and the screens beside it |
| `public/doc-files.js` | a document as the page shows it, and as a file: blocks, Markdown and HTML download |
| `public/hops.js` | no imports: the hop rule, `startsClean(from, to)`, which says whether a hop from one workflow to another starts the new skill on a clean page (to or from the dashboard, into Git, or from one skill into another off a finished screen, but never out of Git or into Review); shared by `cmd-open.mjs`, `server.mjs` (its Ask reset) and `screens/core.js` |
| `public/looks.js` | how the page looks and sounds: the saved looks, their sync, and the preferences dialog's swatches |
| `public/mention-box.js` | the @name suggestions popover under a text box |
| `public/net.js` | the page talking to its own server |
| `public/palette.js` | the highlight colors, the sound events and the card widths, as data (importable by Node so a test can check every shade in both themes) |
| `public/render.js` | Markdown to DOM, safely: no HTML string is ever produced, only nodes built with `createElement` and `textContent`; also the shared page helpers (`el`, `md`, `copyButton`, `lightDismiss`) |
| `public/selectors.js` | what the page reads off its state: the questions, the finish, the scan, who has the ball |
| `public/send-state.js` | whether Send is available, and what its button says |
| `public/skills.js` | the skill list: every per-skill fact the console uses (card, order, start pose, launch scoring, subagent opt-in, which spec states light its card), data only, imported by the page and by Node; the older tables (`SKILL_CATALOG`, `START_POSES`, `CONSOLE_WORKFLOWS` and the rest, in `answers.js`) are lookups on it. Each entry also carries `weight` (what its launch and `run` score on the meter, or null), `started` and `ran` (the meter's labels for them, or null), `resume` (`"overview"`, `"folder"` or null: what the resume command takes after the skill's command) and an optional `card.help` (Help's line for the card when it differs from `blurb`). `WORKFLOWS` (every entry's workflow, in order) and `isWorkflow()` are what the CLI checks a `--workflow` against. The meter's `WEIGHTS`, `LAUNCH_LABELS` and `RUN_LABELS`, `resumeCommand()`, Help's card list and `cmd-help`'s workflow list are all derived from it, so a new skill is one entry here, not an edit to each of those |
| `public/sound.js` | the sound cues: which plays, one at a time, held until the first click |
| `public/spec-states.js` | the spec states (`diagnosed`, `fixed`, `exploring`, `mapped`, `planned`, `documented`, `building`, `built`, `unrecognized`): each one's picker label, the card it is the natural next step for and its recommendation, data only; which cards a state lights lives in `skills.js`, how a folder maps to a state in `classifySpec()` in `scan.mjs` |
| `public/state.js` | the page's shared state (`page.S` the server's truth, `page.local` what is staged) and the `redraw()` / save hooks every screen calls; defines only |
| `public/uploads.js` | pictures and documents attached to a note: chips, trays, re-encoding, upload, retry, and the page's shared full-screen picture preview (`openPicview`, the `#picview` dialog every thumbnail opens) |
| `public/screens/ask.js` | the Ask chat, the Subagents tab, and attaching files to notes |
| `public/screens/cards.js` | question cards: every kind, the pager, settled and in-flight records |
| `public/screens/cleanup.js` | User Preferences' Cleanup section, on the System tab |
| `public/screens/core.js` | the core every screen sits inside: connection, the render loop, the page chrome and Send; the only file that imports the screens, and only `app.js` imports it |
| `public/screens/dashboard.js` | the dashboard: cards, the spec picker, handoff chips, delete, and the first-open wake-up |
| `public/screens/loop-setup.js` | the Implementation Loop's setup screen on the dashboard (app only): the fields, their defaults and read-only facts, the Start checks, and the request to the app. The page locks while `state.loop.driving` is set (`loopDriving()` in `selectors.js`) until the app posts `loopEnd`; Activities, Notebook, Help and Preferences stay usable. `loopEnd.can` accepts `ask` (`LOOP_CAN` in `patches.mjs`); the app adds it first to every stop that offers `resume`, and the stopped screen's **Ask a question** wakes an ordinary agent on the same session |
| `public/screens/docs.js` | documents: tabs, blocks, print and download, and the brief button |
| `public/screens/ending.js` | how a session ends: the finished screen, its offers, Stop and the way home |
| `public/screens/git-host.js` | hosts the git board: tabs, panels and what each click sends |
| `public/screens/help-dialog.js` | the Help dialog and the first-run Welcome (named so it is never confused with the pure help.js). Help reads right in both modes: a phrase that differs under the desktop app carries its app wording in `data-app` (swapped in by `renderAppWording()`), and a paragraph that differs is a `.for-browser` / `.for-app` sibling pair, switched by `:root.in-app` (set in `core.js` from `page.inApp`, rule in `help.css`). The older `render*Help()` functions patch a few ids the same way. `scripts/test-web-console-page-help.mjs` sweeps every topic's visible text in each mode for the other mode's wording |
| `public/screens/looks.js` | User Preferences: the look and sound controls, which save as they change |
| `public/screens/agents-view.js` | the agents view's mount, state and server calls, serving both User Preferences' Agents & models tab and the setup page as a master-detail split: the pickable list on the left, the picked agent's form or state in the right pane. Picking a row is the navigation; a dirty form asks the dialog's unsaved prompt first. Each form edits a draft; Save sends the saved list with only that draft swapped in (`POST /models` or `POST /agents`), Discard drops it. `hasUnsaved`, `saveOpen` and `discardOpen` feed the dialog's unsaved prompt. `mountAgentsView(container, {mode, forCli, onStart})` hands its renderers one `ctx` (state plus callbacks); `mode: "prefs"` draws the agent rows with Found / Not found on PATH badges and a v3 orchestrator placeholder, `mode: "setup"` draws the pick list (found / outside-PATH / missing states, install lines, Use it from here, templates, Start) inside a caller-supplied container |
| `public/screens/agents/agents-data.js` | PURE, no imports, `node --test` importable: the agents view's data helpers. `MODEL_CLIS`/`BUILT_IN` (the built-in rows, pinned to `src/launcher/agents.json` by a test), `emptyLists`, `newAgent`, `normalizeAgent`, `cliOf`/`agentId` draft keys, `savedEntry`, `canonical`/`isDirty`, `nameOf`, `modelNames`, `summaryRows`, `serverStateFor`, `cleanAgent` and `templateDraft` |
| `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`) |
| `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 |
| `public/screens/workspace.js` | the read-only Workspace of extra folders, and @mentions |
| `public/styles/ask.css` | The Ask pane and its Quick question chat |
| `public/styles/dashboard.css` | The dashboard: the menu, the spec picker, its confirm and the launching pane |
| `public/styles/docs.css` | Documents and the doc tools |
| `public/styles/ending.css` | The end of a session: the hand-off and the stopping screen |
| `public/styles/git.css` | The git board |
| `public/styles/help.css` | The help dialog, its diagrams and its tabs |
| `public/styles/looks.css` | The looks button and the highlight swatches |
| `public/styles/prefs.css` | User Preferences' side list of tabs, the strip below 720 px, the Saved mark, the setup screen's own chrome, and the in-dialog unsaved prompt (new classes only: the Subagents dialog shares `.looks`) |
| `public/styles/agents.css` | the Agents & models view: the master-detail `.split` (list column, pickable `.split-row`s with `aria-current`, the `.split-pane`), badges, the form's fields, folds and foot, the models lists, the setup pane's state area, and the under-720 px single-column treatment |
| `public/styles/pieces.css` | Shared pieces: cards, options, settled answers, pager, forms, checklist, markdown and the modal |
| `public/styles/planny.css` | Planny the mascot: the flight, his moods and variants, and the wake-up |
| `public/styles/poses.css` | The start-screen poses, one per skill. After the dashboard on purpose: its narrow-window rules override the dashboard's |
| `public/styles/responsive.css` | Print, then the narrow-window rules: last, so its overrides come after everything they override |
| `public/styles/shell.css` | The page shell: banner, top bar and meter, layout, sidebar, aside, footer, waiting and arrival |
| `public/styles/tokens.css` | Colors, type, sizes and the light and dark themes: the variables every other file reads |
| `public/help.js` | the Help dialog's PURE rules: `HELP_TABS` (20 tabs: ids, order, labels, diagram flags; every tab uses the chosen highlight color; Implementation Loop sits right after Watching a build, The git board right after it, and Activities right after Ask a quick question), `helpTabFor()` (which tab opens, FR-8 order, first match wins: finished → Stopping and finishing, server gone or agent adrift → When something looks stuck, opened from the Workspace dialog → Your workspace, then Ask, the Subagents tab → Helpers (subagents), a red-meter dashboard → Session meter, dashboard, a doc or the Overview, a git session → The git board, a build, else What this page is) and `helpKeyTarget()` (roving arrow keys, Home, End, wrapping; a re-export of `tabs.js`'s `tabKeyTarget`). No module-scope DOM, so `node --test` covers it |
| `public/tabs.js` | the WAI-ARIA tabs shared by Help and User Preferences: `wireTabs()` (buttons and panel links, roving tabindex, automatic activation, `aria-orientation` switching at 720 px, an optional `beforeSelect` guard) and the pure `tabKeyTarget()` |
| `public/prefs.js` | User Preferences' PURE rules: `PREFS_TABS` (Appearance, Agents & models, System, Sounds & activities, with hints and the sections each holds), `prefsOpenTab()` and `prefsResetScope()` (the looks keys Back to default resets per tab, or null) |
| `public/git-board.js` | PURE, one import (`pr-url.js`): the git board's rules from a `state.git` snapshot: branch order and the Remote only fold at `REMOTE_FOLD` 50, whether a new branch name is free, which buttons show and are enabled, whether the board still waits on the agent (`boardAwaiting()`: from a click until the agent's next post, not just until `wait` collects it), the plain sentence each click sends as `reply`, the "Last refreshed" line, which files start ticked in the commit dialog, and the pull-request link; the next step (ten rules, `nextStep()`), the tab that owns it, per-tab badges (`tabBadges()`), the busy mode and per-control gate (`busyMode()`, `controlAllowed()`), the tab to show (`pickTab()`), and the create-panel sources and clean-up groups. `app.js` only renders what it says |
| `public/git-board-view.js` | No DOM access of its own: `drawGitBoard(ctx)` draws the tabbed board (header, tab strip with Done with git, the card slot, step strip, Changes / Branches / Sync) from the helpers it is handed (`el`, `md`, `copyButton`), every control through one gate; `screens/git-host.js` hosts it, and `scripts/test-web-console-git-board.mjs` drives it with a recording fake `el` |
| `public/pr-url.js` | PURE, no imports: `prUrl()`, the "open a pull request" link for the GitHub, GitLab, Azure DevOps and Bitbucket shapes (`null` for an unknown kind, no web address, or a non-https result). `git-repo.mjs` re-exports it, and the board's base picker rebuilds the link in the browser with the same code |
| `public/workspace.js` | PURE, no imports: the Workspace's name rules (`nameProblem()`, `NAME_MAX`, `defaultName()`, `freeName()` for the `-2` suggestion), the footer label and its width tiers (`footerLabel()`, `FOOTER_TIERS`) and `changeLine()`, the `Workspace: …` reply line an agent is handed per change. Imported by the server, `cmd-chat.mjs`, `cmd-post-wait.mjs`, `workspace.mjs` and the page |
| `public/meter.js` | PURE, imports only `skills.js`: the session meter. `WEIGHTS` (the events that are not a skill's own launch, merged with each skill's `weight` from `skills.js`; its keys are also `RUN_EVENTS`, the `run` events `post` accepts), `LAUNCH_COUNTED` (workflows whose launch itself scores), the built-phase sizing (`TASK_EVENTS`, the keys of `TASK_BONUS`: `implement-phase` +0 and `implement-review-phase` +1; `isTaskCount()` accepts a whole `tasks` from 1 to `MAX_TASKS` 999; `runPoints()` scores such a run `ceil(tasks / TASKS_PER_POINT)` (3) plus its bonus, and any other run its `WEIGHTS` value), `ANSWERS_PER_POINT` 2 (`answer` entries score per skill run, `floor(count / 2)`), `breakdownFrom()` (the click-the-ring list: one row per scoring entry plus one answers row per skill run), `pointsFrom()` (the count, its sum, folded from `ledger.ndjson` and deduplicated by id, never stored), `levelFor()` with `YELLOW_AT` 5 / `RED_AT` 10, `ringFraction()` (full at `RING_FULL` 15), `WORDS`, `tooltipFor()`, `RED_BANNER` and `meterView()` |
| `public/mentions.js` | PURE, no imports: the `@name` popover's logic — `mentionAt()` finds an `@partial` at the caret, `matchNames()` filters the workspace names, `applyMention()` splices a pick in and returns the new caret. Used by the Ask box, notes and text answers |
| `public/favicon.js` | The tab icon's status bar. `faviconState({ mood, spin })` (PURE) maps the call `renderStatus()` makes for Planny's line to `busy` (the spinning ring), `ready` (`point`), `attention` (`adrift`, `gone`, or `work` without the ring — the stale line) or `plain` (`done`, `happy`); a finished screen gets no special case, so one still offering a press points and lights `ready` (the desktop app's taskbar dot follows), a stranded press is `attention`, and only all done or paused is `plain`; `faviconSvg()` is `FAVICON_BODY` (kept equal to `favicon.svg` by a test) plus a bar along the bottom edge in the `FAVICON_COLORS` color (busy dashed on a white strip, so the states differ by pattern; the rest solid); `setFavicon()` swaps both `<link rel=icon>` hrefs only on a change — the SVG as a data URL, the PNG link drawn through a canvas. Called from `say()` in `renderStatus()`, which runs every second |
| `public/continue-button.js` | The one control that wakes a quiet agent. `continueButton(label, cls)` is a button asking the app for `agent-continue` (held off 4 s after a press); `reconnectOffer(cls)` is that button labeled **Reconnect to agent** under the app and, in a browser, a line telling the person to type `continue` in their terminal. Used by the status line (`screens/core.js`: the dashboard's quiet, launch-saved and way-home-saved lines), the Ask tab (`screens/ask.js`, left of Send while the red no-agent line shows) and the saved-and-waiting launch screen (`screens/starting.js`, app only; a browser reads the hint). |
| `public/app-bridge.js` | The messages the page posts to the desktop app that frames it. `framed()` is true inside a frame; `tellApp(kind, extra)` posts `{ plan2code: kind }`, a named request with no free text: `looks` (the highlight's dark shades, from `applyLooks()`, for the app bar's buttons), `agent-continue` (the in-app **continue** button on the Not running line: the app types the keystrokes `continueKeys()` in `plan2code-app/ui/meter.js` names into the agent's terminal, `continue` and Enter, then under Claude Code its send-now chord ctrl+x ctrl+s, so a word queued behind a stuck turn is delivered), `terminal-open` (the in-app **terminal** button, shown in place of the word in every What to check line while the app's terminal panel is collapsed: the app presses the panel's own Collapse/View button, and only when collapsed; the app tells the page the panel's state with `terminal-state` `{ collapsed }` on the page's `console-ready` and on every change, heard through `onAppMessage` into `page.terminalCollapsed`), `new-session` (the meter popover's New Session: the app presses its own bar button, confirm and all) and `activities-full` (`{ on }`, an Activities game going in or out of full screen: the app lays the console's frame over its bar and terminal and puts the window in full screen, and out of it only if it put it there; `taskbarSwitch()` checks the boolean, and the window permissions are in `capabilities/default.json`). Nothing outside a frame |
| `public/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table, one entry per non-null `subagents` field in `skills.js`, each with its default instruction), `cleanSetting()` (`{ on, instruction, max, strength }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20, `strength` not one of `STRENGTHS`; `strength` is `balanced`, `thrifty`, `best` or `session`, missing reads as `balanced`, saved per project and skill in each `subagents.json` entry and sent as a `Helper strength:` line in the "on" block), `FRAME_LINES`, `blockFor(setting, told)` (the `Subagents:` lines and `subagents` field an agent is owed, given the session setting and its cursor; never says "off" to an agent not told "on"), `checkHelper()` / `checkHelpers()` (the `helpers` house rule) and the page's view rules `showSwitch()`, `switchLabel()`, `helperRows()`, `showTab()`, `CHECKIN_LINE`. Imported by the server, the `cmd-*.mjs` files, `patches.mjs`, `settings.mjs`, the page and the tests; in `SERVABLE` and preloaded |
| `public/notepad.js` | PURE, no imports: the Notebook's rules. `SAVE_DEBOUNCE_MS` 800, `RETRY_STEPS_MS` (1 s up to 30 s), `NOTE_MAX_BYTES` / `NOTEPAD_MAX_IMAGES` / `TAB_NAME_MAX` / `NOTEPAD_MAX_TABS` / `IMAGE_ID_RE` / `TAB_ID_RE` (kept equal to `notepads.mjs` by a test), `noteBytes()`, the save-state reducer `nextSave(state, event)` from `SAVE_START` (states `idle`, `pending`, `saving`, `saved`, `failed`, `too-long`; it returns the timer to arm), `saveStatus()` (the status line's words), `unsaved()` (what `beforeunload` asks on), `keepsText()` (unsaved or too long: a reopen never replaces the editor's text then), `tabSwitch()` (whether leaving a tab must save it first), `NOT_LOADED`, `EDITOR_NOT_LOADED`, `errorSentence()` (one sentence per `/notepad` refusal, else a lost connection), the tab rules `cleanTabName()`, `nameTaken()`, `tabNameProblem()`, `moveTab()`, `dropTab()` and the two-confirm delete `nextDelete()` / `DELETE_STAGES`, and `step()` (wrapping through the pictures) |
| `public/screens/notepad.js` | the Notebook: `#btn-notepad` in the top bar on every screen (disabled while the server is gone, `renderNotepadButton()` in the render pass), `#notepad-modal`, the one CodeMirror editor (made on first open by a dynamic import of `notepad-editor.js`), the page's view of the notepad as `{ tabs, activeId }`, the name form (New tab and Rename, never `window.prompt`), the in-modal two-step delete, and autosave through `nextSave()` to `POST /notepad/text?tab=<id>`, flushed on close, when the page is hidden and before a switch. The editor stays read-only until the first read lands, so nothing typed into an empty editor is saved over a note. **Every save and every picture is bound to the tab it was made in**: `saveTab` is fixed when the change is made, a picture entry carries its `tab`, and a switch waits for the save (`settled()`), stays put with "Not saved yet, so staying on this tab." when it cannot, and drops a deleted tab's unsaved text without sending it |
| `public/notepad-tabs.js` | the tab bar: `createTabs({ onSwitch, onChange })` with `draw(tabs, activeId)` (`role="tab"` buttons, roving `tabindex`, arrow keys, Alt+arrows to reorder, F2 and double-click to rename, native drag and drop with an `.is-drop-before` mark that only a tab drag lights, focus kept across redraws, `#notepad-empty` and `#notepad-body` toggled) and `focusTab()`. No fetches: it calls back, and `screens/notepad.js` owns every request |
| `public/notepad-editor.js` | the Notebook's live-preview editor on CodeMirror 6 (`makeCodeMirrorEditor(parent, { onChange, label })` returning `{ getValue, setValue, setReadOnly, focus, destroy }`). A `ViewPlugin` decorates only the lines in view from the Markdown syntax tree: heading line classes `cm-h1` to `cm-h6`, bullets drawn as a widget, the marks around bold, links, quotes and a heading hidden on every line the selection is not on. The editor sits in a shadow root (`.notepad-cm-host`), because CodeMirror writes its rules as a `<style>` element, which `style-src 'self'` refuses, and adopts them as a constructed stylesheet inside a shadow root. `setValue()` is `setState()`: not reported through `onChange`, and the undo history is cleared (so each tab starts with a clean one) |
| `public/notepad-editor.css` | the one stylesheet of that shadow root, linked from `notepad-editor.js` (a `<link>` inside the root, in `SERVABLE`, not in `CSS_ORDER`): heading sizes, bullets, quote, code and link looks on the console's tokens (custom properties inherit across the boundary, so both themes work). Rules that meet CodeMirror's own base theme use `div.cm-editor` for the specificity |
| `public/vendor/codemirror.esm.js` | CodeMirror 6 (state, view, language, commands, lang-markdown, MIT), bundled into one minified ES module by `scripts/vendor-codemirror.mjs` (sha256 `4ff96d58fc1a5497eb933426bd2d160d2fb0cf490de8bb9302c304096c71c1d4`, the six top-level versions in the script and the file's header comment, everything they pull in pinned by `scripts/vendor-codemirror-lock.json` and installed with `npm ci`, so the same lock gives the same bytes). Never edited by hand: change a version in the script and run `node scripts/vendor-codemirror.mjs --update-lock` (needs npm and network; the packages install in a temp folder, never in the repo), or without the flag to rebuild from the lock |
| `public/styles/notepad.css` | the notebook's own rules: the top bar button, the dialog, the tab bar and its tools, the name form, the delete question, the empty state and the pictures. The editor's look is `notepad-editor.css`, inside its shadow root |
| `public/chat.js` | the Quick question chat's PURE rules, shared by the server and the page: `CHAT_LIMIT` / `CHAT_MAX_CHARS` / `CHAT_MAX_ATTACHMENTS` (the combined image + document cap; `CHAT_MAX_IMAGES` is kept as an alias of it), `chatOffline()` (the server's `409 offline` guard), and the page's view model (`chatView`, `sendState`, `nextAbout`, `contextOptions`, `unreadDot` / `shouldChime`). Ask context is the `{ history, about }` model: `nextAbout()` records the last 3 places visited in `history` and sets `about` only when the person picks one from **+ Add context** (`contextOptions()` lists that history plus *This spec*); dropping it or a successful send clears it, so the page never attaches context on its own. Imports only `answers.js`, no module-scope DOM, so `node --test` covers it |
| `public/starters.js` | PURE, no imports: the Role list (`ROLES`, `ROLE_NOT_SET`, `normalizeRole()`, `needsRoleNudge()`: the dashboard banner shows until `looks.json` carries any `role`), the 19 starter templates (Markdown `## heading` sections, shape pinned by a test) and their per-role orders (`TEMPLATES`, `TEMPLATE_ORDERS`, `templatesFor()`, `templateSwap()` for the replace prompt), and the Ask starter sets (`STARTER_SETS`, `STARTER_SET_FOR`, `startersFor()`). Imported by the page's looks and screens and by the tests; in `SERVABLE`, preloaded by `index.html` and parse-checked. The page owns the wording; a skill only flags its fresh-idea `text` card with `"templates": "idea"` |
| `public/answers.js` | the page's PURE answer-shaping logic (what an answer reads as, what a placeholder offers, whether a send carries an answer at all). Kept out of the page's entry because `app.js` cannot be imported outside a browser, so anything left in it is untestable. The `scripts/test-web-console-*.mjs` tests import it directly. |
| `public/labels.js` | `taskLabel()` / `activityLabel()`: rewrites a build's `Task 4.2 of 6` activity line to `Task 2 of 6` (only for `implement` / `implement-review`; a plan's `Task 2.1` is a real section number). A separate module for the same reason as `answers.js`: pure, so `node --test` can import it |
| `public/boot.js` | `playWake()`: the dashboard's first-open wake-up. Self-contained (it owns its timers, the listeners that swallow input mid-run and the one measured glide transform; the page's `stir()` callback times the nudge between the click and the boot, which `screens/dashboard.js` fills with one snore; `skipEl` — the muted Skip button, and Escape — ends the run early with `onSkip` as the cue to silence queued sounds) and free of module-scope DOM access, so it can be imported by the tests and kept out of the screens' render paths; `GLIDE_AT_MS` / `DONE_AT_MS` are its timings |
@@ -0,0 +1,47 @@
# Architecture: web console server and contract
> Part of [AGENTS.md](../AGENTS.md) and the [Architecture index](./AGENTS-architecture.md): project guidance for AI coding agents.
The web console is split by area: this file (the server, the CLI and the agent contract files), [the page](./AGENTS-architecture-console-page.md) (every `public/` file), [the design points](./AGENTS-architecture-console-design.md) (why it is built as it is) and [Activities](./AGENTS-architecture-activities.md) (the games). Each file below has one row in exactly one of these tables.
## Web Console
Optional local browser UI shipped with **every** skill. Source lives in `src/web-console/` and is fanned into each skill by an `additionalReferences: [{ source: 'web-console', target: 'web-console' }]` entry in `SOURCE_PROMPTS`, landing at `skills/<skill>/references/web-console/`. The bare `plan2code` skill is the hub: it opens the console as `--workflow dashboard`, the page draws the skill menu itself (from each `SKILLS` entry's `card` in `public/skills.js`, through `SKILL_CATALOG` in `public/answers.js`, kept in sync with the install set by a test), and a card click reaches the agent as a `{ "i": "__launch", "skill": ..., "workflow": ... }` send — the dashboard then **resumes its own session** under the launched skill's workflow (`open --resume <sid> --workflow <w>` restates `workflow`/`title`/`specDir` on the live server) and runs that skill's file. `plan2code-review` now has a console of its own AND still runs inside builds on the page (a `review` verdict on Implementation's sign-off card, the **Review it now** button on a finished quick task, or Finalize's Step 2.5 final review, offered on every run), so `plan2code-3-implement`, `plan2code-quick-task` and `plan2code-4-finalize` also carry `review.md`, the review references and `review-scope.mjs`, the same way `implement-review` does. `CONSOLE_WORKFLOWS` in `public/answers.js`, built from the same `SKILLS` list, decides whether a copied hand-off asks the next session for the console.
| File | Role |
|---|---|
| `console.mjs` | the CLI the agent drives: `open`, `post`, `wait`, `chat` (the instant Quick question check), `keep` (copy a cited note attachment into `specs/<idea>/attachments/`), `delete-spec`, `handoff new`, `delete-handoff` (both on `handoffs.mjs`), `status`, `stop`, `help` (a compact summary for an agent that found the binary but not `console.md`; `help <topic>` prints one contract file, `help topics` lists them). `post --wait <N>` posts and waits in one command |
| `server.mjs` | HTTP server, spawned **detached** by `open` (never as a harness background task, which get killed on compaction and at assorted timeouts) |
| `cmd-chat.mjs` | the `chat` command: hand over Quick questions now, never waiting |
| `cmd-help.mjs` | the `help` command: the CLI's usage and the contract's topic files; the usage's workflow list and its build sessions come from `WORKFLOWS` and `isBuild()` in `skills.js` |
| `cmd-open.mjs` | the `open` command: start or resume a session, its server and the browser; refuses a `--workflow` that `isWorkflow()` does not know (exit 2, naming the valid ones), and asks `startsClean()` (`public/hops.js`) whether a resume blanks the page |
| `in-app.mjs` | the desktop app's signal to `open`: `inAppSignal()` reads `PLAN2CODE_IN_APP`, `PLAN2CODE_CONSOLE_SID`, `PLAN2CODE_APP_ANNOUNCE` and `PLAN2CODE_APP_TOKEN`; `announcePage()` POSTs the page to that window's loopback endpoint. Under the app `open` never starts a browser, resumes the app's session and announces the page; with the variables unset nothing here runs. Imported by `cmd-open.mjs` |
| `open-link.mjs` | the desktop app's webview opens no new windows, so the page there sends links off the console (`linkLeavesPage()` in `public/app-bridge.js`: http or https on another origin, caught in `wireChrome()`) to `POST /open-link`. `linkToOpen()` takes http and https only (400 otherwise); `openLink()` starts the default browser with the link as one argument, never through a shell (`rundll32 url.dll,FileProtocolHandler` on Windows, `open` on macOS, `$BROWSER` or `xdg-open` elsewhere) and skips it under `PLAN2CODE_NO_BROWSER`. When that fails the page shows the link with a Copy button to paste into a browser |
| `loop-setup.mjs` | the Implementation Loop's setup, remembered per project in `~/.plan2code/console/loop-setup.json` (one entry per folded project folder, schema 1): defaults, validation and the read and write the `/loop-setup` route uses. The app reads the same file itself for the quick check, so the page never carries that command |
| `cmd-post-wait.mjs` | `post` and `wait`: publish a patch, then collect what the person sent |
| `cmd-small.mjs` | the small commands: keep, forget, delete-spec, handoff, delete-handoff, status and stop; `handoff new` refuses an unknown `--workflow` the same way `open` does |
| `files.mjs` | where the console's files live, how they are written safely, and the argument parser both command lines share |
| `agents.mjs` | the rules of `~/.plan2code/agents.json` (see "Agents file" in [the install file](./AGENTS-architecture-install.md)), console side: `normalizeAgents()` reads the file into clean entries and warnings, never throwing; `validateForSave()` checks what User Preferences sends and names the first bad entry and field; `makeId()`, `buildArgs()` (the command line from an entry) and `resolveCommand()` (where a command runs from, never running it). Served by `GET` / `POST /agents` and `POST /agents/test` in `routes.mjs` |
| `agent-lookup.mjs` | where an agent lives on this machine: `loadAgentList()` reads the shipped `bin/agents.json` (built-in agents and starter templates; `optional` keeps an absent file silent); `findAgent()` gives one command its `found` / `outside` / `missing` state, the path and which search found it (PATH, the Windows saved PATH, npm's global bin, the entry's `installDirs`), with `{bypass}` / `{model}` placeholders expanded to the user's picks. Used by `GET /agents`, `POST /agents/use-path`, the launcher's `chooseCli()` and the Windows picker |
| `inbox.mjs` | the Quick question chat's inbox beside the card slot |
| `console-docs.md` | the topic file for `docs` in a patch (tabs of blocks), named by the console at the first patch that carries `docs`; not read up front. Byte-budgeted with the card and the notes in `scripts/test-console-wire-budgets.mjs` |
| `pointers.mjs` | which topic file the console names and when: once per session per topic, remembered in the session folder (`pointers.json`), reset by a resume |
| `patches.mjs` | checking and merging an agent's patch into the session state: `validate()` (the house rules; allows `templates` only as `"idea"` on a `text` item, anything else exits 3), the patch merge, `resolveDocFiles()` and `applyPatch()` |
| `routes.mjs` | every URL the page can call, in one ordered list (`ROUTES`, walked by `handle()`); `server.mjs` hands each request to it |
| `scan.mjs` | what the dashboard knows about the repo: `scanProject()`, `classifySpec()` (a folder's files to a spec state), `TASK_LINE_RE` (re-exported from `spec-files.mjs`) and `removeSpec()` |
| `sessions.mjs` | a session's roots and handle files (`repoRoots()`, `healthOk()`, `attachmentName()`: the kept-file name `<slug>-<id8>.<ext>`, the same upload always gets the same name, `readOverview()`) and the console folder's housekeeping: the three sweeps `open` runs fire-and-forget after it prints (`sweepUploads()`, `staleSessions()` / `removeSessions()`, `staleScratch()` / `removeScratch()`) and `cleanupFindings()` / `removeCleanup()` for User Preferences → System → Cleanup |
| `settings.mjs` | the person's saved console settings: Subagents and pull-request hosts |
| `spec-files.mjs` | no imports: how a spec's markdown files are read, `MARKERS`, `TASK_LINE_RE`, `TASK_ID_RE`, `CHECKBOX_RE`, `STATUS_RE`, `statusOf()` and `countTasks()`; shared by `scan.mjs`, `patches.mjs` and `src/skill-scripts/specs.mjs` (through `consoleModule()`) |
| `static.mjs` | serving the page's own files: `SERVABLE` (the allow-list), `TYPES`, caching and ETags, the accent colors, and `CSS_ORDER` + `joinedStyles()`, the one place the cascade order is stated |
| `workspace.mjs` | the session's extra folders, and the folders remembered per project and spec |
| `strengths.mjs` | the server-side name for `public/strengths.js` (a re-export) |
| `strengths` key (`src/launcher/models.json`, `~/.plan2code/models.json`) | per agent, `thrifty`/`balanced`/`best` rows of `{model, effort?}`; a user row beats the shipped one, and a row whose model is not in the agent's Models list is ignored. `models.rs` `strengths_for` and the JS resolver are held to `scripts/fixtures/strength-cases.json` (change the fixture first, then both) |
| loop setup `phaseStrength` / `strengths` | `loop-setup.mjs` keeps the per-project toggle and, per spec folder, a list of `{n, name, strength}` picks, pruned as specs finish and phases move (twin: `LoopSetup` in `loop_driver.rs`). `loop_driver.rs` starts a phase with `AgentManager::start_phase_on(prompt, model, effort, env)` and sets `PLAN2CODE_LOOP_STRENGTH` (thrifty, balanced or best) in its environment, which `cmd-open.mjs` reads to give the phase's helpers the same Helper strength line; a retry goes one step up with `models::next_strength` (Rust twin of `nextStrength`; a Match my session phase stays) |
| `git-repo.mjs` | the one read-only reader of a git repository: the worktree status (`countPending()`, behind `pendingFiles()`), the branch table, the default branch, a merge or rebase in progress, the remotes and their web addresses, the last fetch and the pull-request link; `snapshot()` is what `open` and every `reread` store as `state.git`. Every git call carries `GIT_OPTIONAL_LOCKS=0`, so a background look never takes the index lock. Imported by `cmd-open.mjs`, `cmd-post-wait.mjs` and `sessions.mjs`; the git skill's `git.mjs` reaches it through `common.mjs` |
| `handoffs.mjs` | the handoff store, the only code that names, lists, marks, deletes and sweeps handoffs, all in `~/.plan2code/handoffs/` (`PLAN2CODE_HANDOFFS_DIR` for tests; `PLAN2CODE_NOW` pins its clock): `newHandoff()` claims `YYYY-MM-DD-HHmm-handoff` (`-2`, `-3` on a clash, the `.json` created exclusively) and writes only `<id>.json` (`{ v: 1, id, title, worktree, project, spec, workflow, skill, written, fromStop, usedAt }`), the agent writing `<id>.md`; `listHandoffs(worktree)` (unused, same worktree, `.md` present, newest first, title and Next task read off the document); `readHandoffMeta()`, `markHandoffUsed()`; `removeHandoff()` (`HANDOFF_ID` only, regular files, never a link, realpath inside the folder, throws on any refusal); `staleHandoffs()` / `removeHandoffs()` for the sweep |
| `notepads.mjs` | the notebook store (the feature is named Notebook; its code, routes and storage folder keep the name `notepad`), the only code that names, reads, writes and removes notebooks, one per folder Plan2Code runs in, in `~/.plan2code/notepads/<folder-name>-<12 hex>/` (`PLAN2CODE_NOTEPADS_DIR` for tests), split into named tabs: `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order, last, tabs: { id: { name, created, sent? } } }`) and `tabs/<id>/note.md` with `tabs/<id>/images/`. `notepadKey()` (the folder's basename slug and the first 12 hex of `sha256(foldKey(folder))`), `listTabs()` / `defaultTabId()`, `readNotepad(folder, tab)` (never creates or writes anything; `{ tabs, last, tab }` with the tab's `text`, `savedAt` and `images` repeated at the top), the tab changes `createTab()` / `renameTab()` / `reorderTabs()` / `setLastTab()` / `deleteTab()` (index first, then the folder; names pass `normalizeTabName()`, `TAB_NAME_MAX` 40, any case compared by `nameKey()`, `NOTEPAD_MAX_TABS` 20), `saveNote(folder, tab, text)` (1 MB cap, atomic), `addImage()` / `addThumb()` / `removeImage()` (JPEG bytes only, 200 pictures per tab, UUID names), `imagePath()` (regular files whose realpath stays inside the folder), `staleNotepads(now, maxAgeMs)` (the real folders directly under it named like a key, never a link or a file, whose newest file is at least `maxAgeMs` old, as `{ key, folder, path }` with `folder` from `meta.json` or null), `removeNotepad(key)` (the key checked against `NOTEPAD_KEY_RE`, the path kept inside the notepads folder by `path.relative`, a link refused, then the whole folder removed; User Preferences, Cleanup is its only caller) and `NotepadError` (`code` and `status`, turned into `{ error }` by the `/notepad` routes). **Migration:** a notepad in the first shape (`note.md` and `images/` at the top) reads as one virtual tab, Notes (`LEGACY_TAB_ID`), and writes nothing; its first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, every step safe to run again after a crash. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders on the next write. Every write runs under a `notepad.lock` in the notepad's folder. The agent CLI never imports it: nothing in a notepad reaches the agent |
| `picker.mjs` | the per-OS native folder picker behind **Browse…** (`pickerCommand()` → `{ command, args, env }` or `null`; `pickFolder()` runs it with async `spawn`, so the server keeps serving while the dialog is open). Copied from `src/launcher/plan2code.js` (self-contained CommonJS, so it cannot be shared) with the prompt as a parameter; a drift test keeps the two in step |
| `update-check.mjs` | the dashboard's release check, server-only (never in `SERVABLE`): `compareVersions()` (numeric X.Y.Z, `null` otherwise), `latestTag()` (the highest `refs/tags/vX.Y.Z`, peeled `^{}` and pre-release tags skipped), `checkForUpdate({ installed, cacheFile, now, run })` (never throws) and `runLsRemote()` (`git ls-remote --tags` on the repo: no shell, `GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`, SSH `BatchMode` when `GIT_SSH_COMMAND` is unset, `windowsHide`, killed at 10 s; git authenticates itself, the console never touches a credential). The answer, failures included, is cached for an hour in `~/.plan2code/console/update-check.json` (`UPDATE_CHECK_FILE`, in `PROTECTED_CONSOLE_FILES` so no sweep removes it). `server.mjs` starts it after the ready line and never awaits it; `stateFrame()` carries `update: { installed, latest }` only when a newer release exists (its `latest` is part of `haveKey()`, so a page that connected first still gets it), and `GET /version` returns `{ version, latest }`. Tests seed a fresh cached failure in every console home, so no test server reaches the network. The `plan2code` launcher reads the same cache for its terminal release notice (a copy of this module sits in `~/.plan2code/bin/`) |
| `console.md` | the core of the agent-facing contract, read once per conversation (every skill ships the same copy, so a dashboard hop never re-reads it): starting, the turn (`post --wait`, the exit codes, handling a send, `settle`), posting, the payload and its kinds, documents (including `file` blocks), the house rules, and an index of the topic files below with the moment each is read. A test caps it at 24,000 characters |
| `console-finish.md` · `console-stop.md` · `console-chat.md` · `console-workspace.md` · `console-subagents.md` · `console-launches.md` · `console-meter.md` · `console-attachments.md` · `console-trouble.md` | topic files, each read only when its moment first comes: finishing (the finish and its buttons), stop requests (the way home mid-workflow, `stopWarning`, resuming a pause), Quick questions, the Workspace, standing instructions and helper reports, dashboard launches and the menu payload, the session meter's `run` events (read only when a `run` is refused: the notes inline every `run`), keeping a cited note attachment, and recovery |
| `notes/<workflow>.md` | per-workflow notes (`init` for both inits, `pathfinder` with Briefs, `plan`, `revise-plan`, `document`, `implement` for both builds, `loop` for a build the desktop app's Implementation Loop runs with `--loop` (where it reports a `loopOutcome` instead of asking for sign-off), `quick-task`, `review`, `finalize`, `handoff`, `changelog`, `git`, `xray`, `diagnose`, `pr-prep`, `test`). Each skill's Interface line reads `<D>/console.md` and its own notes file right after `open`; a test checks every skill names one that exists |
| `building.md` · `building-review.md` | the build half of the contract, for `implement`, `implement-review` and `quick-task`: progress posts (`agent.activity`, `agent.quietMinutes`, `file` blocks re-read with `refresh`), the chat check between tasks, questions mid-build and stop requests; `building-review.md` is the review run on the page (the sign-off's `review` verdict, **Review it now**, Implement + Review's Stage 2, Finalize's Step 2.5), read only when asked for |
@@ -0,0 +1,44 @@
# Architecture: Ghoul Rush core
> Part of [AGENTS.md](../AGENTS.md) and the [Architecture index](./AGENTS-architecture.md): project guidance for AI coding agents.
Ghoul Rush's shared core, drawing, weapons, story and sound files under `src/web-console/public/activities/ghoul-rush/`. The other games and the rules every game follows are in [Activities](./AGENTS-architecture-activities.md); Ghoul Rush is split over [core](./AGENTS-architecture-ghoul-core.md), [stages](./AGENTS-architecture-ghoul-stages.md) and [rides](./AGENTS-architecture-ghoul-rides.md).
| File | Role |
|---|---|
| `public/activities/ghoul-rush/ghoul.js` | Ghoul Rush's public face and nothing else: it re-exports the parts below, so the page and the tests import from one place. Everything lives under `ghoul-rush/`: `core/` (the rules, rooms, run flow, power-ups, dice, bonus rounds), `arms/` (secondary weapons), `draw/` (shared drawing), `story/` (the intro story, stage and boss cards, game over), `sfx/` (shared sounds), `stages/<stage>/` and `rides/<ride>/` (each with its rules, art and sounds). |
| `public/activities/ghoul-rush/core/ghoul-tables.js` | Ghoul Rush's numbers and tables: the shared timings and sizes, `PACKS` with every pack's monsters, bosses and hooks joined in, the seeded dice, and `roomFor`. Loads first and imports none of the other parts. |
| `public/activities/ghoul-rush/core/ghoul-kit.js` | `KIT`, the helpers handed to the stage packs: one object `ghoul-play.js` fills as it loads, so a part that only passes it on has no load-order tie to the play loop. |
| `public/activities/ghoul-rush/core/ghoul-planny.js` | The ground and Planny: surfaces, shelves, landing, and how he runs, jumps and falls. |
| `public/activities/ghoul-rush/core/ghoul-monsters.js` | The monsters: spawning, how each kind moves, and what they throw. |
| `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/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/arms/ghoul-flare.js` | The Road Flare's rules (`useFlare`, `stepFlareFly`, `stepRoadFire`; no imports, handed the helpers by `ghoul-arms.js`): a lob that lands as a patch of fire, burns monsters on a tick, melts a Frozen Ghoul at once, shows a shade and melts the Widow's veil; never hurts Planny |
| `public/activities/ghoul-rush/story/ghoul-story.js` | Ghoul Rush's intro story: the pages' text as data and the rules (lockout, reveal, skip) as plain functions over a round; drawn by `ghoul-story-draw.js`, sounded by `ghoul-sfx-story.js`, the lore bible in `prototypes/Ghoul-Rush-TODO.md` |
| `public/activities/ghoul-rush/story/ghoul-story-draw.js` | The intro story's drawing (`storyArt(d)`): eight animated scenes in canvas shapes (the road, the house on the hill, the hunger, the long arms, the farthest rooms, why YOU, no way back, the door to The Long Hall) with the heading, the lines typing out, the page dots, the always-visible skip hint with its hold bar and the pulsing continue hint; drawn over the field while `round.phase === "story"`; reuses the intro card's helpers (`poly`, `dot`, `stroke`, `faint`, `flame`, `titleLayout`, `dropAt`); no gradients |
| `public/activities/ghoul-rush/story/ghoul-sfx-story.js` | The intro story's own sounds as data (no imports): `STORY_SFX` tones for the pages' `cues` (wind, a bell, a heartbeat, a door creak, knocks, a whisper, the flashlight click, the page turn) and the `hums` drone under the whole story; merged by `ghoul-sfx.js` |
| `public/activities/ghoul-rush/draw/ghoul-picker-draw.js` | The choice of stage, its drawing: `pickerArt(d)`, handed `ghoul-draw.js`'s helpers (`lookOf`, `label`, `roundRect`, `circle`, `BOSS_ART`, `drawGourdFire`, `GOLD`), returning `drawPicker` (a card per stage offered: its picture of its rooms with its boss standing there, its name, line and boss, the pick raised and edged in gold, and how to choose), `drawSelect` (the stage select for testing: every stage in a list, two columns past 8, the one picked out with its picture and a chip per room) and `stageColor` (a stage's boss room's color, also the tally dots'). Split from `ghoul-draw.js` to keep it under the 3,000-line cap |
| `public/activities/ghoul-rush/core/ghoul-powers.js` | Ghoul Rush's power-ups and pickups (no imports: `ghoul.js` hands its rules a kit, `POWER_KIT`, of `landing` and the numbers they need): `POWERS` (each power-up's name, line, color, `ms` if timed, drop `weight`, and its rule, the Lantern's `dark`), `TIMED`, `PILL_WORDS`, `FLAP_CLEAR`, `HOURGLASS_MS`, `CANDY_POINTS`, `POWER_POINTS`, `CRYSTAL_POINTS`, `powerHere(round, kind)` (whether a power-up can turn up in the room as it is now; a new rule, such as a stage-only power-up, goes in `POWERS` and is checked here), `pickPower`, `applyPower(round, kind, kit)` (`ghoul.js` exports it bound to its kit as `applyPower(round, kind)`) and `pickups` (candy, placed and dropped power-ups, crystals up high and the key, taken by touch; drops fall and fade). Split from `ghoul.js` to keep it under the 3,000-line cap |
| `public/activities/ghoul-rush/arms/ghoul-arms.js` | Ghoul Rush's secondary weapons (imports only `ghoul-powers.js`; a pack in `PACKS`, `ARMS`): the double tap (`pressFire`, `releaseFire`, called from the game's `key()` and `release()`, never from `round.input.fire`, so bots never throw), the bag `round.arms` (`useArm`, `armOnTop`: a ride room skips what needs a floor), each weapon's rule (a shot with `arm` through `moveShots`, or a hazard), and `armBossDamage` (scaled to depth, capped at `ARM_BOSS_SHARE` of a boss's hp a fight). Weapons' names, bundles and caps are in `POWERS` (`arm: true`, weight 0), the stage's own in `STAGE_ARMS`, the kill drop band in `armDrop`, all in `ghoul-powers.js`. |
| `public/activities/ghoul-rush/arms/ghoul-arms-draw.js` | The weapons' art (`armsArt(d)`): their badges (`powers`), `hazards`, `shot` for one in flight, `pill` for the HUD's icon and count, `front` (stars over the dazed), `lights` and `react`. Dynamite's stick, blast and badge stay in `ghoul-mine-draw.js`. |
| `public/activities/ghoul-rush/arms/ghoul-rockets.js` | The Bottle Rocket's rules, the common weapon every stage sells: one use lights three rockets, one ahead, one up and one behind |
| `public/activities/ghoul-rush/arms/ghoul-rockets-draw.js` | The Bottle Rocket's drawing (`rocketArt(d)`): the muzzle's flash and smoke, the flared rocket on a stick with a glowing head, the fountain of sparks it sheds and the burst when it goes off |
| `public/activities/ghoul-rush/arms/ghoul-pans.js` | The Cast-Iron Skillet's rules, the East Wing's weapon: three pans that circle Planny, then spiral outward until they are off screen |
| `public/activities/ghoul-rush/arms/ghoul-sfx-arms.js` | The weapons' `tones` (`ARMS_SFX`), merged by `ghoul-sfx.js` like a stage's. A first pass, not yet picked by ear. |
| `public/activities/ghoul-rush/core/ghoul-run.js` | Ghoul Rush's run flow (no imports: `ghoul.js` hands its rules `RUN_KIT`, the room and stage tables, the timings and the helpers that set a room up, and binds them): `newRound`, `setupRoom`/`resetRoom`, the stage pick (`stagesLeft`, `nextRoom`, `steerPick`, `pickStage`), the stage select for testing (`openSelect`, `steerSelect`, `takeSelect`: a practice round, `round.practice`, that keeps no best score or record), `camera`, `respawn`, `lockArena`, `clearRoom`, and a room's monster supply (`spawners`, `horde`, `hurry`). `ghoul.js` re-exports `newRound`, `stagesLeft`, `steerPick`, `pickStage`, `steerSelect` and `takeSelect`, and its game answers `stageSelect()`. Split from `ghoul.js` to keep it under the 3,000-line cap, with the same random draws in the same order |
| `public/activities/ghoul-rush/core/ghoul-dice.js` | Ghoul Rush's Lucky die rules (no imports: `ghoul.js` hands them `DICE_KIT`): `MAX_DICE` (9, the most one bonus or ride pays; dice in hand have no limit), `ROLL_MS`, `TUMBLE_MS`, `SAVED_TIME_MS`, `markRest` (the last solid ground Planny stood on), `reviveSpot`, `beginRoll` (called by `lose` when `round.dice > 0` and not `round.infinite`: the round holds in the phase `ask` and asks "Use a Lucky Die?", the event `diceAsk`), `askStep`, `steerAsk`, `answerAsk` (Yes spends one die and holds in the phase `roll`; No keeps every die, the event `diceKeep`, and lets the loss go ahead; a press inside `ASK_GUARD_MS` is ignored so the key held at the death cannot answer), , `rollDice` (one die at a time from advance's `random`, events `diceStart`, `diceRoll`, `diceFace`, `diceSaved`, `diceFail`; a six revives with the Garlic shield and `SAFE_MS`, and blows apart every monster in view in a room without a boss (`diceBlast`, kills with `how: "luck"`, points but no drops); no six hands the loss back to `takeLife`) |
| `public/activities/ghoul-rush/core/ghoul-bonus.js` | Ghoul Rush's bonus rounds, the rules (imports only `MAX_DICE`; no random numbers): a room with `bonus: true` (the Runaway Cart; the Carnival's dark ride is meant to follow) gets `round.bonusRound = { hearts, max, dice, over, won, perf }` on entering it (null elsewhere; `round.bonus` is already the time bonus score). A life lost in it is a heart lost through the same `lose`/`takeLife` (so Garlic, the safe moment and `round.infinite` work as ever; no Lucky die is rolled for a heart); the last heart gone calls `endBonus(round, false)` from `respawn` (no dice, no game over, the run's lives untouched), and a finish alive calls `endBonus(round, true)` from `clearRoom` (`diceFor`: `BONUS_FLOOR` 3 plus up to 6 by hearts, clean obstacles, acts and a steady hand, added to `round.dice`, which has no limit). A room's pack notes its performance in `bonusRound.perf` (`total`, `hits`, `acts`, `goal`, `steady`); both ends hold the phase "clear" for the card (`CARD_MS`, `CARD_LOST_MS`) and set `bonusRound.result`. Events `bonusStart`, `bonusEnd`; `heartsText(b)` is the HUD pill |
| `public/activities/ghoul-rush/core/ghoul-bonus-draw.js` | The bonus rounds' art (`bonusArt(d, die)`): `card` ("BONUS CLEARED! +N LUCKY DICE" with the dice tumbling in, or the short "BONUS LOST"), `react` (the intro banner, the end, the hearts-left float) and `tick` (a click for each die landed) |
| `public/activities/ghoul-rush/core/ghoul-dice-draw.js` | The Lucky die's art (`diceArt(d)`: the small drop, the rolling die on a panel placed away from Planny, the `ask` panel ("Use a Lucky Die?" with YES and NO, the lit one gold), the sweeping "LUCKY-SAVE" word, and `react` for the dice events, which plays `ghoulLuckySave` once on the revive) |
| `public/activities/ghoul-rush/story/ghoul-gameover-draw.js` | The lost end screen's "G A M E - O V E R" (`gameOverBanner(d)`, `dropAt`): nine letters dropping in with a stagger and one bounce, then bobbing on a sine wave under a slow pulse, red and bone with a dark shadow, drawn above the score panel and never on a win. `ghoul.js` keeps ticking the clock on the lost end screen (`view.overMs`) and plays the mechanical laugh track there: `ghoulLaughTrack`, `ghoulLaughTrack2` and `ghoulLaughTrack3` in `ghoul-sfx.js`, one second apiece (a tone may not pass 1.2 s). |
| `public/activities/ghoul-rush/story/ghoul-intros.js` | The stage intro cards' words and colors: `INTROS` per stage id (`title`, `palette` {a, b, glow}, `kicker`, 3 or 4 `lines` of flavor text at most `MAX_LINE` characters, `boss`), `introFor(id)`. Always addressed to YOU. A test fails for a stage in `STAGES` with no card. |
| `public/activities/ghoul-rush/story/ghoul-intro-draw.js` | The intro card's drawing (`introArt(d)`, `titleLayout`, `dropAt`): the title's letters dropping in and glowing, one themed flourish per stage (frost crystals, bunting, pickaxe sparks, leaves, candle flames, ...), the lines fading in, the boss and the pulsing "Press any move key or fire to enter". Drawn over the field while `round.phase === "intro"`. The phase itself lives in `ghoul-run.js` (`startIntro`, `stepIntro`, `takeIntro`, `INTRO_MIN_MS` 1.2 s: any fresh move key, fire or a click moves on after it, repeats never, and the card never moves on by itself); the tone is `ghoulStageIntro`. |
| `public/activities/ghoul-rush/story/ghoul-boss-intros.js` | The boss intro cards' words: `BOSS_INTROS` per boss id (`name`, which must equal the boss's `name` in its pack's `bosses` table, an `epithet` of at most `MAX_EPITHET` characters and an optional `accent` color), `bossIntroFor(id)`. A test fails for a boss room whose boss has no entry. |
| `public/activities/ghoul-rush/story/ghoul-bossintro-draw.js` | The boss intro card's drawing (`bossIntroArt(d)`): a "BOSS FIGHT" title whose letters slam in with a screen shake and a heartbeat pulse, the boss drawn from its own art (`BOSS_ART`, the way the stage pick does) at a big scale in a spotlight on the stage's palette, its name, the epithet and the pulsing "Press any move key or fire to start the fight"; a boss whose art throws falls back to a silhouette. Drawn over the field while `round.phase === "bossintro"`. The phase lives in `ghoul-run.js` (`startBossIntro`, run by `enter` on every boss room, and `onCard`; it shares `introMs`, `stepIntro`, `takeIntro` and `INTRO_MIN_MS` with the stage card, and a respawn never shows it); the tone is `ghoulBossIntro`. |
| `public/activities/ghoul-rush/draw/ghoul-monsters-draw.js` | The generic monsters' art (`monsterArt(d)`, no imports; `ghoul-draw.js` hands it its helpers `ellipse`, `circle`, `line`, `rotate`, `turned`, `eye` and the colors): `drawZombie`, `drawZombieKin`, `drawHuntsman`, `drawCrawler`, `drawBat`, `drawGhost`, `drawSkeleton`, `drawGourdling`, `drawHound`, `drawSpider`, `drawWraith`, `drawSpitter` and the missiles `drawBoneShape` and `drawGlob`. Split from `ghoul-draw.js` to keep it under the 3,000-line cap |
| `public/activities/snake-sfx.js` · `public/activities/flock-sfx.js` · `public/activities/golf-sfx.js` · `public/activities/trails-sfx.js` · `public/activities/bugs-sfx.js` · `public/activities/drive-sfx.js` · `public/activities/stack-sfx.js` · `public/activities/bumper-sfx.js` · `public/activities/rapids-sfx.js` · `public/activities/fuse-sfx.js` · `public/activities/hop-sfx.js` · `public/activities/bounce-sfx.js` · `public/activities/ghoul-rush/sfx/ghoul-sfx.js` | each game's own sound effects as data, `{ tones, hums }` in the shapes `tones.js` documents, every name prefixed with the game id (`driveEngine`, `ghoulMoan`), merged and frozen by `tones.js`; no imports, but for `ghoul-sfx.js`, which merges each Ghoul Rush stage's own `ghoul-sfx-<stage>.js` into its `tones`, `hums` and `music`, and `snake-sfx.js`, which merges `snake-music.js` as its `music`; `trails-sfx.js` and `flock-sfx.js` have `songs` instead of `music` |
@@ -0,0 +1,56 @@
# Architecture: Ghoul Rush rides
> Part of [AGENTS.md](../AGENTS.md) and the [Architecture index](./AGENTS-architecture.md): project guidance for AI coding agents.
Ghoul Rush's ride files (the mat, the stair, the cart and the rest). The other games and the rules every game follows are in [Activities](./AGENTS-architecture-activities.md); Ghoul Rush is split over [core](./AGENTS-architecture-ghoul-core.md), [stages](./AGENTS-architecture-ghoul-stages.md) and [rides](./AGENTS-architecture-ghoul-rides.md).
| File | Role |
|---|---|
| `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/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/rides/cart/ghoul-cart.js` | Ghoul Rush's Runaway Cart, the Mine's ride room, its rules (no imports; draws no random number): the first room where a pack takes Planny's movement over. It adds the pack fields `ride` (a list of `(round, ms, k) => true` hooks run each slice before the walking rules; one that returns true has moved him) and `place` (a list of `(round, k)` hooks run whenever he is put down in a room: a room set up, a respawn), uses `target` (the crates), and `round.camLead` (units the camera leads further). The cart (`round.cart`, null elsewhere) rides the room's `ride.track` polylines (slope speed, lean and brake, jump, air steering, ramp launch, landing on the line under it, derail into the chasm), ducks under `ride.beams`, wrecks on `rubble` and unbroken `crates` (two bolts break one), is chased by the boulder, passes `checks` (a life lost puts it back at the last) and halts at `stop` where the door opens; a ledge imp (`ledgeimp`) leaps into it and steals light, a canary's scream drops a slide of rubble on the track ahead. Exports `flight`, `trackY`, `linesAt` and `linesOf` for the unit suite. Events `cartJump`, `cartLand`, `cartLaunch`, `cartBrake`, `cartDuck`, `crateHit`, `crateBreak`, `cartCrash`, `boulderNear`, `checkpoint`, `cartStop`, `ledgeLeap`, `slideWarn`, `slideFall`; causes `derail`, `beam`, `crash`, `boulder` |
| `public/activities/ghoul-rush/rides/cart/ghoul-cart-draw.js` | The Runaway Cart's art: `LOOKS` (`custom: true`, `pack: "cart"`, always dark), `cartArt(d)` returning `backdrop`, `ground`, `moving` (every frame: the cave in cached parallax tiles over a chasm, the trestled track, ledge pillars, signal posts, rubble and the buffer stop in cached chunks, hanging lamps, signal lamps, crates, a slide's dust and pour; the cart too once it has stopped, so Planny walks out past it), `front` (the cart over Planny, the beams, the boulder, flying splinters, speed streaks, the foreground rock), `lights` (headlamp, hanging and far lamps, signals, beams), `monsters` (the ledge imp) and `react`; its `VOICES` (borrowed tones), `EVENT_VOICE`, `LOSE_WORDS` and `LOSE_SOUNDS`. It keeps its own offscreen layer cache (keyed by scale), draws no random numbers (a hash) and leaves short-lived bits in the view's `fx` (`cartBits`, `cartPours`, `cartLand`, `cartStop`). Its header lists every field the art reads off the rules |
| `public/activities/ghoul-rush/rides/lantern/ghoul-lantern.js` | The Drowned Lantern (Gallows Bog's bonus round, not a ride) as a pack (`LANTERN`): a top-down game on one fixed screen where YOU carry a lantern over an island of mossy hummocks and plank walks round Old Mother Bog's pool, light five wisp shrines (stand on a stone `SHRINE_MS`, the time kept if you step off), then run back to the boat at the landing. Pack fields `ride` (moves Planny) and `place`; state in `round.runner` (`id` "lantern"), positions in field units with y counted down; the room's `ride` holds the island (`hummocks`, `planks` as hummock pairs, `shrines`, `start`, `boat`, `pool`, `bodies`) and the hunters' tables (`lurker` route, `leeches` routes, `wisps`: a guardian per shrine with its `phase`, roamers with `wake`). Keys: arrows walk (a walk into the water slides along the shore or plank, `slide`), SPACE flares (a ring `FLARE_R` that bursts wisps and scatters leeches, costing `FLARE_OIL`; a sputter without the oil); `fire()` and the arm double-tap are off for this room. The oil burns down over `OIL_MS` and the light (`lightR`) with it; a lit shrine fills it. One rule per hunter: the Lurker hears steps on wood, flares and shrines, swims to the spot, lines up a lane through it (`AIM_MS`) and dashes (it strikes where it heard you), rests deaf, and cowers once Mother rises; guardian wisps circle their shrine and rush a lantern within `GUARD_SENSE` on a `LEASH`, roamers leave the pool at the third to fifth shrine; leeches stay at the light's edge and bite only once the flame gutters; bog bodies rise only for someone standing still beside them; Mother's hand (from the third shrine or `MOTHER_LATE_S`) tracks, locks and slams, one after another once the fifth raises her. Catches cost the bonus round's hearts and never move Planny; `lanternMeet` names each hunter's rule once; `runner.marks` lists what a banner must keep clear of (read by ghoul.js's `underBanner`); `lanternHums` gives ghoul.js the held sounds; the grade is `total` 5, `hits` (kinds that caught you), `acts` (flare pops and close calls), `steady` (the flame never guttered). No random numbers; a Planny put at the door finishes too, as a ride's finish line does |
| `public/activities/ghoul-rush/rides/lantern/ghoul-lantern-draw.js` | The Drowned Lantern's art, the whole field drawn by `lanternArt(d).field` (like Holy Roller's): `LOOKS`, `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`, `TAGS` (each hunter's rule, shown once over it, one at a time); the water and Mother's pool, the island and the boat, then one dark layer with a hole per light (`paintDark` from ghoul-draw.js), and over it what the dark must never hide: the island's moonlit edges, the shrines' beacons and progress, the bodies' bubbles and red reach, the leeches' eyes, Mother's eyes, head and hand shadow, the Lurker's eyes, its lane and dash, the wisps, Planny with the ring of his light (the leeches' line, red when the oil is low) and the boat's beacon; the HUD band (shrine flames, the hint line, the oil bar with its flare ticks); no random numbers, everything from a hash and the clock |
| `public/activities/ghoul-rush/rides/lantern/ghoul-sfx-lantern.js` | The Drowned Lantern's own sounds as data (no imports): `LANTERN_SFX` with `tones` (`ghoulLantern<Act>`: a creak per step on wood, the flare, the shrine, a cue per hunter heard before it reaches you, Mother's wake, rise, hand and slam), `hums` (`ghoulLanternLurk`, `ghoulLanternMother`, asked for through `lanternHums`) and `music` (`ghoulLanternTheme`, the picked Tiptoe plucks track, named in `ROOM_MUSIC`); first drafts until the vote; merged by `ghoul-sfx.js` via `STAGE_SFX` |
| `public/activities/ghoul-rush/rides/dark-ride/ghoul-ride.js` | The Carnival's dark ride (a bonus round) as a pack (`RIDE`), the rules ported from `prototypes/ghoul-rush-ride/gallery.html`. Pack fields `ride` (returns true, so Planny never walks; steps the ride in 16 ms steps), `place` (makes `round.gallery`, the ride's state) and a new `pointer` (the mouse, handed on by `ghoul.js`'s `pointer(type, x, y)`); the entities (`K`: pop, lant, axe, chand, door, hand, head, eyes, boss, inno, mir, web, mini), hit tests with aim assist, the duck zone, hearts through `kit.lose`, the grade (5 to 9 dice, `perf.dice`). Events `ride<Name>` (`SOUNDS`), causes `CAUSES`. Its own seeded random stream; draws no `Math.random` |
| `public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-scenes.js` | The dark ride's scene table as data (12 rooms, lengths, speeds, spawn rows in author coordinates), no imports |
| `public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-core.js` | The ride's shared basics: the 96 by 54 field's constants, math helpers, the bound state `G` (a live import), `rnd`/`rand` (seeded) and `vrand` (visual) |
| `public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-draw.js` | The ride's art entry (`rideArt(d, die)`: `field(ctx, v)` draws the whole field by phase, `tick` the cascade's sounds); `ghoul-draw.js` hands over to it when `round.gallery` is set. Parts: `ghoul-ride-gfx.js` (canvas helpers), `ghoul-ride-draw-kinds.js` (animatronics, mini-bosses, the Barker), `ghoul-ride-draw-sets.js` (the 12 sets, far walls, aisle, near layer), `ghoul-ride-draw-hud.js` (car and Planny, HUD, duck strip, reticle, title, end cascade) |
| `public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-gfx.js` | The ride's drawing helpers: the bound 2D context and the short fill, stroke and shape calls the ride's art is written in |
| `public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-draw-kinds.js` | The ride's drawn things: every figure, beast, lantern, blade, door, hand, head, mirror, web and boss, a port of the prototype's draw code (`prototypes/ghoul-rush-ride/gallery.html`) |
| `public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-draw-sets.js` | The ride's rooms drawn: each room's far wall, set pieces front and back, aisle and the near pillars, a port of the prototype's world draw |
| `public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-draw-hud.js` | The ride's car and the screen around it: Planny in his car, blood and sparks, the lens, the hearts, the progress bar, the room plaque, the aim, the title and the cleared card |
| `public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-voices.js` | The ride's `LOOKS`, `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS` and `react` (every `ride<Name>` event plays tone `ghoulRide<Name>`) |
| `public/activities/ghoul-rush/rides/dark-ride/ghoul-sfx-ride.js` | The ride's synthesized sounds as `tones` (`ghoulRide<Kind>`) and its music `ghoulRideDrone` (`RIDE_SFX`, merged by `ghoul-sfx.js`) |
| `public/activities/ghoul-rush/rides/sled/ghoul-sled.js` | The Coffin Sled (the Frozen Lake's bonus round) as a pack (`SLED`), modeled on the Runaway Cart (`ghoul-cart.js`): pack fields `ride`, `place` and `target`; the track of ice lines with cracks, headstones, drifts, low branches, hands, icicles and popping ghouls, checkpoints, hearts through the Cart's bonus machinery and the grade (3 to 9 dice). Adds no monster, boss or hazard kind and draws no random number; every number is an exported constant documented in its header |
| `public/activities/ghoul-rush/rides/hearse/ghoul-hearse.js` | The Midnight Hearse (the Graveyard's bonus round) as a pack (`HEARSE`), modeled on the Coffin Sled: pack fields `ride`, `place` and `target`; state in `round.runner` (`id: "hearse"`); a flat road of two lanes (road and verge) switched with LEFT/RIGHT inside the lane gates, open graves, headstones and crosses to jump, low branches and the lychgate arch to duck, hands and crows to shoot, closed stretches to go round, lanterns that keep the lamp lit (an unbroken lamp is the grade's `steady` die), and coffins thrown out by each hit with a ghoul to shoot in each. Adds no monster, boss or hazard kind and draws no random number; every number is an exported constant documented in its header |
| `public/activities/ghoul-rush/rides/hearse/ghoul-hearse-draw.js` | The Midnight Hearse's art: `LOOKS` (`pack: "hearse"`), `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`, `telegraphMarks`/`telegraphs` (JUMP, DUCK, SHOOT and SWITCH glyphs for the hearse's lane) and `hearseArt(d)` (sky, hills, cemetery, road, verge, things and the hearse by `moving`; the cab door, lows, fog, glyphs and lamp gauge by `front`; `dim` when the lamp is out); no random numbers. Its header lists what the art reads off the rules |
| `public/activities/ghoul-rush/rides/sled/ghoul-sled-draw.js` | The Coffin Sled's art: `LOOKS`, `VOICES` (borrowed tones), `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS` and `sledArt(d)` (the sky, hills, ice and things by `moving`, the lid, the lows and foreground flakes by `front`); no random numbers. Its header lists what the art reads off the rules |
| `public/activities/ghoul-rush/rides/gurney/ghoul-gurney.js` | Code Blue (Blackmoor Sanatorium's bonus round) as a pack (`GURNEY`), modeled on the Coffin Sled: pack fields `ride`, `place` and `target`; the gurney along `ride.track` (shafts are the gaps), wheelchairs that roll, IV stands, lamps and doors overhead, orderlies in doorways, the lights-out waves (`lightsAt`), the surge lamps and the heartbeat monitor's beat; its state is `round.runner` (`pack: "codeblue"`, put back if another pack's `place` clears the shared slot); draws no random number; imports the cart's track helpers |
| `public/activities/ghoul-rush/rides/gurney/ghoul-gurney-draw.js` | Code Blue's art: `LOOKS`, `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`, `telegraphMarks`/`telegraphs` and `gurneyArt(d)` (the corridors, shafts and floors by `moving`; the gurney, lows, glyphs, countdown and monitor by `front`; `dim` and `lights` for the blackouts); no imports but the Sled's glyph colors |
| `public/activities/ghoul-rush/rides/mower/ghoul-mower.js` | The Gardener's Revenge (the Grounds' bonus round) as a pack (`MOWER`), modeled on the Coffin Sled: pack fields `ride`, `place` and `target`; state in the shared `round.runner` slot (id `mower`); a flat lawn run on a ride-on mower with gaps (ponds, ha-ha ditches), junk, hedge arches, clothes lines of gloves and snapping topiary beasts, and the twist: holding fire lowers the blades, which cut tall grass, weeds and thorn hedges in the zone ahead (the blades heat and jam, so they are pulsed); the lawn-cut share is the grade's steady die; hearts through the Cart's bonus machinery; no random numbers |
| `public/activities/ghoul-rush/rides/mower/ghoul-mower-draw.js` | The Gardener's Revenge's art: `LOOKS`, `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`, `telegraphMarks`/`telegraphs` (JUMP, DUCK and CUT glyphs) and `mowerArt(d)` (sky, manor, topiary and railings by `moving`, the lawn with its ponds and ditches, the mower with its blades and heat gauge, the lows and the lawn gauge by `front`); no random numbers |
| `public/activities/ghoul-rush/rides/mower/ghoul-sfx-mower.js` | The Gardener's Revenge's own sounds as data (no imports): `MOWER_SFX` with first-draft `tones` (`ghoulMower<Act>`, each under 1.2 s) and the `ghoulMowerRide` track (sound and music picks still pending); merged by `ghoul-sfx.js` via `STAGE_SFX`, the track set in `ROOM_MUSIC` |
| `public/activities/ghoul-rush/rides/pew/ghoul-pew.js` | Holy Roller (the Chapel's bonus round) as a pack (`PEW`): a Subway-Surfers style endless-runner seen from behind, pack fields `ride`, `place` and `target`; state in the shared `round.runner` slot (id `pew`). `you.x` is only the distance run; the pew's own `lane` (a float to `laneTo`), `h`, `slide`, `combo` and `magnet` live in `round.runner`. Left/right presses change lane (a wall bump at the edge), up jumps, down slides (fast-fall in the air), fire shoots down the lane; a speed ramp by distance (`speedAt`); `KINDS` (switch: pillar, confessional, pewx; jump: kneeler, stand, cracks, hatch; slide: censer, banner, beam; shoot: garg with 2 hp, bell rope), wax souls and halos, the combo and the steady die (souls share); a hit shoves the pew to a calm lane. Pure rules, no random numbers |
| `public/activities/ghoul-rush/rides/pew/ghoul-pew-course.js` | Holy Roller's seeded course (no imports): written in seconds and laid by the speed ramp (`xAt`, `speedAt`, `V0`, `ACC`), `COURSE` { items [x, lane, kind, len], souls, checks, finish } |
| `public/activities/ghoul-rush/rides/pew/ghoul-pew-draw.js` | Holy Roller's art: `LOOKS`, `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS` and `pewArt(d)`, whose `field(ctx, view)` draws the WHOLE field (ghoul-draw.js has a `round.runner.id === "pew"` branch like the dark ride's `round.gallery` one, then adds the hearts, flash, banner, cards and HUD pills) plus the progress track, souls and combo strip, and the events' effects |
| `public/activities/ghoul-rush/rides/pew/ghoul-pew-world.js` | Holy Roller's pseudo-3D nave: `worldArt(d)` with `paint(ctx, view)`; the projection `(lane, depth, height)` to the screen with scale = near / (near + depth) toward a vanishing point, far-to-near cells with fog as alpha, stained glass, pillars and ribs, pews, candlelight and god rays pulsing on the organ's beat (`pulse`, `BPM`), every thing's art and telegraph glyph, the souls, bolts, the pew and hero from behind, speed streaks and vignette. A reusable pattern for "run into the screen" rides. No random numbers (hashes) |
| `public/activities/ghoul-rush/rides/pew/ghoul-sfx-pew.js` | Holy Roller's own sounds as data (no imports): `PEW_SFX` with 17 tones (lane, bump, jump, land, slide, dive, soul, halo, crash, check, finish, speed swell, gargoyle and bell) and the driving `ghoulPewDirge` track at 132 BPM (first drafts, merged by `ghoul-sfx.js`) |
| `public/activities/ghoul-rush/rides/hearse/ghoul-sfx-hearse.js` | The Midnight Hearse's own sounds as data (no imports): `HEARSE_SFX` with 19 first-draft `ghoulHearse<Act>` tones (none over 1.2 s) and the `ghoulHearseRide` track (a funeral march at a gallop, built from three four-bar parts); merged by `ghoul-sfx.js`, named in `ROOM_MUSIC`. Sounds and music still to be picked by ear |
| `public/activities/ghoul-rush/rides/sled/ghoul-sfx-sled.js` | The Coffin Sled's own sounds as data (no imports): `SLED_SFX` with an empty `tones` and `music` until the user picks them; merged by `ghoul-sfx.js` (the room plays the Graveyard's `ghoulGraves`) |
| `public/activities/ghoul-rush/rides/banister/ghoul-banister.js` | The Grand Banister (the Manor's bonus round) as a pack (`BANISTER`), modeled on the Coffin Sled: pack fields `ride`, `place` and `target`; state in the shared `round.runner` slot (id `banister`); YOU slide down a grand staircase's banister along `ride.track` (the first `rails` lines are the handrail, the breaks between them gaps to jump; the rest are brass under-rails beside it, the split track: a jump with DOWN held dives onto one, a jump off its end lands back on the handrail), vases and candlesticks to jump, hanging portrait frames to duck, chandeliers on a pendulum (`swingAt`: a wall from the bob to the roof, lethal to a ducking rider while the bob is mid-swing, so you brake or lean (LEFT/RIGHT) to time them or take the under-rail), ghostly butlers that lunge (jump or two bolts) and cobwebs to shoot. Adds no monster, boss or hazard kind; no random numbers. Its header documents the room fields |
| `public/activities/ghoul-rush/rides/banister/ghoul-banister-draw.js` | The Grand Banister's art: `LOOKS` (`pack: "banister"`), `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`, `telegraphMarks`/`telegraphs` (JUMP, DUCK and DIVE glyphs) and `banisterArt(d)` (damask wall, moonlit windows, a zig-zag of staircase flights, portraits whose eyes follow YOU, the rails, props, butlers and webs by `moving`; the hanging frames, the chandeliers with the arc they swing through, sparks and glyphs by `front`); no random numbers. Its header lists what the art reads off the rules |
| `public/activities/ghoul-rush/rides/banister/ghoul-sfx-banister.js` | The Grand Banister's own sounds as data (no imports): `BANISTER_SFX` with 14 first-draft `ghoulBan<Act>` tones (each under 1.2 s) and the `ghoulBanister` track (a harpsichord waltz at a gallop, built from three four-bar parts); merged by `ghoul-sfx.js` via `STAGE_SFX`, named in `ROOM_MUSIC` (sound and music picks still pending) |
| `public/activities/ghoul-rush/rides/wagon/ghoul-wagon.js` | The Torch Mob (Hollow End Village's bonus round) as a pack (`WAGON`), modeled on the Coffin Sled: pack fields `ride`, `place` and `target`; a hay wagon along `ride.track` (ditches and the collapsed bridge are the gaps, a rising line end a ramp), barrels and crates, washing lines and inn signs, villagers who hurl pitchforks (duck) and torches (jump), spooked horses, and the pursuit meter (`gap`: the mob runs at `MOB_V`, DOWN is a duck and the brake, a hit, a burning hay load and the surge close it, a shot torch or fork opens it, inside `PANIC_ON` the horses bolt, at `CATCH_GAP` it is a heart); its state is `round.runner` (`id: "wagon"`); draws no random number; imports the cart's track helpers |
| `public/activities/ghoul-rush/rides/wagon/ghoul-wagon-draw.js` | The Torch Mob's art: `LOOKS` (`pack: "wagon"`), `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`, `telegraphMarks`/`telegraphs` and `wagonArt(d)` (the sky, rooftops, street, cobbled road, ditches, the bridge and river, the things, the mob and the wagon by `moving`; the lows, throws in the air, the hay fire, glyphs and the mob's meter by `front`); no random numbers; imports the Sled's glyph colors and the rules' constants |
| `public/activities/ghoul-rush/rides/wagon/ghoul-sfx-wagon.js` | The Torch Mob's own sounds as data (no imports): `WAGON_SFX` with 18 first-sketch `ghoulWagon<Act>` tones and the `ghoulWagonRide` track (a D minor gallop built from three 4-bar patterns); merged by `ghoul-sfx.js`, the room's track named in `ROOM_MUSIC` (`wagon`) |
| `public/activities/ghoul-rush/rides/gurney/ghoul-sfx-gurney.js` | Code Blue's own sounds as data (no imports): `GURNEY_SFX`, 18 first-pick `ghoulBlue<Act>` tones and the track `ghoulBlueRide`; merged by `ghoul-sfx.js` (the room plays it via `ROOM_MUSIC.codeblue`) |
| `public/activities/ghoul-rush/rides/tray/ghoul-tray.js` | The Servants' Back Stairs (the East Wing's bonus round) as a pack (`TRAY`), modeled on the Coffin Sled: pack fields `ride`, `place` and `target`; the track of shelves and stair flights with gaps, rolling pots and cutlery, hams and pans, cooks who fling dishes, the courses (silver domes and flying plates, seven is the grade's acts die), the cherries, grease stretches, checkpoints and the grade (3 to 9 dice). State is `round.runner` (id `tray`), the shared slot for a rolling bonus ride. Adds no monster, boss or hazard kind and draws no random number; every number is an exported constant documented in its header |
| `public/activities/ghoul-rush/rides/tray/ghoul-tray-draw.js` | The Servants' Back Stairs' art: `LOOKS`, `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`, the telegraph glyphs (`telegraphMarks`, `telegraphs`: JUMP, DUCK, SHOOT) and `trayArt(d)` (the kitchen, shelves and stairs, things and cooks by `moving`; the tray, hams and pans, flour and glyphs by `front`); no random numbers |
| `public/activities/ghoul-rush/rides/tray/ghoul-sfx-tray.js` | The Servants' Back Stairs' sounds and music as data (no imports): `TRAY_SFX` with 13 first-draft tones and the `ghoulTrayRide` track; merged by `ghoul-sfx.js` |
@@ -0,0 +1,69 @@
# Architecture: Ghoul Rush stages
> Part of [AGENTS.md](../AGENTS.md) and the [Architecture index](./AGENTS-architecture.md): project guidance for AI coding agents.
Ghoul Rush's stage and boss files and every stage test. The other games and the rules every game follows are in [Activities](./AGENTS-architecture-activities.md); Ghoul Rush is split over [core](./AGENTS-architecture-ghoul-core.md), [stages](./AGENTS-architecture-ghoul-stages.md) and [rides](./AGENTS-architecture-ghoul-rides.md).
| File | Role |
|---|---|
| `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/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/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/stages/wing/ghoul-bones.js` | Old Rattlebones' fight, the East Wing's boss, as a boss pack in the shape of the stage packs (no imports; `ghoul.js` hands each rule its kit `k`; it plugs in through `PACKS` with `bosses`, `boss` and `hazards`, and `ghoul.js` re-exports `BONES_KEEP`, `BONES_MS`, `BONES_RAGE_MS`, `BONES_WINDUP_MS` and `VOLLEY`): 90 hp; every `BONES_MS` he winds up for a volley, a slam or the skull, picked at random by `pickAct` (never one three times running, the first a volley); the skull is a `skull` hazard that flies level at your chest `SKULL_REACH` past you and curves back to his neck while `b.headless` (no weak spot; a bolt to the skull does `SKULL_HIT`, eaten, with `SKULL_STAGGER_MS` between hits); at half his hp (`BONES_RAGE`) he shakes (`BONES_SHAKE_MS`), attacks every `BONES_RAGE_MS`, slams in a double (`DOUBLE_GAP_MS`), hurls bone rain (`rain` hazards: a shadow for `RAIN_WARN_MS`, then a bone) and raises skeletons (`raise` hazards, at most `MAX_BONY` alive or cracking). |
| `public/activities/ghoul-rush/stages/wing/ghoul-bones-draw.js` | Old Rattlebones' drawing, `boneArt(d)` plugged into `ghoul-draw.js`'s `PACK_ART`: the boss (headless while the skull is out, arms to the skull or up for rain, shaking with flaring eyes in his rage), the skull in flight, the bone rain's shadows and falling bones, the cracking floor, `lights`, `react` cases for his new events (`skullWind`, `skullThrow`, `skullTurn`, `skullBack`, `rainWind`, `rainThrow`, `rainLand`, `bonesRage`, `raiseWind`, `raised`), and `LOSE_WORDS` / `LOSE_SOUNDS` for `skull` and `rain`. |
| `scripts/test-web-console-activities-ghoul-bones.mjs` | Old Rattlebones' suite: the random attack order, the volley and slam, the skull's flight and the headless window, the skull shot, the rage, the double slam, bone rain, the skeleton cap and the reactions. |
| `public/activities/ghoul-rush/stages/graveyard/ghoul-graveyard.js` | Ghoul Rush's Graveyard stage pack, its rules (no imports: `ghoul.js` hands each rule a kit `k` of its own helpers). A stage pack is plain data and functions that `ghoul.js` merges into its own tables (`PACKS`): `monsters` (with `perch`: its spawn names its height, `flies`: a horde one comes in high), `walkers`/`zombies`/`stackers`/`climbers` (joining the sets of those names), `act` (start), `solid`, `move`, `kill`, `horde` (fields a horde one comes with), `bosses`, `boss` (one slice of its fight), `guard` (true while shots and stomps glance off, a `bossBlock` event) and `hazards` (by kind, one slice of a box on the floor that hurts while `live`; kept in `round.hazards`). Three more fields a stage may add (the Grounds does): `cut` (kinds the Hedge shears kill outright), `weak` (by boss kind, `(boss, shot) => damage multiplier` for a weak spot; `bossHit` then carries `how: "weak"` and `weak: true`) and `cause` (what a boss's touch is called when it costs a life). The Chapel adds more: `tick(round, ms, k)` (a stage-wide twist run first in every slice; it may set `round.stunMs`, which freezes you and every monster, boss, hazard and missile while bolts in flight still fly, and keeps its state in `round.twist`), `stone` (by kind, true while shots glance off and a stomp does nothing; `glance` event), `shot(round, m, s, k, random)` (the damage multiplier of a bolt that hit `m`, free to splash), `target(round, s, k)` (true when a bolt struck something of the pack's that is no monster, such as an organ pipe) and, on a monster, `hasteMs` and `haste` (its time runs faster while `hasteMs` is over 0). On the drawing side a look may be `custom: true` with a `pack` id (the pack's art then draws the whole wall, floor and shelves) and the art may return `decor` (by the look's `decor` name). On the drawing side a stage's art may also return `react(e, k)` (its own events; `ghoul-draw.js`'s `react` falls through to `ART.react`, which returns true when it handled `e`), `ground` and `shelf` (the floor pieces and shelves of an outdoor look), `waves` and `powers`; a boss event must carry `kind` or its voice never plays. The Graveyard's: grasping hands (`HANDS_*`: lurk unseen, rise, grab, sink, creep under level ground after you), the mourner (wails every `WAIL_MS`, slowing you to `SLOW_SHARE` speed for `SLOW_MS` within `WAIL_REACH`; `round.you.slowMs`), the grave robber (digs in within `ROBBER_DIG`, comes up `ROBBER_BEHIND` behind you), the rotter (a zombie whose body-shot death leaves its `legs` walking), the carrion crow (perches, dives at your chest, climbs, dives again), and Mother Mourning (`angel`: weeps `ANGEL_WEEP_MS` as stone flinging headstones, turns `ANGEL_TURN_MS`, watches `ANGEL_WATCH_MS` when only she can be hurt and any move drops a `fist` hazard after `FIST_WARN_MS`; at `ANGEL_RAGE` her wings spread, the weep shorter, the watch longer, a shockwave each way as each weep begins) |
| `public/activities/ghoul-rush/stages/graveyard/ghoul-graveyard-draw.js` | The Graveyard's drawing: `LOOKS` for its four rooms (`outdoor: true`, so `ghoul-draw.js` draws `backdrop` instead of walls: the night sky, stars, the moon, hills with dead trees, iron fences, mausoleums, fog and headstones) and `graveyardArt(d)`, handed `ghoul-draw.js`'s helpers, returning the open `grave` and `openGrave` a rotter climbs out of, `monsters`, `bosses` (Mother Mourning: hands over her face while she weeps, lowered with burning eyes while she watches, wings spread in a rage, cracks as she is worn down), `missiles` (a flung headstone), `hazards` (a stone fist: its shadow, then the fist) and `lights` |
| `public/activities/ghoul-rush/stages/grounds/ghoul-grounds.js` | Ghoul Rush's Grounds stage pack, its rules (no imports; same shape as the Graveyard's, plus the pack fields `cut`, `weak` and `cause`): the topiary beast (`still` while you face it, `creep` when your back is turned; events `rustle` and `freeze`), the rootling (`trail`, `warn`, `up`, `sink`; events `rootWarn` and `rootUp`), the lantern moth (flocks of three, quicker in the dark), the mulch crawler (`pile`, `burst`, `crawl`; event `leaves`), the Hedge shears' `snip` event, and the Groundskeeper (`keeper`: a scythe sweep along the floor (or, now and then, a high `sweep` hazard you stay on the ground under), a lobbed lantern fire hazard, his lantern a `weak` spot only while open (`b.lit`), and at half hp a mower with `rev`, `charge` and `stall`) |
| `public/activities/ghoul-rush/stages/grounds/ghoul-grounds-draw.js` | The Grounds' drawing: `LOOKS` for its four rooms (`outdoor: true`), `groundsArt(d)` returning `monsters`, `bosses`, `hazards` (the fire), `waves` (the scythe), `powers` (the shears), `lights`, `backdrop`, `ground`, `shelf` and `react(e, k)` for the Grounds' own events; its `VOICES` (each kind's tone per act, `keeper.weak` for a weak-spot hit instead of `keeper.hurt`, `shears.snip` for a cut instead of the dying cry), `LOSE_WORDS` and `LOSE_SOUNDS`, which `ghoul-draw.js` spreads into its own tables |
| `public/activities/ghoul-rush/stages/chapel/ghoul-chapel.js` | Ghoul Rush's Chapel stage pack, its rules (no imports; same shape as the Grounds', plus the pack hooks `tick`, `stone`, `shot` and `target`, and a room field `toll`): the gargoyle (`perch` as stone, `wake`, `dive`, `return`; events `glance`, `gargoyleWake`, `gargoyleDive`, `gargoylePerch`), the choir ghost (sings, giving nearby monsters `hasteMs`), the censer monk (`smoke` hazard), the bell bat (`roost` until the toll), the bell toll (`tick`: `bellSwing`, `toll`, `tollEnd`, `round.stunMs`), Holy Water's splash (`shot`, event `holySplash`) and the Choirmaster (`choirmaster`: four pipes in `b.pipes` that bolts hit through `target`, a `guard` while any sounds, columns of `note` hazards with one gap, a rage that brings pipes back one by one) |
| `public/activities/ghoul-rush/stages/chapel/ghoul-chapel-draw.js` | The Chapel's drawing: `LOOKS` for its four rooms (indoor but `custom: true` with `pack: "chapel"`, so `ghoul-draw.js` hands the walls, floor and shelves to `chapelArt(d)`'s `backdrop`, `ground` and `shelf`), `chapelArt(d)` returning those plus `decor` (the room's pews, belfry, organ or stalls), `monsters`, `bosses`, `hazards` (smoke, the bell, notes), `powers`, `lights` and `react(e, k)`; its `VOICES` (the bell has only `swing` and `toll`: the thaw after a toll is quiet on purpose), `LOSE_WORDS` and `LOSE_SOUNDS` |
| `public/activities/ghoul-rush/stages/sanatorium/ghoul-sanatorium.js` | Ghoul Rush's Blackmoor Sanatorium stage pack, its rules (no imports; same shape as the Chapel's, plus the pack fields `unseen`, `harmless`, `platform` and `land`, a room field `flicker`, `round.blackout`/`round.twist` for the lamps and the kit's `fling`): the orderly (`reach`, `hold`, a throw that costs no life, `you.heldMs`; events `orderlyReach`, `orderlyGrab`, `orderlyThrow`, `saltsBreak`), the gurney (`parked` as a floor you can stand on, `rattle`, `roll`, `rest`; `gurneyRattle`, `gurneyRoll`, `gurneyRest`), the flicker (`m.unseen`: bolts and touch go through it until a blackout, the Lantern's light or the Salts' glow; `flickerShow`), the specimen bloater (a `jar` missile with its own `cause` that `land`s as a `formaldehyde` hazard; `jarWind`, `jarBreak`), the lamps (`tick`: `flickerWarn`, `lightsOut`, `lightsOn`), the Salts and the Saw (`shot`) and the Night Matron (`matron`: `b.beam` cone, `b.heat`, `b.cabinets`, syringes, arms, rage; `syringeWind`, `syringes`, `armWarn`, `armReach`, `matronRage`) |
| `public/activities/ghoul-rush/stages/sanatorium/ghoul-sanatorium-draw.js` | The Sanatorium's art: `LOOKS` (indoor but `custom: true` with `pack: "sanatorium"` and `noMoon`, so `sanatoriumArt(d)`'s `backdrop`, `ground` and `shelf` draw the tiled walls, windows, decor, floors, the ward's cabinets, the baths' tubs and each room's boards), `monsters` (orderly with its grab pose, gurney, flicker with its fade and afterimage, specimen bloater), the `matron` with her cone cut by the floor and the cabinets, `missiles` (jar, syringe), `hazards` (formaldehyde, arm with its crack of light), `powers` (Salts, Saw), `lights`, `react(e, k)` and two generic hooks `ghoul-draw.js` calls: `front(ctx, v)` (over Planny and before the dark: the ceiling lamps, the tubs' water, the orderly's fingers, the Matron's heat on him) and `dim(v)` (the dark layer's alpha, raised in a blackout and in a stutter); its `VOICES` (borrowed tones; `lights`, `salts` and `saw` are no monsters), `LOSE_WORDS` and `LOSE_SOUNDS` |
| `public/activities/ghoul-rush/stages/village/ghoul-village.js` | Ghoul Rush's Hollow End Village stage pack, its rules (no imports; no new pack field: it uses `tick`, `shot`, `land`, `weak` (now handed `(boss, shot, round, k)`) and `solid`, and draws no random number): the moonrise (`tick`; `round.twist` = `{ moon, full, ms }`, events `fullMoon`, `villagerTurn`, `villagerWolf`, `houndGrow`), the torch mob villager (a group of three, `torchWind`, the `torch` missile that `land`s as a `torchfire` hazard, `torchLand`; turned into a leaping wolf-man at full moon), the hanged man (`hangedWarn`, `hangedDrop`, `hangedSnap`, `hangedHaul`), the shutter ghoul (`solid` only while out; `shutterRattle`, `shutterLunge`, `shutterPull`), the moonhound (the hellhound's leap, grown at full moon), Wolfsbane's double damage and shying (`baneShy`) and the Beast of Hollow End (`beastLeap`, `beastCling`, `beastPounce` with a `shadow` hazard, `beastLand`, `swipeWind`, `beastSwipe` with a `claw` hazard, `beastHowl`, `houndCall`, `beastMoon`) |
| `public/activities/ghoul-rush/stages/village/ghoul-village-draw.js` | The Village's art: `LOOKS` (street, square and green outdoors, the inn a `custom` indoor look, all `pack: "village"`), `villageArt(d)` returning the world's hooks plus the monsters (the torch mob villager and the wolf-man it turns into over 800 ms, the hanged man on his rope, the shutter ghoul reaching out of a window, the moonhound with a glowing mane when grown), the `beast` (a werewolf in every move: cling with a glowing weak spot, bound, pounce, land, swipe, howl at the moon, rage), `missiles` (torch), `hazards` (torchfire, the landing shadow, the claw swipe), `powers` (Wolfsbane's badge), `lights` and `react(e, k)`; its `VOICES` (borrowed tones, plus `moon.full` and `bane.active`), `EVENT_VOICE` (event to `[kind, act]`, each played once; the hounds' call is quiet), `LOSE_WORDS` and `LOSE_SOUNDS`. Its header lists what the art reads off the rules |
| `public/activities/ghoul-rush/stages/village/ghoul-village-world.js` | The Village's world: the night sky and the moon that climbs and reddens with `round.twist.moon` (`sky`, drawn every frame under the still layers), the crooked timber-framed houses with a window for every shutter ghoul, the church and spire, the gallows, the green's far cottages, well and arena walls, the Crooked Inn (hearths, barrels, bar, lanterns, the moon in its windows), cobbles, planks and turf (`ground`), awnings, rooftops, balconies, tables, carts and thatch (`shelf`), and `moving` (curtains that twitch as you pass, fire, moonlight falling in), `front` (the full-moon wash, Wolfsbane's petals, the Beast's rage) and `lights` |
| `public/activities/ghoul-rush/stages/mine/ghoul-mine-world.js` | The Deep Seam Mine's world (no imports; `mineWorld(d)` takes ghoul-draw.js's helpers): the rock wall with its strata and facets, the timber that holds it up (props and cap beams, scaffolds and galleries as `shelf`), rails and sleepers on the floor (`ground`), oil lamps on hooks with their flames and warm halos (`moving`) and their holes in the dark (`lights`, none in a blackout), the shaft's lining, walers, guide rails and headframe with the cage lift drawn on its cable over a winch wheel with a counterweight (`cage`, and its front bars in `front`), the tunnels' low roof, pipes, stalled pump, drips and knee-deep water with a lit surface and Planny's wake (`front`), the collapse's broken props, cracks, rubble heaps and buried cart, the seam's glittering ore vein, stalactites and galleries, and the `rock` hazard in its three states; layouts are worked out once per room from the room alone and kept. Scene tool: `prototypes/ghoul-rush-tools/scene-mine-world.mjs` |
| `public/activities/ghoul-rush/stages/village/ghoul-village-wolf.js` | The Village's werewolf, one skeleton for the Beast and a turned villager: poses (`POSES`: stand, rear, swipe, howl, crouch, leap, land, rest, cling, shy, down, sleep), `mixPose` to blend them, and `wolfKit(d).figure` to draw one |
| `public/activities/ghoul-rush/stages/mine/ghoul-mine.js` | Ghoul Rush's Deep Seam Mine stage pack, its rules (no imports; draws no random number): uses `tick`, `harmless`, `platform`, `solid`, `kill`, `weak` and a boss's blackout (`round.blackout`). The rockfall (`tick`; a room field `rocks` in ms; the `rock` hazard in states `warn`, `fall`, `rubble`, events `rockWarn`, `rockFall`, `rockLand`; the Hard Hat's `rockBounce`), the noise you make (`round.twist` = `{ next, quiet, noise, reach, wade }`, `wade` splashes), the knocker imp (touch steals light, not a life: `you.dimMs` and `you.dimBy`, `impSteal`, `impDrop`; the Hard Hat stops it), the canary ghost (`canaryScream`: three rocks), the dead miner (buried in the wall, `minerDig`, `pickWind`, `pickSwing` with a `pick` hazard, cause `pickaxe`), the blind crawler (`blindLost`, `blindHear`), the cage lift (a spawn row `["cage", x, lowest y, highest y]`, a `platform` kind that is not solid and never hurts), Dynamite placed in each room (its rules, the `stick` and `blast` hazards, `dynThrow` and `dynBlast`, moved to `ghoul-arms.js`) and the Tommyknocker (`tommyKnock`, `sweepWind`, `tommySweep` with a `hammer` hazard, `tommyDark`, `tommySink`, `tommyKnockDark`, `tommyBurst`, `tommyRage`; dazed double damage through `weak`) |
| `public/activities/ghoul-rush/stages/mine/ghoul-mine-draw.js` | The Mine's art (the rooms in `ghoul-mine-world.js`, the Tommyknocker in `ghoul-mine-tommy.js`): `LOOKS` (`custom: true`, `pack: "mine"`, always dark), `mineArt(d)` returning `backdrop` (rock, strata, timber props, oil lamps), `ground` (rails), `shelf` (timber landings), `front` (the water along the floor), `dim` (the blackout), `monsters` (imp, canary, miner, blind crawler, cage), the `tommy` boss, `hazards` (rock, stick, blast, pick, hammer), `powers` (Hard Hat, Dynamite), `lights` and `react`; its `VOICES` (borrowed tones), `EVENT_VOICE`, `LOSE_WORDS` and `LOSE_SOUNDS`. Its header lists every field the art reads off the rules; `ghoul-draw.js` shrinks Planny's glow and drops his cone while `you.dimMs` is over 0 |
| `public/activities/ghoul-rush/stages/mine/ghoul-mine-tommy.js` | The Tommyknocker's figure for `ghoul-mine-draw.js`: `tommyKit(d)` (no imports, `ghoul-draw.js`'s helpers handed in) returns `figure(ctx, v, b)`, a miner-giant half grown into the seam (stone shoulder with crystals, lantern on his helmet, a door-sized hammer) drawn by act: leaning on the hammer, the overhead knocks, the drawn-back sweep, rest, sinking, bursting out dazed with stars, raged cracks, hurt flash. |
| `public/activities/ghoul-rush/stages/mine/ghoul-sfx-mine.js` | The Mine's own sounds as data (no imports): `MINE_SFX` with an empty `tones` and `music` until the user picks them; merged by `ghoul-sfx.js` via `STAGE_SFX` (its rooms play existing tracks, set in `ROOM_MUSIC`) |
| `public/activities/ghoul-rush/stages/bog/ghoul-bog.js` | Ghoul Rush's Gallows Bog stage pack, its rules (no imports; a pack `ghoul.js` plugs in through `PACKS`, handed the kit `k`): the lurker, leech swarm, will-o'-wisp and bog body (`MONSTERS`, with `walkers`/`zombies` sets), `act`, `solid`, `swoops`, `unseen`, `move`, `kill`, `horde`, `tick` (the wisp's lure), `bosses`/`boss`, `weak`, `cause` and `hazards`, and Old Mother Bog (`BOSSES`, hp 360, her fight in `moveMother` with `startMove` setting each move's wind-up act, wait and telegraph event: the wave opens, then a weighted `pickAttack` by phase (`phaseOf`, `WEIGHTS`; never one move three times running, `COOLDOWN` picks for the slow moves, a summon only under its cap, counted by `hagAdds` on adds marked `m.hag`). Full health: wave, spit, bog hands (`boghand` hazards: a ripple, then a hand), surge (a waist-deep charge past you), mud shell (`shellShot` in `target` chips it; broken she reels in `stagger` with the cauldron open, ignored she heals `SHELL_HEAL`) and dive (relocate); under three quarters the double wave, volley and leech brood join. Under half (after her first dive): stomp (a shadow, a leap, a slam and a wave each way), tide (a `tide` hazard over every plank after `TIDE_WARN_MS`; shelves are dry), drowning pull (drags `you.x` toward her on the planks, never off a plank's end) and call the drowned (bog bodies). Under a quarter: the wisp lantern (her wisps, gone for good once shot out) and combos (`toIdle`, `motherCombo`). `guard` is under water or shelled; `weak` is the open cauldron (late in a rest, or reeling). `planked` keeps her whole body on one plank height except in `UNSTOOD` acts; `b.floor` is the plank height; `b.plan` forces a move for tests). The stage's second twist lives in the engine, not here: a room field `mud` (frozen `[x0, x1]` spans), `mudAt` in `ghoul.js`, `you.mud` and `you.mudMs` (the run sags from `WATER_SPEED` toward `MUD_SPEED_MIN` and a jump toward `MUD_JUMP_MIN` over `MUD_MS`; a shelf, the air and Stilt Boots (`round.effects.boots`) let go of it) |
| `public/activities/ghoul-rush/stages/bog/ghoul-bog-draw.js` | The Gallows Bog's drawing: `LOOKS` for its rooms (`outdoor: true`, `pack: "bog"`) and `bogArt(d)`, handed `ghoul-draw.js`'s helpers, returning the night swamp rooms (boardwalk planks over black water, moss veils, fireflies, the hag's lit stilt house and her open-water arena), `monsters` (a lurker's eyes, a leech swarm, a will-o'-wisp, a bog body), `bosses` (Old Mother Bog and her cauldron, a pose for every move, plus `motherMarks`: the boiling mud of a call, the stomp's shadow, the undertow's streaks), `hazards` (the mud wave, the muck patches, the bog hands' ripples and arms, the tide's warning and its water over the planks), the Stilt Boots' and Harpoon's badges and the events' looks and sounds; its `VOICES` are borrowed house tones until the sound page's vote, `LOSE_WORDS` and `LOSE_SOUNDS` already named |
| `public/activities/ghoul-rush/stages/bog/ghoul-sfx-bog.js` | Gallows Bog's own sounds as data (no imports): `BOG_SFX` with `tones` (a `ghoul<Kind><Act>` tone for each act of the lurker, leech, wisp, bog body and Old Mother Bog, her 22 newer acts first drafts too: a telegraph tone per move and one for each effect) and an empty `music` until the music vote is wired in (the rooms play borrowed tracks through `ROOM_MUSIC`); the tones are first drafts (option 1 of each act) until the sound vote; merged by `ghoul-sfx.js` via `STAGE_SFX` |
| `public/activities/ghoul-rush/stages/carnival/ghoul-carnival.js` | Ghoul Rush's Midnight Carnival stage pack, its rules (no imports; draws no random number): uses `tick` (the ring of samples Mirror You reads and its bolts in `round.twist`), `shot` (Cotton Candy's slow, a marionette's string at the top of its body), `target` (a bolt crossing a marionette's string or one of the puppet's three), `guard` (the Ringmaster is open only with the puppet down), `swoops` (a balloon, a circus hound's leap), `solid`, `kill` and `fourLegged`. Grinner and its acid balloons, marionette (drops when you pass under), Mirror You (copies you 500 ms late, mirrored, its bolts cancel yours), strongman (barbells), circus hound, and the Ringmaster (a gantry over the ring that follows its puppet at a lag, the puppet stalking you and working to a fixed script of leap, stomp, whip and charge, three strings from the gantry to its head and hands that move with it, open 4 s when they are cut, rage with hounds from the cages); `CARNIVAL_ROOMS` lists the stage's rooms, with a place before the Big Top for the dark ride. The room field `belts` and Planny's `you.belt` (the funhouse's conveyor floors) are run by `ghoul.js`. |
| `public/activities/ghoul-rush/stages/carnival/ghoul-carnival-draw.js` | The Carnival's art: `LOOKS` (`custom: true`, `pack: "carnival"`), `carnivalArt(d)` returning the world's hooks (from `ghoul-carnival-world.js`) plus `monsters`, the `ringmaster` boss (gantry, puppet in each pose, strings, whip), `missiles` (barbell), `hazards` (foot, whip, charge), `waves` (the puppet's), `powers` (Cotton Candy), `front` (Mirror You's bolts, Cotton Candy's glow), `lights` and `react`, and `VOICES` (borrowed tones), `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`. Its header lists what the art reads off the rules. |
| `public/activities/ghoul-rush/stages/carnival/ghoul-carnival-world.js` | The Carnival's world (no imports; `carnivalWorld(d)` takes ghoul-draw.js's helpers): the night sky with a Ferris wheel (`sky`), tents, booths and swagged bulbs on the Midway, the Hall of Mirrors' gilded panels and glints, the Funhouse's crooked walls, spiral discs and clown-mouth door, the Big Top's striped canvas, ring curb, crowd, trapeze boards, gantry rail and cages (open once the Ringmaster rages), and the belts' chevrons (`moving`). |
| `public/activities/ghoul-rush/stages/carnival/ghoul-sfx-carnival.js` | The Carnival's own sounds as data (no imports): `CARNIVAL_SFX` with an empty `tones` and `music` until the user picks them; merged by `ghoul-sfx.js` via `STAGE_SFX` (its rooms play existing tracks, set in `ROOM_MUSIC`) |
| `public/activities/ghoul-rush/stages/frozen/ghoul-frozen.js` | Ghoul Rush's Frozen Lake stage pack, its rules (imports only `burrow` from the Graveyard; draws no random number): uses `tick` (thin ice, the blizzard, the Widow's spikes, web and barrels), `place`, `unseen`, `solid`, `kill`, `target`, `land`, `weak`, `cause`, `guard`, `swoops` and `slides`. The generic slippery-ice rule (`iceRun`, room field `ice`) and thin-ice rule (`stepThin`, room field `thin`, `round.thin`), the under-ice hand, snow shade (unseen, footprints), Frozen Ghoul (slides, shatters into shards), Ice Wraith (its dive freezes), Hot Cocoa, the Frost Widow (veil, barrels, weak spot, blizzard, spikes, web, rage) and `FROZEN_ROOMS`. Every constant is exported and documented in its header |
| `public/activities/ghoul-rush/stages/frozen/ghoul-frozen-draw.js` | The Frozen Lake's art: `LOOKS` (`custom: true`), `frozenArt(d)` returning the world's hooks (from `ghoul-frozen-world.js`) plus `monsters`, the Frost Widow boss, `hazards` (shards, spikes, webs, barrels, the flare and its fire), `powers` (Hot Cocoa), `front`, `lights` and `react`, and `VOICES` (borrowed tones), `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`. Its header lists what the art reads off the rules |
| `public/activities/ghoul-rush/stages/frozen/ghoul-frozen-world.js` | The Frozen Lake's world (no imports; `frozenWorld(d)` takes ghoul-draw.js's helpers): the night sky with moon, aurora and far mountains (`sky`), the huts, the Lodge's fallen roof, the Black Ice and the Widow's web (`backdrop`, `ground` with the ice's gloss, `shelf`), and `moving` (open water in the holes, thin ice drawn from `round.thin`, never from `spec.ground`, the faces under the Black Ice, falling snow) and `lights`. Draws no random number |
| `public/activities/ghoul-rush/stages/frozen/ghoul-sfx-frozen.js` | The Frozen Lake's own sounds as data (no imports): `FROZEN_SFX` with an empty `tones` and `music` until the user picks them; merged by `ghoul-sfx.js` via `STAGE_SFX` (its rooms play existing tracks, set in `ROOM_MUSIC`) |
| `public/activities/ghoul-rush/stages/chapel/ghoul-sfx-chapel.js` | The Chapel's own sounds as data (no imports): `CHAPEL_SFX`, its `tones` (the 35 picked `ghoul<Kind><Act>` sounds of the gargoyles, choir ghosts, monks, bell bats, the Choirmaster, the bell and Holy Water's splash) and `music` (`ghoulNave`, `ghoulTower`, `ghoulLoft`, `ghoulChoir`, named in `ROOM_MUSIC`), merged by `ghoul-sfx.js` via `STAGE_SFX` |
| `public/activities/ghoul-rush/stages/sanatorium/ghoul-sfx-sanatorium.js` | Blackmoor Sanatorium's own sounds as data (no imports): `SANATORIUM_SFX`, its `tones` (the 38 picked `ghoul<Kind><Act>` sounds of the orderlies, gurneys, flickers, specimen bloaters, the Night Matron, the lamps, Smelling Salts and the Bone Saw) and `music` (`ghoulAdmissions`, `ghoulBaths`, `ghoulTheater`, `ghoulWard`, named in `ROOM_MUSIC`), merged by `ghoul-sfx.js` via `STAGE_SFX` |
| `public/activities/ghoul-rush/stages/village/ghoul-sfx-village.js` | Hollow End Village's own sounds as data (no imports): `VILLAGE_SFX`, its `tones` (the 42 picked `ghoul<Kind><Act>` sounds of the torch mob, hanged men, shutter ghouls, moonhounds, the Beast, the full moon and Wolfsbane) and `music` (`ghoulStreet`, `ghoulInn`, `ghoulSquare`, `ghoulGreen`, named in `ROOM_MUSIC`), merged by `ghoul-sfx.js` via `STAGE_SFX` |
| `scripts/test-web-console-activities-ghoul-chapel.mjs` | The Chapel's suite: each monster, the bell toll and its freeze, Holy Water's splash, the Choirmaster's pipes, notes and rage, a voice for every act, each event playing exactly one picked sound, and every picked tone present in the merged tones and in `ghoul-sfx-chapel.js` |
| `scripts/test-web-console-activities-ghoul-sanatorium.mjs` | The Sanatorium's suite: the orderly's reach, hold and throw (and the Salts), the gurney's park, rattle, roll and rest and its floor, the flicker's unseen state, the lamps' timing, the specimen's jar and puddle, both power-ups (stage-only), the Matron's cone, heat, cabinets, syringes, arms and rage, endless lives for every new cause, and a voice for every act |
| `scripts/test-web-console-activities-ghoul-village.mjs` | The Village's suite: the rooms, the moonrise timing, the turn and the grow at full moon (and the per-room reset), the villager's group, torch and fire, the hanged man's drop, the shutter ghoul hit only while out, the moonhound, Wolfsbane (stage-only, double damage, shying), the Beast's wall leap, cling weak spot, pounce shadow, swipe, howl and its cap, the rage, endless lives for every new cause, no random draws, and a voice for every act and event |
| `scripts/test-web-console-activities-ghoul-mine.mjs` | The Mine's suite: the rooms and the cage rows, rockfall timing, aim and crush, the Hard Hat (stage-only, bounce), the imp's light steal (no life, ended by a shot or a stomp, blocked by the hat), the canary's scream and its three rocks, the miner's dig and swing, the blind crawler losing and hearing you (and the water's louder steps), water slowing you, the cage carrying Planny, Dynamite (a double tap, the bag, the blast), every Tommyknocker move including the dark, the decoy, the burst, the dazed double damage and the rage cap on imps, no random draws, endless lives for every new cause, and a voice for every act and event |
| `scripts/test-web-console-activities-ghoul-carnival.mjs` | The Carnival's suite: the rooms and the belts, grinners and their balloon cap, balloons and their acid, the marionette's drop and its string, Mirror You (the delay, the mirrored moves, jumps, its bolts and their canceling, stunned by a pie), the strongman, the circus hound (a swoop, duckable), Cotton Candy, the Custard Pie, every Ringmaster move (stalk, leap, charge, stomp, whip, the strings following, open, rage, hounds, the script), no random draws, endless lives for every new cause, and a voice for every act |
| `scripts/test-web-console-activities-ghoul-grounds.mjs` | The Grounds' suite: each monster's behavior, the shears, the Groundskeeper's moves and phases, a voice for every act, each event playing exactly one picked sound, and every picked tone present in the merged tones |
| `scripts/test-web-console-activities-ghoul-bog.mjs` | Gallows Bog's suite: the stage row and its rooms, the mud (slow, sink, jump, shelf, boots), each monster's behavior (the lurker's eyes and snap, the leech's latch, the wisp's light, the bog body's rise), the wisp lure and its fairness cap, the harpoon under the water, Old Mother Bog's wave, weak cauldron, muck, sink and resurface, every move (wind-up, telegraph event, effect, a clean dodge costs nothing, a hit a heart), the phase unlocks, cooldowns and caps, planks while standing, her fall clearing every hazard and add, a skilled bot that must kill her in 60 to 120 s on four seeds and an idle bot she kills, a voice for every act with exactly one picked sound per event, words and a sound for every cause, both cards, the round flow, drawing dark and lit, and a seeded bot on a draw that throws if the pack asks for a random number |
| `scripts/test-web-console-activities-ghoul-marrow.mjs` | The finale's suite: the win condition (`RUN_STAGES` picks that never repeat, then the House with no offer, its stage card and the boss's, the win), the select listing it last at depth 0, the memo (one past every stage only on a win, never from practice) and the words that count `RUN_STAGES`; Kill I, The Lawn: the wall and the out-of-reach guarded box, every window hit from the surface serving its row and passed while shuttered, a window out for good across a life lost, rows opening by windows out, `pickMove`'s rules, each move's telegraph, hit (its cause) and dodge, the doormen's cap, endless lives, the retreat's beats in order and the door it leaves, a steady bot's fight length at full depth and an idle one's death, the voices, words and sounds, and drawing every state lit and dark |
| `scripts/test-web-console-activities-ghoul-mat.mjs` | Down the Hatch's suite: the track, every obstacle's telegraph, hit and dodge, the squeezes, bile, the grade, a good bot finishing and one that never dodges losing its three hearts without a game over |
| `scripts/test-web-console-activities-ghoul-eye.mjs` | Kill II's suite: the Eye's flare, opening and guard, a shade move for every boss in `STAGES`, the lurch and the dresser, the retreat, a bot's fight length, voices and drawing |
| `scripts/test-web-console-activities-ghoul-bonestair.mjs` | The Bone Stair's suite: the flights and seams, the rubble's meter, every obstacle's telegraph, hit and dodge, the grade, and the bot sims |
| `scripts/test-web-console-activities-ghoul-heart.mjs` | Kill III's suite: the beat and its waves, the ribs' window, every attack's warning, the clamp at 1 hp and HOLD FIRE, the white-out and the door of light, a bot's fight length, voices and drawing |
| `scripts/test-web-console-activities-ghoul-ending.mjs` | The ending's suite: the pages' rules, a press turning pages, holding fire to skip, the win once at the end, every scene drawn |
| `scripts/test-web-console-activities-ghoul-lantern.mjs` | The Drowned Lantern's suite: the room and its tables, the walk and the slide, steps on wood, the flare and the oil, the shrines, Mother's wake and rise and the boat, each hunter's rule (the Lurker's hearing, lane and dash, the guardian and roaming wisps, the leeches at the light's edge and their bite, the bodies that take only the still, Mother's hand and its gaps), hearts, endless lives and the grade, the clock, determinism (no random drawn), the balance (a bot that ignores the hunters loses every shrine order, one that plays them wins each with hearts left), the rule tags and banner marks, the hums, voices and drawing |
| `scripts/test-web-console-activities-ghoul-arms.mjs` | The weapons' suite: the double tap through the keys (repeats, feathering, hammering), the bag and its pill, each weapon, bosses (scale, cap, guards, the half-hp drop), placement in every room, the drop band's single draw, ride rooms, drawing and sounds. |
| `public/activities/ghoul-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` |
+221
View File
@@ -0,0 +1,221 @@
# Architecture: layout, prompts and install
> Part of [AGENTS.md](../AGENTS.md) and the [Architecture index](./AGENTS-architecture.md): project guidance for AI coding agents.
## Directory Structure
```
plan2code/
├── 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
│ │ ├── github-issues.md # Issue-backed map (loaded only when Backend is github)
│ │ ├── grilling.md # Folded-in grilling + domain-modeling
│ │ ├── questions.md # On-disk question-file format + markers
│ │ ├── resolve.md # Per-type resolution + graduating the fog
│ │ ├── handoff.md # Clearing gate + PLAN-DRAFT handoff
│ │ └── trail.md # Every-response map visual + pathed resume command
│ ├── shared-references/ # Reference files shared across skills
│ │ ├── building-habits.md # Find the cause, test first, pin behavior (quick-task, implement, implement-review, 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
│ │ ├── false-positives.md # Known false-positive patterns
│ │ ├── reviewer-brief.md # Fill-in brief for the one fresh helper that runs the analysis
│ │ └── session-end.md # Next-step routing at review session end
│ ├── plan2code-init-update-references/ # Reference files for init-update skill
│ │ └── ai-agent-file-sync.md # Step 7: replace AI configs with AGENTS.md refs
│ ├── plan2code-4-finalize-references/ # Reference files for finalize skill
│ │ └── community-feedback-submission.md # STEP 6.5 payload schema + submission tiers
│ ├── 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
│ │ └── prompts/ # Internal AI prompt templates (no char limit)
│ └── dist/ # Built output (tsup)
├── plan2code-app/ # Desktop app (Rust + Tauri): wraps the console in a window, agent-less setup screen; cargo fmt/clippy/test, see its README
├── src/statusline-claude/ # Claude CLI status line (Node.js, zero deps, single file)
│ ├── statusline.js # Self-contained: config, git, formatters, render
│ └── statusline-config.json # Default config template
├── src/launcher/ # Global `plan2code` command (Node.js, zero deps)
│ ├── plan2code.js # Opens /plan2code in Claude Code or Devin in the cwd (or a picked folder)
│ ├── agents.json # Shipped agent list (built-ins + starter templates with per-OS install data), copied to ~/.plan2code/bin/ on install
│ ├── models.json # Curated model menu, copied to ~/.plan2code/bin/ on install
│ └── plan2code.ico # Desktop shortcut icon (Windows)
├── src/web-console/ # Local browser UI bundled into every skill (Node.js, zero deps, no build)
│ ├── console.mjs # CLI the agent drives: open, post, wait, chat, keep, status, stop, help
│ ├── server.mjs, routes.mjs, static.mjs, cmd-*.mjs, picker.mjs, and the by-job files (files, sessions, patches, scan, inbox, workspace, settings, agents, agent-lookup, git-repo, handoffs, in-app, loop-setup, notepads, open-link, pointers, spec-files, update-check)
│ ├── console.md, console-*.md, notes/, building*.md # Agent-facing contract (console.md read once, the rest on demand)
│ └── public/ # Page assets served to the browser
├── scripts/ # Development scripts
│ ├── bench-web-console.mjs # Start-path timing
│ ├── capture-screenshots.mjs # Stages web console screens and saves the docs screenshots (needs a local Chrome or Edge, through `playwright-core`)
│ ├── browser.mjs # The one place a browser is launched (Chrome, then Edge, through `playwright-core`; `PLAN2CODE_TEST_BROWSER` forces one); page tests, the screenshots and the bench use it
│ ├── css-snapshot.mjs # Dev-only: every element's computed style on every screen, both themes; take one before a stylesheet move and `--compare` after
│ ├── vendor-codemirror.mjs # Dev-only: bundles the pinned CodeMirror 6 packages with esbuild into `public/vendor/codemirror.esm.js` (installed in a temp folder from `vendor-codemirror-lock.json`, never in the repo)
│ ├── check-skill-table.mjs # src/plan2code.md "What each skill reads and writes" table vs each skill's prompt and references
│ ├── parse-check.mjs # Imports every shipped browser module as real ESM
│ ├── screenshots/ # JSON payloads posted per shot (`ask` reuses `question.json`; `finish` follows `signoff.json`)
│ ├── test-web-console-*.mjs, web-console-test-helpers.mjs # Web console suites, split by area (the page tests are `-page-*`, the source shape `-shape`), and their shared setup
│ ├── node-test.mjs, page-test-helpers.mjs # `npm test`'s `node --test`, files at once capped at one per spare core; the page tests' browser sessions and their redraw-safe `styleOf()`, `stylesOf()`, `scrollCard()`
│ ├── test-launcher.mjs, test-getting-started.mjs # Launcher suite; newcomer docs kept in step
│ ├── test-skill-scripts.mjs, test-script-<skill>.mjs, test-git-repo.mjs, skill-script-helpers.mjs, fixture-helpers.mjs # Skill script suites and fixtures
│ ├── set-version.mjs, check-doc-size.mjs, check-test-lanes.mjs, test-fast.mjs # Writes one version into every carrier; holds each .agents-docs file under a size limit; the fast test lane and its two-list check (test-lanes.json)
│ ├── check-versions.mjs, fix-line-endings.mjs, play.mjs # Version sync across every file that carries it (twelve places, also run by npm test); restores LF everywhere (also pretest + pre-commit); tries the games from src/
│ ├── measure-console-wire.mjs, css-helpers.mjs, ghoul-test-helpers.mjs, fixtures/, console-wire-runs/ # Wire-size probe and its captured runs; shared CSS and Ghoul Rush test helpers; skill-script fixtures
│ └── validate-char-count.js # Pre-commit character count validator
├── skills/ # Generated, gitignored build output — one Agent Skill per src/ prompt
│ └── plan2code-<name>/ # SKILL.md plus references/ and scripts/ where present
│ # Generated by npm run build:skills; consumed by skills add
├── .husky/ # Git hooks (husky)
│ └── pre-commit # Runs fix-line-endings, then character count validation
├── .agents-docs/ # The detail files AGENTS.md links to (this file and its siblings)
├── .claude/ # Repo-local Claude Code config (NOT installed by install.js)
│ └── skills/ # Maintainer-only dev skills, e.g. plan2code-publish/, plan2code-launcher-update/
├── .github/ISSUE_TEMPLATE/ # bug.yml, idea.yml, config.yml (target of the console's feedback button)
├── .readme/ # User guides linked from README (web-console.md, web-console-design.md, walkthrough.md, metrics.md, status-line.md, test-bot.md)
├── docs/ # Landing page `index.html` served at plan2code.jparkerweb.com (GitHub Pages, `CNAME`) and assets
│ └── screenshots/ # Web console screenshots, <shot>-light.webp and <shot>-dark.webp (generated)
├── specs/ # Feature specs (if any in-progress)
├── install.js # Interactive installer (Node.js)
├── package.json # Root package (husky only, private: true)
├── version.json # Version metadata
├── CHANGELOG.md, QUICK-REFERENCE.md, LICENSE
├── .gitattributes, .editorconfig # Pin LF (see Code Style & Gotchas)
├── prototypes/, specs--completed/, dist/ # Local only, gitignored: design prototypes, archived specs, stale pre-2.2 build output. Ignore root dist/.
└── README.md # User documentation
```
## Key Files
| File | Purpose |
|------|---------|
| `install.js` | Interactive installer — builds `skills/` from `src/`, then delegates installation to the skills CLI |
| `src/plan2code-*.md` | Source workflow prompts (the "source of truth") |
| `skills/` | Generated Agent Skills, gitignored build output regenerated by the installer (and `npm run build:skills`) before every `skills add` |
| `scripts/validate-char-count.js` | Pre-commit validator ensuring all source prompts ≤ 20,000 chars |
| `version.json` | Version metadata (name, version, description) |
| `QUICK-REFERENCE.md` | User quick-reference card |
| `src/statusline-claude/` | Claude CLI status bar (see [the status line file](./AGENTS-architecture-statusline.md)) |
| `src/launcher/plan2code.js` | Global `plan2code` command that opens the dashboard skill in Claude Code, Devin or Codex (installed by `I` and Advanced → `E`; also via Advanced → `D`). When the desktop app is installed (`~/.plan2code/app/plan2code-app[.exe]`, or the file `PLAN2CODE_APP` names) and a display exists (Windows and macOS always; Linux needs `DISPLAY` or `WAYLAND_DISPLAY`), it opens the app after the agent and model questions with `--project <folder> --agent <id> [--model <id>]` and exits; `--classic` (never forwarded to the CLI) and a failed spawn keep the terminal flow. The app reads all three (`project::launch_choice`): the picker starts on `--agent`, and `--model` applies to that agent on every start and Restart (`AgentManager::set_model`); a model never applies to another agent. Its menu, lookup and no-agent flow come from `agents.json` through `agent-lookup.mjs`, loaded by dynamic `import()` from `~/.plan2code/bin/` (the launcher's one stated exception to its Node-built-ins-only rule; a missing copy falls back to the plain printed install steps) |
| `plan2code-app/` | Tauri desktop app (Rust host, xterm panel, the console's dashboard in a frame; its own README). `RELEASE-CHECKLIST.md` lists the by-hand checks before each release. `src-tauri/src/versions.rs` compares the app's version (`tauri.conf.json`) with the installed skills' (`~/.plan2code/bin/version.json`) for the bar's **Update skills** line, which runs `node ~/.plan2code/bin/plan2code.js update` only when pressed |
| `plan2code-app/src-tauri/src/attention.rs` | The taskbar signal's rules, pure and knowing nothing about Tauri: `Signal` (`busy`, `ready`, `attention`, `plain`), `badge_for(signal, os, enabled)` (Windows: green dot on `ready`, red on `attention`; macOS: red `!` on `attention` only; Linux: count 1 on `attention`), `should_flash(prev, next, focused, enabled)` (once, only on a change into `ready` or `attention` while unfocused) and `dot_rgba()` (the dot's pixels, in the favicon's colors, which a test checks against `public/favicon.js`). `main.rs` applies the result through `set_attention`, `set_taskbar_signal` and `clear_attention_cmd`; the page asks with the `attention` and `taskbar` messages (`public/app-bridge.js`) and the switch is `taskbarSignal` in the app's own `~/.plan2code/app.json`. |
| `plan2code-app/src-tauri/src/quit_prompt.rs`, `task_dialog.rs` | The quit check shown while an agent runs. `quit_prompt(last_signal)` is pure: the page's last taskbar signal `ready` or `plain` is the waiting case ("Done for now?", Info icon), and `busy`, `attention` or none yet is the working case ("Leave while your agent is busy?", Warning icon). `task_dialog.rs` (Windows only) draws it with `TaskDialogIndirect` through `winapi`: a heading, Stay as the default, and the app's icon in the title bar, since the dialog plugin has no heading and Windows copies its icon into the title bar (the warning once showed twice). `confirm_quit` in `main.rs` runs it on its own thread; macOS and Linux use the plugin box with the same words, where Quit stays the default button (putting Stay first would make Esc quit). A page reload or an unanswered page clears the signal to none (`clear_attention`), so the box stays on the working words until the page reports again; `QUIT_OPEN` keeps a second box from stacking |
| `plan2code-app/src-tauri/src/loop_driver.rs` | The Implementation Loop's driver. Its decisions are pure functions and carry the unit tests: `phase_prompt()` (the prompt each fresh phase session starts on), `judge_outcome()` (the skill's `loopOutcome` against the spec's marks and the setup), `expect_patch()` (the `loopExpect` judging criteria stamped into the session so the console refuses a bad report at post time), `silence_expired()`, `should_retry()` (one retry for a crash or silence, never for a real failure), `open_question()` and `stop_line()`. Around them sit the running record (app memory only), the watch thread and the stop and resume entry points. **The app, not the agent, marks a loop phase done and commits it**; the skill only builds and reports |
| `plan2code-app/src-tauri/src/loop_commit.rs` | The loop's commit step, called by `handle_outcome` in a fixed order: prepare (subject, message), stage and check the staged names and sizes against a denylist (`.env*` except `.example`, `.sample`, `.template`; oversized files; a bad list unstages all and stops), save the phase file text, mark done, commit with its own limit, and on a failed commit restore the saved text only if the file still equals what the loop wrote (else stop with "marked, not committed", kept in the reports store). Stop now never commits; `judge_outcome` refuses missing task data and failed tests; the watcher runs under `catch_unwind` and counts unreadable sessions as silence; `loop_state` in `main.rs` redraws the strip after a reload |
| `plan2code-app/src-tauri/src/loop_notify.rs` | The loop's notification: `NotifyKind` (query string, JSON body, Discord, Slack, Teams, Google Chat; its comment lists what a new service needs), `valid_url()`, `valid_param()` (mirrored in `loop-setup.mjs` and `screens/loop-setup.js`), `request_for()` (each kind's address and body) and `send()`, with a 10 second limit and errors that never hold the address. The driver writes the message and calls it from `observe()`, `stop_loop()` and `finish()`. |
| `plan2code-app/src-tauri/src/loop_report.rs` | The loop's report on everything done for the person: one `LoopReport` per build, entries in order (passed, stopped, retried) with findings fixed, skipped and left open, assumptions read from the phase file, and reported decisions. Saved in the console's `loop-reports.json` after every entry, because a project file would dirty the tree Resume needs clean; `finish()` writes it to `LOOP-SUMMARY-<date>.md` and removes the entry. |
| `plan2code-app/src-tauri/src/loop_tools.rs` | What the loop runs on its own, each call with a time limit and its output kept: the spec scripts (`specs.mjs status`, `mark --to done`), `commit-msg.mjs`, git (`add`, `commit`, `status`, the short head), the console's `post` and `open --resume`, and the person's quick check. No shell runs here except the quick check, whose text comes only from `loop-setup.json`, never from a page message |
| `plan2code-app/src-tauri/src/agents.rs` | Agents in the app: `CustomAgent`, the `Agent` handle over built-ins and custom entries, `load_custom_agents`, reading the Agents file below; the shipped `agents.json` read at run time with the baked copy as fallback; `find_on_path`, the Rust twin of `agent-lookup.mjs`'s `findAgent` (PATH, PATHEXT, the saved PATH from `node_check::resolved_path()`, npm's global folder, the install folders), held to `scripts/fixtures/agent-lookup-cases.json`. The console side is `src/web-console/agents.mjs` |
| Desktop app install (`install.js`) | `installDesktopApp()` downloads `plan2code-app-<version>-<windows\|macos\|linux>-<x64\|arm64>[.exe]` and `plan2code-app-<version>-SHA256SUMS.txt` from the GitHub release (`PLAN2CODE_RELEASE_BASE` replaces the URL; the tests serve a stand-in), checks the SHA-256 and places the file in `~/.plan2code/app/` (the old file is renamed aside first, since Windows cannot overwrite a running exe). `app` is an install piece (`INSTALL_PIECES`, after `launcher`), so `plan2code update` updates it with the rest. `install()` asks for it after the command (default yes; a no is kept as `skipped` in `install.json`); unattended it installs it unless it is already recorded or was declined. A failed app never fails the install. `.github/workflows/release-app.yml` builds one file per system (`tauri build --no-bundle`) and the checksum list on a published release, after `scripts/check-versions.mjs --tag` |
### Agents file
`~/.plan2code/agents.json` holds the person's custom agent CLIs. The web console is its only writer (User Preferences → Agents & models, through `POST /agents`); the `plan2code` launcher and the desktop app only read it. Each reader carries its own copy of the rules (`src/web-console/agents.mjs` for the console, a copy in `src/launcher/plan2code.js`, `agents.rs` in the app), and `scripts/fixtures/agents-cases.json` is the contract all three readers' tests load: file normalization with its warnings, `buildArgs` command lines and `makeId` ids. Change a rule in the fixture first.
`src/launcher/agents.json` is the shipped list: `kind: "builtin"` entries (Claude Code, Devin, Codex) with `installUrl`, per-OS `install` lines and `installDirs`, and `kind: "template"` entries other CLIs can be saved from. `install.js` copies it to `~/.plan2code/bin/agents.json` beside `agent-lookup.mjs`, which all JS readers share: `loadAgentList()` reads it, `findAgent()` gives a command its `found` / `outside` / `missing` state (PATH, the saved Windows PATH, npm's global bin, the entry's `installDirs`). The app reads the same JSON with `serde_json` at run time (`include_str!` of the repo file baked in as fallback) and `find_on_path` in `agents.rs` is its Rust twin: `scripts/fixtures/agent-lookup-cases.json`, loaded by `scripts/test-agent-lookup.mjs` and by `cargo test` through `include_str!`, is the contract both lookups are held to.
- **File:** `{ "schema": 1, "agents": [...] }`. Any other schema, text that is not JSON, or `agents` that is not a list gives no custom agents and one warning. A missing file is an empty list with no warning. More than 50 entries: the first 50 are used. Unknown keys, in the file and in an entry, are kept when the console saves.
- **Entry:** `id`, `name` and `command` are required; `args` (default `[]`), `prompt` (default `"/plan2code"`, blank allowed), `bypassArgs` (`[]`), `modelArgs` (`["--model", "{model}"]`) and `models` (`[]`, each `{ id, label? }`) are optional. The three argument fields are lists of text, one list item per argument.
- **Rules:** `id` matches `^[a-z0-9][a-z0-9-]{0,31}$`, is not `claude`, `devin` or `codex`, and is unique; `name` is at most 60 characters and unique ignoring case; `command` is not blank. `makeId(name, taken)` makes the id from the name in kebab case (`agent` when nothing is left), with `-2`, `-3` on a clash, at most 32 characters.
- **Bad entries:** a bad entry is skipped with a warning naming it (`agents[i]`, 0-based) and the rest still load, in all three readers. `POST /agents` instead refuses the save with `{ error, index, field }`, and answers `409` while the file holds something `GET /agents` could not read, unless the body says `replace: true`.
- **Command line:** `buildArgs` returns `args` with `{prompt}` filled (the prompt is appended when no argument holds it, and a blank prompt drops an argument that is exactly `{prompt}`), then `modelArgs` with `{model}` filled when a model is chosen, then `bypassArgs` when checks are off. Arguments travel as a list, never through a shell; the Windows `cmd` wrapper for a `.cmd` or `.bat` belongs to the launcher and the app.
## Workflow Prompts (in `src/`)
| File | Step | Purpose |
|------|------|---------|
| `plan2code.md` | — | The dashboard: opens the web console's skill menu and launches the picked skill into its own session |
| `plan2code-init.md` | Init | Generate AGENTS.md as index + `.agents-docs/` section files (progressive discovery) |
| `plan2code-init-update.md` | Update | Update AGENTS.md with learnings; detects and routes edits to `.agents-docs/` files |
| `plan2code-0-pathfinder.md` | 0 | Chart a foggy idea as a map (local files, or GitHub Issues) of decision questions under `specs/<idea>/pathfinder/`, resolve them one at a time, hand a seeded PLAN-DRAFT to Step 1 |
| `plan2code-quick-task.md` | quick | Lightweight planning for small tasks (standalone — not a pipeline step) |
| `plan2code-1-plan.md` | 1 | Requirements analysis & architecture |
| `plan2code-1b-revise-plan.md` | 1b | Mid-implementation revisions |
| `plan2code-2-document.md` | 2 | Create implementation specs |
| `plan2code-3-implement.md` | 3 | Execute implementation (phase by phase) |
| `plan2code-3-implement-review.md` | 3 | Execute one phase, run focused review and fixes, then request approval |
| `plan2code-review.md` | review | Post-implementation comprehensive review, analyzed by one fresh helper when the tool has one (verified in session; the report says who reviewed) |
| `plan2code-4-finalize.md` | 4 | Validate, summarize, feedback, archive (steps 1–7, +optional 6.5) |
| `plan2code-handoff.md` | handoff | Compact the conversation into a self-contained handoff document for a fresh session |
| `plan2code-xray.md` | xray | Explain how and why an area works (files, commits, PRs via `gh` when present), or rank the rough spots worth fixing into `ARCHITECTURE-BRIEF-<date>.md` for Pathfinder or Plan; never edits code |
| `plan2code-diagnose.md` | diagnose | Find a bug's cause under the find-the-cause-first habit (`references/building-habits.md`) and write it up as `specs/<bug-name>/DIAGNOSIS-<YYYYMMDD>.md` without fixing it, then offer Quick Task to fix it, or Plan when the fix is big. The dashboard scan reports such a folder as spec state `diagnosed` ("Bug diagnosed"), which lights Quick Task (suggested) and Plan. Once Quick Task marks the diagnosis `Fixed` (nothing past it in the folder) the state is `fixed` ("Bug fixed"): no pipeline card lights, the picker never pre-selects it, and Quick Task offers to archive it with `specs.mjs archive` |
| `plan2code-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 |
## Naming Convention
Workflow files follow a strict naming pattern:
- **The hub:** `plan2code.md` (bare name — `bare: true` in `SOURCE_PROMPTS`, no suffix; it is the dashboard the rest hang off, not a step)
- **Utilities:** `plan2code-<name>.md` (single dash)
- **Numbered steps:** `plan2code-<N>-<name>.md` (single dash, number, single dash)
Examples:
- `plan2code-init.md` (utility)
- `plan2code-1-plan.md` (step 1)
- `plan2code-1b-revise-plan.md` (step 1b)
## Reference Files
Some workflows use companion reference files for depth that does not need to load on every invocation. The orchestrator (main workflow file) loads them via `Read` directives during execution.
**Pattern:** `src/<source-filename-without-extension>-references/` (e.g., `plan2code-review-references/`). A file several skills read lives in `src/shared-references/` instead and ships to each through `additionalReferences` (e.g., `building-habits.md` into Quick Task, Implement and Implement + Review).
**How the installer handles them:** the directory is copied verbatim to `skills/<skill-name>/references/`, so `Read references/<file>.md` resolves consistently for every agent. There is one output format, with no flat-file sibling directory or path rewrite.
Reference files are NOT subject to the 20,000 character limit. The review workflow pioneered this pattern (`verification-protocol`, `dimensions`, `false-positives`, `session-end`); the init-update workflow also uses it (`ai-agent-file-sync` for its Step 7), `plan2code-4-finalize.md` uses it for STEP 6.5 (`community-feedback-submission`), and `plan2code-0-pathfinder.md` leans on it hardest (`brief`, `chart`, `github-issues`, `grilling`, `questions`, `resolve`, `handoff`, `trail` — the orchestrator is a dispatcher, the depth lives in the references). Other workflows can adopt it when a source file carries detail that is only needed some of the time. The implement-review skill is a generated composition: `additionalReferences` in `SOURCE_PROMPTS` packages the canonical implement prompt, review prompt, and review reference directory into its own `references/` directory so those workflows are reused without source duplication.
## Shared Console
The web console is built once into `skills/_console/<version>/` and installed by `installSharedConsole()` in `install.js` to `<console home>/<version>/` (`~/.plan2code/console`, or `PLAN2CODE_CONSOLE_HOME`, which tests set). Each skill carries only `src/web-console-stub/console.mjs`, with the version baked in at build. The stub tries `<home>/<version>/` first, then the `console-dir` pointer, and needs a matching `version.txt`; with neither it prints one line and exits 5. Only an installed console's `open` writes `console-dir` (a source checkout's does not, or every stub would point at the checkout). `install()` and `installProjectSkills()` call `installSharedConsole({ sweep: false })` before `skills add` and `sweepOldConsoles()` only after it succeeds, so a failed update leaves the old stubs able to find their old console. A test that runs a built skill's `console.mjs` must point `PLAN2CODE_CONSOLE_HOME` at a folder whose `console-dir` names `skills/_console/<version>/`, and a shared console finds skill files in `~/.agents/skills/`.
## Repo-Local Skills (`.claude/skills/`)
Maintainer-only skills committed to the repo but deliberately excluded from the generated `skills/` product artifact:
- `plan2code-publish/` — publishes a GitHub Release after version files agree.
- `plan2code-changelog/` — validates release classification and keeps version files synchronized.
- `plan2code-launcher-update/`: refreshes the launcher's shipped data: the curated model menu (`src/launcher/models.json`) from `devin models list` and Claude Code's documented model aliases, and the agent list's install data (`src/launcher/agents.json`) re-checked against each vendor's docs, including a re-check of the agents left out as templates (Cursor CLI, Aider) against the template rule. Shows a diff, applies only the changes the maintainer approves, validates both files and runs `npm test`. Terminal only, and it never commits.
- `sync-repo/` — decrypts the protected upstream-sync workflow in memory.
Do not run `skills add` against the repository root: recursive discovery also finds these maintainer skills. `install.js` targets `skills/` and passes explicit workflow names instead. Global install/uninstall cleanup removes `plan2code-*` workflow skills from user skill directories; it never operates on this repository's `.claude/skills/` directory, and `sync-repo` intentionally has no `plan2code-` prefix.
## Global `plan2code` Command
Typing `plan2code` in any directory opens the dashboard skill against the current project, **in that directory**, in one of the built-in CLIs (the shipped `src/launcher/agents.json`, plus any custom entries in `~/.plan2code/agents.json`):
| CLI | Runs |
| --- | --- |
| Claude Code | `claude /plan2code [--permission-mode bypassPermissions] [args]` |
| Devin | `devin [--permission-mode bypass] [args] -- /plan2code` |
| Codex | `codex [--dangerously-bypass-approvals-and-sandbox] [args] $plan2code` (Codex starts a skill with `$name`; the launch line follows Codex's documentation) |
The bracketed flags (each entry's `bypassArgs`; a custom agent's own `bypassArgs`) go in only when permission prompts are off. Right after the agent is chosen, and only when it has such a flag, `chooseBypass()` asks `Turn <CLI>'s permission prompts off?` (Codex: `approval prompts and its sandbox`, worded by `bypassQuestion()`) on every launch, with Yes as the default and no answer remembered; `--keep-permissions` answers no and `--bypass-permissions` answers yes (neither is forwarded; keep wins when both are given), and with no TTY on stdin the prompts stay on unless `--bypass-permissions` is given. When the desktop app will take over, the question is skipped (its launch card has its own tick) and asked only if the app fails to start. The installer prints no warning about it.
On a terminal it first prints a Planny banner (`renderBanner()`). With more than one on `PATH` it asks `Plan2Code opens inside an AI coding agent. Pick which one to use:` as a numbered menu, the last pick pre-selected and marked `(last used)` (Enter keeps it; a number or a CLI id also works); with one installed it uses that without asking, printing `Opening with <CLI>…` (as does a `--cli` pick); with none it runs the setup flow when a person can see a page (`hasDisplay()` and a TTY or the shortcut; the desktop app first when it is installed, else the console's agent-less `setup` page in the browser) and otherwise prints the install steps (`printNoAgentGuidance()`: each built-in's install command and page, how to add another agent in `~/.plan2code/agents.json`, and to run `plan2code` again) and exits 127. An uninstalled `--cli` pick goes to the same setup flow on that agent when a page can open, else prints that CLI's own steps after its error. `--cli claude` / `devin` / `codex` (or `--cli=<name>`) skips the menu and is never forwarded; an unknown name exits 2, an uninstalled one 127. The pick is saved as `lastCli` in `~/.plan2code/launcher.json`, merged beside `lastFolder`. Before spawning, unless the forwarded args carry `--model` / `--model=` (or, for Codex, `-m`), it asks `Which model should <CLI> use?` from `models.json` plus the user's additions, Enter keeping the model the CLI last used — Ctrl+C at any launcher prompt exits 130. With no TTY on stdin there is no menu (last pick, else the first installed) and no model question: it prints that the CLI will use the model last used in it (switch it in that CLI on its own, or pass `--model <name>`). Headings, numbers, defaults, retry lines and the `plan2code:` error prefixes are colored with `paint()` (the escape values of `install.js`'s `COLORS`, copied), stdout only when stdout is a TTY and stderr only when stderr is, and never when `NO_COLOR` is set; piped runs print plain text and no banner. Other arguments are forwarded to the CLI (`plan2code --model opus`), and its exit code is passed back. `plan2code update` is the one subcommand: it is never forwarded and opens no agent, it runs `npx --yes --allow-git=all git+https://github.com/jparkerweb/plan2code.git --update`, so `install.js --update` reinstalls what `~/.plan2code/install.json` lists. On every other start, before spawning the CLI, it prints one line when a newer release is out (`Plan2Code v<latest> is out (you have v<installed>). Run: plan2code update`), compared against `~/.plan2code/bin/version.json` and read from the console's cached release check (`~/.plan2code/console/update-check.json`); it never waits on the network, and when the cache is missing or stale it refreshes it in a detached background process so the next start knows. Tests: `scripts/test-launcher.mjs` (run by `npm test`) spawns the launcher against stand-in `claude`/`devin`/`codex` commands and a temp home.
**Design constraints:**
- **Stable copy, not the package dir** — the installer normally runs from an npx cache directory npm may delete, so `installLauncher()` copies `src/launcher/plan2code.js` to `~/.plan2code/bin/plan2code.js` and the shims point there. Beside it go `update-check.mjs` (the web console's release check, for the terminal notice), `agents.json` and `agent-lookup.mjs` (the shared agent list and lookup rule; `plan2code update` restores a missing copy) and a `version.json` (the installed version). (The metrics/bot wrappers point into `__dirname` and don't have this protection.)
- **The setup flow and hand-over.** With no runnable agent, `runSetupFlow()` finds `console.mjs` (the order the app's `find_console_dir` uses) and runs `open --workflow setup [--for-cli <id>]` as a child process, then `wait` in 240-second slices (the agent-less console keeps its app variables out, NFR-2). An `__start` action ends the wait with the pick; the launcher spawns that agent with `PLAN2CODE_SETUP_ANNOUNCE` (the setup server's base URL) and `PLAN2CODE_SETUP_TOKEN`, and the new agent's `open` POSTs its sign-in URL to `POST /handover` on the setup server, which broadcasts a `move` event the waiting tab follows. The post failing or the wait ending unmoved falls back to opening a browser / the printed steps.
- **npm-style shims** — written into npm's global bin (`npm config get prefix`; `<prefix>/bin` off Windows): an sh shim everywhere, plus `.cmd` and `.ps1` on Windows, so cmd.exe, PowerShell and Git Bash all resolve it. On macOS/Linux, when the npm bin isn't writable (system Node), it falls back to `~/.local/bin`.
- **Marker-based ownership** — every shim contains `plan2code-launcher`; `uninstallLauncher()` removes only files carrying it, leaving any other `plan2code` bin alone.
- **Resolving the CLI** — `findAgent()` in the shared `agent-lookup.mjs` does the lookup: `PATH` (+ `PATHEXT` on Windows), the saved Windows PATH from the registry (`addSavedWindowsPath()`), npm's global bin and each entry's `installDirs`, giving `found` / `outside` / `missing` (the desktop app's `find_on_path` in `agents.rs` is its twin, held to `scripts/fixtures/agent-lookup-cases.json`). An `.exe` is spawned directly; a `.cmd`/`.bat` wrapper goes through `cmd.exe /d /s /c` with quoted args, since Node refuses to spawn batch files without a shell. The installer warns only when neither `claude` nor `devin` is on `PATH`.
- **No bin-name overlap** — the installer's own bin in `package.json` is `plan2code-install` (→ `install.js`), so `plan2code` belongs to the launcher alone. npx runs a package's only bin whatever it's named, so the README's `npx … plan2code.git` command is unaffected; keep it the only bin, or npx will need `-c plan2code-install`.
- **`--pick-folder` is shortcut-only** — the launcher strips it before building the CLI's args. The shortcut runs the CLI menu, then the folder picker, then the model menu. With it, a native folder picker chooses the cwd instead: on Windows, the Explorer-style `IFileOpenDialog` (`FOS_PICKFOLDERS`) via `powershell -STA -EncodedCommand`, its C# interop (`WINDOWS_PICKER_SOURCE`) passed in an env var and compiled with `Add-Type` (~0.5s), with a TopMost owner form so it doesn't open behind the console — Windows PowerShell's `FolderBrowserDialog` is the old tree-only dialog, and is kept only as the fallback when `Add-Type` is blocked (Constrained Language Mode, AppLocker); `osascript choose folder` on macOS, and `zenity` then `kdialog` on Linux (only when `DISPLAY`/`WAYLAND_DISPLAY` is set). If there's no picker, or the picker fails, it falls back to a typed `Project folder [last]:` prompt. A picker that exits 0/1 with nothing printed means the person canceled, so the launcher exits 0. The picker starts on the last pick, stored in `~/.plan2code/launcher.json`. From the shortcut, a non-zero exit other than Ctrl+C (130 / `0xC000013A`) waits for Enter so the error doesn't vanish with the window. Typed in a terminal, `plan2code` behaves exactly as before.
**Desktop shortcut** — after the shims are written, `installLauncher()` (now async) calls `offerDesktopShortcut()`. It asks `Also add a Plan2Code shortcut to your desktop? (y/N)`, skips the question when stdin isn't a TTY, and refreshes an existing marked shortcut without asking. `installDesktopShortcut()` writes it to the real desktop (`[Environment]::GetFolderPath('Desktop')` on Windows, which covers OneDrive redirection; `xdg-user-dir DESKTOP` on Linux; `~/Desktop` otherwise):
| OS | File | Runs |
| --- | --- | --- |
| Windows | `Plan2Code.lnk` (written by `WScript.Shell`) | `pwsh.exe` (else Windows PowerShell) `-NoLogo -ExecutionPolicy Bypass -File "<bin>\plan2code.ps1" --pick-folder`, icon `src/launcher/plan2code.ico` (the web console's Peek-a-boo favicon, 16–256 px) copied to `~/.plan2code/bin/plan2code.ico` |
| macOS | `Plan2Code.command` (0755) | `exec "<bin>/plan2code" --pick-folder` in Terminal |
| Linux | `plan2code.desktop` (0755, `Terminal=true`, `gio … metadata::trusted`) | `"<bin>/plan2code" --pick-folder`, `Icon=` the web console's `favicon.png` copied to `~/.plan2code/bin/plan2code.png` |
The macOS and Linux shortcuts carry the `plan2code-launcher` marker as a comment line. A `.lnk` has nowhere to hide one (its Description is the hover tooltip), so it's recognized by what it runs: the UTF-16 strings `plan2code.ps1` and `--pick-folder` stored in the file (`plan2code.cmd` also matches, so shortcuts from before the PowerShell switch get refreshed). `uninstallLauncher()` removes only a recognized shortcut, plus the icons (`plan2code.ico`, `plan2code.png`), `bin/models.json` and `launcher.json` (never the user's `~/.plan2code/models.json`). A shortcut failure prints a warning and never fails the command install.
**Installer integration** lives in `install.js` under the `PLAN2CODE COMMAND` section (`installLauncher`, `uninstallLauncher`, plus the shortcut helpers). `install()` awaits it after a successful skills install (so `I` and Advanced → `E` get it), `U` removes it, and Advanced → `D` installs it alone. Every global install writes `~/.plan2code/install.json`, the install record listing the pieces installed (skills, launcher, statusline, loop, metrics, bot); `install.js --update` (what `plan2code update` runs) reinstalls those (metrics and bot only when run from a git checkout), with no menu and never uninstalling, or with no record the skills and the `plan2code` command. After an install, `printGettingStarted()` prints the three steps (cd into the project, start Plan2Code, pick a card) and, when no agent CLI is on `PATH`, how to get one.
@@ -0,0 +1,37 @@
# Architecture: skill scripts
> Part of [AGENTS.md](../AGENTS.md) and the [Architecture index](./AGENTS-architecture.md): project guidance for AI coding agents.
## Skill Scripts
Anything a workflow step decides with one correct answer (parsing a spec's checkboxes, rebuilding Pathfinder's map markers, the commit message, which AI config files exist) lives in a script the agent runs, not in prose it follows. Prose keeps the judgment.
| Source | Ships to | How |
|---|---|---|
| `src/skill-scripts/<name>.mjs` | `skills/<skill>/scripts/<name>.mjs` | Shared: a skill lists the ones it runs in `scripts: [...]` on its `SOURCE_PROMPTS` entry. Skills install independently, so each gets its own copy |
| `src/skill-scripts/common.mjs` | every skill that has scripts | `SHARED_SCRIPTS_ALWAYS` in `install.js` |
| `src/<source>-scripts/<name>.mjs` | `skills/<skill>/scripts/<name>.mjs` | A skill's own scripts, mirroring `-references/`. A name that collides with a shared script is a build error |
| `version.json` (repo root) | `skills/<skill>/scripts/version.json` | Copied at build, so an installed skill can report its version |
| Script | Skills | Does |
|---|---|---|
| `specs.mjs` | plan, revise-plan, document, implement, implement-review, review, quick-task, finalize, handoff, diagnose | `list` / `status` (the dashboard state, Phase Checklist, groups, task markers, numbering, the implement selection verdict, consistency checks) / `check` / `check-draft` / `metrics` / `mark` / `tick` / `archive`. `list` imports `scanProject()` from the bundled `web-console/scan.mjs`, and `status` calls `deriveSpecState()` and `pickPhaseFiles()` from `web-console/spec-files.mjs`, the one rule the scan also uses, so the dashboard and the skills never disagree on a spec's state (a phase with only blocked tasks left stays `building`, and `finalizeReady` lights Finalize once each has a written reason). `mark` writes the phase file's Status line on every move (`--to in-progress` too). `check`'s format rules (no Status line, a checkbox under Notes, a task pointing at a line number, a bare `[!]`) warn, and fail only a spec whose overview.md carries `<!-- plan2code-format: 2 -->`. `archive` that has to copy removes the source only once every file name and size at the target matches (`PLAN2CODE_ARCHIVE_FAULT` is its test seam) |
| `commit-msg.mjs` | implement(-review), review, quick-task, finalize, init-update, git | The `<subject>` / `AI Assisted` commit command (two `-m` flags), with an optional `git add -- <files>` from `--files`. There is no add-everything option: `--add-all` was retired, and `scripts/test-script-git.mjs` fails if it returns anywhere in `src/` |
| `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, implement(-review), quick-task, finalize, 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, implement(-review), quick-task, finalize, 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` | implement(-review), quick-task, finalize, 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` | implement(-review), quick-task, finalize, 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. With no AGENTS.md yet (Init's run, so said once), `notices` warns when `.gitignore` keeps `specs--completed/` out of git, since archived specs are then not backed up |
| `agent-files.mjs` | init, init-update | Detect and replace other agents' config files with AGENTS.md pointers |
| `pathfinder.mjs` (own) | 0-pathfinder | `init` (the map in its Step 5 state from `--destination`, `--scores` and `--fog`; refuses an existing map) and `add` (the next `questions/NN-<slug>.md` plus its map row), with the references' templates kept as the fallback, then `reconcile`, `frontier`, `claim`, `resolve`, `rule-out`, `trail`, `gate` (which also prints the exact PLAN-DRAFT status line `specs.mjs` reads), `lint`, `brief-data`. Writes rows as `[Name](link): tail` with no em dash, and still reads maps written the old way |
| `feedback-payload.mjs` (own) | 4-finalize | STEP 6.5's payload (real sha256 prompt hashes) and the gh / browser / print submission tiers |
| `xray.mjs` (own) | xray | `hotspots` (churn, files changed together, often-changed files with no test, from `git log` over a capped window) and `history <path>` (commits following renames, a blame summary, PR titles and first paragraphs through `gh` when signed in, and which sources were used). Read-only |
| `changelog-state.mjs` (own) | changelog | `state`, `bump`, `set-package-version`: the default branch's version, whether the branch's entry can be extended (not released, not on another branch), the file's heading style, the gap since the entry was last touched; only `set-package-version` writes, and only the version field |
| `git.mjs` (own) | git | `state`, `plan`, `branch-check`, `init-check`, `delete-check`, `cleanup-list`, `conflicts`, `pr-url`, `classify-error`: the repo snapshot, each action's exact command and confirm text (shared by the terminal and the board), branch-name, delete, cleanup and git init checks, a stopped rebase's conflicts, the pull-request link and git's errors sorted into kinds with a next step. Read-only: the agent runs every command it prints, and `guard()` refuses force push, hook skipping, amend, remote delete and blanket add |
**Conventions** (`common.mjs`): Node 18+ built-ins only; one JSON object on stdout (`ok: false` plus `error`, `message`, `next` on a handled failure, the same line on stderr); exit 0 ok, 1 crash, 2 bad arguments, 3 not found, 4 invalid or check failed, 5 refused; `--help` documents commands and exit codes; writes take `--dry-run`; `PLAN2CODE_NOW` pins the clock for tests. A SKILL.md names a script as `node "<S>/<name>.mjs"`, where `<S>` is `scripts/` beside it.
**Tests:** `scripts/test-skill-scripts.mjs` (installer plumbing and the shared scripts), `scripts/test-script-<skill>.mjs` (a skill's own, 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/`.
@@ -0,0 +1,25 @@
# Architecture: status line
> Part of [AGENTS.md](../AGENTS.md) and the [Architecture index](./AGENTS-architecture.md): project guidance for AI coding agents.
Optional Claude Code status bar living in `src/statusline-claude/`. Three-line bar beside a Planny icon: two content lines with a dashed rule between, showing model (+ effort), project/worktree, branch, uncommitted diff stats, session duration + cost, context window usage, and plan/quota usage.
**Design constraints:**
- **Zero runtime dependencies** — `statusline.js` is self-contained (config loader, git helpers, formatters, render). Copied verbatim to `~/.claude/plan2code-statusline.js` on install; no bundler step.
- **Stdin-driven** — all data comes from Claude Code's stdin JSON (`model`, `workspace`, `context_window`, `rate_limits`, `cost`). No API calls, no auth, no background processes.
- **Silent failure** — outer `try/catch` around `main()` plus `process.exit(0)` on missing stdin guarantees the script never crashes the CLI. All git ops are timeout-bounded (1.5s) and non-git workspaces short-circuit via `isGitRepo()` (walks up to 10 parent dirs looking for `.git`).
- **Atomic settings writes** — installer writes `~/.claude/settings.json` via temp file + rename so a crash never leaves the file truncated.
- **Custom-config respect** — installer detects non-plan2code `statusLine` entries, prompts before replacing, and backs up to `statusline-previous.json`. Uninstall only removes `settings.statusLine` if it points to the plan2code bundle.
**Layout:**
```
src/statusline-claude/
├── statusline.js # Self-contained: config, git, formatters, render
├── statusline-config.json # Default config template
└── README.md # User docs: install, config, debugging
```
**Adaptive plan-usage display:** the formatter auto-selects between `5h/7d` rate-limit percentages (Pro/Max/Teams — when `rate_limits` present in stdin) and `Nk in · Nk out` session-token counts (Bedrock/Vertex/PAYG — when `rate_limits` absent). Segment is hidden when neither shape is available.
**Installer integration** lives in `install.js` under the `STATUS LINE INSTALLATION` section (`installStatusLine`, `uninstallStatusLine`). Included in Advanced → `E` (Everything); also available individually via Advanced → `S`.
+12 -663
View File
@@ -1,668 +1,17 @@
# Architecture
> Part of [AGENTS.md](../AGENTS.md) — project guidance for AI coding agents.
> Part of [AGENTS.md](../AGENTS.md): project guidance for AI coding agents.
## Directory Structure
This file is an index. The architecture notes are split by area so each file stays small enough to read whole (`scripts/check-doc-size.mjs` holds every file in `.agents-docs/` under a size limit). Read only the area you are changing.
```
plan2code/
├── 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
│ │ ├── github-issues.md # Issue-backed map (loaded only when Backend is github)
│ │ ├── grilling.md # Folded-in grilling + domain-modeling
│ │ ├── questions.md # On-disk question-file format + markers
│ │ ├── resolve.md # Per-type resolution + graduating the fog
│ │ ├── handoff.md # Clearing gate + PLAN-DRAFT handoff
│ │ └── trail.md # Every-response map visual + pathed resume command
│ ├── shared-references/ # Reference files shared across skills
│ │ ├── building-habits.md # Find the cause, test first, pin behavior (quick-task, implement, implement-review, 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
│ │ ├── false-positives.md # Known false-positive patterns
│ │ ├── reviewer-brief.md # Fill-in brief for the one fresh helper that runs the analysis
│ │ └── session-end.md # Next-step routing at review session end
│ ├── plan2code-init-update-references/ # Reference files for init-update skill
│ │ └── ai-agent-file-sync.md # Step 7: replace AI configs with AGENTS.md refs
│ ├── plan2code-4-finalize-references/ # Reference files for finalize skill
│ │ └── community-feedback-submission.md # STEP 6.5 payload schema + submission tiers
│ ├── 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
│ │ └── prompts/ # Internal AI prompt templates (no char limit)
│ └── dist/ # Built output (tsup)
├── plan2code-app/ # Desktop app (Rust + Tauri): wraps the console in a window, agent-less setup screen; cargo fmt/clippy/test, see its README
├── src/statusline-claude/ # Claude CLI status line (Node.js, zero deps, single file)
│ ├── statusline.js # Self-contained: config, git, formatters, render
│ └── statusline-config.json # Default config template
├── src/launcher/ # Global `plan2code` command (Node.js, zero deps)
│ ├── plan2code.js # Opens /plan2code in Claude Code or Devin in the cwd (or a picked folder)
│ ├── agents.json # Shipped agent list (built-ins + starter templates with per-OS install data), copied to ~/.plan2code/bin/ on install
│ ├── models.json # Curated model menu, copied to ~/.plan2code/bin/ on install
│ └── plan2code.ico # Desktop shortcut icon (Windows)
├── src/web-console/ # Local browser UI bundled into every skill (Node.js, zero deps, no build)
│ ├── console.mjs # CLI the agent drives: open, post, wait, chat, keep, status, stop, help
│ ├── server.mjs, routes.mjs, static.mjs, cmd-*.mjs, picker.mjs, and the by-job files (files, sessions, patches, scan, inbox, workspace, settings, agents, agent-lookup, git-repo, handoffs, in-app, loop-setup, notepads, open-link, pointers, spec-files, update-check)
│ ├── console.md, console-*.md, notes/, building*.md # Agent-facing contract (console.md read once, the rest on demand)
│ └── public/ # Page assets served to the browser
├── scripts/ # Development scripts
│ ├── bench-web-console.mjs # Start-path timing
│ ├── capture-screenshots.mjs # Stages web console screens and saves the docs screenshots (needs a local Chrome or Edge, through `playwright-core`)
│ ├── browser.mjs # The one place a browser is launched (Chrome, then Edge, through `playwright-core`; `PLAN2CODE_TEST_BROWSER` forces one); page tests, the screenshots and the bench use it
│ ├── css-snapshot.mjs # Dev-only: every element's computed style on every screen, both themes; take one before a stylesheet move and `--compare` after
│ ├── vendor-codemirror.mjs # Dev-only: bundles the pinned CodeMirror 6 packages with esbuild into `public/vendor/codemirror.esm.js` (installed in a temp folder from `vendor-codemirror-lock.json`, never in the repo)
│ ├── check-skill-table.mjs # src/plan2code.md "What each skill reads and writes" table vs each skill's prompt and references
│ ├── parse-check.mjs # Imports every shipped browser module as real ESM
│ ├── screenshots/ # JSON payloads posted per shot (`ask` reuses `question.json`; `finish` follows `signoff.json`)
│ ├── test-web-console-*.mjs, web-console-test-helpers.mjs # Web console suites, split by area (the page tests are `-page-*`, the source shape `-shape`), and their shared setup
│ ├── node-test.mjs, page-test-helpers.mjs # `npm test`'s `node --test`, files at once capped at one per spare core; the page tests' browser sessions and their redraw-safe `styleOf()`, `stylesOf()`, `scrollCard()`
│ ├── test-launcher.mjs, test-getting-started.mjs # Launcher suite; newcomer docs kept in step
│ ├── test-skill-scripts.mjs, test-script-<skill>.mjs, test-git-repo.mjs, skill-script-helpers.mjs, fixture-helpers.mjs # Skill script suites and fixtures
│ ├── check-versions.mjs, fix-line-endings.mjs, play.mjs # Version sync across every file that carries it (twelve places, also run by npm test); restores LF everywhere (also pretest + pre-commit); tries the games from src/
│ ├── measure-console-wire.mjs, css-helpers.mjs, ghoul-test-helpers.mjs, fixtures/, console-wire-runs/ # Wire-size probe and its captured runs; shared CSS and Ghoul Rush test helpers; skill-script fixtures
│ └── validate-char-count.js # Pre-commit character count validator
├── skills/ # Generated, gitignored build output — one Agent Skill per src/ prompt
│ └── plan2code-<name>/ # SKILL.md plus references/ and scripts/ where present
│ # Generated by npm run build:skills; consumed by skills add
├── .husky/ # Git hooks (husky)
│ └── pre-commit # Runs fix-line-endings, then character count validation
├── .agents-docs/ # The detail files AGENTS.md links to (this file and its siblings)
├── .claude/ # Repo-local Claude Code config (NOT installed by install.js)
│ └── skills/ # Maintainer-only dev skills, e.g. plan2code-publish/, plan2code-launcher-update/
├── .github/ISSUE_TEMPLATE/ # bug.yml, idea.yml, config.yml (target of the console's feedback button)
├── .readme/ # User guides linked from README (web-console.md, web-console-design.md, walkthrough.md, metrics.md, status-line.md, test-bot.md)
├── docs/ # Landing page `index.html` served at plan2code.jparkerweb.com (GitHub Pages, `CNAME`) and assets
│ └── screenshots/ # Web console screenshots, <shot>-light.webp and <shot>-dark.webp (generated)
├── specs/ # Feature specs (if any in-progress)
├── install.js # Interactive installer (Node.js)
├── package.json # Root package (husky only, private: true)
├── version.json # Version metadata
├── CHANGELOG.md, QUICK-REFERENCE.md, LICENSE
├── .gitattributes, .editorconfig # Pin LF (see Code Style & Gotchas)
├── prototypes/, specs--completed/, dist/ # Local only, gitignored: design prototypes, archived specs, stale pre-2.2 build output. Ignore root dist/.
└── README.md # User documentation
```
## Key Files
| File | Purpose |
|------|---------|
| `install.js` | Interactive installer — builds `skills/` from `src/`, then delegates installation to the skills CLI |
| `src/plan2code-*.md` | Source workflow prompts (the "source of truth") |
| `skills/` | Generated Agent Skills, gitignored build output regenerated by the installer (and `npm run build:skills`) before every `skills add` |
| `scripts/validate-char-count.js` | Pre-commit validator ensuring all source prompts ≤ 20,000 chars |
| `version.json` | Version metadata (name, version, description) |
| `QUICK-REFERENCE.md` | User quick-reference card |
| `src/statusline-claude/` | Claude CLI status bar (see Status Line below) |
| `src/launcher/plan2code.js` | Global `plan2code` command that opens the dashboard skill in Claude Code, Devin or Codex (installed by `I` and Advanced → `E`; also via Advanced → `D`). When the desktop app is installed (`~/.plan2code/app/plan2code-app[.exe]`, or the file `PLAN2CODE_APP` names) and a display exists (Windows and macOS always; Linux needs `DISPLAY` or `WAYLAND_DISPLAY`), it opens the app after the agent and model questions with `--project <folder> --agent <id> [--model <id>]` and exits; `--classic` (never forwarded to the CLI) and a failed spawn keep the terminal flow. The app reads all three (`project::launch_choice`): the picker starts on `--agent`, and `--model` applies to that agent on every start and Restart (`AgentManager::set_model`); a model never applies to another agent. Its menu, lookup and no-agent flow come from `agents.json` through `agent-lookup.mjs`, loaded by dynamic `import()` from `~/.plan2code/bin/` (the launcher's one stated exception to its Node-built-ins-only rule; a missing copy falls back to the plain printed install steps) |
| `plan2code-app/` | Tauri desktop app (Rust host, xterm panel, the console's dashboard in a frame; its own README). `RELEASE-CHECKLIST.md` lists the by-hand checks before each release. `src-tauri/src/versions.rs` compares the app's version (`tauri.conf.json`) with the installed skills' (`~/.plan2code/bin/version.json`) for the bar's **Update skills** line, which runs `node ~/.plan2code/bin/plan2code.js update` only when pressed |
| `plan2code-app/src-tauri/src/attention.rs` | The taskbar signal's rules, pure and knowing nothing about Tauri: `Signal` (`busy`, `ready`, `attention`, `plain`), `badge_for(signal, os, enabled)` (Windows: green dot on `ready`, red on `attention`; macOS: red `!` on `attention` only; Linux: count 1 on `attention`), `should_flash(prev, next, focused, enabled)` (once, only on a change into `ready` or `attention` while unfocused) and `dot_rgba()` (the dot's pixels, in the favicon's colors, which a test checks against `public/favicon.js`). `main.rs` applies the result through `set_attention`, `set_taskbar_signal` and `clear_attention_cmd`; the page asks with the `attention` and `taskbar` messages (`public/app-bridge.js`) and the switch is `taskbarSignal` in the app's own `~/.plan2code/app.json`. |
| `plan2code-app/src-tauri/src/quit_prompt.rs`, `task_dialog.rs` | The quit check shown while an agent runs. `quit_prompt(last_signal)` is pure: the page's last taskbar signal `ready` or `plain` is the waiting case ("Done for now?", Info icon), and `busy`, `attention` or none yet is the working case ("Leave while your agent is busy?", Warning icon). `task_dialog.rs` (Windows only) draws it with `TaskDialogIndirect` through `winapi`: a heading, Stay as the default, and the app's icon in the title bar, since the dialog plugin has no heading and Windows copies its icon into the title bar (the warning once showed twice). `confirm_quit` in `main.rs` runs it on its own thread; macOS and Linux use the plugin box with the same words, where Quit stays the default button (putting Stay first would make Esc quit). A page reload or an unanswered page clears the signal to none (`clear_attention`), so the box stays on the working words until the page reports again; `QUIT_OPEN` keeps a second box from stacking |
| `plan2code-app/src-tauri/src/loop_driver.rs` | The Implementation Loop's driver. Its decisions are pure functions and carry the unit tests: `phase_prompt()` (the prompt each fresh phase session starts on), `judge_outcome()` (the skill's `loopOutcome` against the spec's marks and the setup), `expect_patch()` (the `loopExpect` judging criteria stamped into the session so the console refuses a bad report at post time), `silence_expired()`, `should_retry()` (one retry for a crash or silence, never for a real failure), `open_question()` and `stop_line()`. Around them sit the running record (app memory only), the watch thread and the stop and resume entry points. **The app, not the agent, marks a loop phase done and commits it**; the skill only builds and reports |
| `plan2code-app/src-tauri/src/loop_commit.rs` | The loop's commit step, called by `handle_outcome` in a fixed order: prepare (subject, message), stage and check the staged names and sizes against a denylist (`.env*` except `.example`, `.sample`, `.template`; oversized files; a bad list unstages all and stops), save the phase file text, mark done, commit with its own limit, and on a failed commit restore the saved text only if the file still equals what the loop wrote (else stop with "marked, not committed", kept in the reports store). Stop now never commits; `judge_outcome` refuses missing task data and failed tests; the watcher runs under `catch_unwind` and counts unreadable sessions as silence; `loop_state` in `main.rs` redraws the strip after a reload |
| `plan2code-app/src-tauri/src/loop_notify.rs` | The loop's notification: `NotifyKind` (query string, JSON body, Discord, Slack, Teams, Google Chat; its comment lists what a new service needs), `valid_url()`, `valid_param()` (mirrored in `loop-setup.mjs` and `screens/loop-setup.js`), `request_for()` (each kind's address and body) and `send()`, with a 10 second limit and errors that never hold the address. The driver writes the message and calls it from `observe()`, `stop_loop()` and `finish()`. |
| `plan2code-app/src-tauri/src/loop_report.rs` | The loop's report on everything done for the person: one `LoopReport` per build, entries in order (passed, stopped, retried) with findings fixed, skipped and left open, assumptions read from the phase file, and reported decisions. Saved in the console's `loop-reports.json` after every entry, because a project file would dirty the tree Resume needs clean; `finish()` writes it to `LOOP-SUMMARY-<date>.md` and removes the entry. |
| `plan2code-app/src-tauri/src/loop_tools.rs` | What the loop runs on its own, each call with a time limit and its output kept: the spec scripts (`specs.mjs status`, `mark --to done`), `commit-msg.mjs`, git (`add`, `commit`, `status`, the short head), the console's `post` and `open --resume`, and the person's quick check. No shell runs here except the quick check, whose text comes only from `loop-setup.json`, never from a page message |
| `plan2code-app/src-tauri/src/agents.rs` | Agents in the app: `CustomAgent`, the `Agent` handle over built-ins and custom entries, `load_custom_agents`, reading the Agents file below; the shipped `agents.json` read at run time with the baked copy as fallback; `find_on_path`, the Rust twin of `agent-lookup.mjs`'s `findAgent` (PATH, PATHEXT, the saved PATH from `node_check::resolved_path()`, npm's global folder, the install folders), held to `scripts/fixtures/agent-lookup-cases.json`. The console side is `src/web-console/agents.mjs` |
| Desktop app install (`install.js`) | `installDesktopApp()` downloads `plan2code-app-<version>-<windows\|macos\|linux>-<x64\|arm64>[.exe]` and `plan2code-app-<version>-SHA256SUMS.txt` from the GitHub release (`PLAN2CODE_RELEASE_BASE` replaces the URL; the tests serve a stand-in), checks the SHA-256 and places the file in `~/.plan2code/app/` (the old file is renamed aside first, since Windows cannot overwrite a running exe). `app` is an install piece (`INSTALL_PIECES`, after `launcher`), so `plan2code update` updates it with the rest. `install()` asks for it after the command (default yes; a no is kept as `skipped` in `install.json`); unattended it installs it unless it is already recorded or was declined. A failed app never fails the install. `.github/workflows/release-app.yml` builds one file per system (`tauri build --no-bundle`) and the checksum list on a published release, after `scripts/check-versions.mjs --tag` |
### Agents file
`~/.plan2code/agents.json` holds the person's custom agent CLIs. The web console is its only writer (User Preferences → Agents & models, through `POST /agents`); the `plan2code` launcher and the desktop app only read it. Each reader carries its own copy of the rules (`src/web-console/agents.mjs` for the console, a copy in `src/launcher/plan2code.js`, `agents.rs` in the app), and `scripts/fixtures/agents-cases.json` is the contract all three readers' tests load: file normalization with its warnings, `buildArgs` command lines and `makeId` ids. Change a rule in the fixture first.
`src/launcher/agents.json` is the shipped list: `kind: "builtin"` entries (Claude Code, Devin, Codex) with `installUrl`, per-OS `install` lines and `installDirs`, and `kind: "template"` entries other CLIs can be saved from. `install.js` copies it to `~/.plan2code/bin/agents.json` beside `agent-lookup.mjs`, which all JS readers share: `loadAgentList()` reads it, `findAgent()` gives a command its `found` / `outside` / `missing` state (PATH, the saved Windows PATH, npm's global bin, the entry's `installDirs`). The app reads the same JSON with `serde_json` at run time (`include_str!` of the repo file baked in as fallback) and `find_on_path` in `agents.rs` is its Rust twin: `scripts/fixtures/agent-lookup-cases.json`, loaded by `scripts/test-agent-lookup.mjs` and by `cargo test` through `include_str!`, is the contract both lookups are held to.
- **File:** `{ "schema": 1, "agents": [...] }`. Any other schema, text that is not JSON, or `agents` that is not a list gives no custom agents and one warning. A missing file is an empty list with no warning. More than 50 entries: the first 50 are used. Unknown keys, in the file and in an entry, are kept when the console saves.
- **Entry:** `id`, `name` and `command` are required; `args` (default `[]`), `prompt` (default `"/plan2code"`, blank allowed), `bypassArgs` (`[]`), `modelArgs` (`["--model", "{model}"]`) and `models` (`[]`, each `{ id, label? }`) are optional. The three argument fields are lists of text, one list item per argument.
- **Rules:** `id` matches `^[a-z0-9][a-z0-9-]{0,31}$`, is not `claude`, `devin` or `codex`, and is unique; `name` is at most 60 characters and unique ignoring case; `command` is not blank. `makeId(name, taken)` makes the id from the name in kebab case (`agent` when nothing is left), with `-2`, `-3` on a clash, at most 32 characters.
- **Bad entries:** a bad entry is skipped with a warning naming it (`agents[i]`, 0-based) and the rest still load, in all three readers. `POST /agents` instead refuses the save with `{ error, index, field }`, and answers `409` while the file holds something `GET /agents` could not read, unless the body says `replace: true`.
- **Command line:** `buildArgs` returns `args` with `{prompt}` filled (the prompt is appended when no argument holds it, and a blank prompt drops an argument that is exactly `{prompt}`), then `modelArgs` with `{model}` filled when a model is chosen, then `bypassArgs` when checks are off. Arguments travel as a list, never through a shell; the Windows `cmd` wrapper for a `.cmd` or `.bat` belongs to the launcher and the app.
## Workflow Prompts (in `src/`)
| File | Step | Purpose |
|------|------|---------|
| `plan2code.md` | — | The dashboard: opens the web console's skill menu and launches the picked skill into its own session |
| `plan2code-init.md` | Init | Generate AGENTS.md as index + `.agents-docs/` section files (progressive discovery) |
| `plan2code-init-update.md` | Update | Update AGENTS.md with learnings; detects and routes edits to `.agents-docs/` files |
| `plan2code-0-pathfinder.md` | 0 | Chart a foggy idea as a map (local files, or GitHub Issues) of decision questions under `specs/<idea>/pathfinder/`, resolve them one at a time, hand a seeded PLAN-DRAFT to Step 1 |
| `plan2code-quick-task.md` | quick | Lightweight planning for small tasks (standalone — not a pipeline step) |
| `plan2code-1-plan.md` | 1 | Requirements analysis & architecture |
| `plan2code-1b-revise-plan.md` | 1b | Mid-implementation revisions |
| `plan2code-2-document.md` | 2 | Create implementation specs |
| `plan2code-3-implement.md` | 3 | Execute implementation (phase by phase) |
| `plan2code-3-implement-review.md` | 3 | Execute one phase, run focused review and fixes, then request approval |
| `plan2code-review.md` | review | Post-implementation comprehensive review, analyzed by one fresh helper when the tool has one (verified in session; the report says who reviewed) |
| `plan2code-4-finalize.md` | 4 | Validate, summarize, feedback, archive (steps 1–7, +optional 6.5) |
| `plan2code-handoff.md` | handoff | Compact the conversation into a self-contained handoff document for a fresh session |
| `plan2code-xray.md` | xray | Explain how and why an area works (files, commits, PRs via `gh` when present), or rank the rough spots worth fixing into `ARCHITECTURE-BRIEF-<date>.md` for Pathfinder or Plan; never edits code |
| `plan2code-diagnose.md` | diagnose | Find a bug's cause under the find-the-cause-first habit (`references/building-habits.md`) and write it up as `specs/<bug-name>/DIAGNOSIS-<YYYYMMDD>.md` without fixing it, then offer Quick Task to fix it, or Plan when the fix is big. The dashboard scan reports such a folder as spec state `diagnosed` ("Bug diagnosed"), which lights Quick Task (suggested) and Plan. Once Quick Task marks the diagnosis `Fixed` (nothing past it in the folder) the state is `fixed` ("Bug fixed"): no pipeline card lights, the picker never pre-selects it, and Quick Task offers to archive it with `specs.mjs archive` |
| `plan2code-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 |
## Naming Convention
Workflow files follow a strict naming pattern:
- **The hub:** `plan2code.md` (bare name — `bare: true` in `SOURCE_PROMPTS`, no suffix; it is the dashboard the rest hang off, not a step)
- **Utilities:** `plan2code-<name>.md` (single dash)
- **Numbered steps:** `plan2code-<N>-<name>.md` (single dash, number, single dash)
Examples:
- `plan2code-init.md` (utility)
- `plan2code-1-plan.md` (step 1)
- `plan2code-1b-revise-plan.md` (step 1b)
## Reference Files
Some workflows use companion reference files for depth that does not need to load on every invocation. The orchestrator (main workflow file) loads them via `Read` directives during execution.
**Pattern:** `src/<source-filename-without-extension>-references/` (e.g., `plan2code-review-references/`). A file several skills read lives in `src/shared-references/` instead and ships to each through `additionalReferences` (e.g., `building-habits.md` into Quick Task, Implement and Implement + Review).
**How the installer handles them:** the directory is copied verbatim to `skills/<skill-name>/references/`, so `Read references/<file>.md` resolves consistently for every agent. There is one output format, with no flat-file sibling directory or path rewrite.
Reference files are NOT subject to the 20,000 character limit. The review workflow pioneered this pattern (`verification-protocol`, `dimensions`, `false-positives`, `session-end`); the init-update workflow also uses it (`ai-agent-file-sync` for its Step 7), `plan2code-4-finalize.md` uses it for STEP 6.5 (`community-feedback-submission`), and `plan2code-0-pathfinder.md` leans on it hardest (`brief`, `chart`, `github-issues`, `grilling`, `questions`, `resolve`, `handoff`, `trail` — the orchestrator is a dispatcher, the depth lives in the references). Other workflows can adopt it when a source file carries detail that is only needed some of the time. The implement-review skill is a generated composition: `additionalReferences` in `SOURCE_PROMPTS` packages the canonical implement prompt, review prompt, and review reference directory into its own `references/` directory so those workflows are reused without source duplication.
## Skill Scripts
Anything a workflow step decides with one correct answer (parsing a spec's checkboxes, rebuilding Pathfinder's map markers, the commit message, which AI config files exist) lives in a script the agent runs, not in prose it follows. Prose keeps the judgment.
| Source | Ships to | How |
| Area | File | Holds |
|---|---|---|
| `src/skill-scripts/<name>.mjs` | `skills/<skill>/scripts/<name>.mjs` | Shared: a skill lists the ones it runs in `scripts: [...]` on its `SOURCE_PROMPTS` entry. Skills install independently, so each gets its own copy |
| `src/skill-scripts/common.mjs` | every skill that has scripts | `SHARED_SCRIPTS_ALWAYS` in `install.js` |
| `src/<source>-scripts/<name>.mjs` | `skills/<skill>/scripts/<name>.mjs` | A skill's own scripts, mirroring `-references/`. A name that collides with a shared script is a build error |
| `version.json` (repo root) | `skills/<skill>/scripts/version.json` | Copied at build, so an installed skill can report its version |
| Layout, prompts, install | [AGENTS-architecture-install.md](./AGENTS-architecture-install.md) | Directory Structure, Key Files, the Agents file, Workflow Prompts, Naming Convention, Reference Files, Repo-Local Skills, the Global `plan2code` Command (launcher) |
| Skill scripts | [AGENTS-architecture-skill-scripts.md](./AGENTS-architecture-skill-scripts.md) | the Node scripts shipped in each skill's `scripts/` |
| Status line | [AGENTS-architecture-statusline.md](./AGENTS-architecture-statusline.md) | the Claude Code status bar |
| Web console: server and contract | [AGENTS-architecture-console.md](./AGENTS-architecture-console.md) | overview and the files table for the server, the CLI and the agent-facing contract files |
| Web console: page | [AGENTS-architecture-console-page.md](./AGENTS-architecture-console-page.md) | the files table for every `public/` file except the games |
| Web console: design points | [AGENTS-architecture-console-design.md](./AGENTS-architecture-console-design.md) | why the console is built as it is: preferences, the wait, the transport, notebook, handoffs, tests, adding a page file |
| Activities | [AGENTS-architecture-activities.md](./AGENTS-architecture-activities.md) | every game but Ghoul Rush, and the rules every game follows ("Building an Activities game") |
| Ghoul Rush | [core](./AGENTS-architecture-ghoul-core.md), [stages](./AGENTS-architecture-ghoul-stages.md), [rides](./AGENTS-architecture-ghoul-rides.md) | the files table for the Ghoul Rush game |
| Script | Skills | Does |
|---|---|---|
| `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, 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` |
| `feedback-payload.mjs` (own) | 4-finalize | STEP 6.5's payload (real sha256 prompt hashes) and the gh / browser / print submission tiers |
| `xray.mjs` (own) | xray | `hotspots` (churn, files changed together, often-changed files with no test, from `git log` over a capped window) and `history <path>` (commits following renames, a blame summary, PR titles and first paragraphs through `gh` when signed in, and which sources were used). Read-only |
| `changelog-state.mjs` (own) | changelog | `state`, `bump`, `set-package-version`: the default branch's version, whether the branch's entry can be extended (not released, not on another branch), the file's heading style, the gap since the entry was last touched; only `set-package-version` writes, and only the version field |
| `git.mjs` (own) | git | `state`, `plan`, `branch-check`, `init-check`, `delete-check`, `cleanup-list`, `conflicts`, `pr-url`, `classify-error`: the repo snapshot, each action's exact command and confirm text (shared by the terminal and the board), branch-name, delete, cleanup and git init checks, a stopped rebase's conflicts, the pull-request link and git's errors sorted into kinds with a next step. Read-only: the agent runs every command it prints, and `guard()` refuses force push, hook skipping, amend, remote delete and blanket add |
**Conventions** (`common.mjs`): Node 18+ built-ins only; one JSON object on stdout (`ok: false` plus `error`, `message`, `next` on a handled failure, the same line on stderr); exit 0 ok, 1 crash, 2 bad arguments, 3 not found, 4 invalid or check failed, 5 refused; `--help` documents commands and exit codes; writes take `--dry-run`; `PLAN2CODE_NOW` pins the clock for tests. A SKILL.md names a script as `node "<S>/<name>.mjs"`, where `<S>` is `scripts/` beside it.
**Tests:** `scripts/test-skill-scripts.mjs` (installer plumbing and the shared scripts), `scripts/test-script-<skill>.mjs` (a skill's own, 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/`)
Maintainer-only skills committed to the repo but deliberately excluded from the generated `skills/` product artifact:
- `plan2code-publish/` — publishes a GitHub Release after version files agree.
- `plan2code-changelog/` — validates release classification and keeps version files synchronized.
- `plan2code-launcher-update/`: refreshes the launcher's shipped data: the curated model menu (`src/launcher/models.json`) from `devin models list` and Claude Code's documented model aliases, and the agent list's install data (`src/launcher/agents.json`) re-checked against each vendor's docs, including a re-check of the agents left out as templates (Cursor CLI, Aider) against the template rule. Shows a diff, applies only the changes the maintainer approves, validates both files and runs `npm test`. Terminal only, and it never commits.
- `sync-repo/` — decrypts the protected upstream-sync workflow in memory.
Do not run `skills add` against the repository root: recursive discovery also finds these maintainer skills. `install.js` targets `skills/` and passes explicit workflow names instead. Global install/uninstall cleanup removes `plan2code-*` workflow skills from user skill directories; it never operates on this repository's `.claude/skills/` directory, and `sync-repo` intentionally has no `plan2code-` prefix.
## Web Console
Optional local browser UI shipped with **every** skill. Source lives in `src/web-console/` and is fanned into each skill by an `additionalReferences: [{ source: 'web-console', target: 'web-console' }]` entry in `SOURCE_PROMPTS`, landing at `skills/<skill>/references/web-console/`. The bare `plan2code` skill is the hub: it opens the console as `--workflow dashboard`, the page draws the skill menu itself (from each `SKILLS` entry's `card` in `public/skills.js`, through `SKILL_CATALOG` in `public/answers.js`, kept in sync with the install set by a test), and a card click reaches the agent as a `{ "i": "__launch", "skill": ..., "workflow": ... }` send — the dashboard then **resumes its own session** under the launched skill's workflow (`open --resume <sid> --workflow <w>` restates `workflow`/`title`/`specDir` on the live server) and runs that skill's file. `plan2code-review` now has a console of its own AND still runs inside builds on the page (a `review` verdict on Implementation's sign-off card, the **Review it now** button on a finished quick task, or Finalize's Step 2.5 final review, offered on every run), so `plan2code-3-implement`, `plan2code-quick-task` and `plan2code-4-finalize` also carry `review.md`, the review references and `review-scope.mjs`, the same way `implement-review` does. `CONSOLE_WORKFLOWS` in `public/answers.js`, built from the same `SKILLS` list, decides whether a copied hand-off asks the next session for the console.
| File | Role |
|---|---|
| `console.mjs` | the CLI the agent drives: `open`, `post`, `wait`, `chat` (the instant Quick question check), `keep` (copy a cited note attachment into `specs/<idea>/attachments/`), `delete-spec`, `handoff new`, `delete-handoff` (both on `handoffs.mjs`), `status`, `stop`, `help` (a compact summary for an agent that found the binary but not `console.md`; `help <topic>` prints one contract file, `help topics` lists them). `post --wait <N>` posts and waits in one command |
| `server.mjs` | HTTP server, spawned **detached** by `open` (never as a harness background task, which get killed on compaction and at assorted timeouts) |
| `public/` (other files) | `index.html`, `favicon.svg` (Planny peeking up from the tab bar, served as `image/svg+xml`) with `favicon.png` (the same icon at 192 px, served as `image/png`) as the fallback, `vendor/marked.esm.js`, the chimes (`start-skill.mp3`, `bootup.mp3`, `start-stop.mp3`, `next.mp3`, `insert.mp3`, `sleeping.mp3`; which moment plays which is `SOUND_EVENTS` in `palette.js`, one switch per event saved in `looks.json`), and a `package.json` that only says `"type": "module"`, so Node (the server and the tests import the pure modules) parses them as ES modules without a reparse warning. The stylesheet is the files in `public/styles/`, joined by the server into the one `/app.css` the page asks for |
| `cmd-chat.mjs` | the `chat` command: hand over Quick questions now, never waiting |
| `cmd-help.mjs` | the `help` command: the CLI's usage and the contract's topic files; the usage's workflow list and its build sessions come from `WORKFLOWS` and `isBuild()` in `skills.js` |
| `cmd-open.mjs` | the `open` command: start or resume a session, its server and the browser; refuses a `--workflow` that `isWorkflow()` does not know (exit 2, naming the valid ones), and asks `startsClean()` (`public/hops.js`) whether a resume blanks the page |
| `in-app.mjs` | the desktop app's signal to `open`: `inAppSignal()` reads `PLAN2CODE_IN_APP`, `PLAN2CODE_CONSOLE_SID`, `PLAN2CODE_APP_ANNOUNCE` and `PLAN2CODE_APP_TOKEN`; `announcePage()` POSTs the page to that window's loopback endpoint. Under the app `open` never starts a browser, resumes the app's session and announces the page; with the variables unset nothing here runs. Imported by `cmd-open.mjs` |
| `open-link.mjs` | the desktop app's webview opens no new windows, so the page there sends links off the console (`linkLeavesPage()` in `public/app-bridge.js`: http or https on another origin, caught in `wireChrome()`) to `POST /open-link`. `linkToOpen()` takes http and https only (400 otherwise); `openLink()` starts the default browser with the link as one argument, never through a shell (`rundll32 url.dll,FileProtocolHandler` on Windows, `open` on macOS, `$BROWSER` or `xdg-open` elsewhere) and skips it under `PLAN2CODE_NO_BROWSER`. When that fails the page shows the link with a Copy button to paste into a browser |
| `loop-setup.mjs` | the Implementation Loop's setup, remembered per project in `~/.plan2code/console/loop-setup.json` (one entry per folded project folder, schema 1): defaults, validation and the read and write the `/loop-setup` route uses. The app reads the same file itself for the quick check, so the page never carries that command |
| `cmd-post-wait.mjs` | `post` and `wait`: publish a patch, then collect what the person sent |
| `cmd-small.mjs` | the small commands: keep, forget, delete-spec, handoff, delete-handoff, status and stop; `handoff new` refuses an unknown `--workflow` the same way `open` does |
| `files.mjs` | where the console's files live, how they are written safely, and the argument parser both command lines share |
| `agents.mjs` | the rules of `~/.plan2code/agents.json` (see Agents file above), console side: `normalizeAgents()` reads the file into clean entries and warnings, never throwing; `validateForSave()` checks what User Preferences sends and names the first bad entry and field; `makeId()`, `buildArgs()` (the command line from an entry) and `resolveCommand()` (where a command runs from, never running it). Served by `GET` / `POST /agents` and `POST /agents/test` in `routes.mjs` |
| `agent-lookup.mjs` | where an agent lives on this machine: `loadAgentList()` reads the shipped `bin/agents.json` (built-in agents and starter templates; `optional` keeps an absent file silent); `findAgent()` gives one command its `found` / `outside` / `missing` state, the path and which search found it (PATH, the Windows saved PATH, npm's global bin, the entry's `installDirs`), with `{bypass}` / `{model}` placeholders expanded to the user's picks. Used by `GET /agents`, `POST /agents/use-path`, the launcher's `chooseCli()` and the Windows picker |
| `inbox.mjs` | the Quick question chat's inbox beside the card slot |
| `console-docs.md` | the topic file for `docs` in a patch (tabs of blocks), named by the console at the first patch that carries `docs`; not read up front. Byte-budgeted with the card and the notes in `scripts/test-console-wire-budgets.mjs` |
| `pointers.mjs` | which topic file the console names and when: once per session per topic, remembered in the session folder (`pointers.json`), reset by a resume |
| `patches.mjs` | checking and merging an agent's patch into the session state: `validate()` (the house rules; allows `templates` only as `"idea"` on a `text` item, anything else exits 3), the patch merge, `resolveDocFiles()` and `applyPatch()` |
| `routes.mjs` | every URL the page can call, in one ordered list (`ROUTES`, walked by `handle()`); `server.mjs` hands each request to it |
| `scan.mjs` | what the dashboard knows about the repo: `scanProject()`, `classifySpec()` (a folder's files to a spec state), `TASK_LINE_RE` (re-exported from `spec-files.mjs`) and `removeSpec()` |
| `sessions.mjs` | a session's roots and handle files (`repoRoots()`, `healthOk()`, `attachmentName()`: the kept-file name `<slug>-<id8>.<ext>`, the same upload always gets the same name, `readOverview()`) and the console folder's housekeeping: the three sweeps `open` runs fire-and-forget after it prints (`sweepUploads()`, `staleSessions()` / `removeSessions()`, `staleScratch()` / `removeScratch()`) and `cleanupFindings()` / `removeCleanup()` for User Preferences → System → Cleanup |
| `settings.mjs` | the person's saved console settings: Subagents and pull-request hosts |
| `spec-files.mjs` | no imports: how a spec's markdown files are read, `MARKERS`, `TASK_LINE_RE`, `TASK_ID_RE`, `CHECKBOX_RE`, `STATUS_RE`, `statusOf()` and `countTasks()`; shared by `scan.mjs`, `patches.mjs` and `src/skill-scripts/specs.mjs` (through `consoleModule()`) |
| `static.mjs` | serving the page's own files: `SERVABLE` (the allow-list), `TYPES`, caching and ETags, the accent colors, and `CSS_ORDER` + `joinedStyles()`, the one place the cascade order is stated |
| `workspace.mjs` | the session's extra folders, and the folders remembered per project and spec |
| `public/activities.js` | the list of activities (`ACTIVITIES`: each game's id, title, picker card line `blurb` and module path) an optional `courses` list (Mini golf's six course ids, which open a course dashboard), `bestKey(id, course?)`, the flat looks.json key for its best score (`activityBestSnake`, one per golf course `activityBestGolfPirate` to `activityBestGolfFrost`, `activityBestTrails`, `activityBestBugs`, `activityBestDrive`, `activityBestStack`, `activityBestBumper`, `activityBestRapids`, `activityBestFuse`, `activityBestHop`, `activityBestBounce`, `activityBestGhoul`, `activityBestFlock`); lists Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, `bestKeys(entry)`, every best key a game keeps, and documents the game contract including the course parts (`courses` and `preview()` on the export, `setCourse()` and `course` on the game), the optional `pointer(type, x, y)`, `release(name)` (a game key let go) and `lowerIsBetter`; data only, imported by the page and by Node |
| `public/activities/snake.js` | Snake: its rules as plain exported functions and the game contract (`create({ canvas, tone, onScore })` returning `start`, `pause`, `resume`, `key`, `tick`, `resize`, `score`, `state`); it never runs a timer or listens for keys, so the Activities window drives it; 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 |
| `public/activities/bumper.js` | Bumper Ring: its rules and physics as plain exported functions (`newRound`, `newHeat`, `advance` on a fixed 4 ms sub-step over `round.input`, which `key()` and `release()` set, `push` (accel toward the held direction, capped at the top speed that way, drag easing a car to the floor's own speed), `collide` (circle bounce with restitution `BOUNCE`; the faster car rams and gives `SHOVE_BONUS` more, takes that much less back; under `IMPACT_SPEED` it is a lean, no bounce and no shove, so a pushing match goes to the stronger push), `dash`, `edgeGap` and `outOfRing` (a car is out when its center is past the edge or over an open hole; round or, in the Hall of Mirrors, square), `shrinkAt` and `nextShrinkIn` (whole for `SHRINK_START_MS`, `SHRINK_STEP` a step to `MIN_RING`, then after `SUDDEN_MS` sudden death to `LAST_RING`, under one car's radius, so every heat ends), `aim` (a rival's push, dash and target per personality, with panic near the edge and a sharpness-scaled chance to misjudge), `applyPower`, `spawnPad`, `creditKo` (the last toucher within `CREDIT_MS`, your hit carried through a rival counting as yours, and a rival you rammed into another keeping your credit, the carry lasting `CAROM_MS` from your hit; the combo, the double and the bait bonus), `rivalPower` and `arenaFor` (each built once per arena, since the rules ask every slice), `holeState`), the `ARENAS` (rivals, sharpness, shrink pace, then endless Finals past the ninth), the `RIVALS` personalities and the `POWERS` pads, and the game contract with `release()`; a rival winds a dash up for `WINDUP_MS` (shorter when sharper) before it goes, which is the player's moment to step aside; a big hit holds the action for `HIT_STOP_MS`; memo is the furthest arena reached, which can pass 9; a read-only `round` getter for the tests only. Hand-tuned from the brief's starting numbers (the changes are listed under "As built" in `game-ideas/bumper-ring.md`), aiming for heats of 20 to 60 s from arena 2 on |
| `public/activities/bumper-draw.js` | Bumper Ring's drawing: `drawScene(ctx, view)` from a plain view `bumper.js` builds (the round, the board geometry, the effects, the pill numbers), each arena's ring in its fixed palette (`themeFor`), the floor (ice, oil, holes, bumpers, the magnet, the warning bands), the cars (Planny upright at the wheel of a car in `--accent`, star eye and stick arms; rivals with a face each), the pills (laid out by `hudLayout`, which starts a row below rather than run into the ring's countdown or off the board), banners and the start and end strip, and `readColors(canvas)`; decides nothing |
| `public/activities/rapids.js` | Rapids Run: its rules as plain exported functions over a round on a river scrolling down a 64 unit wide field, 84 units of it on the board (`newRound(seed)`, `newRiver(seed)`, `buildStretch(river, n, random)` (a stretch's rows from its own seed, each row a center, width and island width: a calm opening, then drifts, narrows and islands, every bank slanting at most `SLOPE` a unit, every channel at least `MIN_CHANNEL` wide, then a `BASIN_W` basin on a boss stretch and the narrowing to the `DAM_W` dam; and its plan of foes, buoys and crates, none in the first `SAFE_START` (where you start again) or by the dam), `ensureRiver`, `riverAt` (a row's banks and island eased from the row before's, so they slant as drawn), `channelsAt`, `channelAt`, `isWater`, `onLand` (the hull sampled at seven points), `placeAt` (the start of a stretch, its dam whole and its plan loaded afresh), `advance` in 4 ms slices over `round.input`, which `key()` and `release()` set: steering eased in, the whirlpools' tug, the speed held (up, down or neither, times the stretch's `pace`), the battery drained (`DRAIN` a second cruising, more at speed), distance points, the guns (`FIRE_MS`, Spread's fan), shots against foes, the boss, the dam and buoys, the foes (skiffs and darters drift and turn at the banks, a darter swerves into your lane, gulls take off as you near and swoop across, sentries fire at you), the boss (`spawnBoss` holds the river and the battery; its volleys by kind), bolts, pickups (a buoy `BUOY_CHARGE`, the magnet's pull, crates), crashes (`lose`: a shield takes any crash but a flat battery and slides you off a bank; blinking for `GRACE_MS` after a restart), skims (`SKIM_POINTS` each `SKIM_MS` closer than `SKIM_GAP` at speed), the dam (`hitDam`, then past it the next stretch, with `FLAWLESS_POINTS` times it for no life lost), `hurtFoe` (the combo, up to `MAX_COMBO`), `hurtBoss` (a life back and a crate), `applyPower`, `stretchFor` (built once a stretch; past the eighth, Night Water 2, 3 and on), `underBanner`, `screenY`, `seeded`), the `FOES`, `BOSSES`, `POWERS` and `STRETCHES`, and the game contract with `release()` (held arrows steer, speed and slow, held space fires; a pause lets go of every key); memo is the furthest dam blasted, which can pass 8; a read-only `round` getter for the tests only. Tuned by a scratch sim: a careful bot clears a stretch in 20 to 35 seconds, and the battery runs flat for one that grabs too few buoys |
| `public/activities/rapids-draw.js` | Rapids Run's drawing: `drawScene(ctx, view)` from one view object `rapids.js` refills each frame, in field units: the strip above the field in the page's colors with the pills (laid out by `hudLayout`, which starts a second row rather than run off the board and centers its rows in the strip), the river a look at a time (`LOOKS`: meadow, autumn, canyon, marsh, dusk and night, each in fixed colors, the look changing at each dam): banded banks, the water between them with shore lines and flow streaks carried downstream by the view's clock, pointed islands, trees or rocks; the dam ahead (hazard stripes, a crack for every share knocked out, a trickle once it is close to going) and the broken one behind; charge buoys, crates with their glyphs, whirlpools, skiffs, darters, mines, bank sentries aiming at you and gull drones with their shadows; the mini-boss and its health bar; Planny's jet-skimmer in your highlight with a white trim (so a blue highlight still shows on blue water), his wake, jets, arms to the bars (up when a dam or a boss goes), his box and his star eye in your highlight, bobbing with the star spinning after a crash; shots, bolts, sparks, rings, floating words (kept on the field by `labelSpot`), the combo's big number, the battery gauge beside the field (green, amber, then red and blinking under the low mark), banners, and the start and end strip with the big final score and a dot per named stretch whose dam you have blasted; `readColors(canvas)`, `lookColor`, `inkOn`, `contrast`; decides nothing |
| `public/activities/flock.js` | Flock Dash: its rules as plain exported functions over a round scrolling right to left over a 96 by 54 unit field (`newRound(seed)`, `steer` (the leader eased up and down inside the `BAND_MIN` to `BAND_MAX` band at the left), `recordPath`, `placeFlock`, `screenX`, `collect` and `spawnStrays` (a stray joins the flock, the combo up to `MAX_COMBO` within `COMBO_MS`), `buildStage(seed, n)` (a stage's hazards by distance from its own seed, a clear `SAFE_START` and `SAFE_END`, and `clearGap` keeping a way through), `moveHazards`, `hazardHits`, `snapAt` (a snap drops the birds behind the one hit, `scattered` for `SCATTER_MS` so they can be picked up again), `hitLeader` (a life, or a shield; `GRACE_MS` after), `reachPortal` (the jet stream portal, the V of `V_POINTS` a bird when the flock has `min`, `FLAWLESS_POINTS` for no snap or life lost, and the final portal that sways), `applyPower` (crates: tailwind, shield up to `MAX_SHIELDS`, magnet), `banner`, `bannerRow`, `underBanner`, `advance` in `SLICE_MS` slices, `teaser`, `seeded`, `dealMusic`), the `STAGES` table (eight stages, each with its speed, length, stray gap, portal `min`, hazard weights and gap; the place to tune the difficulty), the `HAZARDS` (balloon, gust, stream, cluster, storm, kite, each from its own stage) and `POWERS`, and the game contract with `release()` (held arrows steer, a pause lets go of every key); the round also carries `events` (what the draw and the sounds react to) and `warned` (one gust or storm warning each); memo is the furthest stage reached. The flock is a recorded path with running arc length: follower k sits `k * SPACING` behind the leader along it, so it copies every turn at any speed. `MUSIC_TRACKS` names the five songs, dealt afresh each round |
| `public/activities/flock-draw.js` | Flock Dash's drawing: `drawScene(ctx, view)` and `hudLayout` from one view object `flock.js` refills each frame, in field units: the sunset sky (`SKIES`, one palette per stage: the sun sinking, clouds, a rim light from stage 6 and stars on the last), the hazards (balloons and bunches, the head-wind's warning band and gust, slipstreams, thunderheads with their flash and bolt, kites on their strings), the strays and scattered birds, the flock, Planny as the lead bird with a star for an eye, crates and the magnet ring, the tailwind streaks, the portal and the V, the pills (laid out by `hudLayout`, which shrinks them to fit the board), banners, and the end strip with the final score, the best and the teaser; `readColors(canvas)`; decides nothing |
| `public/activities/fuse.js` | Hot Potato: its rules as plain exported functions over a round on a 104 by 70 arena (`newRound`, `newMatch(round, venue)`, which lights each bomb on a rival, never you, in a match's first fuse, `advance` in 8 ms slices over `round.input`, which `key()` and `release()` set, `move` (speed eased toward the held direction at `GRIP`, a dash holding its line, belts and ice from the floor), `dash` (a holder's dash is a numbered lunge), `tag` (a holder touching a runner with no bomb passes it, never inside `NO_TAGBACK_MS` of the bomb changing hands, nor back to the one who just passed it within `TAGBACK_MS` while three or more are left, `tagBack`, with `tagSafe` saying who is safe that way for the drawing; a fuse under `PASS_FLOOR_MS`, `NO_TAGBACK_MS` plus `PASS_REACT_MS`, is raised to it on any pass, once a fuse for each runner (`bomb.lifted`); your pass scores, a hot one under `HOT_MS` as passed steps the streak), `burn` (Freeze takes its share first), `blast` (the holder out, everyone near knocked back, the match over when that was you or one is left), `nextFuse` (a survivor with no bomb, the next shorter fuse from `fuseFor`, never more bombs than one for every two left), `think` (a holder chases by its own flood-fill path, weighted toward a boxed-in or dashless target; a runner without a bomb scores candidate spots by the holders' path distance against its own and flees to the best; personalities bend both), `applyPower`, `spawnPickup`, `speedOf`, `clearLine`, `rivalPower` and `venueFor` (each built once per venue), `rivalColors(you)`), the `VENUES`, `LAYOUTS`, `RIVALS` and `POWERS`, and the game contract with `release()` (`key(name, repeat)` never dashes on a repeat); a rival holder winds up (`WINDUP_MS`, shorter when sharp) or, a Trickster, feints (`FAKE_MS`) before a lunge, and a runner a lunge comes at dodges once a lunge at its venue's odds after its reaction time; the fuse ticks quicker and higher as it burns down, on one clock however many bombs burn (yours, else the shortest); a bomb whose fuse has run out passes to nobody; memo is the furthest venue reached, which can pass 9; a read-only `round` getter for the tests only. Tuned by a scratch sim (see "As built" in `game-ideas/hot-potato.md`) |
| `public/activities/fuse-draw.js` | Hot Potato's drawing: `drawScene(ctx, view)` from one view object `fuse.js` refills each frame, in arena units: the strip above the arena in the page's colors with the pills (laid out by `hudLayout`, which starts a second row rather than run into the fuse and centers its rows in the strip), each venue's floor in its fixed palette (`themeFor`, `venueColor`), ice, running belts, the Rooftop's open edge, the things to run round, pickups, the runners (Planny on his feet with his star eye and stick arms, flailing while he holds a bomb, and still Planny when charred; arms and feet on the floor in `limbInk(level)`, the ink that stands out from that venue's tiles; rivals with a mark per personality; a white ring with a dark edge at the feet of a runner safe from a tag-back; the charred waddle to the nearest wall and the fall from the roof), the bomb over its holder (a red ball with a `<<<` band, growing and glowing as it burns, flashing white while it cannot be passed, its fuse a shortening curl with a spark, the last seconds in big numbers (under the holder's feet when there is no room above, `countY`), a hop across on a pass), blast clouds, the Blackout's dark worked out once a frame in cells, the red edge pulse in a fuse's last second, banners and the start and end strip with the big final score, and `readColors(canvas)`; decides nothing |
| `public/activities/hop.js` | Crossing Rush: its rules as plain exported functions over a round on a strip `COLS` (11) cells wide of 30 to 40 lanes, `VIEW_ROWS` (14) on the board at once (`newRound`, `newHeat(round, zone)`, which builds the heat's lanes from the round's seed, kept when a heat runs again, `buildLanes(zone, seed)` (groups of road, highway, ice, river, turtle, rapids or rail lanes with a grass row between each two, the zone's new thing first; the same seed builds the same lanes), `advance` in 8 ms slices (lanes flow, riders drift with their log, rivals choose, everyone is checked where they stand before any hop moves on, then hops and flights; hoppers home in the same slice finish by the moment each landed, a dead heat to you), `hop(round, hopper, dir)` (one cell, two with a Spring; a hopper counts in the cell it leaves for the first half and the one it lands on for the second; an icy lane slides it a cell more), `laneAt`, `occupied(round, row, col, atMs)` (a car or a train on it, or in a river no float or the edge, `atMs` ahead through `shiftAt`, which follows a lane's flips, surges and a Horn exactly), `sendBack` (to the last grass row, `safeBelow`, crediting a shove within `SHOVE_CREDIT_MS`), `shove(round, from, to)` (a cell the way `from` faces, only on a hopper `inReach` and never on one past the half of its hop home, once every `SHOVE_MS`), `plan(round, hopper, random, power)` (a look ahead of `LOOKAHEAD` to `LOOKAHEAD_SHARP` hops over the lanes as they will move, each hop followed by the hopper's wait where it lands; never a hop where it would be hit or fall in at full sharpness; a sloppy rival now and then hops on regardless), `applyPower`, `zoneFor` and `rivalPower` (each built once per zone), `rivalColors(you)`, `standings`), the `ZONES`, `RIVALS` and `POWERS`, and the game contract with `release()` (`key(name, repeat)` hops once a press: never on a repeat, never again until the arrow is let go, never with the press that plays on, and with one hop queued behind the one in the air; a pause drops what is held and the queue); rivals wait `REACT_MS` down to a sharp rival's after each landing, a Bruiser shoves anyone beside it into a lane, a Tagalong follows a row behind you and shoves near the top, and a rival that lets a shove go weighs the next one only after `SHOVE_LOOK_MS`; memo is the furthest zone reached, which can pass 9; a read-only `round` getter for the tests only. Tuned by a scratch sim (see "As built" in `game-ideas/crossing-rush.md`) |
| `public/activities/hop-draw.js` | Crossing Rush's drawing: `drawScene(ctx, view)` from one view object `hop.js` refills each frame, in board units: the strip above the field in the page's colors with the pills (laid out by `hudLayout`, which starts a second row rather than run into your place and centers its rows in the strip), the lanes in fixed colors (`LANES`, `lookOf`; pavement, grass with tufts, bushes and rocks, the checkered finish, roads with dashes and surge chevrons, icy roads, rivers with ripples and Rapids arrows, tracks with a signal that flashes while a train is coming), cars, vans, trucks, logs, turtles that sink and dive, the train, pickups, the hoppers (Planny on his stick feet with his star eye in every state: stretching mid-hop, spinning as he flies back, cheering, slumped when beaten; rival critters with a Hopper's ears, a Daredevil's goggles, a Bruiser's brow and a Tagalong's beak; arms and feet, and each rival's body edge, in `limbInk(look)`, the ink that stands out from that lane), a Shield's ring and a Spring's coil, staggered stars, arrows at the edge for hoppers out of view, the Night Market's dark (soft lights cut from a layer the size of the field with one gradient made with the layer, or in steps with no second canvas), the race bar in the page's colors, banners, and the start and end strip with the big final score; every word kept on the field by `labelSpot`, and `readColors(canvas)`, `zoneColor`; decides nothing |
| `public/activities/bounce.js` | Bounce Road: the cars, the hazards against them, the scoring and the round, as plain exported functions over a round on a road scrolling up a 72 unit wide field, 90 units of it on the board (it re-exports every rule of `bounce-road.js` and `bounce-rivals.js`, so the suite imports one module): `newRound(seed, random)`, `advance` in 4 ms slices over `round.input`, which `key()` and `release()` set (a jump press first, then your `move`, the rivals' `think` and `move`, the pads (a boost strip pushes you to `NITRO_TOP` for `BOOST_MS` even off the throttle, and the brake cuts it; a ramp launches any car crossing its lip quick enough `RAMP_AIR` the usual jump; a slick eases the steering at `SLICK_EASE` and makes a knock last for `SLICK_MS`), the bumps (`collide`: boxes pushed apart along the shallower overlap, side on a knock split by mass and harder for the car that did not steer in, end on speed passed forward, into a `HEAVY` truck's back at `CRASH_CLOSE` a crash; with Mega wheels a touch flattens; a close shave, `NEAR_GAP` or less between the boxes at speed and no touch, scores once), the barriers (a cone or a tire knocked flying slows you to `CONE_SLOW`; a block, pot or bucket nose first is a crash, from the side a push out), the hazards placed by the round's clock (a train hits a car on its track, a ball knocks a car by `BALL_KICK`, a sprinkler's jet pushes at `SPRAY_PUSH`, a drop falls `DROP_FALL_MS` after you come within `DROP_TRIGGER`, aimed at your line, and lies there after, a gust pushes at `WIND_PUSH`), then the ground (water or a hole under your middle a life, a flowerbed nose first a crash, a rival off the road out and yours within `CREDIT_MS`)), `jump`, `land` (on a car: flattened for its `points` times the chain up to `MAX_CHAIN`, a truck's roof `HAUL_POINTS`, the Monster a stomp, `STOMP_POINTS`, and on its last of `BOSS_HP` `BOSS_POINTS` times the lap and a life; on the road the chain ends, and the holes, trains, balls and barriers flown over and a ramp's big air score), `stunt` (a stunt's points times `comboOf(streak)`: every `COMBO_STEP` stunts within `STREAK_MS` of each other one more, up to `MAX_COMBO`), `lose` (a Bubble throws you clear instead), `applyPower`, `underBanner(round, y, cam)` (a rival, a coming train, a ball or a thing still falling in the strip) and `BANNER_Y`, `rivalColors(you)`), the `POWERS` (Spring, Bubble, Nitro, Mega wheels) and the game contract with `release()` (`key(name, repeat)`: held arrows drive and steer, space jumps once a press, never on a repeat or with the press that plays on, and a press up to `JUMP_BUFFER_MS` before a landing jumps on it; a pause lets go of every key and drops a press). A stage line scores `STAGE_POINTS` times the stage, `TIME_POINTS` a second under its par and, flawless, `FLAWLESS_POINTS` and a life back up to `MAX_LIVES`. Memo is the furthest stage reached, which can pass 10. A read-only `round` getter is for the tests only. Tuned by scratch bots: a careful bot clears all ten stages with no rivals on every seed tried (23 to 42 s a stage), and a bot with 150 ms reactions and 80 ms jump timing error reaches a median of stage 5 with the rivals out, stage 10 without |
| `public/activities/bounce-draw.js` | Bounce Road's drawing: `drawScene(ctx, view)` from one view object `bounce.js` refills each frame, in field units: the strip above the field in the page's colors with the pills (laid out by `hudLayout`: stage, lives, Spring, Bubble, Nitro and Mega with their timers, the chain and the combo with its timer; a pill that would run off the board starts a second row), the road a chunk of `CHUNK_ROWS` rows at a time, drawn off screen once per road and scale, a few kept and copied each frame (rows from `bounce-scenery.js`), the layers over it (`bounce-scenery.js`), the landing rings (yours in your highlight, a rival's in red, the Monster's its own size), the cars through `bounce-cars.js` (every shadow first, upright, then every body with its tumble: Planny in your highlight with his box in the page's panel color and his star eye, arms to the wheel, up in the air or cheering, down at the end; each rival kind in its own style and color, the Cop's siren while it chases, the Monster's dents and a star per life left above it, headlights at Night Lights), sparks, rings, the dark of Night Lights, the chain's big number, the stage bar beside the field, banners, and the start and end strip with the big final score and a dot per stage reached; every word kept on the field by `labelSpot`, and `readColors(canvas)`, `limbInk`, `inkOn`; decides nothing |
| `public/activities/bounce-cars.js` | Bounce Road's cars, drawing only and no imports: `drawCarBody(ctx, style, opts)` draws one top-down toy car about the origin, nose up, filling `w` by `h` field units exactly (tires on the box's corners), in one of `CAR_STYLES` (`STYLE_NAMES`: Planny's convertible with his star eye and arms to the wheel, hatch, sedan, coupe, muscle, pickup, van, box truck, police, racer, taxi, jeep, monster) with flat-fill shading worked out from `color` and `accent` (`shade`, `rgbOf`), and options for roll (`tilt`), a jump (`air`: it draws the shadow and the lift itself), a pancake (`squash`), night beams, a siren bar, damage, a boost flame and brake lights, all moving parts on `opts.clock`; `drawCarShadow` and `shadow: false` for a shadows-first pass in screen space; `carLength(style, w)` for a style's natural length and `carReach(style, opts)` (with `MARGINS`) for what reaches outside the box |
| `public/activities/bounce-scenery.js` | Bounce Road's scenery, drawing only: each stage's look in fixed colors (`LOOKS`: patio slabs, lawn stripes, kitchen tiles, garden, sand, a toy room's rug, a pond with lily pads, roof shingles, the night lawn with lamps and the Monster's dirt; `lookOf`, `stageColor`, `contrast`, `better`), `drawRow` (one row of the road in three passes over a chunk: the yard, the road's surface, the details: edges slanting from row to row, rivers, plank bridges with jagged broken ends, cracks, flowerbeds, rails across a crossing, cracked road over a pit, checkered stage lines, verge decor), and the layers drawn fresh each frame from the round's clock: `drawTimed` (a drawbridge lifting with its red lights, a swaying bridge where it is now, crumbled road gone to the pit), `drawPads` (running boost chevrons, ramps, slicks), `drawBlocks` (cones, toy blocks, pots, buckets, acorns and tires, knocked ones tumbling off), `drawStars`, `drawSigns` (a mark per hazard), `drawItems`, `drawHazardsLow` (crossing lights, the train, a rolling ball, a falling thing's growing shadow, a sprinkler's head), `drawHazardsHigh` (the jet, gust streaks, the thing still falling), `drawNight` and `drawFireflies`; decides nothing |
| `public/activities/bounce-road.js` | Bounce Road's road, rules only: the jump math every hole is sized by (`airMs(v)`, `reach(v)`, `LONGEST_JUMP`, `JUMP_FAIR`, `TOP_SPEED`, `MAX_SPEED`), `stageFor(n)` (built once a stage: the ten of `bounce-roads.js`, then laps from `LAP_FROM`, quicker, keener, busier, the Monster at every Monster Mash) and `stageName`, `newRoad(seed)` and `buildStage(road, n, random)` (a stage's rows from its own seed, by the stage's piece weights: straights, cracks, rivers on bridges with one or two broken spans or a drawbridge, splits round flowerbeds, ramps before a crack with stars beyond, cone or block chicanes, crumbling road, train crossings, swaying bridges, boost strips, slicks, balls, sprinklers, drops and gusts; every hole after a `RUNUP` with a sign and no longer than `MAX_HOLE`, the bridge between two breaks long enough to land `LONGEST_JUMP` on), `ensureRoad`, `groundAt(road, x, d, t)` (a row's edges eased from the row before's; a drawbridge water while lifted, a swaying bridge shifted, crumbled road a hole), `rowGone`, `spanAt`, `holesIn`, `firstAt`, `plainRow`, `safeSpot` (no hole, water, timed part or rails for `RESPAWN_RUN` ahead), and where each timed thing is at a moment: `swayOff`, `drawLift`, `crumbleAt` (falling away `CRUMBLE_DELAY` after you reach it, at `CRUMBLE_SPEED`, under a fair speed), `trainAt` (on, and lit `TRAIN_WARN_MS` before), `ballX`, `sprayAt`, `gustAt`; plus `seeded`, `GROUND`, `MARK`, `SPAN` |
| `public/activities/bounce-rivals.js` | Bounce Road's rivals, rules only: `RIVALS` (the Zigzag, Brick, Frog, Nudge, Hauler, Sneak, Bruiser, Racer, Cop and Monster: box, mass, speed, points, how readily each dodges, how often each comes, its car style and whether it comes from behind), `makeCar`, `think(round, car, ms, random)` (each kind's choice of speed and line: the Zigzag's weave, into your path when you follow; the Brick holding your lane and brake-checking from in front, then resting `BRAKE_REST_MS` or more; the Frog's hops toward you; the Nudge's chase and up to 1 + 2 times the stage's `sharp` swipes; the Hauler drifting to block; the Sneak dropping up to `SNEAK_DROPS` cones while you follow; the Bruiser slamming you within `BRUISER_RANGE`; the Racer passing then fleeing; the Cop sitting on your roomier side and leaning in to push you to the near edge for `COP_MS`, never on a bridge or by the water (`nearWater`), nor the Bruiser; the Monster keeping `BOSS_AHEAD` in front, hopping every `BOSS_HOP_MS` to come down where you will be and dropping tires; every rival rubber-banded to stay near you, swerving from under your landing as sharply as its stage allows, keeping to the narrowest road just ahead and the band a swaying bridge always covers, holding a slower car's speed, and hopping any hole, drawbridge, barrier or coming train, or flying off a ramp), `spawnRival`, `pickKind` (one of each special kind at a time), `HEAVY`, `RIVAL_MIN_SPEED` |
| `public/activities/bounce-roads.js` | Bounce Road's ten stages as data (no imports): `FIELD_W`, `FIELD_H`, `ROW`, `MAX_HOLE`, `LAP_FROM`, and per stage its length, par time, road widths, piece weights (straights, holes, rivers, splits, ramps, chicanes, crumbling road, trains, swaying bridges, boost strips, slicks, balls, sprinklers, drops, gusts), crack and broken span lengths, bridge widths and shares of broken, double and drawbridge spans, flowerbed sizes, barrier and drop kinds, the rivals' count, kinds, pace and sharpness, power-ups, stars, and whether the Monster comes |
| `public/md-field.js` | A Markdown answer field on CodeMirror 6: every multiline box the person types into renders its Markdown live. |
| `public/md-field.css` | The frame a Markdown field wears inside its shadow root, linked beside `notepad-editor.css`. |
| `public/activities/ghoul-rush/ghoul.js` | Ghoul Rush's public face and nothing else: it re-exports the parts below, so the page and the tests import from one place. Everything lives under `ghoul-rush/`: `core/` (the rules, rooms, run flow, power-ups, dice, bonus rounds), `arms/` (secondary weapons), `draw/` (shared drawing), `story/` (the intro story, stage and boss cards, game over), `sfx/` (shared sounds), `stages/<stage>/` and `rides/<ride>/` (each with its rules, art and sounds). |
| `public/activities/ghoul-rush/core/ghoul-tables.js` | Ghoul Rush's numbers and tables: the shared timings and sizes, `PACKS` with every pack's monsters, bosses and hooks joined in, the seeded dice, and `roomFor`. Loads first and imports none of the other parts. |
| `public/activities/ghoul-rush/core/ghoul-kit.js` | `KIT`, the helpers handed to the stage packs: one object `ghoul-play.js` fills as it loads, so a part that only passes it on has no load-order tie to the play loop. |
| `public/activities/ghoul-rush/core/ghoul-planny.js` | The ground and Planny: surfaces, shelves, landing, and how he runs, jumps and falls. |
| `public/activities/ghoul-rush/core/ghoul-monsters.js` | The monsters: spawning, how each kind moves, and what they throw. |
| `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`, 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). |
| `public/activities/ghoul-rush/stages/wing/ghoul-bones-draw.js` | Old Rattlebones' drawing, `boneArt(d)` plugged into `ghoul-draw.js`'s `PACK_ART`: the boss (headless while the skull is out, arms to the skull or up for rain, shaking with flaring eyes in his rage), the skull in flight, the bone rain's shadows and falling bones, the cracking floor, `lights`, `react` cases for his new events (`skullWind`, `skullThrow`, `skullTurn`, `skullBack`, `rainWind`, `rainThrow`, `rainLand`, `bonesRage`, `raiseWind`, `raised`), and `LOSE_WORDS` / `LOSE_SOUNDS` for `skull` and `rain`. |
| `scripts/test-web-console-activities-ghoul-bones.mjs` | Old Rattlebones' suite: the random attack order, the volley and slam, the skull's flight and the headless window, the skull shot, the rage, the double slam, bone rain, the skeleton cap and the reactions. |
| `public/activities/ghoul-rush/stages/graveyard/ghoul-graveyard.js` | Ghoul Rush's Graveyard stage pack, its rules (no imports: `ghoul.js` hands each rule a kit `k` of its own helpers). A stage pack is plain data and functions that `ghoul.js` merges into its own tables (`PACKS`): `monsters` (with `perch`: its spawn names its height, `flies`: a horde one comes in high), `walkers`/`zombies`/`stackers`/`climbers` (joining the sets of those names), `act` (start), `solid`, `move`, `kill`, `horde` (fields a horde one comes with), `bosses`, `boss` (one slice of its fight), `guard` (true while shots and stomps glance off, a `bossBlock` event) and `hazards` (by kind, one slice of a box on the floor that hurts while `live`; kept in `round.hazards`). Three more fields a stage may add (the Grounds does): `cut` (kinds the Hedge shears kill outright), `weak` (by boss kind, `(boss, shot) => damage multiplier` for a weak spot; `bossHit` then carries `how: "weak"` and `weak: true`) and `cause` (what a boss's touch is called when it costs a life). The Chapel adds more: `tick(round, ms, k)` (a stage-wide twist run first in every slice; it may set `round.stunMs`, which freezes you and every monster, boss, hazard and missile while bolts in flight still fly, and keeps its state in `round.twist`), `stone` (by kind, true while shots glance off and a stomp does nothing; `glance` event), `shot(round, m, s, k, random)` (the damage multiplier of a bolt that hit `m`, free to splash), `target(round, s, k)` (true when a bolt struck something of the pack's that is no monster, such as an organ pipe) and, on a monster, `hasteMs` and `haste` (its time runs faster while `hasteMs` is over 0). On the drawing side a look may be `custom: true` with a `pack` id (the pack's art then draws the whole wall, floor and shelves) and the art may return `decor` (by the look's `decor` name). On the drawing side a stage's art may also return `react(e, k)` (its own events; `ghoul-draw.js`'s `react` falls through to `ART.react`, which returns true when it handled `e`), `ground` and `shelf` (the floor pieces and shelves of an outdoor look), `waves` and `powers`; a boss event must carry `kind` or its voice never plays. The Graveyard's: grasping hands (`HANDS_*`: lurk unseen, rise, grab, sink, creep under level ground after you), the mourner (wails every `WAIL_MS`, slowing you to `SLOW_SHARE` speed for `SLOW_MS` within `WAIL_REACH`; `round.you.slowMs`), the grave robber (digs in within `ROBBER_DIG`, comes up `ROBBER_BEHIND` behind you), the rotter (a zombie whose body-shot death leaves its `legs` walking), the carrion crow (perches, dives at your chest, climbs, dives again), and Mother Mourning (`angel`: weeps `ANGEL_WEEP_MS` as stone flinging headstones, turns `ANGEL_TURN_MS`, watches `ANGEL_WATCH_MS` when only she can be hurt and any move drops a `fist` hazard after `FIST_WARN_MS`; at `ANGEL_RAGE` her wings spread, the weep shorter, the watch longer, a shockwave each way as each weep begins) |
| `public/activities/ghoul-rush/stages/graveyard/ghoul-graveyard-draw.js` | The Graveyard's drawing: `LOOKS` for its four rooms (`outdoor: true`, so `ghoul-draw.js` draws `backdrop` instead of walls: the night sky, stars, the moon, hills with dead trees, iron fences, mausoleums, fog and headstones) and `graveyardArt(d)`, handed `ghoul-draw.js`'s helpers, returning the open `grave` and `openGrave` a rotter climbs out of, `monsters`, `bosses` (Mother Mourning: hands over her face while she weeps, lowered with burning eyes while she watches, wings spread in a rage, cracks as she is worn down), `missiles` (a flung headstone), `hazards` (a stone fist: its shadow, then the fist) and `lights` |
| `public/activities/ghoul-rush/stages/grounds/ghoul-grounds.js` | Ghoul Rush's Grounds stage pack, its rules (no imports; same shape as the Graveyard's, plus the pack fields `cut`, `weak` and `cause`): the topiary beast (`still` while you face it, `creep` when your back is turned; events `rustle` and `freeze`), the rootling (`trail`, `warn`, `up`, `sink`; events `rootWarn` and `rootUp`), the lantern moth (flocks of three, quicker in the dark), the mulch crawler (`pile`, `burst`, `crawl`; event `leaves`), the Hedge shears' `snip` event, and the Groundskeeper (`keeper`: a scythe sweep along the floor (or, now and then, a high `sweep` hazard you stay on the ground under), a lobbed lantern fire hazard, his lantern a `weak` spot only while open (`b.lit`), and at half hp a mower with `rev`, `charge` and `stall`) |
| `public/activities/ghoul-rush/stages/grounds/ghoul-grounds-draw.js` | The Grounds' drawing: `LOOKS` for its four rooms (`outdoor: true`), `groundsArt(d)` returning `monsters`, `bosses`, `hazards` (the fire), `waves` (the scythe), `powers` (the shears), `lights`, `backdrop`, `ground`, `shelf` and `react(e, k)` for the Grounds' own events; its `VOICES` (each kind's tone per act, `keeper.weak` for a weak-spot hit instead of `keeper.hurt`, `shears.snip` for a cut instead of the dying cry), `LOSE_WORDS` and `LOSE_SOUNDS`, which `ghoul-draw.js` spreads into its own tables |
| `public/activities/ghoul-rush/stages/chapel/ghoul-chapel.js` | Ghoul Rush's Chapel stage pack, its rules (no imports; same shape as the Grounds', plus the pack hooks `tick`, `stone`, `shot` and `target`, and a room field `toll`): the gargoyle (`perch` as stone, `wake`, `dive`, `return`; events `glance`, `gargoyleWake`, `gargoyleDive`, `gargoylePerch`), the choir ghost (sings, giving nearby monsters `hasteMs`), the censer monk (`smoke` hazard), the bell bat (`roost` until the toll), the bell toll (`tick`: `bellSwing`, `toll`, `tollEnd`, `round.stunMs`), Holy Water's splash (`shot`, event `holySplash`) and the Choirmaster (`choirmaster`: four pipes in `b.pipes` that bolts hit through `target`, a `guard` while any sounds, columns of `note` hazards with one gap, a rage that brings pipes back one by one) |
| `public/activities/ghoul-rush/stages/chapel/ghoul-chapel-draw.js` | The Chapel's drawing: `LOOKS` for its four rooms (indoor but `custom: true` with `pack: "chapel"`, so `ghoul-draw.js` hands the walls, floor and shelves to `chapelArt(d)`'s `backdrop`, `ground` and `shelf`), `chapelArt(d)` returning those plus `decor` (the room's pews, belfry, organ or stalls), `monsters`, `bosses`, `hazards` (smoke, the bell, notes), `powers`, `lights` and `react(e, k)`; its `VOICES` (the bell has only `swing` and `toll`: the thaw after a toll is quiet on purpose), `LOSE_WORDS` and `LOSE_SOUNDS` |
| `public/activities/ghoul-rush/stages/sanatorium/ghoul-sanatorium.js` | Ghoul Rush's Blackmoor Sanatorium stage pack, its rules (no imports; same shape as the Chapel's, plus the pack fields `unseen`, `harmless`, `platform` and `land`, a room field `flicker`, `round.blackout`/`round.twist` for the lamps and the kit's `fling`): the orderly (`reach`, `hold`, a throw that costs no life, `you.heldMs`; events `orderlyReach`, `orderlyGrab`, `orderlyThrow`, `saltsBreak`), the gurney (`parked` as a floor you can stand on, `rattle`, `roll`, `rest`; `gurneyRattle`, `gurneyRoll`, `gurneyRest`), the flicker (`m.unseen`: bolts and touch go through it until a blackout, the Lantern's light or the Salts' glow; `flickerShow`), the specimen bloater (a `jar` missile with its own `cause` that `land`s as a `formaldehyde` hazard; `jarWind`, `jarBreak`), the lamps (`tick`: `flickerWarn`, `lightsOut`, `lightsOn`), the Salts and the Saw (`shot`) and the Night Matron (`matron`: `b.beam` cone, `b.heat`, `b.cabinets`, syringes, arms, rage; `syringeWind`, `syringes`, `armWarn`, `armReach`, `matronRage`) |
| `public/activities/ghoul-rush/stages/sanatorium/ghoul-sanatorium-draw.js` | The Sanatorium's art: `LOOKS` (indoor but `custom: true` with `pack: "sanatorium"` and `noMoon`, so `sanatoriumArt(d)`'s `backdrop`, `ground` and `shelf` draw the tiled walls, windows, decor, floors, the ward's cabinets, the baths' tubs and each room's boards), `monsters` (orderly with its grab pose, gurney, flicker with its fade and afterimage, specimen bloater), the `matron` with her cone cut by the floor and the cabinets, `missiles` (jar, syringe), `hazards` (formaldehyde, arm with its crack of light), `powers` (Salts, Saw), `lights`, `react(e, k)` and two generic hooks `ghoul-draw.js` calls: `front(ctx, v)` (over Planny and before the dark: the ceiling lamps, the tubs' water, the orderly's fingers, the Matron's heat on him) and `dim(v)` (the dark layer's alpha, raised in a blackout and in a stutter); its `VOICES` (borrowed tones; `lights`, `salts` and `saw` are no monsters), `LOSE_WORDS` and `LOSE_SOUNDS` |
| `public/activities/ghoul-rush/stages/village/ghoul-village.js` | Ghoul Rush's Hollow End Village stage pack, its rules (no imports; no new pack field: it uses `tick`, `shot`, `land`, `weak` (now handed `(boss, shot, round, k)`) and `solid`, and draws no random number): the moonrise (`tick`; `round.twist` = `{ moon, full, ms }`, events `fullMoon`, `villagerTurn`, `villagerWolf`, `houndGrow`), the torch mob villager (a group of three, `torchWind`, the `torch` missile that `land`s as a `torchfire` hazard, `torchLand`; turned into a leaping wolf-man at full moon), the hanged man (`hangedWarn`, `hangedDrop`, `hangedSnap`, `hangedHaul`), the shutter ghoul (`solid` only while out; `shutterRattle`, `shutterLunge`, `shutterPull`), the moonhound (the hellhound's leap, grown at full moon), Wolfsbane's double damage and shying (`baneShy`) and the Beast of Hollow End (`beastLeap`, `beastCling`, `beastPounce` with a `shadow` hazard, `beastLand`, `swipeWind`, `beastSwipe` with a `claw` hazard, `beastHowl`, `houndCall`, `beastMoon`) |
| `public/activities/ghoul-rush/stages/village/ghoul-village-draw.js` | The Village's art: `LOOKS` (street, square and green outdoors, the inn a `custom` indoor look, all `pack: "village"`), `villageArt(d)` returning the world's hooks plus the monsters (the torch mob villager and the wolf-man it turns into over 800 ms, the hanged man on his rope, the shutter ghoul reaching out of a window, the moonhound with a glowing mane when grown), the `beast` (a werewolf in every move: cling with a glowing weak spot, bound, pounce, land, swipe, howl at the moon, rage), `missiles` (torch), `hazards` (torchfire, the landing shadow, the claw swipe), `powers` (Wolfsbane's badge), `lights` and `react(e, k)`; its `VOICES` (borrowed tones, plus `moon.full` and `bane.active`), `EVENT_VOICE` (event to `[kind, act]`, each played once; the hounds' call is quiet), `LOSE_WORDS` and `LOSE_SOUNDS`. Its header lists what the art reads off the rules |
| `public/activities/ghoul-rush/stages/village/ghoul-village-world.js` | The Village's world: the night sky and the moon that climbs and reddens with `round.twist.moon` (`sky`, drawn every frame under the still layers), the crooked timber-framed houses with a window for every shutter ghoul, the church and spire, the gallows, the green's far cottages, well and arena walls, the Crooked Inn (hearths, barrels, bar, lanterns, the moon in its windows), cobbles, planks and turf (`ground`), awnings, rooftops, balconies, tables, carts and thatch (`shelf`), and `moving` (curtains that twitch as you pass, fire, moonlight falling in), `front` (the full-moon wash, Wolfsbane's petals, the Beast's rage) and `lights` |
| `public/activities/ghoul-rush/stages/mine/ghoul-mine-world.js` | The Deep Seam Mine's world (no imports; `mineWorld(d)` takes ghoul-draw.js's helpers): the rock wall with its strata and facets, the timber that holds it up (props and cap beams, scaffolds and galleries as `shelf`), rails and sleepers on the floor (`ground`), oil lamps on hooks with their flames and warm halos (`moving`) and their holes in the dark (`lights`, none in a blackout), the shaft's lining, walers, guide rails and headframe with the cage lift drawn on its cable over a winch wheel with a counterweight (`cage`, and its front bars in `front`), the tunnels' low roof, pipes, stalled pump, drips and knee-deep water with a lit surface and Planny's wake (`front`), the collapse's broken props, cracks, rubble heaps and buried cart, the seam's glittering ore vein, stalactites and galleries, and the `rock` hazard in its three states; layouts are worked out once per room from the room alone and kept. Scene tool: `prototypes/ghoul-rush-tools/scene-mine-world.mjs` |
| `public/activities/ghoul-rush/stages/village/ghoul-village-wolf.js` | The Village's werewolf, one skeleton for the Beast and a turned villager: poses (`POSES`: stand, rear, swipe, howl, crouch, leap, land, rest, cling, shy, down, sleep), `mixPose` to blend them, and `wolfKit(d).figure` to draw one |
| `public/activities/ghoul-rush/stages/mine/ghoul-mine.js` | Ghoul Rush's Deep Seam Mine stage pack, its rules (no imports; draws no random number): uses `tick`, `harmless`, `platform`, `solid`, `kill`, `weak` and a boss's blackout (`round.blackout`). The rockfall (`tick`; a room field `rocks` in ms; the `rock` hazard in states `warn`, `fall`, `rubble`, events `rockWarn`, `rockFall`, `rockLand`; the Hard Hat's `rockBounce`), the noise you make (`round.twist` = `{ next, quiet, noise, reach, wade }`, `wade` splashes), the knocker imp (touch steals light, not a life: `you.dimMs` and `you.dimBy`, `impSteal`, `impDrop`; the Hard Hat stops it), the canary ghost (`canaryScream`: three rocks), the dead miner (buried in the wall, `minerDig`, `pickWind`, `pickSwing` with a `pick` hazard, cause `pickaxe`), the blind crawler (`blindLost`, `blindHear`), the cage lift (a spawn row `["cage", x, lowest y, highest y]`, a `platform` kind that is not solid and never hurts), Dynamite placed in each room (its rules, the `stick` and `blast` hazards, `dynThrow` and `dynBlast`, moved to `ghoul-arms.js`) and the Tommyknocker (`tommyKnock`, `sweepWind`, `tommySweep` with a `hammer` hazard, `tommyDark`, `tommySink`, `tommyKnockDark`, `tommyBurst`, `tommyRage`; dazed double damage through `weak`) |
| `public/activities/ghoul-rush/stages/mine/ghoul-mine-draw.js` | The Mine's art (the rooms in `ghoul-mine-world.js`, the Tommyknocker in `ghoul-mine-tommy.js`): `LOOKS` (`custom: true`, `pack: "mine"`, always dark), `mineArt(d)` returning `backdrop` (rock, strata, timber props, oil lamps), `ground` (rails), `shelf` (timber landings), `front` (the water along the floor), `dim` (the blackout), `monsters` (imp, canary, miner, blind crawler, cage), the `tommy` boss, `hazards` (rock, stick, blast, pick, hammer), `powers` (Hard Hat, Dynamite), `lights` and `react`; its `VOICES` (borrowed tones), `EVENT_VOICE`, `LOSE_WORDS` and `LOSE_SOUNDS`. Its header lists every field the art reads off the rules; `ghoul-draw.js` shrinks Planny's glow and drops his cone while `you.dimMs` is over 0 |
| `public/activities/ghoul-rush/stages/mine/ghoul-mine-tommy.js` | The Tommyknocker's figure for `ghoul-mine-draw.js`: `tommyKit(d)` (no imports, `ghoul-draw.js`'s helpers handed in) returns `figure(ctx, v, b)`, a miner-giant half grown into the seam (stone shoulder with crystals, lantern on his helmet, a door-sized hammer) drawn by act: leaning on the hammer, the overhead knocks, the drawn-back sweep, rest, sinking, bursting out dazed with stars, raged cracks, hurt flash. |
| `public/activities/ghoul-rush/rides/cart/ghoul-cart.js` | Ghoul Rush's Runaway Cart, the Mine's ride room, its rules (no imports; draws no random number): the first room where a pack takes Planny's movement over. It adds the pack fields `ride` (a list of `(round, ms, k) => true` hooks run each slice before the walking rules; one that returns true has moved him) and `place` (a list of `(round, k)` hooks run whenever he is put down in a room: a room set up, a respawn), uses `target` (the crates), and `round.camLead` (units the camera leads further). The cart (`round.cart`, null elsewhere) rides the room's `ride.track` polylines (slope speed, lean and brake, jump, air steering, ramp launch, landing on the line under it, derail into the chasm), ducks under `ride.beams`, wrecks on `rubble` and unbroken `crates` (two bolts break one), is chased by the boulder, passes `checks` (a life lost puts it back at the last) and halts at `stop` where the door opens; a ledge imp (`ledgeimp`) leaps into it and steals light, a canary's scream drops a slide of rubble on the track ahead. Exports `flight`, `trackY`, `linesAt` and `linesOf` for the unit suite. Events `cartJump`, `cartLand`, `cartLaunch`, `cartBrake`, `cartDuck`, `crateHit`, `crateBreak`, `cartCrash`, `boulderNear`, `checkpoint`, `cartStop`, `ledgeLeap`, `slideWarn`, `slideFall`; causes `derail`, `beam`, `crash`, `boulder` |
| `public/activities/ghoul-rush/rides/cart/ghoul-cart-draw.js` | The Runaway Cart's art: `LOOKS` (`custom: true`, `pack: "cart"`, always dark), `cartArt(d)` returning `backdrop`, `ground`, `moving` (every frame: the cave in cached parallax tiles over a chasm, the trestled track, ledge pillars, signal posts, rubble and the buffer stop in cached chunks, hanging lamps, signal lamps, crates, a slide's dust and pour; the cart too once it has stopped, so Planny walks out past it), `front` (the cart over Planny, the beams, the boulder, flying splinters, speed streaks, the foreground rock), `lights` (headlamp, hanging and far lamps, signals, beams), `monsters` (the ledge imp) and `react`; its `VOICES` (borrowed tones), `EVENT_VOICE`, `LOSE_WORDS` and `LOSE_SOUNDS`. It keeps its own offscreen layer cache (keyed by scale), draws no random numbers (a hash) and leaves short-lived bits in the view's `fx` (`cartBits`, `cartPours`, `cartLand`, `cartStop`). Its header lists every field the art reads off the rules |
| `public/activities/ghoul-rush/stages/mine/ghoul-sfx-mine.js` | The Mine's own sounds as data (no imports): `MINE_SFX` with an empty `tones` and `music` until the user picks them; merged by `ghoul-sfx.js` via `STAGE_SFX` (its rooms play existing tracks, set in `ROOM_MUSIC`) |
| `public/activities/ghoul-rush/stages/bog/ghoul-bog.js` | Ghoul Rush's Gallows Bog stage pack, its rules (no imports; a pack `ghoul.js` plugs in through `PACKS`, handed the kit `k`): the lurker, leech swarm, will-o'-wisp and bog body (`MONSTERS`, with `walkers`/`zombies` sets), `act`, `solid`, `swoops`, `unseen`, `move`, `kill`, `horde`, `tick` (the wisp's lure), `bosses`/`boss`, `weak`, `cause` and `hazards`, and Old Mother Bog (`BOSSES`, hp 360, her fight in `moveMother` with `startMove` setting each move's wind-up act, wait and telegraph event: the wave opens, then a weighted `pickAttack` by phase (`phaseOf`, `WEIGHTS`; never one move three times running, `COOLDOWN` picks for the slow moves, a summon only under its cap, counted by `hagAdds` on adds marked `m.hag`). Full health: wave, spit, bog hands (`boghand` hazards: a ripple, then a hand), surge (a waist-deep charge past you), mud shell (`shellShot` in `target` chips it; broken she reels in `stagger` with the cauldron open, ignored she heals `SHELL_HEAL`) and dive (relocate); under three quarters the double wave, volley and leech brood join. Under half (after her first dive): stomp (a shadow, a leap, a slam and a wave each way), tide (a `tide` hazard over every plank after `TIDE_WARN_MS`; shelves are dry), drowning pull (drags `you.x` toward her on the planks, never off a plank's end) and call the drowned (bog bodies). Under a quarter: the wisp lantern (her wisps, gone for good once shot out) and combos (`toIdle`, `motherCombo`). `guard` is under water or shelled; `weak` is the open cauldron (late in a rest, or reeling). `planked` keeps her whole body on one plank height except in `UNSTOOD` acts; `b.floor` is the plank height; `b.plan` forces a move for tests). The stage's second twist lives in the engine, not here: a room field `mud` (frozen `[x0, x1]` spans), `mudAt` in `ghoul.js`, `you.mud` and `you.mudMs` (the run sags from `WATER_SPEED` toward `MUD_SPEED_MIN` and a jump toward `MUD_JUMP_MIN` over `MUD_MS`; a shelf, the air and Stilt Boots (`round.effects.boots`) let go of it) |
| `public/activities/ghoul-rush/stages/bog/ghoul-bog-draw.js` | The Gallows Bog's drawing: `LOOKS` for its rooms (`outdoor: true`, `pack: "bog"`) and `bogArt(d)`, handed `ghoul-draw.js`'s helpers, returning the night swamp rooms (boardwalk planks over black water, moss veils, fireflies, the hag's lit stilt house and her open-water arena), `monsters` (a lurker's eyes, a leech swarm, a will-o'-wisp, a bog body), `bosses` (Old Mother Bog and her cauldron, a pose for every move, plus `motherMarks`: the boiling mud of a call, the stomp's shadow, the undertow's streaks), `hazards` (the mud wave, the muck patches, the bog hands' ripples and arms, the tide's warning and its water over the planks), the Stilt Boots' and Harpoon's badges and the events' looks and sounds; its `VOICES` are borrowed house tones until the sound page's vote, `LOSE_WORDS` and `LOSE_SOUNDS` already named |
| `public/activities/ghoul-rush/rides/lantern/ghoul-lantern.js` | The Drowned Lantern (Gallows Bog's bonus round, not a ride) as a pack (`LANTERN`): a top-down game on one fixed screen where YOU carry a lantern over an island of mossy hummocks and plank walks round Old Mother Bog's pool, light five wisp shrines (stand on a stone `SHRINE_MS`, the time kept if you step off), then run back to the boat at the landing. Pack fields `ride` (moves Planny) and `place`; state in `round.runner` (`id` "lantern"), positions in field units with y counted down; the room's `ride` holds the island (`hummocks`, `planks` as hummock pairs, `shrines`, `start`, `boat`, `pool`, `bodies`) and the hunters' tables (`lurker` route, `leeches` routes, `wisps`: a guardian per shrine with its `phase`, roamers with `wake`). Keys: arrows walk (a walk into the water slides along the shore or plank, `slide`), SPACE flares (a ring `FLARE_R` that bursts wisps and scatters leeches, costing `FLARE_OIL`; a sputter without the oil); `fire()` and the arm double-tap are off for this room. The oil burns down over `OIL_MS` and the light (`lightR`) with it; a lit shrine fills it. One rule per hunter: the Lurker hears steps on wood, flares and shrines, swims to the spot, lines up a lane through it (`AIM_MS`) and dashes (it strikes where it heard you), rests deaf, and cowers once Mother rises; guardian wisps circle their shrine and rush a lantern within `GUARD_SENSE` on a `LEASH`, roamers leave the pool at the third to fifth shrine; leeches stay at the light's edge and bite only once the flame gutters; bog bodies rise only for someone standing still beside them; Mother's hand (from the third shrine or `MOTHER_LATE_S`) tracks, locks and slams, one after another once the fifth raises her. Catches cost the bonus round's hearts and never move Planny; `lanternMeet` names each hunter's rule once; `runner.marks` lists what a banner must keep clear of (read by ghoul.js's `underBanner`); `lanternHums` gives ghoul.js the held sounds; the grade is `total` 5, `hits` (kinds that caught you), `acts` (flare pops and close calls), `steady` (the flame never guttered). No random numbers; a Planny put at the door finishes too, as a ride's finish line does |
| `public/activities/ghoul-rush/rides/lantern/ghoul-lantern-draw.js` | The Drowned Lantern's art, the whole field drawn by `lanternArt(d).field` (like Holy Roller's): `LOOKS`, `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`, `TAGS` (each hunter's rule, shown once over it, one at a time); the water and Mother's pool, the island and the boat, then one dark layer with a hole per light (`paintDark` from ghoul-draw.js), and over it what the dark must never hide: the island's moonlit edges, the shrines' beacons and progress, the bodies' bubbles and red reach, the leeches' eyes, Mother's eyes, head and hand shadow, the Lurker's eyes, its lane and dash, the wisps, Planny with the ring of his light (the leeches' line, red when the oil is low) and the boat's beacon; the HUD band (shrine flames, the hint line, the oil bar with its flare ticks); no random numbers, everything from a hash and the clock |
| `public/activities/ghoul-rush/stages/bog/ghoul-sfx-bog.js` | Gallows Bog's own sounds as data (no imports): `BOG_SFX` with `tones` (a `ghoul<Kind><Act>` tone for each act of the lurker, leech, wisp, bog body and Old Mother Bog, her 22 newer acts first drafts too: a telegraph tone per move and one for each effect) and an empty `music` until the music vote is wired in (the rooms play borrowed tracks through `ROOM_MUSIC`); the tones are first drafts (option 1 of each act) until the sound vote; merged by `ghoul-sfx.js` via `STAGE_SFX` |
| `public/activities/ghoul-rush/rides/lantern/ghoul-sfx-lantern.js` | The Drowned Lantern's own sounds as data (no imports): `LANTERN_SFX` with `tones` (`ghoulLantern<Act>`: a creak per step on wood, the flare, the shrine, a cue per hunter heard before it reaches you, Mother's wake, rise, hand and slam), `hums` (`ghoulLanternLurk`, `ghoulLanternMother`, asked for through `lanternHums`) and `music` (`ghoulLanternTheme`, the picked Tiptoe plucks track, named in `ROOM_MUSIC`); first drafts until the vote; merged by `ghoul-sfx.js` via `STAGE_SFX` |
| `public/activities/ghoul-rush/stages/carnival/ghoul-carnival.js` | Ghoul Rush's Midnight Carnival stage pack, its rules (no imports; draws no random number): uses `tick` (the ring of samples Mirror You reads and its bolts in `round.twist`), `shot` (Cotton Candy's slow, a marionette's string at the top of its body), `target` (a bolt crossing a marionette's string or one of the puppet's three), `guard` (the Ringmaster is open only with the puppet down), `swoops` (a balloon, a circus hound's leap), `solid`, `kill` and `fourLegged`. Grinner and its acid balloons, marionette (drops when you pass under), Mirror You (copies you 500 ms late, mirrored, its bolts cancel yours), strongman (barbells), circus hound, and the Ringmaster (a gantry over the ring that follows its puppet at a lag, the puppet stalking you and working to a fixed script of leap, stomp, whip and charge, three strings from the gantry to its head and hands that move with it, open 4 s when they are cut, rage with hounds from the cages); `CARNIVAL_ROOMS` lists the stage's rooms, with a place before the Big Top for the dark ride. The room field `belts` and Planny's `you.belt` (the funhouse's conveyor floors) are run by `ghoul.js`. |
| `public/activities/ghoul-rush/stages/carnival/ghoul-carnival-draw.js` | The Carnival's art: `LOOKS` (`custom: true`, `pack: "carnival"`), `carnivalArt(d)` returning the world's hooks (from `ghoul-carnival-world.js`) plus `monsters`, the `ringmaster` boss (gantry, puppet in each pose, strings, whip), `missiles` (barbell), `hazards` (foot, whip, charge), `waves` (the puppet's), `powers` (Cotton Candy), `front` (Mirror You's bolts, Cotton Candy's glow), `lights` and `react`, and `VOICES` (borrowed tones), `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`. Its header lists what the art reads off the rules. |
| `public/activities/ghoul-rush/stages/carnival/ghoul-carnival-world.js` | The Carnival's world (no imports; `carnivalWorld(d)` takes ghoul-draw.js's helpers): the night sky with a Ferris wheel (`sky`), tents, booths and swagged bulbs on the Midway, the Hall of Mirrors' gilded panels and glints, the Funhouse's crooked walls, spiral discs and clown-mouth door, the Big Top's striped canvas, ring curb, crowd, trapeze boards, gantry rail and cages (open once the Ringmaster rages), and the belts' chevrons (`moving`). |
| `public/activities/ghoul-rush/stages/carnival/ghoul-sfx-carnival.js` | The Carnival's own sounds as data (no imports): `CARNIVAL_SFX` with an empty `tones` and `music` until the user picks them; merged by `ghoul-sfx.js` via `STAGE_SFX` (its rooms play existing tracks, set in `ROOM_MUSIC`) |
| `public/activities/ghoul-rush/rides/dark-ride/ghoul-ride.js` | The Carnival's dark ride (a bonus round) as a pack (`RIDE`), the rules ported from `prototypes/ghoul-rush-ride/gallery.html`. Pack fields `ride` (returns true, so Planny never walks; steps the ride in 16 ms steps), `place` (makes `round.gallery`, the ride's state) and a new `pointer` (the mouse, handed on by `ghoul.js`'s `pointer(type, x, y)`); the entities (`K`: pop, lant, axe, chand, door, hand, head, eyes, boss, inno, mir, web, mini), hit tests with aim assist, the duck zone, hearts through `kit.lose`, the grade (5 to 9 dice, `perf.dice`). Events `ride<Name>` (`SOUNDS`), causes `CAUSES`. Its own seeded random stream; draws no `Math.random` |
| `public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-scenes.js` | The dark ride's scene table as data (12 rooms, lengths, speeds, spawn rows in author coordinates), no imports |
| `public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-core.js` | The ride's shared basics: the 96 by 54 field's constants, math helpers, the bound state `G` (a live import), `rnd`/`rand` (seeded) and `vrand` (visual) |
| `public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-draw.js` | The ride's art entry (`rideArt(d, die)`: `field(ctx, v)` draws the whole field by phase, `tick` the cascade's sounds); `ghoul-draw.js` hands over to it when `round.gallery` is set. Parts: `ghoul-ride-gfx.js` (canvas helpers), `ghoul-ride-draw-kinds.js` (animatronics, mini-bosses, the Barker), `ghoul-ride-draw-sets.js` (the 12 sets, far walls, aisle, near layer), `ghoul-ride-draw-hud.js` (car and Planny, HUD, duck strip, reticle, title, end cascade) |
| `public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-gfx.js` | The ride's drawing helpers: the bound 2D context and the short fill, stroke and shape calls the ride's art is written in |
| `public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-draw-kinds.js` | The ride's drawn things: every figure, beast, lantern, blade, door, hand, head, mirror, web and boss, a port of the prototype's draw code (`prototypes/ghoul-rush-ride/gallery.html`) |
| `public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-draw-sets.js` | The ride's rooms drawn: each room's far wall, set pieces front and back, aisle and the near pillars, a port of the prototype's world draw |
| `public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-draw-hud.js` | The ride's car and the screen around it: Planny in his car, blood and sparks, the lens, the hearts, the progress bar, the room plaque, the aim, the title and the cleared card |
| `public/activities/ghoul-rush/rides/dark-ride/ghoul-ride-voices.js` | The ride's `LOOKS`, `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS` and `react` (every `ride<Name>` event plays tone `ghoulRide<Name>`) |
| `public/activities/ghoul-rush/rides/dark-ride/ghoul-sfx-ride.js` | The ride's synthesized sounds as `tones` (`ghoulRide<Kind>`) and its music `ghoulRideDrone` (`RIDE_SFX`, merged by `ghoul-sfx.js`) |
| `public/activities/ghoul-rush/stages/frozen/ghoul-frozen.js` | Ghoul Rush's Frozen Lake stage pack, its rules (imports only `burrow` from the Graveyard; draws no random number): uses `tick` (thin ice, the blizzard, the Widow's spikes, web and barrels), `place`, `unseen`, `solid`, `kill`, `target`, `land`, `weak`, `cause`, `guard`, `swoops` and `slides`. The generic slippery-ice rule (`iceRun`, room field `ice`) and thin-ice rule (`stepThin`, room field `thin`, `round.thin`), the under-ice hand, snow shade (unseen, footprints), Frozen Ghoul (slides, shatters into shards), Ice Wraith (its dive freezes), Hot Cocoa, the Frost Widow (veil, barrels, weak spot, blizzard, spikes, web, rage) and `FROZEN_ROOMS`. Every constant is exported and documented in its header |
| `public/activities/ghoul-rush/stages/frozen/ghoul-frozen-draw.js` | The Frozen Lake's art: `LOOKS` (`custom: true`), `frozenArt(d)` returning the world's hooks (from `ghoul-frozen-world.js`) plus `monsters`, the Frost Widow boss, `hazards` (shards, spikes, webs, barrels, the flare and its fire), `powers` (Hot Cocoa), `front`, `lights` and `react`, and `VOICES` (borrowed tones), `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`. Its header lists what the art reads off the rules |
| `public/activities/ghoul-rush/stages/frozen/ghoul-frozen-world.js` | The Frozen Lake's world (no imports; `frozenWorld(d)` takes ghoul-draw.js's helpers): the night sky with moon, aurora and far mountains (`sky`), the huts, the Lodge's fallen roof, the Black Ice and the Widow's web (`backdrop`, `ground` with the ice's gloss, `shelf`), and `moving` (open water in the holes, thin ice drawn from `round.thin`, never from `spec.ground`, the faces under the Black Ice, falling snow) and `lights`. Draws no random number |
| `public/activities/ghoul-rush/arms/ghoul-flare.js` | The Road Flare's rules (`useFlare`, `stepFlareFly`, `stepRoadFire`; no imports, handed the helpers by `ghoul-arms.js`): a lob that lands as a patch of fire, burns monsters on a tick, melts a Frozen Ghoul at once, shows a shade and melts the Widow's veil; never hurts Planny |
| `public/activities/ghoul-rush/rides/sled/ghoul-sled.js` | The Coffin Sled (the Frozen Lake's bonus round) as a pack (`SLED`), modeled on the Runaway Cart (`ghoul-cart.js`): pack fields `ride`, `place` and `target`; the track of ice lines with cracks, headstones, drifts, low branches, hands, icicles and popping ghouls, checkpoints, hearts through the Cart's bonus machinery and the grade (3 to 9 dice). Adds no monster, boss or hazard kind and draws no random number; every number is an exported constant documented in its header |
| `public/activities/ghoul-rush/rides/hearse/ghoul-hearse.js` | The Midnight Hearse (the Graveyard's bonus round) as a pack (`HEARSE`), modeled on the Coffin Sled: pack fields `ride`, `place` and `target`; state in `round.runner` (`id: "hearse"`); a flat road of two lanes (road and verge) switched with LEFT/RIGHT inside the lane gates, open graves, headstones and crosses to jump, low branches and the lychgate arch to duck, hands and crows to shoot, closed stretches to go round, lanterns that keep the lamp lit (an unbroken lamp is the grade's `steady` die), and coffins thrown out by each hit with a ghoul to shoot in each. Adds no monster, boss or hazard kind and draws no random number; every number is an exported constant documented in its header |
| `public/activities/ghoul-rush/rides/hearse/ghoul-hearse-draw.js` | The Midnight Hearse's art: `LOOKS` (`pack: "hearse"`), `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`, `telegraphMarks`/`telegraphs` (JUMP, DUCK, SHOOT and SWITCH glyphs for the hearse's lane) and `hearseArt(d)` (sky, hills, cemetery, road, verge, things and the hearse by `moving`; the cab door, lows, fog, glyphs and lamp gauge by `front`; `dim` when the lamp is out); no random numbers. Its header lists what the art reads off the rules |
| `public/activities/ghoul-rush/rides/sled/ghoul-sled-draw.js` | The Coffin Sled's art: `LOOKS`, `VOICES` (borrowed tones), `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS` and `sledArt(d)` (the sky, hills, ice and things by `moving`, the lid, the lows and foreground flakes by `front`); no random numbers. Its header lists what the art reads off the rules |
| `public/activities/ghoul-rush/rides/gurney/ghoul-gurney.js` | Code Blue (Blackmoor Sanatorium's bonus round) as a pack (`GURNEY`), modeled on the Coffin Sled: pack fields `ride`, `place` and `target`; the gurney along `ride.track` (shafts are the gaps), wheelchairs that roll, IV stands, lamps and doors overhead, orderlies in doorways, the lights-out waves (`lightsAt`), the surge lamps and the heartbeat monitor's beat; its state is `round.runner` (`pack: "codeblue"`, put back if another pack's `place` clears the shared slot); draws no random number; imports the cart's track helpers |
| `public/activities/ghoul-rush/rides/gurney/ghoul-gurney-draw.js` | Code Blue's art: `LOOKS`, `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`, `telegraphMarks`/`telegraphs` and `gurneyArt(d)` (the corridors, shafts and floors by `moving`; the gurney, lows, glyphs, countdown and monitor by `front`; `dim` and `lights` for the blackouts); no imports but the Sled's glyph colors |
| `public/activities/ghoul-rush/rides/mower/ghoul-mower.js` | The Gardener's Revenge (the Grounds' bonus round) as a pack (`MOWER`), modeled on the Coffin Sled: pack fields `ride`, `place` and `target`; state in the shared `round.runner` slot (id `mower`); a flat lawn run on a ride-on mower with gaps (ponds, ha-ha ditches), junk, hedge arches, clothes lines of gloves and snapping topiary beasts, and the twist: holding fire lowers the blades, which cut tall grass, weeds and thorn hedges in the zone ahead (the blades heat and jam, so they are pulsed); the lawn-cut share is the grade's steady die; hearts through the Cart's bonus machinery; no random numbers |
| `public/activities/ghoul-rush/rides/mower/ghoul-mower-draw.js` | The Gardener's Revenge's art: `LOOKS`, `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`, `telegraphMarks`/`telegraphs` (JUMP, DUCK and CUT glyphs) and `mowerArt(d)` (sky, manor, topiary and railings by `moving`, the lawn with its ponds and ditches, the mower with its blades and heat gauge, the lows and the lawn gauge by `front`); no random numbers |
| `public/activities/ghoul-rush/stages/frozen/ghoul-sfx-frozen.js` | The Frozen Lake's own sounds as data (no imports): `FROZEN_SFX` with an empty `tones` and `music` until the user picks them; merged by `ghoul-sfx.js` via `STAGE_SFX` (its rooms play existing tracks, set in `ROOM_MUSIC`) |
| `public/activities/ghoul-rush/rides/mower/ghoul-sfx-mower.js` | The Gardener's Revenge's own sounds as data (no imports): `MOWER_SFX` with first-draft `tones` (`ghoulMower<Act>`, each under 1.2 s) and the `ghoulMowerRide` track (sound and music picks still pending); merged by `ghoul-sfx.js` via `STAGE_SFX`, the track set in `ROOM_MUSIC` |
| `public/activities/ghoul-rush/rides/pew/ghoul-pew.js` | Holy Roller (the Chapel's bonus round) as a pack (`PEW`): a Subway-Surfers style endless-runner seen from behind, pack fields `ride`, `place` and `target`; state in the shared `round.runner` slot (id `pew`). `you.x` is only the distance run; the pew's own `lane` (a float to `laneTo`), `h`, `slide`, `combo` and `magnet` live in `round.runner`. Left/right presses change lane (a wall bump at the edge), up jumps, down slides (fast-fall in the air), fire shoots down the lane; a speed ramp by distance (`speedAt`); `KINDS` (switch: pillar, confessional, pewx; jump: kneeler, stand, cracks, hatch; slide: censer, banner, beam; shoot: garg with 2 hp, bell rope), wax souls and halos, the combo and the steady die (souls share); a hit shoves the pew to a calm lane. Pure rules, no random numbers |
| `public/activities/ghoul-rush/rides/pew/ghoul-pew-course.js` | Holy Roller's seeded course (no imports): written in seconds and laid by the speed ramp (`xAt`, `speedAt`, `V0`, `ACC`), `COURSE` { items [x, lane, kind, len], souls, checks, finish } |
| `public/activities/ghoul-rush/rides/pew/ghoul-pew-draw.js` | Holy Roller's art: `LOOKS`, `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS` and `pewArt(d)`, whose `field(ctx, view)` draws the WHOLE field (ghoul-draw.js has a `round.runner.id === "pew"` branch like the dark ride's `round.gallery` one, then adds the hearts, flash, banner, cards and HUD pills) plus the progress track, souls and combo strip, and the events' effects |
| `public/activities/ghoul-rush/rides/pew/ghoul-pew-world.js` | Holy Roller's pseudo-3D nave: `worldArt(d)` with `paint(ctx, view)`; the projection `(lane, depth, height)` to the screen with scale = near / (near + depth) toward a vanishing point, far-to-near cells with fog as alpha, stained glass, pillars and ribs, pews, candlelight and god rays pulsing on the organ's beat (`pulse`, `BPM`), every thing's art and telegraph glyph, the souls, bolts, the pew and hero from behind, speed streaks and vignette. A reusable pattern for "run into the screen" rides. No random numbers (hashes) |
| `public/activities/ghoul-rush/rides/pew/ghoul-sfx-pew.js` | Holy Roller's own sounds as data (no imports): `PEW_SFX` with 17 tones (lane, bump, jump, land, slide, dive, soul, halo, crash, check, finish, speed swell, gargoyle and bell) and the driving `ghoulPewDirge` track at 132 BPM (first drafts, merged by `ghoul-sfx.js`) |
| `public/activities/ghoul-rush/rides/hearse/ghoul-sfx-hearse.js` | The Midnight Hearse's own sounds as data (no imports): `HEARSE_SFX` with 19 first-draft `ghoulHearse<Act>` tones (none over 1.2 s) and the `ghoulHearseRide` track (a funeral march at a gallop, built from three four-bar parts); merged by `ghoul-sfx.js`, named in `ROOM_MUSIC`. Sounds and music still to be picked by ear |
| `public/activities/ghoul-rush/rides/sled/ghoul-sfx-sled.js` | The Coffin Sled's own sounds as data (no imports): `SLED_SFX` with an empty `tones` and `music` until the user picks them; merged by `ghoul-sfx.js` (the room plays the Graveyard's `ghoulGraves`) |
| `public/activities/ghoul-rush/rides/banister/ghoul-banister.js` | The Grand Banister (the Manor's bonus round) as a pack (`BANISTER`), modeled on the Coffin Sled: pack fields `ride`, `place` and `target`; state in the shared `round.runner` slot (id `banister`); YOU slide down a grand staircase's banister along `ride.track` (the first `rails` lines are the handrail, the breaks between them gaps to jump; the rest are brass under-rails beside it, the split track: a jump with DOWN held dives onto one, a jump off its end lands back on the handrail), vases and candlesticks to jump, hanging portrait frames to duck, chandeliers on a pendulum (`swingAt`: a wall from the bob to the roof, lethal to a ducking rider while the bob is mid-swing, so you brake or lean (LEFT/RIGHT) to time them or take the under-rail), ghostly butlers that lunge (jump or two bolts) and cobwebs to shoot. Adds no monster, boss or hazard kind; no random numbers. Its header documents the room fields |
| `public/activities/ghoul-rush/rides/banister/ghoul-banister-draw.js` | The Grand Banister's art: `LOOKS` (`pack: "banister"`), `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`, `telegraphMarks`/`telegraphs` (JUMP, DUCK and DIVE glyphs) and `banisterArt(d)` (damask wall, moonlit windows, a zig-zag of staircase flights, portraits whose eyes follow YOU, the rails, props, butlers and webs by `moving`; the hanging frames, the chandeliers with the arc they swing through, sparks and glyphs by `front`); no random numbers. Its header lists what the art reads off the rules |
| `public/activities/ghoul-rush/rides/banister/ghoul-sfx-banister.js` | The Grand Banister's own sounds as data (no imports): `BANISTER_SFX` with 14 first-draft `ghoulBan<Act>` tones (each under 1.2 s) and the `ghoulBanister` track (a harpsichord waltz at a gallop, built from three four-bar parts); merged by `ghoul-sfx.js` via `STAGE_SFX`, named in `ROOM_MUSIC` (sound and music picks still pending) |
| `public/activities/ghoul-rush/rides/wagon/ghoul-wagon.js` | The Torch Mob (Hollow End Village's bonus round) as a pack (`WAGON`), modeled on the Coffin Sled: pack fields `ride`, `place` and `target`; a hay wagon along `ride.track` (ditches and the collapsed bridge are the gaps, a rising line end a ramp), barrels and crates, washing lines and inn signs, villagers who hurl pitchforks (duck) and torches (jump), spooked horses, and the pursuit meter (`gap`: the mob runs at `MOB_V`, DOWN is a duck and the brake, a hit, a burning hay load and the surge close it, a shot torch or fork opens it, inside `PANIC_ON` the horses bolt, at `CATCH_GAP` it is a heart); its state is `round.runner` (`id: "wagon"`); draws no random number; imports the cart's track helpers |
| `public/activities/ghoul-rush/rides/wagon/ghoul-wagon-draw.js` | The Torch Mob's art: `LOOKS` (`pack: "wagon"`), `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`, `telegraphMarks`/`telegraphs` and `wagonArt(d)` (the sky, rooftops, street, cobbled road, ditches, the bridge and river, the things, the mob and the wagon by `moving`; the lows, throws in the air, the hay fire, glyphs and the mob's meter by `front`); no random numbers; imports the Sled's glyph colors and the rules' constants |
| `public/activities/ghoul-rush/rides/wagon/ghoul-sfx-wagon.js` | The Torch Mob's own sounds as data (no imports): `WAGON_SFX` with 18 first-sketch `ghoulWagon<Act>` tones and the `ghoulWagonRide` track (a D minor gallop built from three 4-bar patterns); merged by `ghoul-sfx.js`, the room's track named in `ROOM_MUSIC` (`wagon`) |
| `public/activities/ghoul-rush/story/ghoul-story.js` | Ghoul Rush's intro story: the pages' text as data and the rules (lockout, reveal, skip) as plain functions over a round; drawn by `ghoul-story-draw.js`, sounded by `ghoul-sfx-story.js`, the lore bible in `prototypes/Ghoul-Rush-TODO.md` |
| `public/activities/ghoul-rush/story/ghoul-story-draw.js` | The intro story's drawing (`storyArt(d)`): eight animated scenes in canvas shapes (the road, the house on the hill, the hunger, the long arms, the farthest rooms, why YOU, no way back, the door to The Long Hall) with the heading, the lines typing out, the page dots, the always-visible skip hint with its hold bar and the pulsing continue hint; drawn over the field while `round.phase === "story"`; reuses the intro card's helpers (`poly`, `dot`, `stroke`, `faint`, `flame`, `titleLayout`, `dropAt`); no gradients |
| `public/activities/ghoul-rush/story/ghoul-sfx-story.js` | The intro story's own sounds as data (no imports): `STORY_SFX` tones for the pages' `cues` (wind, a bell, a heartbeat, a door creak, knocks, a whisper, the flashlight click, the page turn) and the `hums` drone under the whole story; merged by `ghoul-sfx.js` |
| `public/activities/ghoul-rush/rides/gurney/ghoul-sfx-gurney.js` | Code Blue's own sounds as data (no imports): `GURNEY_SFX`, 18 first-pick `ghoulBlue<Act>` tones and the track `ghoulBlueRide`; merged by `ghoul-sfx.js` (the room plays it via `ROOM_MUSIC.codeblue`) |
| `public/activities/ghoul-rush/rides/tray/ghoul-tray.js` | The Servants' Back Stairs (the East Wing's bonus round) as a pack (`TRAY`), modeled on the Coffin Sled: pack fields `ride`, `place` and `target`; the track of shelves and stair flights with gaps, rolling pots and cutlery, hams and pans, cooks who fling dishes, the courses (silver domes and flying plates, seven is the grade's acts die), the cherries, grease stretches, checkpoints and the grade (3 to 9 dice). State is `round.runner` (id `tray`), the shared slot for a rolling bonus ride. Adds no monster, boss or hazard kind and draws no random number; every number is an exported constant documented in its header |
| `public/activities/ghoul-rush/rides/tray/ghoul-tray-draw.js` | The Servants' Back Stairs' art: `LOOKS`, `VOICES`, `EVENT_VOICE`, `LOSE_WORDS`, `LOSE_SOUNDS`, the telegraph glyphs (`telegraphMarks`, `telegraphs`: JUMP, DUCK, SHOOT) and `trayArt(d)` (the kitchen, shelves and stairs, things and cooks by `moving`; the tray, hams and pans, flour and glyphs by `front`); no random numbers |
| `public/activities/ghoul-rush/rides/tray/ghoul-sfx-tray.js` | The Servants' Back Stairs' sounds and music as data (no imports): `TRAY_SFX` with 13 first-draft tones and the `ghoulTrayRide` track; merged by `ghoul-sfx.js` |
| `public/activities/ghoul-rush/stages/chapel/ghoul-sfx-chapel.js` | The Chapel's own sounds as data (no imports): `CHAPEL_SFX`, its `tones` (the 35 picked `ghoul<Kind><Act>` sounds of the gargoyles, choir ghosts, monks, bell bats, the Choirmaster, the bell and Holy Water's splash) and `music` (`ghoulNave`, `ghoulTower`, `ghoulLoft`, `ghoulChoir`, named in `ROOM_MUSIC`), merged by `ghoul-sfx.js` via `STAGE_SFX` |
| `public/activities/ghoul-rush/stages/sanatorium/ghoul-sfx-sanatorium.js` | Blackmoor Sanatorium's own sounds as data (no imports): `SANATORIUM_SFX`, its `tones` (the 38 picked `ghoul<Kind><Act>` sounds of the orderlies, gurneys, flickers, specimen bloaters, the Night Matron, the lamps, Smelling Salts and the Bone Saw) and `music` (`ghoulAdmissions`, `ghoulBaths`, `ghoulTheater`, `ghoulWard`, named in `ROOM_MUSIC`), merged by `ghoul-sfx.js` via `STAGE_SFX` |
| `public/activities/ghoul-rush/stages/village/ghoul-sfx-village.js` | Hollow End Village's own sounds as data (no imports): `VILLAGE_SFX`, its `tones` (the 42 picked `ghoul<Kind><Act>` sounds of the torch mob, hanged men, shutter ghouls, moonhounds, the Beast, the full moon and Wolfsbane) and `music` (`ghoulStreet`, `ghoulInn`, `ghoulSquare`, `ghoulGreen`, named in `ROOM_MUSIC`), merged by `ghoul-sfx.js` via `STAGE_SFX` |
| `scripts/test-web-console-activities-ghoul-chapel.mjs` | The Chapel's suite: each monster, the bell toll and its freeze, Holy Water's splash, the Choirmaster's pipes, notes and rage, a voice for every act, each event playing exactly one picked sound, and every picked tone present in the merged tones and in `ghoul-sfx-chapel.js` |
| `scripts/test-web-console-activities-ghoul-sanatorium.mjs` | The Sanatorium's suite: the orderly's reach, hold and throw (and the Salts), the gurney's park, rattle, roll and rest and its floor, the flicker's unseen state, the lamps' timing, the specimen's jar and puddle, both power-ups (stage-only), the Matron's cone, heat, cabinets, syringes, arms and rage, endless lives for every new cause, and a voice for every act |
| `scripts/test-web-console-activities-ghoul-village.mjs` | The Village's suite: the rooms, the moonrise timing, the turn and the grow at full moon (and the per-room reset), the villager's group, torch and fire, the hanged man's drop, the shutter ghoul hit only while out, the moonhound, Wolfsbane (stage-only, double damage, shying), the Beast's wall leap, cling weak spot, pounce shadow, swipe, howl and its cap, the rage, endless lives for every new cause, no random draws, and a voice for every act and event |
| `scripts/test-web-console-activities-ghoul-mine.mjs` | The Mine's suite: the rooms and the cage rows, rockfall timing, aim and crush, the Hard Hat (stage-only, bounce), the imp's light steal (no life, ended by a shot or a stomp, blocked by the hat), the canary's scream and its three rocks, the miner's dig and swing, the blind crawler losing and hearing you (and the water's louder steps), water slowing you, the cage carrying Planny, Dynamite (a double tap, the bag, the blast), every Tommyknocker move including the dark, the decoy, the burst, the dazed double damage and the rage cap on imps, no random draws, endless lives for every new cause, and a voice for every act and event |
| `scripts/test-web-console-activities-ghoul-carnival.mjs` | The Carnival's suite: the rooms and the belts, grinners and their balloon cap, balloons and their acid, the marionette's drop and its string, Mirror You (the delay, the mirrored moves, jumps, its bolts and their canceling, stunned by a pie), the strongman, the circus hound (a swoop, duckable), Cotton Candy, the Custard Pie, every Ringmaster move (stalk, leap, charge, stomp, whip, the strings following, open, rage, hounds, the script), no random draws, endless lives for every new cause, and a voice for every act |
| `scripts/test-web-console-activities-ghoul-grounds.mjs` | The Grounds' suite: each monster's behavior, the shears, the Groundskeeper's moves and phases, a voice for every act, each event playing exactly one picked sound, and every picked tone present in the merged tones |
| `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 |
| `public/activities/ghoul-rush/arms/ghoul-arms.js` | Ghoul Rush's secondary weapons (imports only `ghoul-powers.js`; a pack in `PACKS`, `ARMS`): the double tap (`pressFire`, `releaseFire`, called from the game's `key()` and `release()`, never from `round.input.fire`, so bots never throw), the bag `round.arms` (`useArm`, `armOnTop`: a ride room skips what needs a floor), each weapon's rule (a shot with `arm` through `moveShots`, or a hazard), and `armBossDamage` (scaled to depth, capped at `ARM_BOSS_SHARE` of a boss's hp a fight). Weapons' names, bundles and caps are in `POWERS` (`arm: true`, weight 0), the stage's own in `STAGE_ARMS`, the kill drop band in `armDrop`, all in `ghoul-powers.js`. |
| `public/activities/ghoul-rush/arms/ghoul-arms-draw.js` | The weapons' art (`armsArt(d)`): their badges (`powers`), `hazards`, `shot` for one in flight, `pill` for the HUD's icon and count, `front` (stars over the dazed), `lights` and `react`. Dynamite's stick, blast and badge stay in `ghoul-mine-draw.js`. |
| `public/activities/ghoul-rush/arms/ghoul-rockets.js` | The Bottle Rocket's rules, the common weapon every stage sells: one use lights three rockets, one ahead, one up and one behind |
| `public/activities/ghoul-rush/arms/ghoul-rockets-draw.js` | The Bottle Rocket's drawing (`rocketArt(d)`): the muzzle's flash and smoke, the flared rocket on a stick with a glowing head, the fountain of sparks it sheds and the burst when it goes off |
| `public/activities/ghoul-rush/arms/ghoul-pans.js` | The Cast-Iron Skillet's rules, the East Wing's weapon: three pans that circle Planny, then spiral outward until they are off screen |
| `public/activities/ghoul-rush/arms/ghoul-sfx-arms.js` | The weapons' `tones` (`ARMS_SFX`), merged by `ghoul-sfx.js` like a stage's. A first pass, not yet picked by ear. |
| `scripts/test-web-console-activities-ghoul-arms.mjs` | The weapons' suite: the double tap through the keys (repeats, feathering, hammering), the bag and its pill, each weapon, bosses (scale, cap, guards, the half-hp drop), placement in every room, the drop band's single draw, ride rooms, drawing and sounds. |
| `public/activities/ghoul-rush/core/ghoul-run.js` | Ghoul Rush's run flow (no imports: `ghoul.js` hands its rules `RUN_KIT`, the room and stage tables, the timings and the helpers that set a room up, and binds them): `newRound`, `setupRoom`/`resetRoom`, the stage pick (`stagesLeft`, `nextRoom`, `steerPick`, `pickStage`), the stage select for testing (`openSelect`, `steerSelect`, `takeSelect`: a practice round, `round.practice`, that keeps no best score or record), `camera`, `respawn`, `lockArena`, `clearRoom`, and a room's monster supply (`spawners`, `horde`, `hurry`). `ghoul.js` re-exports `newRound`, `stagesLeft`, `steerPick`, `pickStage`, `steerSelect` and `takeSelect`, and its game answers `stageSelect()`. Split from `ghoul.js` to keep it under the 3,000-line cap, with the same random draws in the same order |
| `public/activities/ghoul-rush/core/ghoul-dice.js` | Ghoul Rush's Lucky die rules (no imports: `ghoul.js` hands them `DICE_KIT`): `MAX_DICE` (9, the most one bonus or ride pays; dice in hand have no limit), `ROLL_MS`, `TUMBLE_MS`, `SAVED_TIME_MS`, `markRest` (the last solid ground Planny stood on), `reviveSpot`, `beginRoll` (called by `lose` when `round.dice > 0` and not `round.infinite`: the round holds in the phase `ask` and asks "Use a Lucky Die?", the event `diceAsk`), `askStep`, `steerAsk`, `answerAsk` (Yes spends one die and holds in the phase `roll`; No keeps every die, the event `diceKeep`, and lets the loss go ahead; a press inside `ASK_GUARD_MS` is ignored so the key held at the death cannot answer), , `rollDice` (one die at a time from advance's `random`, events `diceStart`, `diceRoll`, `diceFace`, `diceSaved`, `diceFail`; a six revives with the Garlic shield and `SAFE_MS`, and blows apart every monster in view in a room without a boss (`diceBlast`, kills with `how: "luck"`, points but no drops); no six hands the loss back to `takeLife`) |
| `public/activities/ghoul-rush/core/ghoul-bonus.js` | Ghoul Rush's bonus rounds, the rules (imports only `MAX_DICE`; no random numbers): a room with `bonus: true` (the Runaway Cart; the Carnival's dark ride is meant to follow) gets `round.bonusRound = { hearts, max, dice, over, won, perf }` on entering it (null elsewhere; `round.bonus` is already the time bonus score). A life lost in it is a heart lost through the same `lose`/`takeLife` (so Garlic, the safe moment and `round.infinite` work as ever; no Lucky die is rolled for a heart); the last heart gone calls `endBonus(round, false)` from `respawn` (no dice, no game over, the run's lives untouched), and a finish alive calls `endBonus(round, true)` from `clearRoom` (`diceFor`: `BONUS_FLOOR` 3 plus up to 6 by hearts, clean obstacles, acts and a steady hand, added to `round.dice`, which has no limit). A room's pack notes its performance in `bonusRound.perf` (`total`, `hits`, `acts`, `goal`, `steady`); both ends hold the phase "clear" for the card (`CARD_MS`, `CARD_LOST_MS`) and set `bonusRound.result`. Events `bonusStart`, `bonusEnd`; `heartsText(b)` is the HUD pill |
| `public/activities/ghoul-rush/core/ghoul-bonus-draw.js` | The bonus rounds' art (`bonusArt(d, die)`): `card` ("BONUS CLEARED! +N LUCKY DICE" with the dice tumbling in, or the short "BONUS LOST"), `react` (the intro banner, the end, the hearts-left float) and `tick` (a click for each die landed) |
| `public/activities/ghoul-rush/core/ghoul-dice-draw.js` | The Lucky die's art (`diceArt(d)`: the small drop, the rolling die on a panel placed away from Planny, the `ask` panel ("Use a Lucky Die?" with YES and NO, the lit one gold), the sweeping "LUCKY-SAVE" word, and `react` for the dice events, which plays `ghoulLuckySave` once on the revive) |
| `public/activities/ghoul-rush/story/ghoul-gameover-draw.js` | The lost end screen's "G A M E - O V E R" (`gameOverBanner(d)`, `dropAt`): nine letters dropping in with a stagger and one bounce, then bobbing on a sine wave under a slow pulse, red and bone with a dark shadow, drawn above the score panel and never on a win. `ghoul.js` keeps ticking the clock on the lost end screen (`view.overMs`) and plays the mechanical laugh track there: `ghoulLaughTrack`, `ghoulLaughTrack2` and `ghoulLaughTrack3` in `ghoul-sfx.js`, one second apiece (a tone may not pass 1.2 s). |
| `public/activities/ghoul-rush/story/ghoul-intros.js` | The stage intro cards' words and colors: `INTROS` per stage id (`title`, `palette` {a, b, glow}, `kicker`, 3 or 4 `lines` of flavor text at most `MAX_LINE` characters, `boss`), `introFor(id)`. Always addressed to YOU. A test fails for a stage in `STAGES` with no card. |
| `public/activities/ghoul-rush/story/ghoul-intro-draw.js` | The intro card's drawing (`introArt(d)`, `titleLayout`, `dropAt`): the title's letters dropping in and glowing, one themed flourish per stage (frost crystals, bunting, pickaxe sparks, leaves, candle flames, ...), the lines fading in, the boss and the pulsing "Press any move key or fire to enter". Drawn over the field while `round.phase === "intro"`. The phase itself lives in `ghoul-run.js` (`startIntro`, `stepIntro`, `takeIntro`, `INTRO_MIN_MS` 1.2 s: any fresh move key, fire or a click moves on after it, repeats never, and the card never moves on by itself); the tone is `ghoulStageIntro`. |
| `public/activities/ghoul-rush/story/ghoul-boss-intros.js` | The boss intro cards' words: `BOSS_INTROS` per boss id (`name`, which must equal the boss's `name` in its pack's `bosses` table, an `epithet` of at most `MAX_EPITHET` characters and an optional `accent` color), `bossIntroFor(id)`. A test fails for a boss room whose boss has no entry. |
| `public/activities/ghoul-rush/story/ghoul-bossintro-draw.js` | The boss intro card's drawing (`bossIntroArt(d)`): a "BOSS FIGHT" title whose letters slam in with a screen shake and a heartbeat pulse, the boss drawn from its own art (`BOSS_ART`, the way the stage pick does) at a big scale in a spotlight on the stage's palette, its name, the epithet and the pulsing "Press any move key or fire to start the fight"; a boss whose art throws falls back to a silhouette. Drawn over the field while `round.phase === "bossintro"`. The phase lives in `ghoul-run.js` (`startBossIntro`, run by `enter` on every boss room, and `onCard`; it shares `introMs`, `stepIntro`, `takeIntro` and `INTRO_MIN_MS` with the stage card, and a respawn never shows it); the tone is `ghoulBossIntro`. |
| `public/activities/ghoul-rush/draw/ghoul-monsters-draw.js` | The generic monsters' art (`monsterArt(d)`, no imports; `ghoul-draw.js` hands it its helpers `ellipse`, `circle`, `line`, `rotate`, `turned`, `eye` and the colors): `drawZombie`, `drawZombieKin`, `drawHuntsman`, `drawCrawler`, `drawBat`, `drawGhost`, `drawSkeleton`, `drawGourdling`, `drawHound`, `drawSpider`, `drawWraith`, `drawSpitter` and the missiles `drawBoneShape` and `drawGlob`. Split from `ghoul-draw.js` to keep it under the 3,000-line cap |
| `public/activities/pills.js` | The pills every game but Mini golf draws along its top (no imports): `drawPill(ctx, x, y, w, h, text, color, fill, textY)` on one opaque dark backing, `PILL`, the same in light and dark and over any scene, a timer's share still left tinted at `PILL_TINT`, and the text in `pillInk(color, tinted)`: the pill's own color when it reads at `PILL_CONTRAST` (4.5:1) on the backing (and on the tint while a timer runs), else the least step toward white that does, so warnings stay red; lives are the one solid pill: a pill in the `LIVES` color is drawn on `LIVES_BACK` in white (`LIVES_INK`), its text from `livesText(n)` (a heart per life up to five, `♥ xN` past that, `♡` at none); `pillTint` and `pillContrast` for the unit suite |
| `public/activities/golf.js` | Mini golf: six eighteen-hole courses, one round at a time; its rules and physics as plain exported functions (`newRound(courseId)`, `holesOf`, `coursePar`, `strike`, `advance` on a fixed 4 ms sub-step, `nextHole`, `total`, `toPar`, `predictPath` for the spyglass, `moverAt`, `gateShut`, plus ice that barely slows the ball and wells that pull it in or push it away), the `POWERUPS` held for the next putt (`round.held`, then `round.active` for that putt), the arcade swing (`startSwing`, `setPower`, `meterAt`, `meterZone`, `swingShot`: a ping-pong power meter, slow at the bottom and fast at the top, with a MAX band that boosts and an overswing band that shanks; a shot clock in `advance()` that starts the meter after `SHOT_CLOCK_MS` and dribbles the ball after `METER_TRIPS` trips; all on the round's own clock), the pop-up gags, and the game contract with `pointer()` (the aim follows the pointer, a press swings, a press held on a roll fast-forwards), `release()` (held arrows turn the aim, held space fast-forwards) and `lowerIsBetter`, `courses` (the dashboard's cards), `preview(canvas, id, w, h)` (a course's card art) and `setCourse(id)`; deterministic (no `Math.random()`), a read-only `round` getter for the unit suite only |
| `public/activities/golf-draw.js` | Mini golf's drawing: `drawCourse(ctx, view)` from a plain view `golf.js` builds, each hole in its theme's fixed palette (`pirate`, `cave` with its darkness and glows, or a newer course's look from `golf-looks.js`, asked first for its grounds, water, tunnels, gates and wells), ice, the scorecard and banners in the course's voice, a bare view for the dashboard's card art, `knownGround`/`knownLiquid` for the unit suite, and `readColors(canvas)`, which reads the `--golf-*` properties `styles/activities.css` mixes from the tokens for the ball, pills and scorecard; decides nothing |
| `public/activities/golf-decor.js` | Mini golf's scenery and props for Pirate Cove and the Caves of Doom: each `decor` kind (sharks, ships, parrots, bats, torches, eyes, a dragon) on its layer, the looks of bumpers, movers and spinners, and the power-up icons, each asking the hole's course look first (`decorKinds(theme)` lists a theme's scenery); drawing only, moving with the round's clock |
| `public/activities/golf-holes.js` | Mini golf's courses: `COURSES`, the six eighteen-hole courses in dashboard order (Pirate Cove, Caves of Doom, Dino Valley, Candy Carnival, Cosmic Glow, Frosty Peaks), `courseById`, `HOLE_COUNT`, `FRONT_NINE`, `COURSE_W`, `COURSE_H` |
| `public/activities/golf-kit.js` | Mini golf's course kit, data only: `COURSE_W`, `COURSE_H`, the helpers course files build holes with (`pt`, `rect`, `wall`, `bump`, `pad`, `deco`), `hole(def, defaults)` (what a hole holds: theme, quip, ground, liquid, tee, cup, outline, walls, bumpers, sand, ice, water, slopes, wells, bridges, spinners, tunnels, movers, gates, powerups, decor) and `course()`, which freezes a course with its name, card line, cover hole and voice |
| `public/activities/golf-course-pirate.js` | Mini golf's Pirate Cove course: its eighteen holes and its `voice` (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only |
| `public/activities/golf-course-cave.js` | Mini golf's the Caves of Doom course: its eighteen holes and its `voice` (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only |
| `public/activities/golf-course-dino.js` | Mini golf's Dino Valley course: its eighteen holes and its `voice` (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only |
| `public/activities/golf-course-candy.js` | Mini golf's Candy Carnival course: its eighteen holes and its `voice` (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only |
| `public/activities/golf-course-space.js` | Mini golf's Cosmic Glow course: its eighteen holes and its `voice` (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only |
| `public/activities/golf-course-frost.js` | Mini golf's Frosty Peaks course: its eighteen holes and its `voice` (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only |
| `public/activities/golf-looks.js` | Mini golf's course looks by theme id, and the look contract (palette, liquids, grounds, rough, tunnel, lights, and the looks of bumpers, movers, spinners, gates, wells and scenery) |
| `public/activities/golf-look-dino.js` | How Dino Valley is drawn: its palette, ground, water, props and scenery; drawing only, moving with the round's clock |
| `public/activities/golf-look-candy.js` | How Candy Carnival is drawn: its palette, ground, water, props and scenery; drawing only, moving with the round's clock |
| `public/activities/golf-look-space.js` | How Cosmic Glow is drawn: its palette, ground, water, props and scenery; drawing only, moving with the round's clock |
| `public/activities/golf-look-frost.js` | How Frosty Peaks is drawn: its palette, ground, water, props and scenery; drawing only, moving with the round's clock |
| `public/activities/golf-paint.js` | Mini golf's shared canvas helpers (`polygon`, `circle`, `ellipse`, `radial`, `fill`, `stroke`, `line`, `label`, `turned`, `t`, `scatter`, `bounds`), no imports, so the drawing files and the looks share them without import loops |
| `public/app.js` | the page's entry and the only page file that starts anything: the start-up block. `index.html` loads it; it imports `screens/core.js` and the screens beside it |
| `public/doc-files.js` | a document as the page shows it, and as a file: blocks, Markdown and HTML download |
| `public/hops.js` | no imports: the hop rule, `startsClean(from, to)`, which says whether a hop from one workflow to another starts the new skill on a clean page (to or from the dashboard, into Git, or from one skill into another off a finished screen, but never out of Git or into Review); shared by `cmd-open.mjs`, `server.mjs` (its Ask reset) and `screens/core.js` |
| `public/looks.js` | how the page looks and sounds: the saved looks, their sync, and the preferences dialog's swatches |
| `public/mention-box.js` | the @name suggestions popover under a text box |
| `public/net.js` | the page talking to its own server |
| `public/palette.js` | the highlight colors, the sound events and the card widths, as data (importable by Node so a test can check every shade in both themes) |
| `public/render.js` | Markdown to DOM, safely: no HTML string is ever produced, only nodes built with `createElement` and `textContent`; also the shared page helpers (`el`, `md`, `copyButton`, `lightDismiss`) |
| `public/selectors.js` | what the page reads off its state: the questions, the finish, the scan, who has the ball |
| `public/send-state.js` | whether Send is available, and what its button says |
| `public/skills.js` | the skill list: every per-skill fact the console uses (card, order, start pose, launch scoring, subagent opt-in, which spec states light its card), data only, imported by the page and by Node; the older tables (`SKILL_CATALOG`, `START_POSES`, `CONSOLE_WORKFLOWS` and the rest, in `answers.js`) are lookups on it. Each entry also carries `weight` (what its launch and `run` score on the meter, or null), `started` and `ran` (the meter's labels for them, or null), `resume` (`"overview"`, `"folder"` or null: what the resume command takes after the skill's command) and an optional `card.help` (Help's line for the card when it differs from `blurb`). `WORKFLOWS` (every entry's workflow, in order) and `isWorkflow()` are what the CLI checks a `--workflow` against. The meter's `WEIGHTS`, `LAUNCH_LABELS` and `RUN_LABELS`, `resumeCommand()`, Help's card list and `cmd-help`'s workflow list are all derived from it, so a new skill is one entry here, not an edit to each of those |
| `public/sound.js` | the sound cues: which plays, one at a time, held until the first click |
| `public/spec-states.js` | the spec states (`diagnosed`, `fixed`, `exploring`, `mapped`, `planned`, `documented`, `building`, `built`, `unrecognized`): each one's picker label, the card it is the natural next step for and its recommendation, data only; which cards a state lights lives in `skills.js`, how a folder maps to a state in `classifySpec()` in `scan.mjs` |
| `public/state.js` | the page's shared state (`page.S` the server's truth, `page.local` what is staged) and the `redraw()` / save hooks every screen calls; defines only |
| `public/tones.js` | the activities' sound engine, all synthesized in the browser. Three parts: a shared kit of rich one-shot sounds (`RICH`: `layers` of parts played together, each a wave or a noise (`noise`, `pink`, `brown`) with its own `delay`, `gain`, `attack`, a sweeping `filter` and `vibrato`: `explode`, `smash`, `skid`, `whoosh`, `splashBig`, `fanfare`, `gameOver` and some fifty more, up to 1.2 s, at most `MAX_VOICES` parts sounding at once), held **hums** (`hum(id, name, level, pitch)`, called every frame a game wants it: oscillators and noise through one filter that follows the pitch, pulsed for an engine's strokes; a hum not asked for within `HUM_HOLD_MS` fades by itself, so a paused or closed game goes quiet without saying so, `hushTones()` quiets every one and the Activities window calls it whenever it stops ticking; at most `MAX_HUMS`; shared ones `car`, `toycar`, `electric`, `outboard`, `river`, `wind`, `cycle`, `fuse`, `haunt`, `squeal`, `meter`, `swarm`, `train`, `crowd`), and each game's own extras in `public/activities/<id>-sfx.js` (`{ tones, hums }`, plain objects, names prefixed with the game id, merged and frozen here; a name may be defined once across all of them, which `scripts/test-web-console-tones.mjs` checks along with every spec's shape and every name a game's source asks for). Everything plays through one compressor. The older single blips (`BLIPS`): `tone(name, level, pitch)` with an optional loudness from 0 to 1 and an optional pitch that scales every frequency, kept between 0.25 and 4, 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` and `flock-sfx.js` have `songs` instead of `music` |
| `public/activities/snake-music.js` | Snake's ten music tracks as data (no imports): `SNAKE_MUSIC`, `{ bpm, rush, voices, patterns, order }` each, named `snake<Place>` and listed in `MUSIC_TRACKS` in `snake.js`. A round deals them in a fresh order, one to each level, so a run hears a different track at every level and none twice. They were picked on the pages in `prototypes/music/snake` (rhythm-first folk and world tunes led by something plucked or reedy, mostly dark or modal), and their bars are not all sixteen steps: 6/8 is 12, 7/8 is 14, ten beats is 20, twelve beats is 24, each pattern a whole number of its bars; merged by `snake-sfx.js` |
| `public/activities/light-trails/1.mp3` to `5.mp3` | Light Trails' five background songs, named `trailsSong1` to `trailsSong5` under `songs` in `trails-sfx.js` and listed in `SERVABLE`; re-encoded for size with ffmpeg (80 kbps stereo MP3 at 44.1 kHz, loudness-normalized to -16 LUFS with `loudnorm`, metadata stripped), about 7.6 MB together, and copied into every skill with the rest of the console. The server leaves them out of its start-up cache warm |
| `public/activities/flock-dash/1.mp3` to `5.mp3` | Flock Dash's five background songs, named `flockSong1` to `flockSong5` under `songs` in `flock-sfx.js` and listed in `SERVABLE`; re-encoded for size with ffmpeg the way Light Trails' were (80 kbps stereo MP3 at 44.1 kHz, loudness-normalized to -16 LUFS with `loudnorm`, metadata stripped), about 6.4 MB together, and copied into every skill with the rest of the console. The server leaves them out of its start-up cache warm; `flock.js` deals all five in a fresh order each round with `dealMusic()`, plays each in full one after another and deals again after the last, never opening on the song that just ended |
| `public/activities/ghoul-rush/stages/graveyard/ghoul-sfx-graveyard.js` | The Graveyard's own sounds as data (no imports): `GRAVEYARD_SFX`, its `tones` (the picked `ghoul<Kind><Act>` sounds of the grasping hands, mourners, grave robbers, rotters and their legs, carrion crows and Mother Mourning) and `music` (`ghoulLychgate`, `ghoulGraves`, `ghoulMausoleums`, `ghoulAngel`, named in `ROOM_MUSIC`), merged by `ghoul-sfx.js` after the house's own. Every new stage gets its own `ghoul-sfx-<stage>.js`, listed in `STAGE_SFX` there |
| `public/activities/ghoul-rush/stages/grounds/ghoul-sfx-grounds.js` | The Grounds' own sounds as data (no imports): `GROUNDS_SFX`, its `tones` (the 32 picked `ghoul<Kind><Act>` sounds of the topiary beasts, rootlings, lantern moths, mulch crawlers, the Groundskeeper and the Hedge shears' snip) and `music` (`ghoulMaze`, `ghoulTopiary`, `ghoulGazebo`, `ghoulYard`, named in `ROOM_MUSIC`), merged by `ghoul-sfx.js` after the house's own via `STAGE_SFX` |
| `public/uploads.js` | pictures and documents attached to a note: chips, trays, re-encoding, upload, retry, and the page's shared full-screen picture preview (`openPicview`, the `#picview` dialog every thumbnail opens) |
| `public/screens/ask.js` | the Ask chat, the Subagents tab, and attaching files to notes |
| `public/screens/cards.js` | question cards: every kind, the pager, settled and in-flight records |
| `public/screens/cleanup.js` | User Preferences' Cleanup section, on the System tab |
| `public/screens/core.js` | the core every screen sits inside: connection, the render loop, the page chrome and Send; the only file that imports the screens, and only `app.js` imports it |
| `public/screens/dashboard.js` | the dashboard: cards, the spec picker, handoff chips, delete, and the first-open wake-up |
| `public/screens/loop-setup.js` | the Implementation Loop's setup screen on the dashboard (app only): the fields, their defaults and read-only facts, the Start checks, and the request to the app. The page locks while `state.loop.driving` is set (`loopDriving()` in `selectors.js`) until the app posts `loopEnd`; Activities, Notebook, Help and Preferences stay usable. `loopEnd.can` accepts `ask` (`LOOP_CAN` in `patches.mjs`); the app adds it first to every stop that offers `resume`, and the stopped screen's **Ask a question** wakes an ordinary agent on the same session |
| `public/screens/docs.js` | documents: tabs, blocks, print and download, and the brief button |
| `public/screens/ending.js` | how a session ends: the finished screen, its offers, Stop and the way home |
| `public/screens/git-host.js` | hosts the git board: tabs, panels and what each click sends |
| `public/screens/help-dialog.js` | the Help dialog and the first-run Welcome (named so it is never confused with the pure help.js). Help reads right in both modes: a phrase that differs under the desktop app carries its app wording in `data-app` (swapped in by `renderAppWording()`), and a paragraph that differs is a `.for-browser` / `.for-app` sibling pair, switched by `:root.in-app` (set in `core.js` from `page.inApp`, rule in `help.css`). The older `render*Help()` functions patch a few ids the same way. `scripts/test-web-console-page-help.mjs` sweeps every topic's visible text in each mode for the other mode's wording |
| `public/screens/looks.js` | User Preferences: the look and sound controls, which save as they change |
| `public/screens/agents-view.js` | the agents view's mount, state and server calls, serving both User Preferences' Agents & models tab and the setup page as a master-detail split: the pickable list on the left, the picked agent's form or state in the right pane. Picking a row is the navigation; a dirty form asks the dialog's unsaved prompt first. Each form edits a draft; Save sends the saved list with only that draft swapped in (`POST /models` or `POST /agents`), Discard drops it. `hasUnsaved`, `saveOpen` and `discardOpen` feed the dialog's unsaved prompt. `mountAgentsView(container, {mode, forCli, onStart})` hands its renderers one `ctx` (state plus callbacks); `mode: "prefs"` draws the agent rows with Found / Not found on PATH badges and a v3 orchestrator placeholder, `mode: "setup"` draws the pick list (found / outside-PATH / missing states, install lines, Use it from here, templates, Start) inside a caller-supplied container |
| `public/screens/agents/agents-data.js` | PURE, no imports, `node --test` importable: the agents view's data helpers. `MODEL_CLIS`/`BUILT_IN` (the built-in rows, pinned to `src/launcher/agents.json` by a test), `emptyLists`, `newAgent`, `normalizeAgent`, `cliOf`/`agentId` draft keys, `savedEntry`, `canonical`/`isDirty`, `nameOf`, `modelNames`, `summaryRows`, `serverStateFor`, `cleanAgent` and `templateDraft` |
| `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 |
| `public/screens/workspace.js` | the read-only Workspace of extra folders, and @mentions |
| `public/styles/ask.css` | The Ask pane and its Quick question chat |
| `public/styles/dashboard.css` | The dashboard: the menu, the spec picker, its confirm and the launching pane |
| `public/styles/docs.css` | Documents and the doc tools |
| `public/styles/ending.css` | The end of a session: the hand-off and the stopping screen |
| `public/styles/git.css` | The git board |
| `public/styles/help.css` | The help dialog, its diagrams and its tabs |
| `public/styles/looks.css` | The looks button and the highlight swatches |
| `public/styles/prefs.css` | User Preferences' side list of tabs, the strip below 720 px, the Saved mark, the setup screen's own chrome, and the in-dialog unsaved prompt (new classes only: the Subagents dialog shares `.looks`) |
| `public/styles/agents.css` | the Agents & models view: the master-detail `.split` (list column, pickable `.split-row`s with `aria-current`, the `.split-pane`), badges, the form's fields, folds and foot, the models lists, the setup pane's state area, and the under-720 px single-column treatment |
| `public/styles/pieces.css` | Shared pieces: cards, options, settled answers, pager, forms, checklist, markdown and the modal |
| `public/styles/planny.css` | Planny the mascot: the flight, his moods and variants, and the wake-up |
| `public/styles/poses.css` | The start-screen poses, one per skill. After the dashboard on purpose: its narrow-window rules override the dashboard's |
| `public/styles/responsive.css` | Print, then the narrow-window rules: last, so its overrides come after everything they override |
| `public/styles/shell.css` | The page shell: banner, top bar and meter, layout, sidebar, aside, footer, waiting and arrival |
| `public/styles/tokens.css` | Colors, type, sizes and the light and dark themes: the variables every other file reads |
| `public/help.js` | the Help dialog's PURE rules: `HELP_TABS` (20 tabs: ids, order, labels, diagram flags; every tab uses the chosen highlight color; Implementation Loop sits right after Watching a build, The git board right after it, and Activities right after Ask a quick question), `helpTabFor()` (which tab opens, FR-8 order, first match wins: finished → Stopping and finishing, server gone or agent adrift → When something looks stuck, opened from the Workspace dialog → Your workspace, then Ask, the Subagents tab → Helpers (subagents), a red-meter dashboard → Session meter, dashboard, a doc or the Overview, a git session → The git board, a build, else What this page is) and `helpKeyTarget()` (roving arrow keys, Home, End, wrapping; a re-export of `tabs.js`'s `tabKeyTarget`). No module-scope DOM, so `node --test` covers it |
| `public/tabs.js` | the WAI-ARIA tabs shared by Help and User Preferences: `wireTabs()` (buttons and panel links, roving tabindex, automatic activation, `aria-orientation` switching at 720 px, an optional `beforeSelect` guard) and the pure `tabKeyTarget()` |
| `public/prefs.js` | User Preferences' PURE rules: `PREFS_TABS` (Appearance, Agents & models, System, Sounds & activities, with hints and the sections each holds), `prefsOpenTab()` and `prefsResetScope()` (the looks keys Back to default resets per tab, or null) |
| `git-repo.mjs` | the one read-only reader of a git repository: the worktree status (`countPending()`, behind `pendingFiles()`), the branch table, the default branch, a merge or rebase in progress, the remotes and their web addresses, the last fetch and the pull-request link; `snapshot()` is what `open` and every `reread` store as `state.git`. Every git call carries `GIT_OPTIONAL_LOCKS=0`, so a background look never takes the index lock. Imported by `cmd-open.mjs`, `cmd-post-wait.mjs` and `sessions.mjs`; the git skill's `git.mjs` reaches it through `common.mjs` |
| `public/git-board.js` | PURE, one import (`pr-url.js`): the git board's rules from a `state.git` snapshot: branch order and the Remote only fold at `REMOTE_FOLD` 50, whether a new branch name is free, which buttons show and are enabled, whether the board still waits on the agent (`boardAwaiting()`: from a click until the agent's next post, not just until `wait` collects it), the plain sentence each click sends as `reply`, the "Last refreshed" line, which files start ticked in the commit dialog, and the pull-request link; the next step (ten rules, `nextStep()`), the tab that owns it, per-tab badges (`tabBadges()`), the busy mode and per-control gate (`busyMode()`, `controlAllowed()`), the tab to show (`pickTab()`), and the create-panel sources and clean-up groups. `app.js` only renders what it says |
| `public/git-board-view.js` | No DOM access of its own: `drawGitBoard(ctx)` draws the tabbed board (header, tab strip with Done with git, the card slot, step strip, Changes / Branches / Sync) from the helpers it is handed (`el`, `md`, `copyButton`), every control through one gate; `screens/git-host.js` hosts it, and `scripts/test-web-console-git-board.mjs` drives it with a recording fake `el` |
| `public/pr-url.js` | PURE, no imports: `prUrl()`, the "open a pull request" link for the GitHub, GitLab, Azure DevOps and Bitbucket shapes (`null` for an unknown kind, no web address, or a non-https result). `git-repo.mjs` re-exports it, and the board's base picker rebuilds the link in the browser with the same code |
| `public/workspace.js` | PURE, no imports: the Workspace's name rules (`nameProblem()`, `NAME_MAX`, `defaultName()`, `freeName()` for the `-2` suggestion), the footer label and its width tiers (`footerLabel()`, `FOOTER_TIERS`) and `changeLine()`, the `Workspace: …` reply line an agent is handed per change. Imported by the server, `cmd-chat.mjs`, `cmd-post-wait.mjs`, `workspace.mjs` and the page |
| `public/meter.js` | PURE, imports only `skills.js`: the session meter. `WEIGHTS` (the events that are not a skill's own launch, merged with each skill's `weight` from `skills.js`; its keys are also `RUN_EVENTS`, the `run` events `post` accepts), `LAUNCH_COUNTED` (workflows whose launch itself scores), the built-phase sizing (`TASK_EVENTS`, the keys of `TASK_BONUS`: `implement-phase` +0 and `implement-review-phase` +1; `isTaskCount()` accepts a whole `tasks` from 1 to `MAX_TASKS` 999; `runPoints()` scores such a run `ceil(tasks / TASKS_PER_POINT)` (3) plus its bonus, and any other run its `WEIGHTS` value), `ANSWERS_PER_POINT` 2 (`answer` entries score per skill run, `floor(count / 2)`), `breakdownFrom()` (the click-the-ring list: one row per scoring entry plus one answers row per skill run), `pointsFrom()` (the count, its sum, folded from `ledger.ndjson` and deduplicated by id, never stored), `levelFor()` with `YELLOW_AT` 5 / `RED_AT` 10, `ringFraction()` (full at `RING_FULL` 15), `WORDS`, `tooltipFor()`, `RED_BANNER` and `meterView()` |
| `public/mentions.js` | PURE, no imports: the `@name` popover's logic — `mentionAt()` finds an `@partial` at the caret, `matchNames()` filters the workspace names, `applyMention()` splices a pick in and returns the new caret. Used by the Ask box, notes and text answers |
| `public/favicon.js` | The tab icon's status bar. `faviconState({ mood, spin })` (PURE) maps the call `renderStatus()` makes for Planny's line to `busy` (the spinning ring), `ready` (`point`), `attention` (`adrift`, `gone`, or `work` without the ring — the stale line) or `plain` (`done`, `happy`); a finished screen gets no special case, so one still offering a press points and lights `ready` (the desktop app's taskbar dot follows), a stranded press is `attention`, and only all done or paused is `plain`; `faviconSvg()` is `FAVICON_BODY` (kept equal to `favicon.svg` by a test) plus a bar along the bottom edge in the `FAVICON_COLORS` color (busy dashed on a white strip, so the states differ by pattern; the rest solid); `setFavicon()` swaps both `<link rel=icon>` hrefs only on a change — the SVG as a data URL, the PNG link drawn through a canvas. Called from `say()` in `renderStatus()`, which runs every second |
| `public/continue-button.js` | The one control that wakes a quiet agent. `continueButton(label, cls)` is a button asking the app for `agent-continue` (held off 4 s after a press); `reconnectOffer(cls)` is that button labeled **Reconnect to agent** under the app and, in a browser, a line telling the person to type `continue` in their terminal. Used by the status line (`screens/core.js`: the dashboard's quiet, launch-saved and way-home-saved lines), the Ask tab (`screens/ask.js`, left of Send while the red no-agent line shows) and the saved-and-waiting launch screen (`screens/starting.js`, app only; a browser reads the hint). |
| `public/app-bridge.js` | The messages the page posts to the desktop app that frames it. `framed()` is true inside a frame; `tellApp(kind, extra)` posts `{ plan2code: kind }`, a named request with no free text: `looks` (the highlight's dark shades, from `applyLooks()`, for the app bar's buttons), `agent-continue` (the in-app **continue** button on the Not running line: the app types the keystrokes `continueKeys()` in `plan2code-app/ui/meter.js` names into the agent's terminal, `continue` and Enter, then under Claude Code its send-now chord ctrl+x ctrl+s, so a word queued behind a stuck turn is delivered), `terminal-open` (the in-app **terminal** button, shown in place of the word in every What to check line while the app's terminal panel is collapsed: the app presses the panel's own Collapse/View button, and only when collapsed; the app tells the page the panel's state with `terminal-state` `{ collapsed }` on the page's `console-ready` and on every change, heard through `onAppMessage` into `page.terminalCollapsed`), `new-session` (the meter popover's New Session: the app presses its own bar button, confirm and all) and `activities-full` (`{ on }`, an Activities game going in or out of full screen: the app lays the console's frame over its bar and terminal and puts the window in full screen, and out of it only if it put it there; `taskbarSwitch()` checks the boolean, and the window permissions are in `capabilities/default.json`). Nothing outside a frame |
| `public/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table, one entry per non-null `subagents` field in `skills.js`, each with its default instruction), `cleanSetting()` (`{ on, instruction, max, strength }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20, `strength` not one of `STRENGTHS`; `strength` is `balanced`, `thrifty`, `best` or `session`, missing reads as `balanced`, saved per project and skill in each `subagents.json` entry and sent as a `Helper strength:` line in the "on" block), `FRAME_LINES`, `blockFor(setting, told)` (the `Subagents:` lines and `subagents` field an agent is owed, given the session setting and its cursor; never says "off" to an agent not told "on"), `checkHelper()` / `checkHelpers()` (the `helpers` house rule) and the page's view rules `showSwitch()`, `switchLabel()`, `helperRows()`, `showTab()`, `CHECKIN_LINE`. Imported by the server, the `cmd-*.mjs` files, `patches.mjs`, `settings.mjs`, the page and the tests; in `SERVABLE` and preloaded |
| `handoffs.mjs` | the handoff store, the only code that names, lists, marks, deletes and sweeps handoffs, all in `~/.plan2code/handoffs/` (`PLAN2CODE_HANDOFFS_DIR` for tests; `PLAN2CODE_NOW` pins its clock): `newHandoff()` claims `YYYY-MM-DD-HHmm-handoff` (`-2`, `-3` on a clash, the `.json` created exclusively) and writes only `<id>.json` (`{ v: 1, id, title, worktree, project, spec, workflow, skill, written, fromStop, usedAt }`), the agent writing `<id>.md`; `listHandoffs(worktree)` (unused, same worktree, `.md` present, newest first, title and Next task read off the document); `readHandoffMeta()`, `markHandoffUsed()`; `removeHandoff()` (`HANDOFF_ID` only, regular files, never a link, realpath inside the folder, throws on any refusal); `staleHandoffs()` / `removeHandoffs()` for the sweep |
| `notepads.mjs` | the notebook store (the feature is named Notebook; its code, routes and storage folder keep the name `notepad`), the only code that names, reads, writes and removes notebooks, one per folder Plan2Code runs in, in `~/.plan2code/notepads/<folder-name>-<12 hex>/` (`PLAN2CODE_NOTEPADS_DIR` for tests), split into named tabs: `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order, last, tabs: { id: { name, created, sent? } } }`) and `tabs/<id>/note.md` with `tabs/<id>/images/`. `notepadKey()` (the folder's basename slug and the first 12 hex of `sha256(foldKey(folder))`), `listTabs()` / `defaultTabId()`, `readNotepad(folder, tab)` (never creates or writes anything; `{ tabs, last, tab }` with the tab's `text`, `savedAt` and `images` repeated at the top), the tab changes `createTab()` / `renameTab()` / `reorderTabs()` / `setLastTab()` / `deleteTab()` (index first, then the folder; names pass `normalizeTabName()`, `TAB_NAME_MAX` 40, any case compared by `nameKey()`, `NOTEPAD_MAX_TABS` 20), `saveNote(folder, tab, text)` (1 MB cap, atomic), `addImage()` / `addThumb()` / `removeImage()` (JPEG bytes only, 200 pictures per tab, UUID names), `imagePath()` (regular files whose realpath stays inside the folder), `staleNotepads(now, maxAgeMs)` (the real folders directly under it named like a key, never a link or a file, whose newest file is at least `maxAgeMs` old, as `{ key, folder, path }` with `folder` from `meta.json` or null), `removeNotepad(key)` (the key checked against `NOTEPAD_KEY_RE`, the path kept inside the notepads folder by `path.relative`, a link refused, then the whole folder removed; User Preferences, Cleanup is its only caller) and `NotepadError` (`code` and `status`, turned into `{ error }` by the `/notepad` routes). **Migration:** a notepad in the first shape (`note.md` and `images/` at the top) reads as one virtual tab, Notes (`LEGACY_TAB_ID`), and writes nothing; its first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, every step safe to run again after a crash. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders on the next write. Every write runs under a `notepad.lock` in the notepad's folder. The agent CLI never imports it: nothing in a notepad reaches the agent |
| `public/notepad.js` | PURE, no imports: the Notebook's rules. `SAVE_DEBOUNCE_MS` 800, `RETRY_STEPS_MS` (1 s up to 30 s), `NOTE_MAX_BYTES` / `NOTEPAD_MAX_IMAGES` / `TAB_NAME_MAX` / `NOTEPAD_MAX_TABS` / `IMAGE_ID_RE` / `TAB_ID_RE` (kept equal to `notepads.mjs` by a test), `noteBytes()`, the save-state reducer `nextSave(state, event)` from `SAVE_START` (states `idle`, `pending`, `saving`, `saved`, `failed`, `too-long`; it returns the timer to arm), `saveStatus()` (the status line's words), `unsaved()` (what `beforeunload` asks on), `keepsText()` (unsaved or too long: a reopen never replaces the editor's text then), `tabSwitch()` (whether leaving a tab must save it first), `NOT_LOADED`, `EDITOR_NOT_LOADED`, `errorSentence()` (one sentence per `/notepad` refusal, else a lost connection), the tab rules `cleanTabName()`, `nameTaken()`, `tabNameProblem()`, `moveTab()`, `dropTab()` and the two-confirm delete `nextDelete()` / `DELETE_STAGES`, and `step()` (wrapping through the pictures) |
| `public/screens/notepad.js` | the Notebook: `#btn-notepad` in the top bar on every screen (disabled while the server is gone, `renderNotepadButton()` in the render pass), `#notepad-modal`, the one CodeMirror editor (made on first open by a dynamic import of `notepad-editor.js`), the page's view of the notepad as `{ tabs, activeId }`, the name form (New tab and Rename, never `window.prompt`), the in-modal two-step delete, and autosave through `nextSave()` to `POST /notepad/text?tab=<id>`, flushed on close, when the page is hidden and before a switch. The editor stays read-only until the first read lands, so nothing typed into an empty editor is saved over a note. **Every save and every picture is bound to the tab it was made in**: `saveTab` is fixed when the change is made, a picture entry carries its `tab`, and a switch waits for the save (`settled()`), stays put with "Not saved yet, so staying on this tab." when it cannot, and drops a deleted tab's unsaved text without sending it |
| `public/screens/activities.js` | Activities: `#btn-activities` (the die right of the megaphone), `#activities-modal`, the one frame timer (`requestAnimationFrame`, swappable with `setTickSource()` for the page tests), the keys (arrows, W/A/S/D, space, P, Esc; stopped at the dialog so none reach the page behind; `CHEAT_CODE`, typed on a game's board, turns on endless lives through the game's `cheat(on)` until the round starts over, and `dropCheats()` turns it off on leaving for the picker or closing; `STAGE_CODE`, the same arrows then S, calls the game's `stageSelect()` where it has one, Ghoul Rush's practice stage select) and `pauseAll()`, which a new question, a finish, a hidden page, a window blur and a close all go through and which never resumes a game (it also sends a pointer game a cancel, dropping a drag). Canvas pointer events (down, move, up, cancel, with pointer capture) go to a game with `pointer()`, and key releases to a game with `release()`; a press on a paused board resumes without starting a drag. While paused, any game key or a board click resumes, except while a round is `held`: a question or finish that pauses a round on an open window holds it, the banner adds `#activities-unpause` (**Unpause game**) beside **Go to it**, and only that button plays on (`play()` refuses a held round), since a key or click already on its way used to dismiss the banner unread. Go to it, or closing the window any other way, lets the hold go, and a banner with nothing left to say drops it. Every start and play-on first counts down 3, 2, 1 (`COUNT_FROM`, 700 ms a number, `setCountdownMs()` for the page tests, which set 0 unless they test it): the game is already `running`, the frame timer just does not tick it, and game keys, overlay clicks and board presses wait, while P and Esc still pause. With two or more games listed the window opens on the picker (`view`: `"picker"` or `"game"`, `applyView()`): a card button per game (`drawPicker()`, covers in `COVERS` drawn as SVG with `cv-*` token classes, since the page's policy refuses a style attribute) with its blurb, best and a **Last played** or **Round paused** tag, arrows walking the cards (`moveFocus()`), and `#activities-back` (**All games**) back to it. One game at a time: `pick()` drops the last game from `games` when another is picked, and `openActivities()` goes straight back into a paused round. The last pick is kept as `lastActivity` and gets the focus; `lowerIsBetter` games keep the lowest round as the best; the header shows the current game's best (`paintTitle()`). `renderActivities()` in the render pass compares `myTurn()` and `finish()` with the last render and shows the banner with **Go to it**. Loads a game with `import()` when it is picked and keeps it until another is picked; `setActivityList()` lets a test list a stub second game, which brings up the picker |
| `public/notepad-tabs.js` | the tab bar: `createTabs({ onSwitch, onChange })` with `draw(tabs, activeId)` (`role="tab"` buttons, roving `tabindex`, arrow keys, Alt+arrows to reorder, F2 and double-click to rename, native drag and drop with an `.is-drop-before` mark that only a tab drag lights, focus kept across redraws, `#notepad-empty` and `#notepad-body` toggled) and `focusTab()`. No fetches: it calls back, and `screens/notepad.js` owns every request |
| `public/notepad-editor.js` | the Notebook's live-preview editor on CodeMirror 6 (`makeCodeMirrorEditor(parent, { onChange, label })` returning `{ getValue, setValue, setReadOnly, focus, destroy }`). A `ViewPlugin` decorates only the lines in view from the Markdown syntax tree: heading line classes `cm-h1` to `cm-h6`, bullets drawn as a widget, the marks around bold, links, quotes and a heading hidden on every line the selection is not on. The editor sits in a shadow root (`.notepad-cm-host`), because CodeMirror writes its rules as a `<style>` element, which `style-src 'self'` refuses, and adopts them as a constructed stylesheet inside a shadow root. `setValue()` is `setState()`: not reported through `onChange`, and the undo history is cleared (so each tab starts with a clean one) |
| `public/notepad-editor.css` | the one stylesheet of that shadow root, linked from `notepad-editor.js` (a `<link>` inside the root, in `SERVABLE`, not in `CSS_ORDER`): heading sizes, bullets, quote, code and link looks on the console's tokens (custom properties inherit across the boundary, so both themes work). Rules that meet CodeMirror's own base theme use `div.cm-editor` for the specificity |
| `public/vendor/codemirror.esm.js` | CodeMirror 6 (state, view, language, commands, lang-markdown, MIT), bundled into one minified ES module by `scripts/vendor-codemirror.mjs` (sha256 `4ff96d58fc1a5497eb933426bd2d160d2fb0cf490de8bb9302c304096c71c1d4`, the six top-level versions in the script and the file's header comment, everything they pull in pinned by `scripts/vendor-codemirror-lock.json` and installed with `npm ci`, so the same lock gives the same bytes). Never edited by hand: change a version in the script and run `node scripts/vendor-codemirror.mjs --update-lock` (needs npm and network; the packages install in a temp folder, never in the repo), or without the flag to rebuild from the lock |
| `public/styles/notepad.css` | the notebook's own rules: the top bar button, the dialog, the tab bar and its tools, the name form, the delete question, the empty state and the pictures. The editor's look is `notepad-editor.css`, inside its shadow root |
| `public/styles/activities.css` | the Activities rules: the die in the top bar, the Notebook-sized dialog, the board and its state overlay, the your-turn banner in the highlight color, the picker and the notes |
| `picker.mjs` | the per-OS native folder picker behind **Browse…** (`pickerCommand()` → `{ command, args, env }` or `null`; `pickFolder()` runs it with async `spawn`, so the server keeps serving while the dialog is open). Copied from `src/launcher/plan2code.js` (self-contained CommonJS, so it cannot be shared) with the prompt as a parameter; a drift test keeps the two in step |
| `update-check.mjs` | the dashboard's release check, server-only (never in `SERVABLE`): `compareVersions()` (numeric X.Y.Z, `null` otherwise), `latestTag()` (the highest `refs/tags/vX.Y.Z`, peeled `^{}` and pre-release tags skipped), `checkForUpdate({ installed, cacheFile, now, run })` (never throws) and `runLsRemote()` (`git ls-remote --tags` on the repo: no shell, `GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`, SSH `BatchMode` when `GIT_SSH_COMMAND` is unset, `windowsHide`, killed at 10 s; git authenticates itself, the console never touches a credential). The answer, failures included, is cached for an hour in `~/.plan2code/console/update-check.json` (`UPDATE_CHECK_FILE`, in `PROTECTED_CONSOLE_FILES` so no sweep removes it). `server.mjs` starts it after the ready line and never awaits it; `stateFrame()` carries `update: { installed, latest }` only when a newer release exists (its `latest` is part of `haveKey()`, so a page that connected first still gets it), and `GET /version` returns `{ version, latest }`. Tests seed a fresh cached failure in every console home, so no test server reaches the network. The `plan2code` launcher reads the same cache for its terminal release notice (a copy of this module sits in `~/.plan2code/bin/`) |
| `public/chat.js` | the Quick question chat's PURE rules, shared by the server and the page: `CHAT_LIMIT` / `CHAT_MAX_CHARS` / `CHAT_MAX_ATTACHMENTS` (the combined image + document cap; `CHAT_MAX_IMAGES` is kept as an alias of it), `chatOffline()` (the server's `409 offline` guard), and the page's view model (`chatView`, `sendState`, `nextAbout`, `contextOptions`, `unreadDot` / `shouldChime`). Ask context is the `{ history, about }` model: `nextAbout()` records the last 3 places visited in `history` and sets `about` only when the person picks one from **+ Add context** (`contextOptions()` lists that history plus *This spec*); dropping it or a successful send clears it, so the page never attaches context on its own. Imports only `answers.js`, no module-scope DOM, so `node --test` covers it |
| `public/starters.js` | PURE, no imports: the Role list (`ROLES`, `ROLE_NOT_SET`, `normalizeRole()`, `needsRoleNudge()`: the dashboard banner shows until `looks.json` carries any `role`), the 19 starter templates (Markdown `## heading` sections, shape pinned by a test) and their per-role orders (`TEMPLATES`, `TEMPLATE_ORDERS`, `templatesFor()`, `templateSwap()` for the replace prompt), and the Ask starter sets (`STARTER_SETS`, `STARTER_SET_FOR`, `startersFor()`). Imported by the page's looks and screens and by the tests; in `SERVABLE`, preloaded by `index.html` and parse-checked. The page owns the wording; a skill only flags its fresh-idea `text` card with `"templates": "idea"` |
| `public/answers.js` | the page's PURE answer-shaping logic (what an answer reads as, what a placeholder offers, whether a send carries an answer at all). Kept out of the page's entry because `app.js` cannot be imported outside a browser, so anything left in it is untestable. The `scripts/test-web-console-*.mjs` tests import it directly. |
| `public/labels.js` | `taskLabel()` / `activityLabel()`: rewrites a build's `Task 4.2 of 6` activity line to `Task 2 of 6` (only for `implement` / `implement-review`; a plan's `Task 2.1` is a real section number). A separate module for the same reason as `answers.js`: pure, so `node --test` can import it |
| `public/boot.js` | `playWake()`: the dashboard's first-open wake-up. Self-contained (it owns its timers, the listeners that swallow input mid-run and the one measured glide transform; the page's `stir()` callback times the nudge between the click and the boot, which `screens/dashboard.js` fills with one snore; `skipEl` — the muted Skip button, and Escape — ends the run early with `onSkip` as the cue to silence queued sounds) and free of module-scope DOM access, so it can be imported by the tests and kept out of the screens' render paths; `GLIDE_AT_MS` / `DONE_AT_MS` are its timings |
| `console.md` | the core of the agent-facing contract, read once per conversation (every skill ships the same copy, so a dashboard hop never re-reads it): starting, the turn (`post --wait`, the exit codes, handling a send, `settle`), posting, the payload and its kinds, documents (including `file` blocks), the house rules, and an index of the topic files below with the moment each is read. A test caps it at 24,000 characters |
| `console-finish.md` · `console-stop.md` · `console-chat.md` · `console-workspace.md` · `console-subagents.md` · `console-launches.md` · `console-meter.md` · `console-attachments.md` · `console-trouble.md` | topic files, each read only when its moment first comes: finishing (the finish and its buttons), stop requests (the way home mid-workflow, `stopWarning`, resuming a pause), Quick questions, the Workspace, standing instructions and helper reports, dashboard launches and the menu payload, the session meter's `run` events (read only when a `run` is refused: the notes inline every `run`), keeping a cited note attachment, and recovery |
| `notes/<workflow>.md` | per-workflow notes (`init` for both inits, `pathfinder` with Briefs, `plan`, `revise-plan`, `document`, `implement` for both builds, `loop` for a build the desktop app's Implementation Loop runs with `--loop` (where it reports a `loopOutcome` instead of asking for sign-off), `quick-task`, `review`, `finalize`, `handoff`, `changelog`, `git`, `xray`, `diagnose`, `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:
- **First-run Welcome.** The first dashboard a person sees (after the wake-up finishes) opens `#welcome-modal`. Any close (button, Esc, backdrop) saves `looks.welcomeSeen: true` to `looks.json`, which survives "Back to default". Help's first tab has a **Show the welcome again** link (`data-action="welcome"`). Logic: `maybeWelcome()` / `openWelcome()` in `screens/help-dialog.js`.
- **Top-bar icons.** `#btn-looks` (gear) opens `#looks-modal`, titled User Preferences (see User Preferences below). `#btn-feedback` (megaphone) is a plain link to `https://github.com/jparkerweb/plan2code/issues/new/choose`, backed by `.github/ISSUE_TEMPLATE/bug.yml` and `idea.yml` (`config.yml` sets `blank_issues_enabled: false`). `DEFAULT_ACCENT` in `palette.js` is `ocean`.
- **Version in Help.** `GET /version` reads `version.json` beside `server.mjs`, falling back to `../../version.json` for a run from `src/` (the `/version` route in `routes.mjs`). `renderHelpVersion()` in `screens/help-dialog.js` fills `#help-version`. `computeExpectedSkills()` in `install.js` injects the root `version.json` into every `references/web-console/`, so a version bump changes every skill.
- **User Preferences is four tabs in a side list.** Appearance (Theme, Card width, Highlight color, Role), Agents & models, System (Cleanup, and Desktop app inside the app only) and Sounds & activities (Sounds, Activities), a sideways strip below 720 px. The tabs are the static `<section class="prefs-panel">` panels in `#looks-modal`, each fieldset in exactly one (its `data-section`, listed in `PREFS_TABS`), wired by the shared `public/tabs.js` (`wireTabs()`, the same helper Help uses: `helpKeyTarget()` re-exports its `tabKeyTarget()`). `public/prefs.js` is the pure part: `PREFS_TABS`, `prefsOpenTab()` (the gear and the dashboard's Set up preferences both open Appearance; nothing is remembered between opens) and `prefsResetScope()` (Back to default resets only the shown tab's looks keys, and is hidden on Agents & models and System). `screens/prefs-dialog.js` owns `openPrefs(tab)`, the one way in, the Saved mark and the unsaved prompt; `screens/looks.js` keeps the look and sound controls, which save to `looks.json` as they change; `screens/agents-view.js` mounts the Agents & models tab, a master-detail split over today's `models.json` and `agents.json` (formats unchanged) whose per-agent form has its own Save and Discard: Save sends the last saved list with only that form's draft swapped in, so another form's half-typed edit is never written. The split's components live under `screens/agents/` (data, list editor, summary, form); the mount owns all state and every fetch and hands them one `ctx`.
- **Models in User Preferences.** `GET` / `POST /models` in `routes.mjs` read the shipped `~/.plan2code/bin/models.json` and read/write the user's `~/.plan2code/models.json` (`SHIPPED_MODELS_FILE` / `USER_MODELS_FILE` in `files.mjs`), edited from each built-in agent's form on the Agents & models tab. `PLAN2CODE_MODELS_DIR` relocates both for tests. The launcher reads the same two files for its model menu.
- **The wait is bounded.** `wait --seconds 240` exits `0` (answers), `10` (still waiting, `message: "Waiting on your answer in the web console"` to relay), `20` (server gone, resume it) or `30` (canceled). The agent loops. Nothing blocks for the whole time a person takes.
- **A turn is one command, and the CLI does the bookkeeping.** Agent speed is model round trips and typed tokens, not the console (`bench-web-console.mjs --roundtrip`: Send→agent ~70 ms, post→page ~180 ms), so the CLI absorbs every step with one right answer: `consume()` marks the agent `working` when it hands over a submit (`markWorking()`), and `wait` hands the turn back (`markWaiting()`) when it starts with an open question, a finish, or on the dashboard or git board; `post --wait <N>` posts and waits in one process; `settle: true | [ids]` (`settleItems()` in `patches.mjs`) records the latest send's cards as answered from their `submitted`; a new or reopened question with no stated status sets `waiting` and waiting drops `quietMinutes` (`settleAgent()`); a doc whose content changed with no `version` moves up one (`mergeDocs()`); a chat reply with no `id` is `r<re>`; doc blocks with `file` (and `select: "tasks"`, doc-level `refresh: true`) are read from the worktree by `resolveDocFiles()` before the merge, refusing paths outside it; and a hop (`__launch`, `__dashboard`, `__commit`, `__pickup`) comes with `resume` (the exact `open --resume` command) and `skillFile` (`hopFor()`), a pick-up also with `handoffFile`. The wait loop's health check runs beside the 50 ms polling instead of blocking it, and is aborted on exit. `help <topic>` prints any contract file; `help topics` lists them. `token` defaults to the option key in the page's `tokenFor()`, and nothing reads `fallbackText`, so the contract no longer asks for either.
- **The CLI hands the agent its terminal line.** `open`, `post` and `wait` (exits `0` and `10`) print `terminalLine: "→ Look at the web console: <url>"` (`terminalLine()` in `sessions.mjs`), and `console.md` asks the agent to end every terminal message with the latest one verbatim, so the tool builds the line rather than the model. In `wait` it is added to the printed result only; the collected `result.json` on disk never carries it. `open` also prints `swept: { sessions, scratch, handoffs }` when it found anything to clean.
- **State fields written by `open`, not the agent.** Every `open` (fresh or resume) records `state.worktree` and `state.branch` from `repoRoots()` — the branch is read off `<gitdir>/HEAD` on the walk that already finds the gitdir (`""` on a detached HEAD or outside git; env-relocated repos ask git, as before) — and the page shows them in the footer as the workspace label (`footerLabel()`: `folder · branch`, or `folder + N folders · branch` once folders are added, stepping down through narrower tiers); a click opens the Workspace dialog. `state.wake = true` is set only by a fresh `open --workflow dashboard` and deleted by every resume (server restart, launch, Back to the dashboard); the page also keeps a per-sid `sessionStorage` guard so a reload never replays it.
- **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `routes.mjs`, which paints `data-width` on first load; `styles/tokens.css` maps `data-width` onto the single `--card-width` variable that every column rule uses.
- **`GET /agents-doc` is the other route that reads a project file** (the dashboard's AGENTS.md tab, right after Dashboard, shown while the project has an `AGENTS.md`). A dashboard session only; it serves `AGENTS.md` or one markdown file directly under `.agents-docs/` (`?file=`, default `AGENTS.md`; `readAgentsDoc()` in `sessions.mjs` allows exactly those two shapes and `realpath`s the file inside the root), as `text/markdown` with `no-store`, or a `204` for anything else. The page links `.agents-docs/` files in place through `md()`'s `link` option (`renderAgentsDoc()` in `screens/docs.js`).
- **`GET /overview` reads a project file too.** It serves `<spec>/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or with `?file=map` / `?file=draft` the spec's `pathfinder/map.md` / live `PLAN-DRAFT-*.md` (the dashboard's Map and Plan draft tabs, shown only while the spec has no overview; `readSpecFile()` picks the file and names it in `x-spec-file`), or an empty `204` when there is no such file (normal for most specs, and no failed request in the browser console). A dashboard session honors `?spec=` only when it equals a `dir` in `state.scan.specs`; every other workflow uses `state.specDir` and ignores the query. The root is `state.worktree` (fallback `state.project`), and `readSpecFile()` (which `readOverview()` wraps) resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all get the same 204, as do an unscanned `?spec=` and an unknown `?file=`.
- **Month-old sessions are deleted whole.** `open` lists `staleSessions()` (directories matching the session-id pattern whose `state.json` mtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) and `staleScratch()` (top-level regular `.json` / `.mjs` files in the console folder older than 30 days, never `looks.json` or `console-dir` — `PROTECTED_CONSOLE_FILES` — never a directory or symlink) before it prints, and removes them after; `removeSessions()` / `removeScratch()` re-check every name against the session-id pattern / the scratch-name rule before deleting — not the age, the skipped sid or the file type, which the `stale*` listing already decided, so never hand them names that did not come from it. `console.md` tells agents to write temporary payload files into the session's own folder so they go with it.
- **User Preferences → System → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes, folder? }], bytes }` (`folder` on `notepad:` items only), ids `session:<sid>` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:<name>` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:<name>` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `install.json`, `models.json`, `handoffs`, `notepads`, `app`, `app.json`, `agents.json`), `notepad:<key>` (a month-old notepad, whole; see Notebook below) and `completed:<name>` (each folder or link directly under the session worktree's `specs--completed/` whose newest mtime is older than the session age, 30 days; loose files there stay; the server passes `project: sessionWorktree() || PROJECT`, and without a `project` the archive is never scanned). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `<file>.<pid>.tmp`, which live for milliseconds. `root:` is only scanned when the console home is `<PLAN2CODE_MODELS_DIR or ~/.plan2code>/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. The page always shows the list before **Delete these**.
- **The console's path is stated, not searched for.** Each Interface line names `references/web-console/` beside the SKILL.md and the `~/.plan2code/console/console-dir` fallback; the prompts with room (all but pathfinder, plan, document and finalize, which sit near the char limit) also name the canonical global install path `~/.agents/skills/<skill>/references/web-console/` (the skills CLI's real store; every agent dir links into it), and every `console.mjs open` writes `HERE` to `~/.plan2code/console/console-dir` (only `open`, so a `help` or dev run from `src/` never repoints it) so a later session can read the path from a fixed place. Without these the agent hunts the skill install dirs on every session.
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<D>/console.mjs" open --workflow <w>` BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `screens/starting.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `styles/poses.css`; each `SKILLS` entry's `pose` in `skills.js` is the list (`START_POSES`/`startPose()` in `answers.js` read it), and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (`.waiting-pane`, agent working with an `activity` and nothing to ask). `posePane()` keeps the pane on screen across renders when the pose is unchanged — `renderMain()` holds any `:scope > [data-pose]` child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.
- **The dashboard scan knows whether the folder is a git repository.** `scanProject()` returns `{ hasAgents, isGit, pending, specs }`; `isGit` comes from `insideGitRepo()`, the same filesystem walk `findRoots()` does (no `git` process, linked worktrees and submodules count, a set `GIT_DIR` / `GIT_WORK_TREE` / `GIT_COMMON_DIR` counts as a repo). The Git card is never grayed, since a clean tree still has branches to switch, pull and push. When `isGit` is `false` the card shows `GIT_INIT_NOTE` ("Not a git repository yet: it offers to start one") as its detail line; a scan with no `isGit` counts as a repo. In a repo, `pending` is `pendingFiles()` in `sessions.mjs`, which calls `countPending()` in `git-repo.mjs`: one bounded `git status --porcelain -z` under `GIT_OPTIONAL_LOCKS=0` (`null` when git cannot say) counting modified, staged, deleted and untracked paths. Above `0` the detail line is `pendingNote(n)` ("3 files to commit"); `0` and `null` show no note. A finish with `commit: true` puts a **Commit it now** button on the finished screen (`commitOffer()`, `renderCommitOffer()`); its `__commit` press makes the agent resume as `git` in the same session and run the commit flow above the board. `open --resume` treats any switch into `git` (this press, or Changelog's "Commit this now?") as a hop, like a dashboard launch: `switchWorkflow()` blanks the page, finish and the last run's `state.git` included, and `draft.json` goes. Without that, the old finish outlived the switch, and the page sat on the old ending above the new questions and the board. A confirm item may carry `files: [{ path, state }]`, drawn as a collapsed table by `filesTable()`. Subagents is **on** by default for the twelve opted-in skills (`defaultSetting()`); a saved Off stays off.
- **The start path is timed, and `open` is built around it.** Measure with `node scripts/bench-web-console.mjs` (`--browser-delay 900` for a real Chrome launch, `--roundtrip` for Send→agent and post→page, `PLAN2CODE_CONSOLE_TRACE=1` on `open` for a step timeline). Four things make it fast, and each is load-bearing:
- **No git process.** `repoRoots()` in `sessions.mjs` finds the common dir and worktree top by walking to `.git` (following `gitdir:` and `commondir` files) — each `git rev-parse` cost 150ms+ on Windows. It asks git only when `GIT_DIR`/`GIT_WORK_TREE`/`GIT_COMMON_DIR` relocate the repo, and uses the native realpath so an 8.3 short name keys the same project git would.
- **The socket handover.** `open` spawns the server first, then binds the loopback port itself (the first `listen()` blocks ~50ms on Windows, overlapped with the server's boot), launches the browser on that URL immediately (Chrome via `start` takes ~900ms to its first request, the longest step of all), and hands the listening socket to the server over IPC (`bindLoopback()`/`handOff()` in `sessions.mjs`, `--handoff` in `server.mjs`). Requests queue in the socket until the server takes it; one `open` already accepted is passed across as a socket and acknowledged (`conn-held`) before the channel is closed. No channel, or no socket within 3s, and the server binds its own port; `open` then opens the real URL.
- **The first paint needs no fetch.** `routes.mjs` (`renderIndex()`) renders `index.html` with the session's title, badge and saved theme (`data-theme`, `data-looks-accent`, matched by accent rules generated from `palette.js` and appended to the joined stylesheet by `static.mjs`) and the whole first state as an inline `<script type="application/json" id="boot">` (every `<` escaped; data blocks are not executed, so the CSP is unchanged). `modulepreload` hints fetch every module in parallel, the page draws in the same task as the script runs, and `/events?have=<key>` skips the opening frame when the page already holds that exact state. The chimes load on first use, not at start-up.
- **Reads are stat-gated.** `fileStamp()` (mtime:size:ino) decides whether `state.json`, `result.json` and `looks.json` changed before anything reads or parses them — per request, per heartbeat and in the 1s poll; the parsed state is cached (`readState()` returns it; `/submit` clones before editing). `wait` stats `result.json` every 50ms instead of parsing it every 400ms. Static assets are held in memory for the server's life and revalidate by ETag.
- **The Workspace and the session meter live beside `state.json`, one writer each, and outlive every hop.** Three session files, none of which `switchWorkflow()` ever touches, so both survive dashboard → skill → dashboard (a new console session starts with a count of 0, and with the folders remembered for its folder and spec, below):
| File | Writer | Holds |
|---|---|---|
| `workspace.json` | the server (`workspace.mjs`) | the folders (`id`, `path`, `name`, `description`, `original`, `nested`), `version`, the `changes` log, `missing` ids, and `remote` (`remoteWarning()` in `sessions.mjs`, computed by the server at boot) |
| `ledger.ndjson` | `console.mjs` | append-only, one JSON line per entry. Meter events: `launch` (every fresh `open` and every resume into another workflow), `run` (a post's `run`, id scoped by launch, with `tasks` when a built phase reports one) and `answer` (one per item the person answered in a collected send, written by `ledgerAnswers()`, id `<launch>:answer:<send stamp>:<item>`). Also `folder-issue` reports |
| `workspace-cursor.json` | `console.mjs` | the last workspace `version` handed to the agent; advanced after the print, never backwards |
The page changes the workspace only through five routes: `GET /workspace` (`?check=1` re-stats every folder first), `POST /workspace/add` (path resolved against `state.worktree`, `~` expanded, case-insensitive duplicate check on win32/darwin; `not-a-folder`, `duplicate`, `bad-name`, `name-taken` + `suggest`), `POST /workspace/edit`, `POST /workspace/remove` (the original folder refuses) and `POST /workspace/browse` (one picker at a time, 409 `busy`; 404 `no-picker` when `remote` is set or no picker exists; `PLAN2CODE_PICKER_ECHO` stands in for the dialog in tests). `stateFrame()` carries `workspace` (folders, `missing`, `remote`, the current launch's folder `issues`) and `meter` (`meterView()` over the ledger), and both files are on the 1s poll; it also carries an optional `update` once the boot-time release check (`update-check.mjs`) finds a newer release. The agent hears of the workspace through `open` output (`workspace: { folders, missing? }`, which also seeds the cursor) and then each change once, as `workspace: [...]` plus `Workspace: …` reply lines on `wait` exit 0 or `chat`; a change alone never ends a `wait` slice (`pendingWorkspace` on exit 10). `post` and `open --file` lift `run` and `folderIssue` out of the patch into the ledger, never into `state.json`; an unknown event or a malformed issue is exit 3. **Remembered workspaces.** `workspace.mjs` keeps `~/.plan2code/console/workspaces.json` (`WORKSPACES_FILE`, under `PLAN2CODE_CONSOLE_HOME` in tests): `projects[<case-folded worktree>] = { path, project, specs: { "specs/<name>": … } }`, each entry `{ original: { name, description }, folders: [{ path, name, description, nested? }], at }`. `rememberedWorkspace()` answers spec, else project, else nothing; `initialWorkspace(worktree, entry)` builds from it, both in the server's first `workspaceNow()` and in `open`'s read-only `workspaceOnOpen()`, so they agree. `workspace.json` carries `scope` (the spec key or `""`). Every user change (`bumpWorkspace`, not `missing`/`found`) calls `rememberWorkspace()`. `setScope()` swaps the list, logging `removed`/`added`/`renamed`/`described` changes so the cursor stays truthful; `POST /workspace/scope { spec }` (the dashboard picker, on selection and before a launch) seeds an unsaved spec from the project's list, and `followSpecDir()` (state poll, boot) moves the scope to a posted `specDir`, saving the current list as an unsaved spec's. Two writers, each a read-modify-write of one key: the server and `console.mjs forget --spec` (Finalize Step 6). The contract is in `console-workspace.md` and `console-meter.md`, and `building.md` (per-phase `run`), so the skill prompts stay unchanged.
- **The Subagents switch is a standing instruction, injected only on change.** The page's icon button (`#btn-subagents`, after Write a brief) and `#subagents-modal` show only when the frame's `subagents` block says `offered && supported`. `offered` comes from `public/subagents.js`; `supported` means the latest `{ "type": "open" }` line in `events.ndjson` carries `caps: ["subagents"]` (`latestOpenCaps()`), so an older skill copy's `open` hides the button. Four places hold it, one writer each:
| File | Writer | Holds |
|---|---|---|
| `~/.plan2code/console/subagents.json` | `server.mjs` | per project folder → workflow: `{ on, instruction, max }`, `instruction: null` being the shipped default; on `PROTECTED_CONSOLE_FILES` |
| `<session>/subagents-setting.json` | the server (`settings.mjs`) | `{ workflow, on, instruction, max, revision }`: synced from the store at boot and on any workflow change (`serverSubagents().sync` in `settings.mjs`), `revision` bumped only by a real change |
| `<session>/subagents-cursor.json` | `console.mjs` | `{ revision, state }`, the last block handed over; `open` resets it, and it moves only after the print |
| `state.json` → `helpers` | `console.mjs post` | the helpers the agent reports, merged by `id`, checked by `checkHelpers()` plus the prose scan; dropped by `switchWorkflow()` on a dashboard hop |
`POST /subagents` (origin-checked; `400` `not-offered` / `bad` / `too-long` / `max`) saves the store and bumps the session setting. `consume()`, `cmdChat()`, `deliverChat()` and `open` append `blockFor()`'s lines last in `reply` and the `subagents` field; a change alone never ends a `wait` slice. The page's Subagents tab (before Ask) draws `state.helpers` through `helperRows()`. Helpers never reach the meter ledger. Contract: `console-subagents.md`.
- **The filesystem is the transport.** Sessions live in `~/.plan2code/console/sessions/<sid>/`, deliberately not under `specs/`, so the console cannot trip the metrics scraper or any marker parser, and survives `git clean`. A result written after the agent dies is picked up by the next session.
- **Attachments on notes and quick questions live in `<sid>/uploads/`**, never in the project: images as `<uuid>.jpg`, documents as `<uuid>.<ext>` with `ext` from `DOC_TYPES` in `answers.js` (text, code, PDF). The browser re-encodes images to JPEG and sends raw bytes to `POST /upload` as `image/jpeg`; documents go as-is as `application/octet-stream`, the extension taken by `docExt()` from the uncut `x-p2c-name`. `readRaw(req, limit, cb)` in `routes.mjs` caps images at `MAX_BODY` (4 MB) and documents at `MAX_DOC_BYTES` (10 MB), and drains rather than destroys so the client gets its 413. Images need the `FF D8 FF` magic; documents pass `checkDocument()` in `sessions.mjs` (`%PDF-` for PDF, strict UTF-8 with no NUL for text), else 415. The server names the file with `crypto.randomUUID()`. `GET /uploads/<id>.<ext>` serves images as `image/jpeg` and documents under a fixed type (`application/pdf`, else `text/plain`) with `nosniff` and, on text, CSP `sandbox` (a sandboxed PDF cannot open in the viewer), so a browser can show but never run one; `recordSubmitted()` writes every send's note onto its item as `sentNote { at, text, images, files, 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.
- **Back to the dashboard is the same kind of post-finish request.** A finish with `finish.dashboard: true` shows the button; a press arrives as `{ "i": "__dashboard", "type": "dashboard" }`, and the agent runs `open --resume <sid> --no-open --workflow dashboard` then posts `"finish": null` with a fresh `menu`. The agent waits ~10 minutes after the finish for it (alongside `__review` / `__done` on a quick task); after that the page swaps the button for the `/plan2code` command. `finish.command` is optional — without one the page shows the "All done" line — and `validate()` rejects a `<placeholder>` command and a non-boolean `dashboard`. The session-level actions are therefore `__brief`, `__stop`, `__launch`, `__review`, `__done` and `__dashboard`; a new post-finish button should copy this precedent.
- **Continue here, Update CHANGELOG first and Ask prompt blocks.** Three small additions on the same pattern. **Continue here** is page-only: `continueOffer(fin)` (`public/answers.js`) reads `finish.command`, and when it starts with a Plan2Code skill (and the finish is not a pause) `screens/ending.js` draws a button beside the Next step block, hidden when the session meter is red; the press is the dashboard's own `{ "i": "__launch", ... }` through `sendAfterBuild("launch", offer)`, so the agent writes nothing new (`startsClean()` cleans the page for the hop, except out of Git and into Review; a same-skill next step keeps the workflow, so the agent posts `"finish": null`). **Update CHANGELOG first** is `finish.changelog: true`, accepted by `validate()` only on `quick-task` and `finalize` (a paused finish is exempt from that check and the page ignores the flag), and it belongs with `commit: true`; the press is `__changelog`, a `HOP_ACTIONS` entry in `cmd-post-wait.mjs` that resumes as `changelog`, whose "Commit this now?" yes carries on to Git. **Ask prompt blocks** are contract only (`console-chat.md` → Prompts to carry away): the page already draws a Copy button on every fenced block.
- **`__dashboard` also arrives mid-workflow.** A left-pointing triangle (`#btn-home`, filled with `--accent`) sits left of Stop session on every non-dashboard page. Its state comes from the pure `homeButtonState()` in `answers.js`: hidden on the dashboard, on a finish and during a stop, and otherwise gated by the same `turnGate()` Stop now uses (the person's turn, unless the agent has gone adrift). The confirm (`#home-modal`) reuses `stopWarning()`, and the submit carries the staged answers plus `__dashboard`, with `HOME_REPLY`. With no finish on the page, the agent treats it as a stop that lands on the menu: it saves its place as for `__stop`, then resumes as the dashboard with `"finish": null` + `menu`, with no finish and no stop in between (console-stop.md → "Back to the dashboard, mid-workflow"; building.md for builds). `local.homeward` drives Planny's "Saving your place and opening the dashboard…" line until the through-the-dashboard reset clears it.
- **Handoffs live outside every repo, in `~/.plan2code/handoffs/`, and the console owns them** (`handoffs.mjs`; the console ships in every skill, so the Stop flow, the Handoff skill and the dashboard all reach it through `console.mjs`). `handoff new --workflow <w> --skill <s> [--spec specs/<x>] [--title <t>] [--from-stop]` claims one for this checkout and prints `{ ok, id, path, meta }` (exit 2 bad usage, 3 a bad value). Off the dashboard the Stop modal offers **Stop with a handoff** (`#stop-handoff`, suggested) above **Just stop and save** (`#stop-go`); the first sends `__stop` with `handoff: true` and `STOP_HANDOFF_REPLY`, and `wait` adds `handoffSkill` (the built Handoff skill's `SKILL.md`, `handoffFor()`); console-stop.md gives the order (answers, save, `handoff new --from-stop`, write, paused finish naming the file, `stop`). On a dashboard, `cmdOpen()` adds `scan.handoffs` (`listHandoffs(worktree)`) and `scan.handoffsDir` after `scanProject()`, which stays handoff-free because `specs.mjs list` shares it. The picker draws them as dashed `.spec-chip.is-handoff` chips after the specs (`specSel = "handoff:<id>"`); a picked one replaces the skill cards with `renderHandoffPreview()`: **Pick it up here**, **Read it all** (`GET /handoff?id=`, served only for an id in the dashboard's own `state.scan.handoffs`), **Copy for a new conversation** (`handoffCopyText()`) and **Delete** (`openHandoffDelete()`, one step). Pick it up sends `{ "i": "__pickup", "type": "pickup", "handoff": <id> }`; `HOP_ACTIONS.pickup` (`pickupHop()`) reads the stored `.json` only, never the page, and falls back to Quick Task with `fallback: true` when the record, its skill or its spec is gone, or the Handoff skill wrote it (resuming that skill would only write another handoff); `markPickedUp()` stamps `usedAt` as the hop is printed, so the next scan drops the chip. Delete sends `__delete` with `handoff` in place of `spec`, and the agent runs `delete-handoff --handoff <id>` (`removeHandoff()`, exit 3 on a refusal, nothing touched). `open` sweeps handoffs untouched for 30 days (`staleHandoffs()`, the `.json`'s mtime, else the `.md`'s), picked up or not, and reports them in `swept.handoffs`; Cleanup never lists the folder (`KEPT_PLAN2CODE_ENTRIES`).
- **Notebook: the person's, one per folder, in `~/.plan2code/notepads/`, in named tabs, and the agent's only when the person sends a tab.** `notepads.mjs` is the store's one owner (`PLAN2CODE_NOTEPADS_DIR` moves it for tests). The folder is the session's worktree, else its project (`notepadRoot()` in `routes.mjs`), keyed `<folder-name>-<12 hex>` by `notepadKey()` (the hash over `foldKey()`, so case-only path differences match on Windows and macOS, and two worktrees get two notepads). **Layout:** `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order: [id], last, tabs: { id: { name, created, sent? } } }`, the index and the only place order and the last tab live) and, per tab, `tabs/<id>/note.md` with `tabs/<id>/images/<uuid>.jpg` and `<uuid>.thumb.jpg`; a tab id is 12 hex. Every write takes the folder's `notepad.lock`; a read never creates a file, so only the person's edits age a notepad. A delete removes the tab from the index first, then its folder, and the next write sweeps away a tab folder the index no longer names (a delete that crashed half way). **Migration:** the first shape (`v: 1`, one `note.md` and `images/` at the top) reads as one virtual tab, Notes, with the fixed id `LEGACY_TAB_ID`, and a read writes nothing; the first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, so a crash in the middle is finished by the next write and never loses a file. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders. **Routes:** twelve, placed after `/upload` in `ROUTES` (the shape test pins the order): `GET /notepad[?tab=<id>]` (`{ tabs, last, tab: { id, text, savedAt, images } }`, with the tab's `text`, `savedAt` and `images` repeated at the top), `POST /notepad/text?tab=` (`{ text }`, 1 MB, 413 `too-long`), `POST /notepad/image?tab=` and `POST /notepad/thumb?id=<uuid>&tab=` (raw `image/jpeg` the page re-encoded with `reencode()`, 4 MB, 200 pictures per tab: 415 `not-jpeg`, 413 `too-large`, 409 `too-many`), `POST /notepad/image/delete?tab=` (`{ id }`), `POST /notepad/tab` (`{ name }`), `/notepad/tab/rename` (`{ id, name }`), `/notepad/tab/delete` (`{ id }`), `/notepad/tab/order` (`{ order }`, every id once) `/notepad/tab/last` (`{ id }`) and `/notepad/tab/sent` (`{ id, workflow, spec? }`, `markTabSent()`: sets `sent: { workflow, spec?, at }` on the tab, replacing an earlier one; `workflow` one of `pathfinder`, `plan`, `quick-task`, `revise-plan`, `spec` matching `^specs/[A-Za-z0-9._-]+$`, else 400 `bad-sent`), and `GET /notepad/images/<tab>/<uuid>[.thumb].jpg` (matched on the raw request line like `/uploads/`, served through `imagePath()`'s realpath containment, `no-store`). A text or picture request with no `?tab` means the last tab used (and makes Notes when there is none), so an unchanged client keeps working. The eleven POSTs are origin-checked, and every refusal is a `NotepadError` turned into `{ error }` (`bad-name`, `duplicate-name`, `too-many-tabs`, `no-such-tab` beside the picture and text codes). None of them writes to the session folder or `events.ndjson`, and `console.mjs` and the `cmd-*.mjs` files never import `notepads.mjs` (a source test pins it; `sessions.mjs` loads it lazily for Cleanup only, listing and removing whole notepads), so nothing in a notepad reaches `state.json` or anything `wait` prints except a tab the person sends (see **Send to a skill**). **The editor, and the CSP.** CodeMirror 6 replaced OverType 2.6.1 after a spike (typing at 200 KB measured about 24 ms a key against about 99 ms, and real heading sizes): `public/vendor/codemirror.esm.js` is one minified file (about 500 KB) made by the dev-only `scripts/vendor-codemirror.mjs` from `scripts/vendor-codemirror-lock.json`, never installed in the repo, and loaded by a dynamic import only when the Notebook first opens. CodeMirror writes its rules as a `<style>` element, which `style-src 'self'` refuses, so the editor lives in the open shadow root of `.notepad-cm-host` where it adopts them as a constructed stylesheet, and its own look is `public/notepad-editor.css`, a `<link>` inside the root. Custom properties inherit across the boundary, so both themes work; page tests reach the editor with Playwright's CSS locators (they pierce open shadow roots) and read its text from `EditorView.findFromDOM()`, since lines the cursor is not on draw without their Markdown marks. CodeMirror's own rules win a tie in specificity (they are adopted after the linked sheet), so `notepad-editor.css` writes `div.cm-editor .cm-scroller` for the few it overrides. `scripts/test-web-console-page-notepad.mjs` fails on any `securitypolicyviolation` with the notepad open. **Upgrading CodeMirror:** change a version in `scripts/vendor-codemirror.mjs`, run `node scripts/vendor-codemirror.mjs --update-lock` (npm and network; it installs in a temp folder), update the sha256 in the files-table row, then run the two notepad test files. **Tabs on the page:** `screens/notLine truncated
- **A Bug fixed spec deletes in one step.** Its chip shows a visible **Delete** (`.spec-chip-del-label`) instead of the hover ✕, `openDeleteConfirm()` gives it a fixed-bug warning and a **Delete it** button, and `deleteStep()` sends `__delete` on the first press, with no name to type. `chipDetail()` drops the scan's repeated "bug fixed" detail under the label.
- **The Quick question chat is a second, append-only channel beside the card slot.** The page's **Ask** tab (always last, every workflow, still there after a finish) posts to `POST /chat` (a message, or `{ reset: true }` for New conversation) and `POST /chat/decision` (Approve / Decline on an edit the agent proposed). The server is the only writer of `<sid>/chat.ndjson` (one JSON line per `message` / `decision` / `reset`, each with a `seq`; `appendChat()` in `inbox.mjs`); `console.mjs` is the only writer of `<sid>/chat-cursor.json` (the last seq handed over, advanced only after printing) and of the agent's replies in `state.json` → `chat.replies` (merged by `id`, checked by `validateChat()`: real `re`, proposal paths outside the running `specs/<idea>/`). The server never writes chat into `state.json` — `post` read-modify-writes it under `withStateLock()` — and `stateFrame()` merges inbox and replies into the frame's `chat` block (`conversation`, `messages`, `typed`, `limit`, `offline`) in memory. `/chat` never checks `pendingResult()`, so neither channel can block the other. `wait` keeps its exit codes 0/10/20/30: exit 0 gains `chat` (or is `type: "chat"` with no actions), and the instant `console.mjs chat` answers 0/10/20 without touching `result.json`, which builds run after every task. Guards: 10 typed messages per conversation (`409 limit`), 4,000 characters (`400 too-long`), own uploads only, of the right kind (`400 image`, `400 file`), `409 offline` when `chatOffline()` says no agent is there, `409 stale` for an old conversation. A hop through the dashboard keeps the conversation: `switchWorkflow()` carries `chat.replies` across and the page keeps its Ask state, so only New conversation appends a `reset` after the opening one. A lone reset never ends a `wait` slice (`deliverableChat()`); it rides along with the next message.
- **`validate()` in `patches.mjs` enforces four workflow rules mechanically**: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait.
- **The palette is written twice for dark, and that duplication is the mechanism.** `@media (prefers-color-scheme: dark) :root:not([data-theme="light"])` follows the system; `:root[data-theme="dark"]` is the explicit choice from the colors panel. Drop the `:not()` and a system-dark browser overrides someone who asked for light. A chosen accent is applied as an inline custom property on `:root` (CSSOM, which the CSP allows), and the default is applied by REMOVING that override so the stylesheet's own per-theme values win. The server's `data-looks-accent` stand-in only lasts until `applyLooks()` runs, which removes it first thing — left on, its rule would beat "Back to default".
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 21 panels and their icon sheet are hand-written HTML and SVG in `<template id="help-content">` in `index.html` (after `#start-poses`), cloned into `#help-panels` the first time **?** is pressed (except the dashboard topic's card list: `buildHelp()` fills its `.help-cards` from `SKILL_CATALOG` and `CATALOG_GROUPS` at that moment, in the dashboard's order), so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `screens/help-dialog.js` the wiring (tab buttons, roving focus, `renderAbout()` for the live connection line on tab 1, `lightDismiss()`, and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a `style=` attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a `data-fact` span a test checks against the constant it comes from.
- **Stuck sessions are explained twice, in Help and on the status line.** `stuck` ("When something looks stuck") is the second tab in `HELP_TABS`; its panel opens with a `help-callout` ("Check this first": Plan2Code often waits for a permission in the terminal, which the page cannot see) and four You see / Likely cause / Do this rows before the diagram. The quiet and Not running status lines carry a "What to check" button (`openHelpOn("stuck")`) inside the existing `role="status"` element, so it exists only while the symptom shows. Every finished and paused screen gets a "Before you close this" panel from `renderCloseGuide()` in `renderHandoff()` (Safe to close, Start fresh, Carry on). Tests in `scripts/test-web-console-source.mjs` check the tab order, the callout and rows, and the `renderCloseGuide` call.
- **Markdown is rendered to DOM nodes, never to an HTML string** (`public/render.js`), so agent-authored text that quotes a hostile source cannot execute. Only `marked.lexer()` is used.
Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --build-skills`, `parse-check.mjs`, `check-skill-table.mjs`, then one `node --test` over the skill-script tests (`test-skill-scripts.mjs`, `test-script-*.mjs`, `test-git-repo.mjs`), `test-launcher.mjs`, `test-getting-started.mjs` and the web console's `test-web-console-*.mjs`, so they run in parallel, one process each. The console tests are split by area (`-session`, `-lifecycle`, `-logic`, `-server`, `-chat`, `-chat-stress`, `-workspace`, `-subagents`, `-concurrency`, `-source`, `-shape`, `-git`, `-git-board`, `-qa`, `-speed`, `-hardening`, `-embed`, `-handoffs`, `-in-app`, `-loop`, `-notepad`, `-pointers`, `-skills`, `-spec-states`, `-state`, `-tones`), plus the `-page-*` browser suites and the per-game `-activities*` suites. Their shared setup is `scripts/web-console-test-helpers.mjs`: importing it gives the file its own console home (so `workspaces.json`, `subagents.json`, `looks.json` and sessions never collide across files) and registers the `stop --all` cleanup. `-session` and `-lifecycle` each run an ordered chain of tests on one session of their own; everything else opens a session per test. A new test goes in the file for its area, after the tests it depends on. The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill.
**Adding a file under `public/`:** a page module needs `SERVABLE` in `static.mjs` and a `<link rel="modulepreload">` in `index.html`. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a module missing from it 404s and the page dies at import with no useful error (the import-fetch test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after `app.js` and slows the first paint. A screen goes in `public/screens/`, imports only `state.js` and the pure modules (never another screen), and is imported by `screens/core.js`; the import guard in `scripts/test-web-console-shape.mjs` fails naming a screen that breaks either rule. A stylesheet goes in `public/styles/` and on `CSS_ORDER` in `static.mjs`, never on `SERVABLE`; the joined-stylesheet test fails when the folder and the list disagree. Every new file also needs its row in the files table above, which the docs-table test (same file) checks.
**Building an Activities game:** the rules every game follows, so a new one plays like the rest.
- **Lives are prominent.** A game with lives draws them as the lives pill: `livesText(round.lives)` in the `LIVES` color from `pills.js`, placed right after the level/stage pill, which `drawPill()` draws solid pink with a heart per life. Never a plain `♥ N` on the dark backing: that was hard to read at a glance. The unit suite checks every game with lives for it.
- **Every game with lives takes the endless-lives code.** Typing up, down, up, down, left, right, left, right, B, A, space on the board gives endless lives until the round starts over or the person leaves the game (`CHEAT_CODE` in `screens/activities.js`, which calls the game's `cheat(true)` and `cheat(false)` on leaving for the picker or closing). A game with lives answers `cheat(on)` by setting `round.infinite`, never takes a life while it is set (`if (!round.infinite) round.lives -= 1`), lets `start()` make a new round without it, and shows `livesText(Infinity)` ("♥ x∞") in its lives pill. `scripts/test-web-console-activities.mjs` checks every listed game whose round has `lives`.
- **Banners never get in the way.** A banner over the board (`"Hit!"`, a new level, a power-up) is placed on the frame it first shows, on the part of the board away from the player, and fades to `BANNER_SEE_THROUGH` (0.12) over `BANNER_FADE_MS` while the player, or anything the player must react to (a diving bug, a bomb, a rival, a hazard, the road over a hill), is in its strip; Snake's `bannerRow()` and `underBanner()` are the model. Give the banner object a `see` field, multiply the draw's alpha by it, and export the strip check (`underBanner`) for the unit suite.
- **The window owns pausing.** A game never resumes itself; `screens/activities.js` decides when a key or click plays on, including the hold on a question or finish (see the row above), so a game needs nothing of its own for it. Full screen is the window's too (`setFull()`: the button, `F`, and a turn or finish putting it back; `fitFull()` sizes the game to the whole screen (black bars where its shape leaves room) and docks the overlaid panel in a bar that holds it, `data-dock="side"` or `"below"`, or floats it, `"float"`, shrunk to the score while a round plays and the pointer is still; and tells the desktop app `activities-full`); a game only sees a bigger `resize()`, so a new game needs nothing for it, as long as its `resize()` sets the canvas's CSS size.
- **Every moment has a sound, and moving things hum.** A game plays a one-shot through the `tone` it is handed for each event worth hearing (a hit, a pickup, a level, a new best, game over) and keeps continuous things (an engine, a motor, wind, water, a fuse, a monster close by) going with `hum(id, name, level, pitch)` from its `tick`, pitch following speed. Never a one-shot every frame: a repeating cue is throttled by a timer in the round. Its own sounds live in `activities/<id>-sfx.js`, named with the game id; the shared kit is in `tones.js`. `create()` defaults `tone` and `hum` to no-ops, since the suites make games with neither, and a sound never changes the game's state.
- **Its logic tests pin the dice.** A game rolls `Math.random` for roads, spawns and layouts, and an unlucky roll once failed a test on CI at random (Ghoul Rush's Eye, Bounce Road twice). Import `./seed-random.mjs` FIRST in every `scripts/test-web-console-activities*.mjs` file: it seeds `Math.random` (set `PLAN2CODE_TEST_SEED` to try another roll), so a test sees the same world on every run.
## Status Line
Optional Claude Code status bar living in `src/statusline-claude/`. Three-line bar beside a Planny icon: two content lines with a dashed rule between, showing model (+ effort), project/worktree, branch, uncommitted diff stats, session duration + cost, context window usage, and plan/quota usage.
**Design constraints:**
- **Zero runtime dependencies** — `statusline.js` is self-contained (config loader, git helpers, formatters, render). Copied verbatim to `~/.claude/plan2code-statusline.js` on install; no bundler step.
- **Stdin-driven** — all data comes from Claude Code's stdin JSON (`model`, `workspace`, `context_window`, `rate_limits`, `cost`). No API calls, no auth, no background processes.
- **Silent failure** — outer `try/catch` around `main()` plus `process.exit(0)` on missing stdin guarantees the script never crashes the CLI. All git ops are timeout-bounded (1.5s) and non-git workspaces short-circuit via `isGitRepo()` (walks up to 10 parent dirs looking for `.git`).
- **Atomic settings writes** — installer writes `~/.claude/settings.json` via temp file + rename so a crash never leaves the file truncated.
- **Custom-config respect** — installer detects non-plan2code `statusLine` entries, prompts before replacing, and backs up to `statusline-previous.json`. Uninstall only removes `settings.statusLine` if it points to the plan2code bundle.
**Layout:**
```
src/statusline-claude/
├── statusline.js # Self-contained: config, git, formatters, render
├── statusline-config.json # Default config template
└── README.md # User docs: install, config, debugging
```
**Adaptive plan-usage display:** the formatter auto-selects between `5h/7d` rate-limit percentages (Pro/Max/Teams — when `rate_limits` present in stdin) and `Nk in · Nk out` session-token counts (Bedrock/Vertex/PAYG — when `rate_limits` absent). Segment is hidden when neither shape is available.
**Installer integration** lives in `install.js` under the `STATUS LINE INSTALLATION` section (`installStatusLine`, `uninstallStatusLine`). Included in Advanced → `E` (Everything); also available individually via Advanced → `S`.
## Global `plan2code` Command
Typing `plan2code` in any directory opens the dashboard skill against the current project, **in that directory**, in one of the built-in CLIs (the shipped `src/launcher/agents.json`, plus any custom entries in `~/.plan2code/agents.json`):
| CLI | Runs |
| --- | --- |
| Claude Code | `claude /plan2code [--permission-mode bypassPermissions] [args]` |
| Devin | `devin [--permission-mode bypass] [args] -- /plan2code` |
| Codex | `codex [--dangerously-bypass-approvals-and-sandbox] [args] $plan2code` (Codex starts a skill with `$name`; the launch line follows Codex's documentation) |
The bracketed flags (each entry's `bypassArgs`; a custom agent's own `bypassArgs`) go in only when permission prompts are off. Right after the agent is chosen, and only when it has such a flag, `chooseBypass()` asks `Turn <CLI>'s permission prompts off?` with Yes as the default; `--keep-permissions` (never forwarded) answers no, and with no TTY on stdin the prompts are off, as before. When the desktop app will take over, the question is skipped (its launch card has its own tick) and asked only if the app fails to start. The installer prints no warning about it.
On a terminal it first prints a Planny banner (`renderBanner()`). With more than one on `PATH` it asks `Plan2Code opens inside an AI coding agent. Pick which one to use:` as a numbered menu, the last pick pre-selected and marked `(last used)` (Enter keeps it; a number or a CLI id also works); with one installed it uses that without asking, printing `Opening with <CLI>…` (as does a `--cli` pick); with none it runs the setup flow when a person can see a page (`hasDisplay()` and a TTY or the shortcut; the desktop app first when it is installed, else the console's agent-less `setup` page in the browser) and otherwise prints the install steps (`printNoAgentGuidance()`: each built-in's install command and page, how to add another agent in `~/.plan2code/agents.json`, and to run `plan2code` again) and exits 127. An uninstalled `--cli` pick goes to the same setup flow on that agent when a page can open, else prints that CLI's own steps after its error. `--cli claude` / `devin` / `codex` (or `--cli=<name>`) skips the menu and is never forwarded; an unknown name exits 2, an uninstalled one 127. The pick is saved as `lastCli` in `~/.plan2code/launcher.json`, merged beside `lastFolder`. Before spawning, unless the forwarded args carry `--model` / `--model=` (or, for Codex, `-m`), it asks `Which model should <CLI> use?` from `models.json` plus the user's additions, Enter keeping the model the CLI last used — Ctrl+C at any launcher prompt exits 130. With no TTY on stdin there is no menu (last pick, else the first installed) and no model question: it prints that the CLI will use the model last used in it (switch it in that CLI on its own, or pass `--model <name>`). Headings, numbers, defaults, retry lines and the `plan2code:` error prefixes are colored with `paint()` (the escape values of `install.js`'s `COLORS`, copied), stdout only when stdout is a TTY and stderr only when stderr is, and never when `NO_COLOR` is set; piped runs print plain text and no banner. Other arguments are forwarded to the CLI (`plan2code --model opus`), and its exit code is passed back. `plan2code update` is the one subcommand: it is never forwarded and opens no agent, it runs `npx --yes --allow-git=all git+https://github.com/jparkerweb/plan2code.git --update`, so `install.js --update` reinstalls what `~/.plan2code/install.json` lists. On every other start, before spawning the CLI, it prints one line when a newer release is out (`Plan2Code v<latest> is out (you have v<installed>). Run: plan2code update`), compared against `~/.plan2code/bin/version.json` and read from the console's cached release check (`~/.plan2code/console/update-check.json`); it never waits on the network, and when the cache is missing or stale it refreshes it in a detached background process so the next start knows. Tests: `scripts/test-launcher.mjs` (run by `npm test`) spawns the launcher against stand-in `claude`/`devin`/`codex` commands and a temp home.
**Design constraints:**
- **Stable copy, not the package dir** — the installer normally runs from an npx cache directory npm may delete, so `installLauncher()` copies `src/launcher/plan2code.js` to `~/.plan2code/bin/plan2code.js` and the shims point there. Beside it go `update-check.mjs` (the web console's release check, for the terminal notice), `agents.json` and `agent-lookup.mjs` (the shared agent list and lookup rule; `plan2code update` restores a missing copy) and a `version.json` (the installed version). (The metrics/bot wrappers point into `__dirname` and don't have this protection.)
- **The setup flow and hand-over.** With no runnable agent, `runSetupFlow()` finds `console.mjs` (the order the app's `find_console_dir` uses) and runs `open --workflow setup [--for-cli <id>]` as a child process, then `wait` in 240-second slices (the agent-less console keeps its app variables out, NFR-2). An `__start` action ends the wait with the pick; the launcher spawns that agent with `PLAN2CODE_SETUP_ANNOUNCE` (the setup server's base URL) and `PLAN2CODE_SETUP_TOKEN`, and the new agent's `open` POSTs its sign-in URL to `POST /handover` on the setup server, which broadcasts a `move` event the waiting tab follows. The post failing or the wait ending unmoved falls back to opening a browser / the printed steps.
- **npm-style shims** — written into npm's global bin (`npm config get prefix`; `<prefix>/bin` off Windows): an sh shim everywhere, plus `.cmd` and `.ps1` on Windows, so cmd.exe, PowerShell and Git Bash all resolve it. On macOS/Linux, when the npm bin isn't writable (system Node), it falls back to `~/.local/bin`.
- **Marker-based ownership** — every shim contains `plan2code-launcher`; `uninstallLauncher()` removes only files carrying it, leaving any other `plan2code` bin alone.
- **Resolving the CLI** — `findAgent()` in the shared `agent-lookup.mjs` does the lookup: `PATH` (+ `PATHEXT` on Windows), the saved Windows PATH from the registry (`addSavedWindowsPath()`), npm's global bin and each entry's `installDirs`, giving `found` / `outside` / `missing` (the desktop app's `find_on_path` in `agents.rs` is its twin, held to `scripts/fixtures/agent-lookup-cases.json`). An `.exe` is spawned directly; a `.cmd`/`.bat` wrapper goes through `cmd.exe /d /s /c` with quoted args, since Node refuses to spawn batch files without a shell. The installer warns only when neither `claude` nor `devin` is on `PATH`.
- **No bin-name overlap** — the installer's own bin in `package.json` is `plan2code-install` (→ `install.js`), so `plan2code` belongs to the launcher alone. npx runs a package's only bin whatever it's named, so the README's `npx … plan2code.git` command is unaffected; keep it the only bin, or npx will need `-c plan2code-install`.
- **`--pick-folder` is shortcut-only** — the launcher strips it before building the CLI's args. The shortcut runs the CLI menu, then the folder picker, then the model menu. With it, a native folder picker chooses the cwd instead: on Windows, the Explorer-style `IFileOpenDialog` (`FOS_PICKFOLDERS`) via `powershell -STA -EncodedCommand`, its C# interop (`WINDOWS_PICKER_SOURCE`) passed in an env var and compiled with `Add-Type` (~0.5s), with a TopMost owner form so it doesn't open behind the console — Windows PowerShell's `FolderBrowserDialog` is the old tree-only dialog, and is kept only as the fallback when `Add-Type` is blocked (Constrained Language Mode, AppLocker); `osascript choose folder` on macOS, and `zenity` then `kdialog` on Linux (only when `DISPLAY`/`WAYLAND_DISPLAY` is set). If there's no picker, or the picker fails, it falls back to a typed `Project folder [last]:` prompt. A picker that exits 0/1 with nothing printed means the person canceled, so the launcher exits 0. The picker starts on the last pick, stored in `~/.plan2code/launcher.json`. From the shortcut, a non-zero exit other than Ctrl+C (130 / `0xC000013A`) waits for Enter so the error doesn't vanish with the window. Typed in a terminal, `plan2code` behaves exactly as before.
**Desktop shortcut** — after the shims are written, `installLauncher()` (now async) calls `offerDesktopShortcut()`. It asks `Also add a Plan2Code shortcut to your desktop? (y/N)`, skips the question when stdin isn't a TTY, and refreshes an existing marked shortcut without asking. `installDesktopShortcut()` writes it to the real desktop (`[Environment]::GetFolderPath('Desktop')` on Windows, which covers OneDrive redirection; `xdg-user-dir DESKTOP` on Linux; `~/Desktop` otherwise):
| OS | File | Runs |
| --- | --- | --- |
| Windows | `Plan2Code.lnk` (written by `WScript.Shell`) | `pwsh.exe` (else Windows PowerShell) `-NoLogo -ExecutionPolicy Bypass -File "<bin>\plan2code.ps1" --pick-folder`, icon `src/launcher/plan2code.ico` (the web console's Peek-a-boo favicon, 16–256 px) copied to `~/.plan2code/bin/plan2code.ico` |
| macOS | `Plan2Code.command` (0755) | `exec "<bin>/plan2code" --pick-folder` in Terminal |
| Linux | `plan2code.desktop` (0755, `Terminal=true`, `gio … metadata::trusted`) | `"<bin>/plan2code" --pick-folder`, `Icon=` the web console's `favicon.png` copied to `~/.plan2code/bin/plan2code.png` |
The macOS and Linux shortcuts carry the `plan2code-launcher` marker as a comment line. A `.lnk` has nowhere to hide one (its Description is the hover tooltip), so it's recognized by what it runs: the UTF-16 strings `plan2code.ps1` and `--pick-folder` stored in the file (`plan2code.cmd` also matches, so shortcuts from before the PowerShell switch get refreshed). `uninstallLauncher()` removes only a recognized shortcut, plus the icons (`plan2code.ico`, `plan2code.png`), `bin/models.json` and `launcher.json` (never the user's `~/.plan2code/models.json`). A shortcut failure prints a warning and never fails the command install.
**Installer integration** lives in `install.js` under the `PLAN2CODE COMMAND` section (`installLauncher`, `uninstallLauncher`, plus the shortcut helpers). `install()` awaits it after a successful skills install (so `I` and Advanced → `E` get it), `U` removes it, and Advanced → `D` installs it alone. Every global install writes `~/.plan2code/install.json`, the install record listing the pieces installed (skills, launcher, statusline, loop, metrics, bot); `install.js --update` (what `plan2code update` runs) reinstalls those (metrics and bot only when run from a git checkout), with no menu and never uninstalling, or with no record the skills and the `plan2code` command. After an install, `printGettingStarted()` prints the three steps (cd into the project, start Plan2Code, pick a card) and, when no agent CLI is on `PATH`, how to get one.
The web console's files tables run across six files (server and contract, page, activities, and the three Ghoul Rush files); `scripts/test-web-console-shape.mjs` reads them all and fails when a console file has no row in any of them.
+1 -1
View File
@@ -14,7 +14,7 @@
## Gotchas / Pitfalls
- **Version sync:** When adding a new version to `CHANGELOG.md`, also update `version.json` and `package.json` (root) to match. `README.md` (the `Version X.Y.Z` line near the top) also carries the version, and `version.json`'s `releaseDate` moves with it. `version.json` is copied into every skill's `references/web-console/` (the console's Help shows it), so after a bump run `npm run build:skills` or `npm test` (`--verify-skills`) fails. The installer displays the version from `version.json` in its header. All three files (`CHANGELOG.md`, `version.json`, `package.json`) must always show the same version number. The desktop app carries it too (under `plan2code-app/`: `package.json`, `package-lock.json` with two lines, `src-tauri/tauri.conf.json`, `src-tauri/Cargo.toml`, `fake-agent/Cargo.toml`, and `Cargo.lock`'s `plan2code-app` and `fake-agent` entries): `node scripts/check-versions.mjs [--tag vX.Y.Z]` compares those, `version.json`, `package.json`, `CHANGELOG.md` and README's line (twelve places in all), `npm test` runs it first on this tree, and the release workflow runs it before building.
- **Version sync:** When adding a new version to `CHANGELOG.md`, run `node scripts/set-version.mjs <x.y.z>` (the one writer of every carrier; it never edits the changelog), which updates `version.json` and `package.json` (root) to match. `README.md` (the `Version X.Y.Z` line near the top) also carries the version, and `version.json`'s `releaseDate` moves with it. `version.json` is copied into every skill's `references/web-console/` (the console's Help shows it), so after a bump run `npm run build:skills` or `npm test` (`--verify-skills`) fails. The installer displays the version from `version.json` in its header. All three files (`CHANGELOG.md`, `version.json`, `package.json`) must always show the same version number. The desktop app carries it too (under `plan2code-app/`: `package.json`, `package-lock.json` with two lines, `src-tauri/tauri.conf.json`, `src-tauri/Cargo.toml`, `fake-agent/Cargo.toml`, and `Cargo.lock`'s `plan2code-app` and `fake-agent` entries): `node scripts/check-versions.mjs [--tag vX.Y.Z]` compares those, `version.json`, `package.json`, `CHANGELOG.md` and README's line (twelve places in all), `npm test` runs it first on this tree, and the release workflow runs it before building.
- **CHANGELOG ordering:** Entries in `CHANGELOG.md` must be in reverse-chronological order — newest version at the top, oldest at the bottom. New entries are always inserted immediately after the file header.
- **CHANGELOG house format is not Keep a Changelog:** version headings are `## vX.Y.Z` — with a `v` prefix and **no date**. The release date is recorded only in `version.json`'s `releaseDate`. Category headings carry emoji: `### ✨ Added`, `### 🔧 Changed`, `### 🐛 Fixed`, `### 💥 Breaking`, `### 🗑️ Removed`, `### 📚 Documentation`. Older entries contain one-off variants (`🎁 Added`, `📦 Updated`, `📝 Documentation`, `🏎️ Improved`, `🧪 Testing`) — do not introduce new ones. The `.claude/skills/plan2code-changelog/` skill automates version selection and formatting; use it rather than hand-rolling an entry.
- **PowerShell mangles the CHANGELOG emoji:** `Get-Content` / `Select-String` render the `###` heading emoji as `?` under the default Windows console encoding, so a heading audit done that way reports garbage. Read `CHANGELOG.md` with a file-read or grep tool instead.
+19 -7
View File
@@ -19,8 +19,17 @@ npm run build:skills
# fresh from disk, so a saved game file shows on the next page reload
npm run play
# Full check (about 70s): char limits, skills/ build, browser-module parse check,
# dashboard skill-table check, web console + launcher + getting-started node:test suites
# Fast lane (about 2 minutes on a 24-core machine, measured outside the desktop app):
# the files listed under "fast" in scripts/test-lanes.json, none of which start a
# console server, run a console page suite or play a game (test-app-meter.mjs opens one
# static page in a browser and skips when none is installed). CI runs it on Ubuntu for
# every pull request, and on all three systems for a push to main or a pull request
# labeled `full-matrix`.
npm run test:fast
# Full check (takes minutes; every page suite drives a browser): list check, char limits,
# skills/ build, browser-module parse check, dashboard skill-table check, web console +
# launcher + getting-started node:test suites
npm test
# Put every text file git sees back to LF (also runs by itself as pretest and in
@@ -51,8 +60,9 @@ cd plan2code-metrics && npm install # First time setup
cd plan2code-metrics && npm run build # Build the CLI
cd plan2code-metrics && npm test # vitest (aggregator, community, improver)
# Desktop app (plan2code-app/, Rust + Tauri). CI's `app` workflow runs all three on
# Windows, macOS and Linux and fails on any rustfmt difference or clippy warning, so run
# Desktop app (plan2code-app/, Rust + Tauri). CI's `app` workflow runs all three on Ubuntu
# for every pull request and push to main, and on Windows and macOS too for a manual run or a
# pull request labeled `full-matrix`. It fails on any rustfmt difference or clippy warning, so run
# them before pushing, not only cargo test (see plan2code-app/README.md "Tests").
# First time: rustup component add rustfmt clippy (for the toolchain in rust-toolchain.toml)
cd plan2code-app && node scripts/vendor.mjs && cargo fmt --check
@@ -68,6 +78,8 @@ cd plan2code-bot && npm test # vitest
The full `npm test` takes minutes and drives a browser per page suite. When a change stays inside one part of the project, run that part's suites instead (with the `PLAN2CODE_*` app variables unset, as for `npm test`), and leave the full run for when a change reaches shared code.
The fast lane is `npm run test:fast` (`scripts/test-fast.mjs`): it runs the files in `scripts/test-lanes.json`'s `fast` array through `node-test.mjs`. **Two-list rule:** every `scripts/test-*.mjs` is named in exactly one of `fast` and `skipFast`. A new test file that starts a console server, runs a console page suite or plays a game goes in `skipFast`; anything else goes in `fast`. `node scripts/check-test-lanes.mjs` fails (and runs first in `npm test`) when a file is in neither list, in both, or named but missing. `test-fast.mjs` itself is a runner and sits in `skipFast`. `.github/workflows/fast-tests.yml` runs the lane on Ubuntu for every pull request, and on all three systems for pushes to main and pull requests labeled `full-matrix`.
| What changed | Run |
|---|---|
| An Activities game (`public/activities/*`), `public/tones.js` or `public/music.js` | `node --test scripts/test-web-console-tones.mjs scripts/test-web-console-activities.mjs`, plus the game's own `scripts/test-web-console-activities-<game>*.mjs` when it has one; add `test-web-console-page-activities.mjs` when the Activities window or its switches changed |
@@ -131,9 +143,9 @@ The root `npm test` does not run the metrics or bot vitest suites; run them in t
## How the Installer Works
1. **Builds `skills/` from `src/`** — one Agent Skill per source prompt, including uncommitted source edits.
2. **Checks the skills CLI is reachable** with `npx --yes skills --version`.
2. **Checks the skills CLI is reachable** with `npx --yes skills@1.7.6 --version` (the version is pinned: `SKILLS_CLI_VERSION` in `install.js`).
3. **Sweeps pre-2.2 install paths** and removes installed `plan2code-*` skills so renamed or retired prompts cannot survive as orphans.
4. **Delegates installation** to `npx --yes skills add "<repo>/skills" -g -s <skill names> -y`.
4. **Delegates installation** to `npx --yes skills@1.7.6 add "<repo>/skills" -g -s <skill names> -y`.
5. **Installs the global `plan2code` command** (only when step 4 succeeded). Advanced → `L` runs the same flow without `-g` and without the launcher.
The skills CLI owns distribution from step 4 onward. It stores canonical skills under `~/.agents/skills/` and links them into agents that maintain their own skill directory. Plan2Code no longer maintains platform-specific output formats.
@@ -181,5 +193,5 @@ See the `skills/` build-artifact gotcha in [Code Style & Gotchas](./AGENTS-code-
- Optional: `STARTER_SET_FOR` in `public/starters.js` (unlisted gets "general").
**Adding a spec state** is shorter: one entry in `src/web-console/public/spec-states.js`, the detection in `classifySpec()` in `src/web-console/scan.mjs`, the `states` of each card in `skills.js` that takes it, and a line in the dashboard skill (`src/plan2code.md`); then `npm test`.
4. Update command inventories in `README.md` (dashboard-card and command tables), `QUICK-REFERENCE.md`, `.agents-docs/AGENTS-architecture.md` (prompt table, own-script rows, notes list), and `CHANGELOG.md`. Update `docs/index.html` for core pipeline steps, and for a utility only when it is a headline change (its `.utils` block).
4. Update command inventories in `README.md` (dashboard-card and command tables), `QUICK-REFERENCE.md`, `.agents-docs/AGENTS-architecture-install.md` (prompt table), `.agents-docs/AGENTS-architecture-skill-scripts.md` (own-script rows) and `.agents-docs/AGENTS-architecture-console.md` (notes list), and `CHANGELOG.md`. Update `docs/index.html` for core pipeline steps, and for a utility only when it is a headline change (its `.utils` block).
5. Run `npm run build:skills` and `npm test`.
+13 -2
View File
@@ -39,7 +39,8 @@ Community submissions arrive as GitHub issues labeled `community-feedback` on `j
| File | Purpose |
|------|---------|
| `types.ts` | All interfaces (`RunMetrics`, `UserFeedback`, `CohortMetrics`, etc.) + `METRIC_TARGETS` |
| `collector.ts` | Reads project artifacts → run JSON (parses plan drafts, overview.md, loop logs) |
| `collector.ts` | Reads project artifacts → run JSON (parses plan drafts, overview.md, phase files) and fingerprints every `src/plan2code-*.md` prompt |
| `metrics-pattern.json` | The scrape shapes the collector reads, a byte-for-byte copy of `src/web-console/metrics-pattern.json` |
| `aggregator.ts` | Merges runs by prompt generation (SHA cohort) → `aggregated.json` |
| `community.ts` | Lists/parses/closes `community-feedback`-labeled GitHub issues via `gh` CLI |
| `analyzer.ts` | AI diagnosis via `prompts/analyze.md` template |
@@ -47,7 +48,7 @@ Community submissions arrive as GitHub issues labeled `community-feedback` on `j
| `applier.ts` | Interactive diff review + file patching |
| `cli.ts` | Menu-driven interactive CLI (100% prompts, no flags) |
| `invoke-llm.ts` | Unified LLM interface (Claude Code, GitHub Copilot CLI, or Devin CLI) |
| `*.test.ts` | vitest suites for aggregator, community, improver (`npm test` in `plan2code-metrics/`) |
| `*.test.ts` | vitest suites for aggregator, collector, community, improver (`npm test` in `plan2code-metrics/`) |
## User Feedback
@@ -87,3 +88,13 @@ Feedback is collected during finalize (Step 5) or retroactively via the CLI. Pip
| `avg_user_rating` | ≥ 7.0 | higher is better |
On start the CLI asks for the plan2code repo path (default: saved `plan2codeRepoPath` in `~/.plan2code-metrics.json`, else auto-detected up to 5 parent dirs) and the project path (default: cwd). Data is stored in `<project>/.plan2code-metrics/` (runs/, aggregated.json, proposals/).
## Prompt fingerprints and the one-time regrouping
`collectPromptVersions` reads every `src/plan2code-*.md` file from the folder (so a new skill is covered with no code change) and keys each hash by name: the eight prompts recorded earlier keep their keys (`plan`, `revise_plan`, `document`, `implement`, `finalize`, `init`, `init_update`, `quick_task`), any other file becomes its name without `plan2code-` and `.md`, dashes as underscores (`3_implement_review`, `git`).
The cohort key hashes every fingerprint that is not the `sha256:missing` sentinel, so the first run recorded after this change has more entries than any earlier one and starts a new cohort. Runs recorded before stay as they are and group together as the previous prompt generation; nothing is rewritten or dropped. This happens once, at the change, and again only when a prompt file is edited or added.
## The scrape pattern (one source)
What the collector reads from a plan draft (the `METRICS_JSON` comment, the confidence labels and the four breakdown labels) lives in `src/web-console/metrics-pattern.json`. The console's bait scanner (`src/web-console/patches.mjs`) reads it, `plan2code-metrics/src/metrics-pattern.json` is its copy (bundled by tsup), and `SCRAPE` in `src/skill-scripts/common.mjs` mirrors it for `specs.mjs check`. `scripts/test-web-console-hardening.mjs` fails when any copy differs. After editing the pattern, copy the file to `plan2code-metrics/` and update `SCRAPE`. A breakdown label then a number counts in prose, and in a table row only when the number ends the row, so an ordinary risk-register row is not refused.
+79
View File
@@ -0,0 +1,79 @@
name: fast-tests
on:
push:
branches: [main]
pull_request:
types: [opened, synchronize, reopened, labeled]
permissions:
contents: read
# A newer push to a pull request replaces its still-running checks. A push to main always
# finishes.
concurrency:
group: fast-tests-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# The fast lane is the files listed under `fast` in scripts/test-lanes.json (no console server,
# no console page tests, no games; test-app-meter.mjs opens one static page in a browser and
# skips when none is installed). Every pull request runs it on Ubuntu; main and pull requests labeled
# `full-matrix` run it on all three systems. The full `npm test` stays manual (see app.yml).
jobs:
ubuntu:
name: fast lane (ubuntu)
# A pull request labeled `full-matrix` gets its Ubuntu run from the matrix job below.
if: github.event_name == 'pull_request' && !contains(github.event.pull_request.labels.*.name, 'full-matrix')
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v4.2.2
- uses: actions/setup-node@v4.4.0
with:
node-version: 20
- name: Cache the npm downloads
# setup-node's own cache needs a tracked lockfile and the root has none, so cache npm's
# download folder directly, as app.yml does.
uses: actions/cache@v6.1.0
with:
path: ~/.npm
key: npm-fast-${{ runner.os }}-${{ hashFiles('package.json') }}
restore-keys: |
npm-fast-${{ runner.os }}-
- run: npm install
- run: npm run build:skills
- name: Run the fast lane
# The desktop app's variables change what the tests check; a runner has none, but unset
# them anyway so the run matches a terminal outside the app.
run: env -u PLAN2CODE_IN_APP -u PLAN2CODE_APP_TOKEN -u PLAN2CODE_APP_VERSION -u PLAN2CODE_APP_ANNOUNCE -u PLAN2CODE_EMBED_ORIGIN -u PLAN2CODE_CONSOLE_SID -u PLAN2CODE_LOOP_STRENGTH npm run test:fast
matrix:
name: fast lane (${{ matrix.os }})
if: github.event_name == 'push' || contains(github.event.pull_request.labels.*.name, 'full-matrix')
runs-on: ${{ matrix.os }}
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v4.2.2
- uses: actions/setup-node@v4.4.0
with:
node-version: 20
- name: Cache the npm downloads
uses: actions/cache@v6.1.0
with:
path: |
~/.npm
~/AppData/Local/npm-cache
key: npm-fast-${{ runner.os }}-${{ hashFiles('package.json') }}
restore-keys: |
npm-fast-${{ runner.os }}-
- run: npm install
- run: npm run build:skills
- name: Run the fast lane
run: env -u PLAN2CODE_IN_APP -u PLAN2CODE_APP_TOKEN -u PLAN2CODE_APP_VERSION -u PLAN2CODE_APP_ANNOUNCE -u PLAN2CODE_EMBED_ORIGIN -u PLAN2CODE_CONSOLE_SID -u PLAN2CODE_LOOP_STRENGTH npm run test:fast
+18 -1
View File
@@ -87,11 +87,28 @@ jobs:
key: cargo-release-${{ matrix.label }}-${{ hashFiles('plan2code-app/Cargo.lock') }}
restore-keys: |
cargo-release-${{ matrix.label }}-
- name: Name this week for the apt cache
if: runner.os == 'Linux'
id: week
run: echo "week=$(date +%G-%V)" >> "$GITHUB_OUTPUT"
- name: Cache the Linux system packages
# Keep the downloaded .deb files (the WebKit packages are hundreds of MB, and the runner's
# mirror is sometimes slow), as app.yml does. The key rolls over weekly.
if: runner.os == 'Linux'
uses: actions/cache@v6.1.0
with:
path: ~/apt-archives
key: apt-tauri-release-${{ runner.os }}-${{ steps.week.outputs.week }}
restore-keys: |
apt-tauri-release-${{ runner.os }}-
- name: Install Linux system packages
if: runner.os == 'Linux'
run: |
mkdir -p "$HOME/apt-archives/partial"
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev build-essential libxdo-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev
sudo apt-get -o Dir::Cache::archives="$HOME/apt-archives" install -y libwebkit2gtk-4.1-dev build-essential libxdo-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev
# apt ran as root: hand the folder back so the cache step can read and save it.
sudo chown -R "$(id -u):$(id -g)" "$HOME/apt-archives"
- name: Install the app's packages
working-directory: plan2code-app
run: npm ci
-1
View File
@@ -6,7 +6,6 @@ plan2code-metrics/node_modules
plan2code-metrics/package-lock.json
.plan2code-loop
.plan2code-metrics
nul
.cognition/
handoffs/
node_modules/
+1
View File
@@ -1,2 +1,3 @@
node scripts/check-staged-nul.mjs
node scripts/fix-line-endings.mjs
node scripts/validate-char-count.js
+1 -1
View File
@@ -3,7 +3,7 @@
**Status:** implemented in v2.4.0. Kept as the design record, because it explains
*why* the thing is shaped the way it is. For how to use it, see
[web-console.md](./web-console.md); for where the code lives, see
[AGENTS-architecture.md](../.agents-docs/AGENTS-architecture.md).
[AGENTS-architecture.md](../.agents-docs/AGENTS-architecture.md) (an index of the area files).
**Date:** 2026-09-20
**Scope:** an optional local browser UI that `plan2code-0-pathfinder` and `plan2code-1-plan` can offer at startup, built as a shared component other workflow steps can adopt later.
+12 -8
View File
@@ -1664,7 +1664,7 @@ named `<slug of your file name>-<8 characters of the upload id>.<ext>`, so
keeping the same upload twice reuses it. Attachments nothing cites stay in the
session, and quick-question attachments are never kept. `keep` is run by the
agent, in its own shell; the server itself still never writes into your
project.
project (its one delete there is Cleanup's, below).
### Ask a quick question
@@ -1830,8 +1830,9 @@ roughly the time the browser itself takes to open.
**It stays up while the page is open.** The page pings it every few seconds, so
the idle clock never runs down while you are there. Close the tab and it shuts
itself down about two minutes later; it stops after four hours regardless, and
the agent stops it outright when the session ends.
itself down about two minutes later; it stops after four hours unless answers
you sent are still waiting for the agent, and the agent stops it outright when
the session ends.
**The setup session hands its tab to the agent it finds.** A `setup` session is
agent-less: nothing reads its sends, so the page's agent-silence and question
@@ -1905,8 +1906,9 @@ reads), `models.json`, `handoffs/` (old handoffs go by age, above),
more is listed as one item, *Notebook for* its folder, and goes whole; no
automatic sweep ever removes one. It also lists each
folder in the project's `specs--completed/` whose newest file is more than 30
days old: archived specs Finalize moved there. Deleting one is permanent:
`specs--completed/` is usually gitignored, so git can't restore it. A stray is listed once
days old: archived specs Finalize moved there. Only a folder git tracks is
deleted: `specs--completed/` is usually gitignored, so git couldn't restore
it, and Cleanup keeps it and says why instead. A stray is listed once
it has sat untouched for an hour, so a lock or temp file another session is
writing right now is never caught. **Delete these** removes
that list and nothing else. A console running from another home
@@ -1985,7 +1987,7 @@ origin.
| | |
| --- | --- |
| Source | `src/web-console/` (one row per file in the files table of `.agents-docs/AGENTS-architecture.md`; a test keeps it complete) |
| Source | `src/web-console/` (one row per file in the files tables of the `.agents-docs/AGENTS-architecture-*.md` area files; a test keeps it complete) |
| Ships as | `skills/<every skill>/references/web-console/` |
| Wiring | one `additionalReferences` entry per skill in `install.js`; the dashboard's menu lives in `public/skills.js` (each entry's `card`; `SKILL_CATALOG` in `public/answers.js` is a lookup on it) |
| Agent contract | a card, `src/web-console/console.md` (read once), plus pointers: the console names a topic file (`console-*.md`, `notes/<workflow>.md`, `building.md` / `building-review.md`) in its own `read` output, once per session per topic, when its moment comes; `console.mjs help <topic>` prints any of them. A `stop` with no `finish`, or a `finish` while `stopWarning` is set, is refused with the fix; `stop --session <sid> --force` ends a dead page or an abandoned session anyway. Patches are one line, with lettered options and the console's own defaults filled in; a refused patch names the field and the fix. Byte budgets keep the card, the notes and a sample session's outputs from growing back (`scripts/test-console-wire-budgets.mjs`) |
@@ -2046,10 +2048,12 @@ Two environment variables help when the start is what you are looking at:
| `PLAN2CODE_CONSOLE_TRACE=1` | `open` prints a timeline of its steps to stderr (roots found, server spawned, port bound, browser sent, state written, server listening). |
| `PLAN2CODE_BROWSER` | The command that opens the link instead of the system default, run through the shell with the link appended, e.g. `PLAN2CODE_BROWSER='firefox --new-tab'`. |
Every `console.mjs open` also writes its own directory to
Every `console.mjs open` of an installed console (one run from a version folder
under `~/.plan2code/console/`) also writes its own directory to
`$PLAN2CODE_CONSOLE_HOME/console-dir` (or `~/.plan2code/console/console-dir`
when the override is unset): it is how an agent finds the console on a later
session without searching the skill install dirs.
session without searching the skill install dirs. A console run from a source
checkout leaves the pointer alone.
The vendored file is `src/web-console/public/vendor/marked.esm.js`,
sha256 `7a7d9a521ac9384e0c3a075120a7c486cbd0c3c32cc5601bbb79a23e97403690`.
+9 -9
View File
@@ -4,7 +4,7 @@ This file provides guidance to AI coding agents working with code in this reposi
## Project Overview
Plan2Code is a structured 4-step workflow methodology for AI-assisted software development. It provides prompt templates that can be installed globally or per-project for various AI coding tools (Claude Code, Cursor, Copilot, Continue, Windsurf, Codeium, Devin, Zed).
Plan2Code is a structured 4-step workflow methodology for AI-assisted software development. It provides prompt templates (skills) that the `skills` CLI installs globally or per-project into any agent it supports (README's "Supported tools" lists them). The `plan2code` command and the desktop app launch the dashboard directly in the built-in agents of `src/launcher/agents.json` (Claude Code, Devin, Codex); Copilot CLI, OpenCode, Gemini CLI and Pi are starter templates there, and any other agent CLI can be added as a custom agent.
**Version:** Check `version.json` for current version
**Author:** Justin Parker
@@ -20,7 +20,7 @@ This file is an index — each section below contains a brief summary and a link
High-level directory structure, key files, workflow prompt inventory, and file naming conventions.
Details: [Architecture](./.agents-docs/AGENTS-architecture.md)
Details: [Architecture index](./.agents-docs/AGENTS-architecture.md) (layout, prompts, install: [AGENTS-architecture-install.md](./.agents-docs/AGENTS-architecture-install.md))
## Plan2Code Metrics
@@ -32,22 +32,22 @@ Details: [Plan2Code Metrics](./.agents-docs/AGENTS-plan2code-metrics.md)
Optional CLI status bar (`src/statusline-claude/`) for Claude Code. Displays model (+ effort), project/worktree, branch, git diff stats, duration + session cost, context usage, and usage stats (rate limits or token counts). Reads data directly from Claude Code's stdin JSON (plus timeout-bounded git calls): no API calls, no auth, no background processes.
Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Status Line section)
Details: [Status line](./.agents-docs/AGENTS-architecture-statusline.md)
## Web Console
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, private: the agent reads a tab only when you start Pathfinder, Plan, Quick Task or Revise plan from the dashboard with it and send the box it fills (an idea box marked `fill: "note"`, up to five ticked pictures attached), which then marks the tab sent via `POST /notepad/tab/sent`; the agent CLI never imports the store; removed only through Cleanup once a month untouched), **Activities** behind the top bar's die (thirteen small games, Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, listed in `public/activities.js` with one module per game under `public/activities/` (Ghoul Rush is its own folder of modules, `public/activities/ghoul-rush/`) and a card line (`blurb`) each, a picker page of game cards once two are listed that plays one game at a time (another pick drops the last game's round), driven by `screens/activities.js` (keys, key releases for a game with `release()`, canvas pointer events for a game with `pointer()`, one frame timer), paused whenever the person's turn comes and resumed only by the person (while that pause's banner is up, only by its **Unpause game** button), best scores in flat `activityBest<Id>` keys in `looks.json` (lowest wins for a game that sets `lowerIsBetter`; Mini golf opens on a dashboard of its six 18-hole courses, one file each under `public/activities/golf-course-<id>.js`, and keeps a best per course, `activityBestGolf<Course>`), and one number a game may keep between sessions in `activityMemo<Id>` (Snake's tally of surprises found, Light Trails' furthest arena, Bug Hunt's tally of finds, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's most stages cleared in a run, Flock Dash's furthest stage), never shown to the agent), a built-in 21-topic Help, the app-only **Implementation Loop** (a dashboard card and a setup screen drawn by the page, `public/screens/loop-setup.js`; the last setup remembered per project in `~/.plan2code/console/loop-setup.json`, owned by `loop-setup.mjs`; a page that locks while `state.loop.driving` is set, until the app posts `loopEnd`; a skill run with `--loop` reports a `loopOutcome` instead of asking for sign-off, per `notes/loop.md`), a first-run Welcome, User Preferences (gear: four tabs, Appearance, Agents & models, System and Sounds & activities, on the `public/tabs.js` helper Help also uses, with `public/prefs.js`, `screens/prefs-dialog.js` and `screens/agents-view.js`), an agent-less **setup** page (the `setup` workflow `plan2code` or the desktop app opens when no agent can run: each built-in's found / outside-PATH / missing state from `agent-lookup.mjs`, install lines, Check again, Use it from here, starter templates and Start, which hands the tab to the new agent through a token-guarded `POST /handover` and a `move` event; the app shows it in its window from a Set up an agent button instead) and a bug/idea link to GitHub issues. On opted-in skills (every workflow but the dashboard, Finalize, Changelog, Git and Handoff) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`), and a Helper strength choice (Balanced, Thrifty, Best, Match my session; rules in `src/shared-references/helper-strength.md`, shipped in the twelve helper skills); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; taskLine truncated
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) installed once under `~/.plan2code/console/<version>/` (`installSharedConsole` in `install.js`) and reached from every skill through a forwarding stub, `src/web-console-stub/console.mjs`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, private: the agent reads a tab only when you start Pathfinder, Plan, Quick Task or Revise plan from the dashboard with it and send the box it fills (an idea box marked `fill: "note"`, up to five ticked pictures attached), which then marks the tab sent via `POST /notepad/tab/sent`; the agent CLI never imports the store; removed only through Cleanup once a month untouched), **Activities** behind the top bar's die (thirteen small games, Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, listed in `public/activities.js` with one module per game under `public/activities/` (Ghoul Rush is its own folder of modules, `public/activities/ghoul-rush/`) and a card line (`blurb`) each, a picker page of game cards once two are listed that plays one game at a time (another pick drops the last game's round), driven by `screens/activities.js` (keys, key releases for a game with `release()`, canvas pointer events for a game with `pointer()`, one frame timer), paused whenever the person's turn comes and resumed only by the person (while that pause's banner is up, only by its **Unpause game** button), best scores in flat `activityBest<Id>` keys in `looks.json` (lowest wins for a game that sets `lowerIsBetter`; Mini golf opens on a dashboard of its six 18-hole courses, one file each under `public/activities/golf-course-<id>.js`, and keeps a best per course, `activityBestGolf<Course>`), and one number a game may keep between sessions in `activityMemo<Id>` (Snake's tally of surprises found, Light Trails' furthest arena, Bug Hunt's tally of finds, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's most stages cleared in a run, Flock Dash's furthest stage), never shown to the agent), a built-in 21-topic Help, the app-only **Implementation Loop** (a dashboard card and a setup screen drawn by the page, `public/screens/loop-setup.js`; the last setup remembered per project in `~/.plan2code/console/loop-setup.json`, owned by `loop-setup.mjs`; a page that locks while `state.loop.driving` is set, until the app posts `loopEnd`; a skill run with `--loop` reports a `loopOutcome` instead of asking for sign-off, per `notes/loop.md`), a first-run Welcome, User Preferences (gear: four tabs, Appearance, Agents & models, System and Sounds & activities, on the `public/tabs.js` helper Help also uses, with `public/prefs.js`, `screens/prefs-dialog.js` and `screens/agents-view.js`), an agent-less **setup** page (the `setup` workflow `plan2code` or the desktop app opens when no agent can run: each built-in's found / outside-PATH / missing state from `agent-lookup.mjs`, install lines, Check again, Use it from here, starter templates and Start, which hands the tab to the new agent through a token-guarded `POST /handover` and a `move` event; the app shows it in its window from a Set up an agent button instead) and a bug/idea link to GitHub issues. On opted-in skills (every workflow but the dashboard, Finalize, Changelog, Git and Handoff) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`), and a Helper strength choice (Balanced, Thrifty, Best, Match my session; rules in `src/shared-references/helper-strength.md`, shipped in the twelve helper skills); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live inLine truncated
One agent list and one lookup rule serve the launcher, the console and the app: `src/launcher/agents.json` (the built-ins and starter templates with per-OS install data) and `src/web-console/agent-lookup.mjs` (`loadAgentList()` and `findAgent()`, both copied by `install.js` into `~/.plan2code/bin/`); the app carries a Rust twin held to the same cases by `scripts/fixtures/agent-lookup-cases.json`.
Building or changing an Activities game: follow the game rules in [Architecture](./.agents-docs/AGENTS-architecture.md) ("Building an Activities game": lives in the solid lives pill, the endless-lives code (`cheat(on)`) in every game with lives, banners placed away from the player and see-through over what matters, pausing left to the window).
Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Web Console section) and [.readme/web-console.md](./.readme/web-console.md)
Building or changing an Activities game: follow the game rules in [Activities](./.agents-docs/AGENTS-architecture-activities.md) ("Building an Activities game": lives in the solid lives pill, the endless-lives code (`cheat(on)`) in every game with lives, banners placed away from the player and see-through over what matters, pausing left to the window).
Details: [Web console server and contract](./.agents-docs/AGENTS-architecture-console.md), [page](./.agents-docs/AGENTS-architecture-console-page.md), [design points](./.agents-docs/AGENTS-architecture-console-design.md), [Activities](./.agents-docs/AGENTS-architecture-activities.md) (and the Ghoul Rush files it links) and [.readme/web-console.md](./.readme/web-console.md)
Why the agent-facing console docs are shaped as they are (the card, pointers, refusals): [Web Console Contract](./.agents-docs/AGENTS-web-console-contract.md); it never ships.
## Skill Scripts
Deterministic workflow steps run as Node scripts shipped in each skill's `scripts/` (shared ones in `src/skill-scripts/`, a skill's own in `src/<skill>-scripts/`, listed per skill in `SOURCE_PROMPTS` → `scripts`). Prose keeps the judgment. JSON on stdout, documented exit codes, tests run against the built `skills/` tree.
Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Skill Scripts section)
Details: [Skill scripts](./.agents-docs/AGENTS-architecture-skill-scripts.md)
## Development Commands
@@ -100,9 +100,9 @@ When you make a mistake, get corrected, or discover something about this codebas
- When a new first-run dialog is added to the web console, set its seen flag in `scripts/capture-screenshots.mjs`'s `looks.json` too: the Welcome dialog once covered the regenerated dashboard screenshots until `welcomeSeen: true` was added.
- Import `scripts/skill-script-helpers.mjs` in any test that builds git fixtures for a skill script or `git-repo.mjs`: it scrubs the whole test process's git config, so fixtures, imported modules and spawned scripts agree. Mixed configs broke `git plan switch` once (a global `core.autocrlf=true` checked fixtures out with CRLF the scrubbed script read as changed). It also rebuilds `skills/` and prunes any skill folder `install.js` does not list, so register a new skill in `SOURCE_PROMPTS` before running its `scripts/test-script-<name>.mjs` or the script under test vanishes.
- 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 every file that carries it in the same change, then run `npm run build:skills`: `version.json` (with its `releaseDate`), the root `package.json`, README's `Version X.Y.Z` line, and under `plan2code-app/`: `package.json`, `package-lock.json` (two lines), `src-tauri/tauri.conf.json`, `src-tauri/Cargo.toml`, `fake-agent/Cargo.toml` and `Cargo.lock` (the `plan2code-app` and `fake-agent` entries). `node scripts/check-versions.mjs` compares all of them and runs in `npm test`; widen its `SOURCES` when a new file carries the version. The changelog skill only touches `package.json`: v2.9.0 nearly shipped with `version.json` at 2.8.1, and README's line sat at 2.6.0 for three releases.
- When a `CHANGELOG.md` heading gets a version number, write the heading by hand, then run `node scripts/set-version.mjs <x.y.z>`, which sets the same number in every file that carries it in the same change, then run `npm run build:skills`: `version.json` (with its `releaseDate`), the root `package.json`, README's `Version X.Y.Z` line, and under `plan2code-app/`: `package.json`, `package-lock.json` (two lines), `src-tauri/tauri.conf.json`, `src-tauri/Cargo.toml`, `fake-agent/Cargo.toml` and `Cargo.lock` (the `plan2code-app` and `fake-agent` entries). `node scripts/check-versions.mjs` compares all of them and runs in `npm test`; widen its `SOURCES` when a new file carries the version. 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"). `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.
- 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`, `PLAN2CODE_CONSOLE_SID` and `PLAN2CODE_LOOP_STRENGTH` unset (`env -u ... npm test`; a Loop phase's agent has the last one, and two `loop_driver` strength tests then fail with `never saw the env line`): 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.
+28
View File
@@ -4,6 +4,12 @@ All notable changes to Plan2Code will be documented in this file.
## v3.0.4
### ✨ Added
- **tests**: a fast test lane, `npm run test:fast`, runs the quick suites (none starts a console server, runs a page suite or plays a game) in about two minutes. `scripts/test-lanes.json` lists every test file in exactly one of two lists, and `scripts/check-test-lanes.mjs` fails when a new test file is in neither. A new `fast-tests` workflow runs the lane on Ubuntu for every pull request, and on all three systems for main and for a pull request labeled `full-matrix`.
- **tooling**: `scripts/set-version.mjs <x.y.z>` writes one version into every file that carries it (`version.json` with its release date, the root `package.json`, README's `Version` line, and the desktop app's `package.json`, `package-lock.json`, `tauri.conf.json`, both `Cargo.toml` files and `Cargo.lock`), and `scripts/check-doc-size.mjs` keeps every file in `.agents-docs/` under a size limit.
- **skill scripts**: one shared rule now derives a spec's state for both the dashboard and `specs.mjs status`, and a spec whose only open tasks are blocked ones, each with a written reason, now lights Finalize. `specs.mjs` gains a format `check` with four rules (a warning, or an error for a spec marked `<!-- plan2code-format: 2 -->`) and an `archive` that verifies names and sizes before it removes a copied source, and Pathfinder's script gains `init` and `add` commands.
### 🐛 Fixed
- **desktop app**: the agent setup page's **Back** button now sits in the app's top bar instead of floating over the page, where it covered the settings and help icons.
@@ -11,10 +17,32 @@ All notable changes to Plan2Code will be documented in this file.
- **web console**: the **Install page** link on the agent setup page now opens in your default browser inside the desktop app. It did nothing there, because the page was not told it was running in the app.
- **web console**: a note you have sent now shows a small spinner in front of "Sent, waiting for Plan2Code" in the Notes panel, so it is clear Plan2Code is still working on it. The spinner hides when the agent has gone quiet, so a dead session is not mistaken for a slow one.
- **web console**: a finished session now has a **Back to the dashboard** button in the footer, beside the disabled Send, so the way home is always in reach. It used to sit far down the finish card, which left the top bar's New Session as the only visible way out.
- **web console**: the session token no longer appears on the server's command line or in its log. `open` hands it over in a one-shot file the server reads and deletes.
- **web console**: a server no longer exits after four hours while a result is waiting to be collected, and a stale lock is judged by whether its holder is still running, not by its age.
- **web console**: Cleanup now refuses a `specs--completed/<feature>` folder that git does not track, and says why on the page.
- **web console**: the light theme's faintest ink now meets WCAG AA contrast, the verdict buttons carry `aria-pressed`, and the Ask log and footer no longer redraw when nothing changed.
- **desktop app**: stopping the console and starting it again reopens the same session, a start or status check no longer holds the console lock while it probes, and the remaining Windows spawns no longer flash a console window. The release build is smaller (`lto`, `strip`, `panic = abort`).
- **install**: each skill's console stub now looks for its own version folder before the `console-dir` pointer, and only an installed console writes that pointer, so running the console from a source checkout can no longer leave every skill unable to find it. An update removes the older console versions only after the skills have installed, so a failed update leaves the old skills working.
- **desktop app**: the Implementation Loop now lists untracked files one by one, so a folder that was untracked before a phase neither hides the agent's new files from the phase commit nor takes the person's files into it, and an unreadable page no longer replaces the Loop's page candidate.
- **skill scripts**: `pathfinder init` now refuses a checkbox line or a loop completion token in its arguments, as `pathfinder add` already did.
- **install**: `plan2code-init` warns once when `specs--completed/` is gitignored, and the test-map and run-check scripts now ship to the skills that use them.
### 🔧 Changed
- **web console**: the Notebook's tab name dialog now counts characters as you type (such as `41/40`), warns the moment a name passes the 40 character limit and disables Save until it fits, instead of only saying so after you press Save.
- **install**: the web console is now installed once, under `~/.plan2code/console/<version>/`, and shared by all 19 skills through a small stub in each, instead of being copied into every skill. An install removes the older version folders and leaves every other entry alone.
- **install**: the `skills` CLI now runs pinned to an exact version (`skills@1.7.6`), so a new release of it can never change an install between two runs of the same Plan2Code.
- **launcher**: with no terminal to ask on (a script or a pipe), `plan2code` now keeps the agent's permission prompts on. `--bypass-permissions` turns them off without asking, and `--keep-permissions` still keeps them and wins. The question names what the flag drops (for Codex, its approval prompts and its sandbox).
- **implementation loop**: a phase run on best guess now stops on the next look when a question is open, instead of carrying on. The loop's commit stages only the phase's own files, by name, and fails closed when it cannot read the list. `commit-msg.mjs --add-all` is retired for `--files`.
- **prompts**: product tool names (the question tool, Glob, Grep) are gone from the prompts, and `scripts/check-prompt-wording.mjs` keeps them out of the built skills. The eighteen console openings are held to nine shared sentences by `scripts/check-console-openings.mjs`, and the rules for a review inside a build live once, in `src/shared-references/review-in-build.md`.
- **metrics**: the metrics scanner no longer refuses ordinary text, so a risk-register row that ends in text is accepted, and the collector now fingerprints every prompt, keyed by name. The dead loop-token item is gone.
- **bot**: the bot copies each of its skills' whole folder, so a skill's references and scripts come along.
- **prompts**: Plan infers the testing posture from the test map instead of asking, Document writes `<!-- plan2code-format: 2 -->` into a new `overview.md`, the six side skills have descriptions that say when they fit, Pathfinder reads its `grilling.md` and `trail.md` only when it needs them, and Finalize's changelog row is gone.
- **tooling**: a stray `nul` file at the repo root and its ignore line are removed, and `scripts/check-staged-nul.mjs` runs first in the pre-commit hook so one cannot be committed again.
### 📚 Documentation
- **docs**: `.agents-docs/AGENTS-architecture.md` is now a short index. The 280 KB file is split by area into the layout and install notes, skill scripts, the status line, the web console (server and contract, page files, design points), the Activities games and Ghoul Rush. Stale facts are corrected (CI runs on Ubuntu for every pull request, and on three systems for main and `full-matrix`), and the lists of supported agents now say what each means: the agents the skills CLI installs into, and the built-ins and starter templates `plan2code` launches.
## v3.0.3
+8 -3
View File
@@ -85,7 +85,10 @@ chooses the model. It works in cmd, PowerShell, Git Bash, macOS and Linux shells
Claude Code, Devin or Codex CLI on your `PATH`. After you pick the agent it asks whether to turn its
permission prompts off (Yes by default; `--permission-mode bypassPermissions` in Claude Code, `--permission-mode bypass`
in Devin, `--dangerously-bypass-approvals-and-sandbox` in Codex, a custom agent's bypass arguments, and no question for a
custom agent that has none). `plan2code --keep-permissions` keeps the prompts without asking. The installer then offers a desktop shortcut (answer `y`),
custom agent that has none; for Codex the question names its sandbox, which that flag turns off too). It asks on every
launch and remembers no answer. `plan2code --keep-permissions` keeps the prompts without asking, and
`plan2code --bypass-permissions` turns them off without asking. With no terminal to ask on (a script or a pipe) the
prompts stay on unless `--bypass-permissions` is given. The installer then offers a desktop shortcut (answer `y`),
which opens a folder picker first. Uninstalling (`U`) removes both.
</details>
@@ -140,10 +143,12 @@ plain `plan2code` command above, without the app, asks instead, with prompts off
[docs/desktop-app.md](docs/desktop-app.md).
</details>
**Supported tools:** every agent supported by the skills CLI, including Claude Code · Cursor ·
**Supported tools** (the agents the skills CLI can install into): every agent it supports, including Claude Code · Cursor ·
GitHub Copilot · Windsurf · Codex · Continue · Codeium · Zed · Amp · OpenCode · Devin · Crush · Pi ·
Gemini CLI · Cline · Roo · Kilo · Goose · Trae · Qwen Code.
**Launched by `plan2code`:** the `plan2code` command and the desktop app open the dashboard directly in Claude Code, Devin and Codex (the built-ins in `src/launcher/agents.json`). GitHub Copilot CLI, OpenCode, Gemini CLI and Pi come as starter templates, and you can add any other agent CLI as a custom agent in User Preferences → Agents & models.
The installer keeps one canonical copy of each skill under `~/.agents/skills/` and links it into
agents that maintain their own directory. To update, run `plan2code update` (or re-run the install command).
@@ -432,7 +437,7 @@ console or the terminal; add `--web` to skip the question and go straight to the
## Troubleshooting
**The skills aren't recognized.** Re-run the installer and restart your AI tool. Confirm the global
install with `npx skills list -g`. For a project install, check the generated directories aren't
install with `npx skills@1.7.6 list -g`. For a project install, check the generated directories aren't
gitignored.
**Your tool doesn't read Agent Skills.** Since v2.2.0, Plan2Code ships only as skills. If your tool
+153 -18
View File
@@ -119,6 +119,18 @@ const SRC_DIR = path.join(__dirname, 'src');
const SHARED_SCRIPTS_DIR = 'skill-scripts';
const SHARED_SCRIPTS_ALWAYS = ['common.mjs'];
// The web console is built once, into skills/_console/<version>/, and installed once, into
// ~/.plan2code/console/<version>/. Each skill carries only a forwarding stub
// (src/web-console-stub/) and the markdown the agent reads by path (the card, its topic files
// and notes/).
const CONSOLE_SOURCE = 'web-console';
const CONSOLE_SHARED_DIR = '_console';
const CONSOLE_STUB_SRC = path.join(SRC_DIR, 'web-console-stub', 'console.mjs');
const CONSOLE_STUB_VERSION_TOKEN = '__PLAN2CODE_VERSION__';
// The same pattern as CONSOLE_VERSION_DIR in src/web-console/sessions.mjs, which keeps these
// folders out of Cleanup.
const CONSOLE_VERSION_DIR = /^\d+\.\d+\.\d+$/;
// ============================================================================
// SYNC PROMPTS CONFIGURATION (merged from sync-prompts.js)
// ============================================================================
@@ -182,10 +194,11 @@ const SOURCE_PROMPTS = [
isUtility: true,
// review.md rides along for the web console's "Review it now" button, which
// runs the review in the same session once the quick task is built.
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs'],
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs', 'glob.mjs', 'test-map.mjs', 'test-match.mjs', 'run-check.mjs'],
additionalReferences: [
{ source: 'web-console', target: 'web-console' },
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' },
{ source: 'shared-references/review-in-build.md', target: 'review-in-build.md' },
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' },
{ source: 'shared-references/test-runs.md', target: 'test-runs.md' },
{ source: 'plan2code-review.md', target: 'review.md' },
@@ -237,10 +250,11 @@ const SOURCE_PROMPTS = [
description: 'Execute implementation phase by phase',
// review.md rides along for the web console's review offer on the sign-off
// card, which runs the review in the same session before the phase is approved.
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs'],
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs', 'glob.mjs', 'test-map.mjs', 'test-match.mjs', 'run-check.mjs'],
additionalReferences: [
{ source: 'web-console', target: 'web-console' },
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' },
{ source: 'shared-references/review-in-build.md', target: 'review-in-build.md' },
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' },
{ source: 'shared-references/test-runs.md', target: 'test-runs.md' },
{ source: 'plan2code-review.md', target: 'review.md' },
@@ -253,11 +267,12 @@ const SOURCE_PROMPTS = [
name: 'implement-review',
displayName: 'Implementation + Review Mode',
description: 'Implement one phase, review it, then request sign-off',
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs'],
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs', 'glob.mjs', 'test-map.mjs', 'test-match.mjs', 'run-check.mjs'],
additionalReferences: [
{ source: 'web-console', target: 'web-console' },
{ source: 'plan2code-3-implement.md', target: 'implement.md' },
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' },
{ source: 'shared-references/review-in-build.md', target: 'review-in-build.md' },
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' },
{ source: 'shared-references/test-runs.md', target: 'test-runs.md' },
{ source: 'plan2code-review.md', target: 'review.md' },
@@ -270,10 +285,13 @@ const SOURCE_PROMPTS = [
name: 'review',
displayName: 'Review Mode',
description: 'Comprehensive post-implementation review with spec compliance checking',
// Shown to the agent in place of the generic header text: when the skill fits and its command.
skillDescription: "Use when a change, branch or spec needs an independent review for bugs, spec drift and gaps, before a commit or pull request. Run it as /plan2code-review.",
isUtility: true,
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs'],
additionalReferences: [
{ source: 'web-console', target: 'web-console' },
{ source: 'shared-references/review-in-build.md', target: 'review-in-build.md' },
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' },
{ source: 'shared-references/test-runs.md', target: 'test-runs.md' }
]
@@ -286,11 +304,12 @@ const SOURCE_PROMPTS = [
description: 'Validate, summarize, and archive completed work',
// review.md rides along for Step 2.5's final review, which runs in the
// same session before the summary is written and the spec is archived.
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs'],
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs', 'glob.mjs', 'test-map.mjs', 'test-match.mjs', 'run-check.mjs'],
additionalReferences: [
{ source: 'web-console', target: 'web-console' },
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' },
{ source: 'shared-references/test-runs.md', target: 'test-runs.md' },
{ source: 'shared-references/review-in-build.md', target: 'review-in-build.md' },
{ source: 'plan2code-review.md', target: 'review.md' },
{ source: 'plan2code-review-references' }
]
@@ -311,6 +330,8 @@ const SOURCE_PROMPTS = [
name: 'xray',
displayName: 'X-ray Mode',
description: 'Explain how and why an area of the code works, or find the rough spots worth fixing',
// Shown to the agent in place of the generic header text: when the skill fits and its command.
skillDescription: "Use when you want to understand how and why an area of the code works, or find its rough spots worth fixing. Run it as /plan2code-xray.",
isUtility: true,
scripts: [],
additionalReferences: [
@@ -324,6 +345,8 @@ const SOURCE_PROMPTS = [
name: 'diagnose',
displayName: 'Diagnose Mode',
description: 'Find and write up a bug\'s cause without fixing it',
// Shown to the agent in place of the generic header text: when the skill fits and its command.
skillDescription: "Use when a bug's cause is unknown and you want it found and written up without a fix. Run it as /plan2code-diagnose.",
isUtility: true,
scripts: ['specs.mjs'],
additionalReferences: [
@@ -338,6 +361,8 @@ const SOURCE_PROMPTS = [
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',
// Shown to the agent in place of the generic header text: when the skill fits and its command.
skillDescription: "Use when a branch is nearly done and you want its checks run, a readiness verdict and a pull-request description. Run it as /plan2code-pr-prep.",
isUtility: true,
scripts: ['review-scope.mjs', 'glob.mjs', 'test-map.mjs', 'test-match.mjs', 'test-commands.mjs', 'run-check.mjs'],
additionalReferences: [
@@ -352,6 +377,8 @@ const SOURCE_PROMPTS = [
name: 'test',
displayName: 'Test Mode',
description: 'Find untested code and write unit and integration tests in the project\'s own style',
// Shown to the agent in place of the generic header text: when the skill fits and its command.
skillDescription: "Use when code has no tests or weak ones and you want unit and integration tests written in the project's own style. Run it as /plan2code-test.",
isUtility: true,
scripts: ['review-scope.mjs', 'glob.mjs', 'test-map.mjs', 'test-match.mjs', 'test-commands.mjs', 'run-check.mjs'],
additionalReferences: [
@@ -367,6 +394,8 @@ const SOURCE_PROMPTS = [
name: 'changelog',
displayName: 'Changelog Mode',
description: 'Check the CHANGELOG version against the default branch, suggest entries for new work, keep package.json aligned',
// Shown to the agent in place of the generic header text: when the skill fits and its command.
skillDescription: "Use before a pull request when CHANGELOG.md needs its version checked against the default branch and entries for the new work. Run it as /plan2code-changelog.",
isUtility: true,
scripts: [],
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
@@ -421,7 +450,7 @@ function generateSkillHeader(prompt, disableModelInvocation = false) {
const lines = [
'---',
`name: ${generateSkillName(prompt)}`,
`description: "Plan2Code ${generateStepLabel(prompt)}: ${prompt.displayName} - user-initiated workflow step. Do not invoke autonomously."`,
`description: "Plan2Code ${generateStepLabel(prompt)}: ${prompt.skillDescription ? `${prompt.skillDescription} User-initiated only; do not invoke autonomously.` : `${prompt.displayName} - user-initiated workflow step. Do not invoke autonomously.`}"`,
];
if (disableModelInvocation) lines.push('disable-model-invocation: true');
lines.push('---');
@@ -654,9 +683,39 @@ function listFilesRecursive(dir, prefix = '') {
return out;
}
/**
* The web console's files, split two ways. `local` is what each skill carries: the forwarding
* stub (with the version baked in) and the markdown the agent reads by path. `shared` is the
* whole console plus its version.txt and version.json, built once under
* skills/_console/<version>/. Both map a path (relative to its folder) to a Buffer.
*/
function loadConsoleFiles(errors) {
const local = new Map();
const shared = new Map();
const version = JSON.parse(fs.readFileSync(path.join(__dirname, 'version.json'), 'utf8')).version;
const source = path.join(SRC_DIR, CONSOLE_SOURCE);
try {
for (const relPath of listFilesRecursive(source)) {
const key = relPath.split(path.sep).join('/');
const bytes = fs.readFileSync(path.join(source, relPath));
shared.set(key, bytes);
if (key.endsWith('.md') && !key.startsWith('public/')) local.set(key, bytes);
}
const stub = fs.readFileSync(CONSOLE_STUB_SRC, 'utf8');
if (!stub.includes(CONSOLE_STUB_VERSION_TOKEN)) throw new Error(`no ${CONSOLE_STUB_VERSION_TOKEN} to bake the version into`);
local.set('console.mjs', Buffer.from(stub.replace(CONSOLE_STUB_VERSION_TOKEN, version)));
} catch (err) {
errors.push(`Could not read the web console sources: ${err.message}`);
}
shared.set('version.txt', Buffer.from(`${version}\n`));
shared.set('version.json', fs.readFileSync(path.join(__dirname, 'version.json')));
return { local, shared, version };
}
function computeExpectedSkills() {
const expected = new Map();
const errors = [];
const consoleFiles = loadConsoleFiles(errors);
for (const prompt of SOURCE_PROMPTS) {
const sourcePath = path.join(SRC_DIR, prompt.source);
@@ -689,11 +748,11 @@ function computeExpectedSkills() {
for (const reference of prompt.additionalReferences || []) {
const absSource = path.join(SRC_DIR, reference.source);
if (reference.source === 'web-console') {
expected.set(
`${SKILLS_DIR_NAME}/${skillName}/references/${reference.target}/version.json`,
fs.readFileSync(path.join(__dirname, 'version.json'))
);
if (reference.source === CONSOLE_SOURCE) {
for (const [relPath, bytes] of consoleFiles.local) {
expected.set(`${SKILLS_DIR_NAME}/${skillName}/references/${reference.target}/${relPath}`, bytes);
}
continue;
}
try {
if (fs.statSync(absSource).isDirectory()) {
@@ -750,6 +809,10 @@ function computeExpectedSkills() {
}
}
for (const [relPath, bytes] of consoleFiles.shared) {
expected.set(`${SKILLS_DIR_NAME}/${CONSOLE_SHARED_DIR}/${consoleFiles.version}/${relPath}`, bytes);
}
return { expected, errors };
}
@@ -775,14 +838,15 @@ function buildSkills(quiet = false) {
if (fs.existsSync(SKILLS_DIR)) {
for (const entry of fs.readdirSync(SKILLS_DIR)) {
const entryPath = path.join(SKILLS_DIR, entry);
if (!fs.statSync(entryPath).isDirectory() || expectedSkillNames.has(entry)) continue;
if (!fs.statSync(entryPath).isDirectory() || expectedSkillNames.has(entry) || entry === CONSOLE_SHARED_DIR) continue;
deleteDirectory(entryPath);
stats.pruned++;
if (!quiet) console.log(` ${COLORS.YELLOW}░░░${COLORS.RESET} Pruned: ${entry}/`);
}
}
for (const skillName of expectedSkillNames) {
// The shared console is swept like a skill folder: an older version's files are not expected.
for (const skillName of [...expectedSkillNames, CONSOLE_SHARED_DIR]) {
const skillDir = path.join(SKILLS_DIR, skillName);
if (!fs.existsSync(skillDir)) continue;
for (const relPath of listFilesRecursive(skillDir)) {
@@ -859,6 +923,62 @@ function verifySkillsSync() {
return true;
}
/**
* The folder the shared console lives in: ~/.plan2code/console, or PLAN2CODE_CONSOLE_HOME (the
* console's own override, which the tests use). Read when called, never at load.
*/
function consoleHomeDir() {
return process.env.PLAN2CODE_CONSOLE_HOME || path.join(os.homedir(), '.plan2code', 'console');
}
/**
* Put the console built under skills/_console/<version>/ at <console home>/<version>/, point
* console-dir at it, and remove every other version folder. Nothing else in the console home is
* touched: sessions/, looks.json, console-dir's siblings and any other kept entry stay as they
* are. Returns true on success, false after saying why not. `sweep: false` keeps the old version
* folders for now: an install calls sweepOldConsoles() once `skills add` has worked, so a failed
* update leaves the old stubs, which name the old version, still able to find their console.
*/
function installSharedConsole({ quiet = false, source: builtFrom, sweep = true } = {}) {
const version = JSON.parse(fs.readFileSync(path.join(__dirname, 'version.json'), 'utf8')).version;
const source = builtFrom || path.join(SKILLS_DIR, CONSOLE_SHARED_DIR, version);
const home = consoleHomeDir();
const dest = path.join(home, version);
try {
if (!fs.existsSync(path.join(source, 'console.mjs'))) throw new Error(`${source} is not built`);
fs.mkdirSync(home, { recursive: true });
// A server still running from this folder holds files open on Windows: the copy below
// overwrites them in place when the removal cannot.
try { fs.rmSync(dest, { recursive: true, force: true }); } catch (err) { /* overwritten below */ }
fs.cpSync(source, dest, { recursive: true, force: true });
fs.writeFileSync(path.join(home, 'console-dir'), `${dest}\n`);
} catch (err) {
console.error(` ${COLORS.RED}${SYMBOLS.ERROR}${COLORS.RESET} Could not install the shared console into ${home}: ${err.message}`);
return false;
}
if (sweep) sweepOldConsoles({ quiet, version });
if (!quiet) console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Shared console ${version} installed in ${dest}`);
return true;
}
/** Remove every console version folder but the current one. */
function sweepOldConsoles({ quiet = false, version } = {}) {
version = version || JSON.parse(fs.readFileSync(path.join(__dirname, "version.json"), "utf8")).version;
const home = consoleHomeDir();
let entries = [];
try { entries = fs.readdirSync(home, { withFileTypes: true }); } catch { return; }
for (const entry of entries) {
if (!entry.isDirectory() || entry.name === version || !CONSOLE_VERSION_DIR.test(entry.name)) continue;
try {
fs.rmSync(path.join(home, entry.name), { recursive: true, force: true });
if (!quiet) console.log(` ${COLORS.YELLOW}░░░${COLORS.RESET} Removed old console ${entry.name}`);
} catch (err) {
// An old console still running keeps its folder; the next update removes it.
if (!quiet) console.log(` ${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} Kept old console ${entry.name}: ${err.message}`);
}
}
}
function cleanLegacyPaths(quiet = false) {
const stats = { removed: 0, errors: 0 };
for (const legacy of LEGACY_PATHS) {
@@ -892,7 +1012,11 @@ function cleanLegacyPaths(quiet = false) {
// SKILLS CLI DELEGATION
// ============================================================================
const SKILLS_CLI = 'npx --yes skills';
// The skills CLI runs pinned to one exact version, so a new release of it can never change an install
// between two runs of the same Plan2Code. Checked against npm on 2026-11-08 (latest was 1.7.6); raise it
// on purpose, after trying an install, never by switching back to an unpinned `npx skills`.
const SKILLS_CLI_VERSION = '1.7.6';
const SKILLS_CLI = `npx --yes skills@${SKILLS_CLI_VERSION}`;
const BENIGN_SKILLS_FAILURE = /does not support (global|project) skill installation/i;
function execSkillsCli(args) {
@@ -946,7 +1070,7 @@ function ensureSkillsCli() {
console.log(` ${COLORS.RED}${SYMBOLS.ERROR}${COLORS.RESET} Could not run the ${COLORS.BRIGHT}skills${COLORS.RESET} CLI.`);
console.log(`\n ${COLORS.DIM}Plan2Code installs through skills.sh, which needs Node 18+ and network access.${COLORS.RESET}`);
console.log(` ${COLORS.DIM}Check that this works, then re-run the installer:${COLORS.RESET}`);
console.log(` ${COLORS.CYAN}npx --yes skills --version${COLORS.RESET}\n`);
console.log(` ${COLORS.CYAN}${SKILLS_CLI} --version${COLORS.RESET}\n`);
return false;
}
@@ -1013,6 +1137,11 @@ async function install({ unattended = false, outcome = {} } = {}) {
}
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} Built ${SOURCE_PROMPTS.length} skills from src/${COLORS.RESET}`);
if (!ensureSkillsCli()) return 1;
// The skills carry only a stub; the console they forward to goes in with them.
if (!installSharedConsole({ quiet: true, sweep: false })) {
outcome.skills = false;
return 1;
}
console.log('');
displayStatusBox('PARAMETERS', [
@@ -1050,7 +1179,10 @@ async function install({ unattended = false, outcome = {} } = {}) {
reportSkillsOutput(result);
const failed = !result.ok;
outcome.skills = !failed;
if (!failed) recordInstalled('skills');
if (!failed) {
recordInstalled('skills');
sweepOldConsoles({ quiet: true });
}
// The `plan2code` command opens the dashboard skill, so it's only worth adding once the
// skills themselves are in place.
@@ -1081,7 +1213,7 @@ async function install({ unattended = false, outcome = {} } = {}) {
if (failed) {
console.log(`${COLORS.RED}${SYMBOLS.ERROR} skills add failed. Re-run, or install by hand:${COLORS.RESET}`);
console.log(` ${COLORS.CYAN}npx --yes skills add "${SKILLS_DIR}" -g ${skillNameArgs()} -y${COLORS.RESET}\n`);
console.log(` ${COLORS.CYAN}${SKILLS_CLI} add "${SKILLS_DIR}" -g ${skillNameArgs()} -y${COLORS.RESET}\n`);
return 1;
}
@@ -1198,6 +1330,8 @@ function installProjectSkills() {
}
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} Built ${SOURCE_PROMPTS.length} skills from src/${COLORS.RESET}`);
if (!ensureSkillsCli()) return 1;
// Project skills forward to the same shared console in the home folder.
if (!installSharedConsole({ quiet: true, sweep: false })) return 1;
console.log('');
displayStatusBox('OVERVIEW', [
@@ -1219,9 +1353,10 @@ function installProjectSkills() {
console.log('');
if (!result.ok) {
console.log(`${COLORS.RED}${SYMBOLS.ERROR} skills add failed. Run it by hand from your project root:${COLORS.RESET}`);
console.log(` ${COLORS.CYAN}npx --yes skills add "${SKILLS_DIR}" ${skillNameArgs()} -y${COLORS.RESET}\n`);
console.log(` ${COLORS.CYAN}${SKILLS_CLI} add "${SKILLS_DIR}" ${skillNameArgs()} -y${COLORS.RESET}\n`);
return 1;
}
sweepOldConsoles({ quiet: true });
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} Installed into ${projectDir}${COLORS.RESET}\n`);
console.log(`${COLORS.DIM} Check the new directories aren't gitignored, or your agents won't see them.${COLORS.RESET}\n`);
return 0;
@@ -2927,4 +3062,4 @@ if (require.main === module) {
}
}
module.exports = { update, installDesktopApp, offerDesktopApp, recordSkipped, appAssetName, checksumFor, APP_DEST, UPDATE_STEPS, INSTALL_RECORD, INSTALL_PIECES, readInstallRecord, recordInstalled, forgetInstalled, SOURCE_PROMPTS, generateSkillName };
module.exports = { installSharedConsole, sweepOldConsoles, consoleHomeDir, CONSOLE_SHARED_DIR, update, installDesktopApp, offerDesktopApp, recordSkipped, appAssetName, checksumFor, APP_DEST, UPDATE_STEPS, INSTALL_RECORD, INSTALL_PIECES, readInstallRecord, recordInstalled, forgetInstalled, SOURCE_PROMPTS, generateSkillName };
+2 -1
View File
@@ -11,7 +11,8 @@
"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/check-versions.mjs && 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-agents-doc.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"
"test:fast": "node scripts/test-fast.mjs",
"test": "node scripts/check-test-lanes.mjs && node scripts/validate-char-count.js && node install.js --build-skills && node scripts/check-versions.mjs && node scripts/check-doc-size.mjs && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/check-prompt-wording.mjs && node scripts/check-console-openings.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-agents-doc.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 scripts/test-check-test-lanes.mjs scripts/test-check-doc-size.mjs scripts/tLine truncated
},
"devDependencies": {
"gpt-tokenizer": "2.9.0",
+7
View File
@@ -1,3 +1,10 @@
[workspace]
resolver = "2"
members = ["src-tauri", "fake-agent"]
# Release builds: whole-program optimization, no symbols in the shipped
# binary, and a panic ends the process instead of unwinding.
[profile.release]
lto = true
strip = true
panic = "abort"
+1 -1
View File
@@ -50,6 +50,6 @@ cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace
```
The `app` workflow runs all three on Windows, macOS and Linux, and fails on any rustfmt difference or clippy warning, so run them before pushing, not only `cargo test`. Clippy on one system does not see code for another: an import used only inside a `#[cfg(windows)]` test is clean on Windows and an unused-import error on macOS and Linux, so put such imports inside the `cfg`'d item.
The `app` workflow runs all three on Ubuntu for every pull request and push to main (and on Windows and macOS too for a manual run or a pull request labeled `full-matrix`), and fails on any rustfmt difference or clippy warning, so run them before pushing, not only `cargo test`. Clippy on one system does not see code for another: an import used only inside a `#[cfg(windows)]` test is clean on Windows and an unused-import error on macOS and Linux, so put such imports inside the `cfg`'d item.
Real Claude, Devin and Codex are never started by a test. The real window and terminal panel are checked by hand before each release.
+9 -3
View File
@@ -414,13 +414,19 @@ fn npm_global_bin_uncached(windows: bool) -> Option<String> {
}
}
}
let child = std::process::Command::new("npm")
let mut command = std::process::Command::new("npm");
command
.args(["config", "get", "prefix"])
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.env("PATH", crate::node_check::resolved_path())
.spawn();
.env("PATH", crate::node_check::resolved_path());
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
}
let child = command.spawn();
let child = match child {
Ok(child) => child,
Err(_) => return None,
@@ -37,6 +37,61 @@ pub struct ConsoleSession {
pub const OLD_CONSOLE: &str =
"The installed Plan2Code console is too old to show inside the app. Press Update skills, then try again.";
/// A supervisor's health check, copied out of it (`ConsoleSupervisor::probe`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ConsoleProbe {
url: String,
stopped: bool,
}
impl ConsoleProbe {
/// Was the supervisor stopped on purpose when the probe was taken.
pub fn stopped(&self) -> bool {
self.stopped
}
/// A GET on the session URL: any HTTP answer means the server is alive.
pub fn health(&self) -> bool {
self.health_within(HEALTH_TIMEOUT)
}
/// `health`, then once more with the longer timeout: a machine busy with
/// a test run can keep a healthy server from answering inside the first.
pub fn alive(&self) -> bool {
self.health() || self.health_within(BUSY_HEALTH_TIMEOUT)
}
fn health_within(&self, timeout: Duration) -> bool {
if self.stopped {
return false;
}
let Ok((host, port, path)) = split_url(&self.url) else {
return false;
};
let Some(addr) = (host.as_str(), port)
.to_socket_addrs()
.ok()
.and_then(|mut a| a.next())
else {
return false;
};
let Ok(mut stream) = TcpStream::connect_timeout(&addr, timeout) else {
return false;
};
let _ = stream.set_read_timeout(Some(timeout));
let _ = stream.set_write_timeout(Some(timeout));
let request = format!("GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n");
if stream.write_all(request.as_bytes()).is_err() {
return false;
}
let mut status = [0u8; 64];
match stream.read(&mut status) {
Ok(n) => String::from_utf8_lossy(&status[..n]).starts_with("HTTP/"),
Err(_) => false,
}
}
}
/// One supervised console for one project folder.
pub struct ConsoleSupervisor {
console_dir: PathBuf,
@@ -273,8 +328,10 @@ impl ConsoleSupervisor {
/// The console moved to another address or session (an announced page that
/// is not the one this supervisor opened): health, stop and the restart
/// brief follow it from now on.
/// brief follow it from now on. An announced page is a running console, so
/// a supervisor the person stopped is no longer stopped.
pub fn follow(&mut self, url: &str, sid: &str) {
self.stopped = false;
if self.session.url == url && self.session.sid == sid {
return;
}
@@ -296,32 +353,16 @@ impl ConsoleSupervisor {
}
fn health_within(&self, timeout: Duration) -> bool {
if self.stopped {
return false;
}
let Ok((host, port, path)) = split_url(&self.session.url) else {
return false;
};
let Some(addr) = (host.as_str(), port)
.to_socket_addrs()
.ok()
.and_then(|mut a| a.next())
else {
return false;
};
let Ok(mut stream) = TcpStream::connect_timeout(&addr, timeout) else {
return false;
};
let _ = stream.set_read_timeout(Some(timeout));
let _ = stream.set_write_timeout(Some(timeout));
let request = format!("GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n");
if stream.write_all(request.as_bytes()).is_err() {
return false;
}
let mut status = [0u8; 64];
match stream.read(&mut status) {
Ok(n) => String::from_utf8_lossy(&status[..n]).starts_with("HTTP/"),
Err(_) => false,
self.probe().health_within(timeout)
}
/// What a health check needs, copied out, so a caller can check with the
/// app's console lock released: the announce thread takes that lock to
/// follow a new page, and a check can wait seconds on a busy machine.
pub fn probe(&self) -> ConsoleProbe {
ConsoleProbe {
url: self.session.url.clone(),
stopped: self.stopped,
}
}
@@ -329,9 +370,17 @@ impl ConsoleSupervisor {
/// when a new session was started. Never loops: the caller (the bar) asks
/// and shows the outcome.
pub fn restart_if_dead(&mut self) -> Result<bool, String> {
if self.stopped || self.health() || self.health_within(BUSY_HEALTH_TIMEOUT) {
if self.stopped || self.probe().alive() {
return Ok(false);
}
self.reopen()?;
Ok(true)
}
/// A fresh `open` on the same session (a new one only when it is gone from
/// disk), with no health check: for a console the caller already found
/// dead, or one the person stopped and now starts again. Clears `stopped`.
pub fn reopen(&mut self) -> Result<(), String> {
let sid = self.session.sid.clone();
let on_disk = session_on_disk(&sid);
let (console_dir, project_dir, embed_origin, workflow) = (
@@ -344,7 +393,7 @@ impl ConsoleSupervisor {
Self::open_session(console_dir, project_dir, embed_origin, resume, workflow)
})?;
self.stopped = false;
Ok(true)
Ok(())
}
/// `console.mjs stop --session <sid> --force`: the console's own orderly
+197 -21
View File
@@ -1,8 +1,8 @@
//! The commit step of the Implementation Loop: its order, and nothing else.
//!
//! A passed phase goes through five calls, in this order: `prepare` (everything
//! that can fail, before any file is touched), `stage_and_check` (stage, then
//! refuse a secret or an oversized file), `mark` (save the files, mark the
//! that can fail, before any file is touched), `stage_and_check` (stage the
//! files the phase changed, then refuse a secret or an oversized file), `mark` (save the files, mark the
//! phase done, write the approval line), `commit` (stage the marked files and
//! commit) and, when the commit fails, `undo` (put the saved text back). The
//! driver decides what to say and where to stop; this module only does the work
@@ -252,6 +252,22 @@ pub fn too_big(file: &StagedFile) -> bool {
file.bytes > MAX_STAGED_BYTES
}
/// A staged file's size from its `symlink_metadata` result: a file that is
/// gone is a deletion and counts as 0 bytes; any other error means the size is
/// not known, so the gate refuses it (`None`) rather than counting 0.
pub fn staged_size(meta: std::io::Result<u64>) -> Option<u64> {
match meta {
Ok(bytes) => Some(bytes),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Some(0),
Err(_) => None,
}
}
/// What a stop says when the files this phase changed cannot be listed, so the
/// loop cannot tell its own files from the person's.
pub const OWN_FILES_UNKNOWN: &str =
"the files this phase changed could not be listed, so nothing was staged";
/// Staged files the loop refuses to commit, by their names.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StagedProblem {
@@ -270,11 +286,47 @@ pub enum StageError {
Problem(StagedProblem),
}
/// Stage everything and look at the list before anything is marked. Any
/// secret-looking or oversized file takes everything out of the index again and
/// Stage the files this phase changed and look at the list before anything is
/// marked. `baseline` is what `git status` listed when the phase began (the
/// person's own changes, left out); `None` when it could not be read. The
/// phase's files are what `git status` lists now less the baseline, staged by
/// name, never with `git add -A`. A baseline or a list that cannot be read
/// stops here with nothing staged. Any secret-looking or oversized file, or
/// one whose size cannot be read, takes everything out of the index again and
/// returns every offending path.
pub fn stage_and_check(project: &Path) -> Result<(), StageError> {
let added = loop_tools::git_add_all(project);
pub fn stage_and_check(project: &Path, baseline: Option<&[String]>) -> Result<(), StageError> {
let unknown = |output: String| {
StageError::Add(CommitFailure {
stage: Stage::Add,
first_line: OWN_FILES_UNKNOWN.to_string(),
output,
})
};
let baseline = baseline
.ok_or_else(|| unknown("git status could not be read when the phase began".to_string()))?;
// Changed names are relative to the repository's top folder.
let top = loop_tools::git_toplevel(project)
.ok_or_else(|| unknown("the repository's top folder could not be found".to_string()))?;
// A list over the cap keeps its own advice (add generated folders to
// .gitignore) as the stop line; any other failure is the generic one.
let changed = loop_tools::git_changed(project).map_err(|output| {
if output == loop_tools::STAGED_TOO_LONG {
StageError::Add(CommitFailure {
stage: Stage::Add,
first_line: output.clone(),
output,
})
} else {
unknown(output)
}
})?;
// A set, not a slice scan: with every untracked file listed, a big folder makes both lists long.
let before: std::collections::HashSet<&str> = baseline.iter().map(String::as_str).collect();
let own: Vec<loop_tools::GitPath> = changed
.into_iter()
.filter(|path| !before.contains(path.shown.as_str()))
.collect();
let added = loop_tools::git_add_listed(&top, &own);
if !added.ok {
return Err(StageError::Add(CommitFailure {
stage: Stage::Add,
@@ -289,20 +341,25 @@ pub fn stage_and_check(project: &Path) -> Result<(), StageError> {
output,
})
})?;
// Staged names are relative to the repository's top folder.
let top = loop_tools::git_toplevel(project).unwrap_or_else(|| project.to_path_buf());
let mut secrets = false;
let mut big = false;
let mut unreadable = false;
let mut files = Vec::new();
for path in staged {
// A deleted file is gone from the tree: it counts as 0 bytes.
let bytes = std::fs::symlink_metadata(top.join(&path)).map_or(0, |m| m.len());
let file = StagedFile { path, bytes };
// Sized by the exact bytes git wrote, so a name that is not UTF-8 is
// still the real file. A deleted file counts as 0 bytes.
let size = staged_size(std::fs::symlink_metadata(path.under(&top)).map(|m| m.len()));
let file = StagedFile {
path: path.shown,
bytes: size.unwrap_or(0),
};
let is_secret = denied(&file.path).is_some();
let is_big = too_big(&file);
if is_secret || is_big {
let is_unsized = size.is_none();
if is_secret || is_big || is_unsized {
secrets |= is_secret;
big |= is_big;
unreadable |= is_unsized;
files.push(file.path);
}
}
@@ -311,10 +368,14 @@ pub fn stage_and_check(project: &Path) -> Result<(), StageError> {
}
let unstaged = loop_tools::git_unstage_all(project);
let left_staged = (!unstaged.ok).then(|| first_line(&unstaged.output));
let why = match (secrets, big) {
(true, true) => "look like secrets or are over 5 MB",
(true, false) => "look like secrets",
_ => "are over 5 MB",
let why = match (secrets, big, unreadable) {
(true, true, false) => "look like secrets or are over 5 MB",
(true, false, false) => "look like secrets",
(false, true, false) => "are over 5 MB",
(false, false, true) => "could not be sized",
(true, false, true) => "look like secrets or could not be sized",
(false, true, true) => "are over 5 MB or could not be sized",
_ => "look like secrets, are over 5 MB or could not be sized",
};
Err(StageError::Problem(StagedProblem {
files,
@@ -751,7 +812,7 @@ mod tests {
let big = std::fs::File::create(repo.join("big.bin")).unwrap();
big.set_len(MAX_STAGED_BYTES + 1).unwrap();
// No commit yet: unstaging must work without a HEAD.
let Err(StageError::Problem(problem)) = stage_and_check(&repo) else {
let Err(StageError::Problem(problem)) = stage_and_check(&repo, Some(&[])) else {
panic!("expected a problem");
};
let mut files = problem.files.clone();
@@ -764,7 +825,7 @@ mod tests {
std::fs::remove_file(repo.join(".env")).unwrap();
std::fs::remove_file(repo.join("big.bin")).unwrap();
std::fs::remove_file(repo.join("sub/server.pem")).unwrap();
stage_and_check(&repo).expect("a clean list passes");
stage_and_check(&repo, Some(&[])).expect("a clean list passes");
let staged = git_in(&repo, &["diff", "--cached", "--name-only"]);
assert!(staged.contains("ok.txt") && staged.contains(".env.example"));
}
@@ -779,11 +840,11 @@ mod tests {
git_in(&repo, &["add", "-A"]);
git_in(&repo, &["commit", "-q", "-m", "First"]);
std::fs::remove_file(repo.join("a.txt")).unwrap();
stage_and_check(&repo).expect("a deletion of an ordinary file passes");
stage_and_check(&repo, Some(&[])).expect("a deletion of an ordinary file passes");
git_in(&repo, &["reset", "-q"]);
let big = std::fs::File::create(repo.join("huge.dat")).unwrap();
big.set_len(MAX_STAGED_BYTES + 1).unwrap();
let Err(StageError::Problem(problem)) = stage_and_check(&repo) else {
let Err(StageError::Problem(problem)) = stage_and_check(&repo, Some(&[])) else {
panic!("expected a problem");
};
assert_eq!(problem.files, vec!["huge.dat"]);
@@ -811,7 +872,7 @@ mod tests {
message: "Add it\n\nAI Assisted".to_string(),
phase_file: spec.join("phase-2.md"),
};
stage_and_check(&repo).unwrap();
stage_and_check(&repo, Some(&[])).unwrap();
let marked = mark(&prepared, &repo, "specs/lunch", 2, "Approved.").unwrap();
let head = commit(&repo, &prepared, &marked, Duration::from_secs(30)).unwrap();
assert!(head.is_some());
@@ -863,4 +924,119 @@ mod tests {
// A phase the spec no longer shows done is not listed.
assert!(marks_without_commits(&base, "specs/lunch", &[2], &report).is_empty());
}
#[test]
fn only_the_phases_own_files_are_staged_and_the_baseline_is_left_alone() {
if !git_ready() {
return;
}
let repo = init_repo("stage-own");
// A setting that hides untracked files from a plain `git status`.
git_in(&repo, &["config", "status.showUntrackedFiles", "no"]);
std::fs::create_dir_all(repo.join("app")).unwrap();
std::fs::write(repo.join("tracked.txt"), "a").unwrap();
std::fs::write(repo.join("app/keep.tsx"), "k").unwrap();
git_in(&repo, &["add", "tracked.txt", "app/keep.tsx"]);
git_in(&repo, &["commit", "-q", "-m", "First"]);
// When the phase began, the person already had two files of their
// own: one of them a name a glob reading of `app/[id].tsx` matches.
std::fs::write(repo.join("mine.txt"), "the person's").unwrap();
std::fs::write(repo.join("app/i.tsx"), "decoy").unwrap();
let mut baseline = loop_tools::git_status_porcelain(&repo).unwrap();
baseline.sort_unstable();
assert_eq!(baseline, vec!["app/i.tsx", "mine.txt"]);
// The agent then edits a tracked file and adds files, one with a
// name that reads as a pattern (listed on its own line, since `app/`
// is tracked).
std::fs::write(repo.join("tracked.txt"), "b").unwrap();
std::fs::write(repo.join("app/[id].tsx"), "x").unwrap();
std::fs::write(repo.join("new.rs"), "y").unwrap();
stage_and_check(&repo, Some(&baseline)).expect("the agent's files pass");
let staged = git_in(&repo, &["diff", "--cached", "--name-only"]);
let mut staged: Vec<&str> = staged.lines().collect();
staged.sort_unstable();
assert_eq!(staged, vec!["app/[id].tsx", "new.rs", "tracked.txt"]);
}
#[test]
fn an_untracked_folder_from_before_the_phase_neither_hides_nor_swallows_files() {
if !git_ready() {
return;
}
let repo = init_repo("stage-untracked-dir");
std::fs::write(repo.join("tracked.txt"), "a").unwrap();
git_in(&repo, &["add", "tracked.txt"]);
git_in(&repo, &["commit", "-q", "-m", "First"]);
// The person's scratch folder was untracked when the phase began.
std::fs::create_dir_all(repo.join("scratch")).unwrap();
std::fs::write(repo.join("scratch/mine.txt"), "the person's").unwrap();
let mut baseline = loop_tools::git_status_porcelain(&repo).unwrap();
baseline.sort_unstable();
assert_eq!(baseline, vec!["scratch/mine.txt"]);
// The agent adds a file beside it, and a folder of its own.
std::fs::write(repo.join("scratch/new.txt"), "the agent's").unwrap();
std::fs::create_dir_all(repo.join("made")).unwrap();
std::fs::write(repo.join("made/a.txt"), "the agent's").unwrap();
stage_and_check(&repo, Some(&baseline)).expect("the agent's files pass");
let staged = git_in(&repo, &["diff", "--cached", "--name-only"]);
let mut staged: Vec<&str> = staged.lines().collect();
staged.sort_unstable();
assert_eq!(staged, vec!["made/a.txt", "scratch/new.txt"]);
}
#[test]
fn staging_fails_closed_when_the_phases_files_cannot_be_listed() {
if !git_ready() {
return;
}
let repo = init_repo("stage-unknown");
std::fs::write(repo.join("a.txt"), "a").unwrap();
// No baseline from the phase's start: nothing is staged.
let Err(StageError::Add(failure)) = stage_and_check(&repo, None) else {
panic!("expected a refusal");
};
assert_eq!(failure.first_line, OWN_FILES_UNKNOWN);
assert_eq!(git_in(&repo, &["diff", "--cached", "--name-only"]), "");
// Outside any repository the list cannot be read either.
let (plain, _) = temp_spec("stage-no-repo");
let Err(StageError::Add(failure)) = stage_and_check(&plain, Some(&[])) else {
panic!("expected a refusal");
};
assert_eq!(failure.first_line, OWN_FILES_UNKNOWN);
}
#[test]
fn a_size_that_cannot_be_read_is_refused_and_a_deletion_is_zero() {
use std::io::{Error, ErrorKind};
assert_eq!(staged_size(Ok(12)), Some(12));
assert_eq!(staged_size(Err(Error::from(ErrorKind::NotFound))), Some(0));
assert_eq!(
staged_size(Err(Error::from(ErrorKind::PermissionDenied))),
None
);
assert_eq!(staged_size(Err(Error::other("odd"))), None);
}
#[cfg(unix)]
#[test]
fn a_big_file_whose_name_is_not_utf8_hits_the_size_gate() {
use std::os::unix::ffi::OsStrExt;
if !git_ready() {
return;
}
let repo = init_repo("stage-non-utf8");
let name = std::ffi::OsStr::from_bytes(b"caf\xe9.bin");
let big = match std::fs::File::create(repo.join(name)) {
Ok(file) => file,
// A file system that refuses such a name (some macOS volumes) has nothing to check.
Err(_) => return,
};
big.set_len(MAX_STAGED_BYTES + 1).unwrap();
let Err(StageError::Problem(problem)) = stage_and_check(&repo, Some(&[])) else {
panic!("expected the size gate to stop it");
};
assert_eq!(problem.files, vec!["caf\u{fffd}.bin"]);
assert_eq!(problem.why, "are over 5 MB");
assert_eq!(git_in(&repo, &["diff", "--cached", "--name-only"]), "");
}
}
+356 -24
View File
@@ -389,6 +389,15 @@ pub struct RunningRecord {
/// 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 `git status` listed when the current phase began: changes that
/// are not the phase's, left out of its commit. `None` when it could not
/// be read, and the commit then stages nothing. A retry keeps the first
/// try's baseline, so the work the crashed try left is still the phase's.
pub phase_baseline: Option<Vec<String>>,
/// An Implement page announced while the phase had no session yet, but
/// not yet locked by the agent's `open --loop`: adopted on a later look
/// once its state shows the lock (`note_page`).
pub page_candidate: Option<String>,
}
/// What one phase runs on, for its start, the strip and the report.
@@ -471,6 +480,8 @@ impl RunningRecord {
strength_rows: BTreeMap::new(),
launch_model: None,
launch_effort: None,
phase_baseline: None,
page_candidate: None,
}
}
@@ -897,16 +908,39 @@ pub fn should_retry(cause: &StopCause, setup: &LoopSetup, retries_used_this_phas
/// Whether the session state holds a question for the person: an item still
/// open or reopened, required, not handled by the loop and not just a notice.
pub fn open_question(state: &Value) -> bool {
state["items"].as_array().is_some_and(|items| {
items.iter().any(|item| {
matches!(item["status"].as_str(), Some("open" | "reopened"))
&& item["required"].as_bool() != Some(false)
&& item["kind"].as_str() != Some("notice")
&& item.get("handledBy").is_none_or(Value::is_null)
})
first_open_question(state).is_some()
}
/// The first question `open_question` would count, as its title (the
/// question's body when it has no title), or `None`.
pub fn first_open_question(state: &Value) -> Option<String> {
state["items"].as_array()?.iter().find_map(|item| {
let open = matches!(item["status"].as_str(), Some("open" | "reopened"))
&& item["required"].as_bool() != Some(false)
&& item["kind"].as_str() != Some("notice")
&& item.get("handledBy").is_none_or(Value::is_null);
if !open {
return None;
}
let title = item["title"].as_str().map(str::trim).unwrap_or_default();
let text = if title.is_empty() {
item["body"].as_str().map(str::trim).unwrap_or_default()
} else {
title
};
Some(one_line(text))
})
}
/// Whether an announced page can be the running phase's session: the agent
/// has locked it with `open --loop` (`loop.driving`) and it holds no report
/// yet. A page without the lock is a plain `open` (or not a loop page at all),
/// and a report already there belongs to an older run.
pub fn page_is_this_phase(state: &Value) -> bool {
state["loop"]["driving"].as_bool().unwrap_or(false)
&& state.get("loopOutcome").is_none_or(Value::is_null)
}
/// The line the stop screen leads with. `detail` is the exit reason for a
/// crash, the minutes for silence and the whole clause for a refused commit.
pub fn stop_line(cause: &StopCause, phase: u32, detail: &str, retried: bool) -> String {
@@ -946,7 +980,13 @@ pub fn stop_line(cause: &StopCause, phase: u32, detail: &str, retried: bool) ->
shown.join(", ")
)
}
StopCause::Question => format!("Phase {phase} stopped: it asked a question"),
StopCause::Question if detail.is_empty() => {
format!("Phase {phase} stopped: it asked a question")
}
StopCause::Question => {
let asked: String = one_line(detail).chars().take(100).collect();
format!("Phase {phase} stopped: it asked a question, \"{asked}\"")
}
StopCause::StoppedByPerson => {
format!("Stopped during Phase {phase}. This phase's changes stay uncommitted.")
}
@@ -1228,7 +1268,10 @@ pub fn commits_to_trunk(rec: &RunningRecord) -> bool {
/// that were already changed when the loop started. A file both the person and
/// the agent changed is hidden from the list, a known limit.
pub fn agent_work(now: Vec<String>, own: &[String]) -> Vec<String> {
now.into_iter().filter(|file| !own.contains(file)).collect()
let before: std::collections::HashSet<&str> = own.iter().map(String::as_str).collect();
now.into_iter()
.filter(|file| !before.contains(file.as_str()))
.collect()
}
/// The app's own Start confirm.
@@ -1495,20 +1538,59 @@ pub fn begin_with_limits(
}
/// A page the app took: while a loop waits for its phase's session, an
/// Implement or Implement + Review page is that session.
pub fn note_page(slot: &LoopSlot, workflow: &str, sid: &str) {
/// Implement or Implement + Review page whose `state` the agent has locked
/// with `open --loop`, and that holds no report yet, is that session
/// (`page_is_this_phase`). One without the lock is kept as a candidate the
/// watch adopts once the lock shows; one with a report is ignored.
pub fn note_page(slot: &LoopSlot, workflow: &str, sid: &str, state: &Value) {
if !matches!(workflow, "implement" | "implement-review") {
return;
}
if let Some(rec) = lock(slot).as_mut() {
if rec.sid.is_none() {
rec.sid = Some(sid.to_string());
rec.last_sid = Some(sid.to_string());
rec.last_activity = SystemTime::now();
if rec.sid.is_some() {
return;
}
if page_is_this_phase(state) {
adopt_page(rec, sid);
} else if state.is_object() && state.get("loopOutcome").is_none_or(Value::is_null) {
// An unreadable page (no state) is no candidate: it must not replace a real one.
rec.page_candidate = Some(sid.to_string());
}
}
}
/// Follow `sid` as the phase's session from here.
fn adopt_page(rec: &mut RunningRecord, sid: &str) {
rec.sid = Some(sid.to_string());
rec.last_sid = Some(sid.to_string());
rec.last_activity = SystemTime::now();
rec.page_candidate = None;
}
/// The candidate `note_page` held back, adopted once its state shows the
/// agent's lock; the session to follow, or `None` while there is none yet.
fn adopt_candidate(ctx: &Ctx, candidate: Option<&str>) -> Option<String> {
let sid = candidate?;
let session = session_reader::load(&ctx.home, sid).ok()?;
if !page_is_this_phase(&session.state) {
return None;
}
let mut guard = lock(&ctx.slot);
let rec = guard.as_mut().filter(|r| r.run_id == ctx.run_id)?;
if rec.sid.is_none() && rec.page_candidate.as_deref() == Some(sid) {
adopt_page(rec, sid);
}
rec.sid.clone()
}
/// What `git status` lists as the phase begins, as its commit's baseline.
/// The first phase of a resumed run leaves out the stopped phase's files: that
/// work is this phase's to commit.
fn phase_baseline(project: &Path, carried: &[String]) -> Option<Vec<String>> {
let now = loop_tools::git_status_porcelain(project).ok()?;
Some(agent_work(now, carried))
}
/// Start a fresh agent on `prompt`: on the agent's stored launch choice when it
/// has one, else on `launch` (an agent the loop stopped has forgotten it). The
/// prompt is transient either way: a later New Session opens the dashboard, it
@@ -1593,9 +1675,29 @@ fn emit(ctx: &Ctx) {
}
fn start_phase(ctx: &Ctx, index: usize) -> Result<(), String> {
// The baseline is read before the agent starts, outside the lock; a retry
// keeps the first try's.
let baseline = {
let guard = lock(&ctx.slot);
let rec = guard.as_ref().ok_or("the loop ended")?;
let first_try = rec.phases.get(index).is_some_and(|p| p.retries == 0);
first_try.then(|| {
let carried = if index == 0 && rec.resumed_files.is_some() {
rec.own_dirty.clone()
} else {
Vec::new()
};
(rec.project.clone(), carried)
})
}
.map(|(project, carried)| phase_baseline(&project, &carried));
let prompt = {
let mut guard = lock(&ctx.slot);
let rec = guard.as_mut().ok_or("the loop ended")?;
if let Some(baseline) = baseline {
rec.phase_baseline = baseline;
}
rec.page_candidate = None;
rec.current = index;
rec.phases[index].status = PhaseStatus::Running;
rec.step = Step::Starting;
@@ -1677,6 +1779,7 @@ struct Snapshot {
phase_retries: u32,
last_activity: SystemTime,
activity_due: bool,
page_candidate: Option<String>,
}
/// The running loop as one look sees it, or `None` when this loop is over.
@@ -1696,6 +1799,7 @@ fn take_snapshot(ctx: &Ctx) -> Option<Snapshot> {
phase_retries: rec.phases[rec.current].retries,
last_activity: rec.last_activity,
activity_due: rec.activity_checked.elapsed() >= ctx.limits.activity_every,
page_candidate: rec.page_candidate.clone(),
}),
_ => None,
}
@@ -1710,7 +1814,8 @@ fn tick(ctx: &Ctx) -> bool {
stop_by_person(ctx, &snap);
return false;
}
let Some(sid) = snap.sid.clone() else {
let adopted = || adopt_candidate(ctx, snap.page_candidate.as_deref());
let Some(sid) = snap.sid.clone().or_else(adopted) else {
if let Some(reason) = crashed(ctx, &snap) {
return fail(ctx, &snap, StopCause::Crash, reason);
}
@@ -1766,6 +1871,16 @@ fn tick(ctx: &Ctx) -> bool {
if let Some(go) = crash_or_outcome(ctx, &snap, &sid) {
return go;
}
// Under best guess a question is one the agent could not guess: the phase
// stops on it at once, the stop card naming it, rather than waiting.
if snap.setup.on_question == OnQuestion::Guess {
if let Some(question) = first_open_question(state) {
let cause = StopCause::Question;
let line = stop_line(&cause, snap.phase_n, &question, false);
stop_loop(ctx, cause, line, &["resume", "fix"]);
return false;
}
}
let asked = snap.setup.on_question != OnQuestion::Guess && open_question(state);
if asked && snap.setup.on_question == OnQuestion::Stop {
let cause = StopCause::Question;
@@ -2103,13 +2218,19 @@ fn handle_outcome(ctx: &Ctx, snap: &Snapshot, raw: &Value) -> bool {
// a secret or an oversized file stops the phase with nothing to undo.
if snap.setup.commit {
set_step(ctx, Step::Commit);
match loop_commit::stage_and_check(&snap.project) {
let baseline = lock(&ctx.slot)
.as_ref()
.filter(|r| r.run_id == ctx.run_id)
.and_then(|r| r.phase_baseline.clone());
match loop_commit::stage_and_check(&snap.project, baseline.as_deref()) {
Ok(()) => {}
Err(loop_commit::StageError::Add(failure)) => {
keep_output(ctx, &failure.output);
let left_staged = loop_commit::unstage(&snap.project);
let cause = StopCause::Commit;
let detail = if failure.first_line == loop_tools::STAGED_TOO_LONG {
let detail = if failure.first_line == loop_tools::STAGED_TOO_LONG
|| failure.first_line == loop_commit::OWN_FILES_UNKNOWN
{
failure.first_line.clone()
} else {
format!("git add failed: {}", failure.first_line)
@@ -2703,7 +2824,8 @@ pub fn evidence_markdown(cause: &StopCause, line: &str, rec: &RunningRecord) ->
StopCause::UnsafeFiles(files) => {
md.push_str("\n## The files\n\n");
for file in files {
let reason = loop_commit::denied(file).unwrap_or("over 5 MB");
let reason =
loop_commit::denied(file).unwrap_or("over 5 MB, or its size could not be read");
md.push_str(&format!("- `{file}` ({reason})\n"));
}
md.push_str(
@@ -2732,6 +2854,9 @@ pub fn evidence_markdown(cause: &StopCause, line: &str, rec: &RunningRecord) ->
"\nThe loop's own watcher stopped working, so the agent was ended. Whatever was committed stays committed; nothing more was. Press Resume to carry on from the spec.\n",
);
}
StopCause::Question if rec.setup.on_question == OnQuestion::Guess => {
md.push_str("\nBest guess was on, but the phase asked a question it could not guess, so the loop stopped rather than wait. Answer it with Fix it by hand, or settle it in the spec, then press Resume.\n");
}
StopCause::Question => {
md.push_str("\nThe setup says to stop when a phase asks something.\n");
}
@@ -3801,15 +3926,97 @@ second line"
fn the_first_phase_page_wins_and_other_workflows_are_ignored() {
let rec = record("specs/x", vec![]);
let slot: LoopSlot = Arc::new(Mutex::new(Some(rec)));
note_page(&slot, "dashboard", "s0");
let locked = json!({ "loop": { "driving": true } });
note_page(&slot, "dashboard", "s0", &locked);
assert!(lock(&slot).as_ref().unwrap().sid.is_none());
note_page(&slot, "implement-review", "s1");
note_page(&slot, "implement", "s2");
note_page(&slot, "implement-review", "s1", &locked);
note_page(&slot, "implement", "s2", &locked);
let guard = lock(&slot);
assert_eq!(guard.as_ref().unwrap().sid.as_deref(), Some("s1"));
assert_eq!(guard.as_ref().unwrap().last_sid.as_deref(), Some("s1"));
}
#[test]
fn a_page_without_the_loops_lock_or_with_a_stale_report_is_never_the_phases() {
let rec = record("specs/x", vec![]);
let slot: LoopSlot = Arc::new(Mutex::new(Some(rec)));
// A plain open (no lock yet): held as a candidate, not followed.
note_page(
&slot,
"implement-review",
"plain",
&json!({ "workflow": "implement-review" }),
);
assert!(lock(&slot).as_ref().unwrap().sid.is_none());
assert_eq!(
lock(&slot).as_ref().unwrap().page_candidate.as_deref(),
Some("plain")
);
// A locked page that already holds a report belongs to an older run.
let stale = json!({ "loop": { "driving": true }, "loopOutcome": { "phase": 1 } });
note_page(&slot, "implement", "stale", &stale);
assert!(lock(&slot).as_ref().unwrap().sid.is_none());
assert_eq!(
lock(&slot).as_ref().unwrap().page_candidate.as_deref(),
Some("plain"),
"a stale page is not even a candidate"
);
// An unreadable page (no state) is no session either.
note_page(&slot, "implement", "gone", &Value::Null);
assert!(lock(&slot).as_ref().unwrap().sid.is_none());
assert_eq!(
lock(&slot).as_ref().unwrap().page_candidate.as_deref(),
Some("plain"),
"an unreadable page does not replace the candidate"
);
// The locked page with no report is the phase's session.
note_page(
&slot,
"implement",
"s1",
&json!({ "loop": { "driving": true } }),
);
let guard = lock(&slot);
let rec = guard.as_ref().unwrap();
assert_eq!(rec.sid.as_deref(), Some("s1"));
assert_eq!(rec.page_candidate, None);
assert!(page_is_this_phase(
&json!({ "loop": { "driving": true }, "loopOutcome": null })
));
assert!(!page_is_this_phase(
&json!({ "loop": { "driving": false } })
));
}
#[test]
fn the_first_open_question_is_named_by_its_title_or_its_body() {
let state = json!({ "items": [
{ "id": "a", "kind": "notice", "status": "open", "title": "Just so you know" },
{ "id": "b", "kind": "choice", "status": "answered", "title": "Old one" },
{ "id": "c", "kind": "multi", "status": "open", "title": "Which to fix", "handledBy": "loop" },
{ "id": "d", "kind": "text", "status": "open", "required": false, "title": "Optional" },
{ "id": "e", "kind": "choice", "status": "open", "title": " Which database " },
] });
assert_eq!(
first_open_question(&state).as_deref(),
Some("Which database")
);
let untitled = json!({ "items": [{ "id": "f", "kind": "text", "status": "reopened", "body": "Where do\nthe files go?" }] });
assert_eq!(
first_open_question(&untitled).as_deref(),
Some("Where do the files go?")
);
assert_eq!(first_open_question(&json!({ "items": [] })), None);
assert_eq!(
stop_line(&StopCause::Question, 2, "Which database", false),
"Phase 2 stopped: it asked a question, \"Which database\""
);
assert_eq!(
stop_line(&StopCause::Question, 2, "", false),
"Phase 2 stopped: it asked a question"
);
}
#[test]
fn the_headline_stage_picks_the_step() {
assert_eq!(step_for_stage("Phase 3: Review"), Step::Review);
@@ -4576,6 +4783,8 @@ second line"
);
rec.sid = Some("s1".into());
rec.last_sid = Some("s1".into());
// What a phase start reads from the clean throwaway repo.
rec.phase_baseline = Some(Vec::new());
let run_id = rec.run_id;
let ctx = Ctx {
slot: Arc::new(Mutex::new(Some(rec))),
@@ -4656,7 +4865,7 @@ second line"
assert_eq!(status["phases"][0]["tasks"]["open"], 2);
add_failing_hook(&repo, "hook says no");
std::fs::write(repo.join("new.txt"), "x").unwrap();
let added = loop_tools::git_add_all(&repo);
let added = loop_tools::git_add_listed(&repo, &loop_tools::git_changed(&repo).unwrap());
assert!(added.ok);
let done = loop_tools::git_commit(&repo, "Add new\n\nAI Assisted");
assert!(!done.ok);
@@ -4690,6 +4899,129 @@ second line"
end_the_test(&ctx);
}
#[test]
fn under_best_guess_a_question_stops_the_phase_at_once_naming_it() {
if !git_ready("guess question") {
return;
}
let repo = throwaway_repo("guess-question");
let (ctx, home) = running_loop(&repo, Limits::default());
lock(&ctx.slot).as_mut().unwrap().setup.on_question = OnQuestion::Guess;
// The loop's own cards never stop it.
write_session(
&home,
json!({ "loop": { "driving": true }, "items": [
{ "id": "fixes", "kind": "multi", "status": "answered", "title": "Which to fix", "handledBy": "loop" },
] }),
);
assert!(tick(&ctx), "nothing to answer yet");
write_session(
&home,
json!({ "loop": { "driving": true }, "items": [
{ "id": "q1", "kind": "choice", "status": "open", "title": "Which database" },
] }),
);
assert!(!tick(&ctx), "the question stops the loop on the first look");
assert!(lock(&ctx.slot).is_none());
let entry = last_entry_saved(&home, &repo);
assert_eq!(entry.result, EntryResult::Stopped);
assert_eq!(
entry.line,
"Phase 2 stopped: it asked a question, \"Which database\""
);
}
#[test]
fn a_page_announced_before_the_lock_is_followed_once_the_lock_shows() {
if !git_ready("candidate page") {
return;
}
let repo = throwaway_repo("candidate-page");
let (ctx, home) = running_loop(&repo, Limits::default());
lock(&ctx.slot).as_mut().unwrap().sid = None;
// The skill's first, plain open announces the page before `open --loop`.
write_session(&home, json!({ "workflow": "implement-review" }));
note_page(
&ctx.slot,
"implement-review",
"s1",
&json!({ "workflow": "implement-review" }),
);
assert!(tick(&ctx));
assert!(
lock(&ctx.slot).as_ref().unwrap().sid.is_none(),
"not locked yet"
);
// `open --loop` locks it: the next look follows it.
write_session(
&home,
json!({ "workflow": "implement-review", "loop": { "driving": true } }),
);
assert!(tick(&ctx));
assert_eq!(lock(&ctx.slot).as_ref().unwrap().sid.as_deref(), Some("s1"));
end_the_test(&ctx);
}
#[test]
fn the_commit_takes_only_the_files_the_phase_changed() {
if !harness_ready("own files") {
return;
}
let repo = throwaway_repo("own-files");
let (ctx, home) = running_loop(&repo, Limits::default());
// The person's own change, there before the phase began.
std::fs::write(repo.join("mine.txt"), "the person's").unwrap();
start_phase(&ctx, 0).expect("start the fake agent");
assert_eq!(
lock(&ctx.slot).as_ref().unwrap().phase_baseline.as_deref(),
Some(&["mine.txt".to_string()][..])
);
let locked = json!({ "loop": { "driving": true } });
write_session(&home, locked.clone());
note_page(&ctx.slot, "implement-review", "s1", &locked);
// The agent's work.
finish_phase_tasks(&repo, 2);
std::fs::write(repo.join("agent.txt"), "built").unwrap();
write_session(
&home,
json!({ "loop": { "driving": true }, "loopOutcome": good_report(2) }),
);
assert!(tick(&ctx), "the loop goes on to Phase 3");
let shown = git_in(&repo, &["show", "--name-only", "--format=", "HEAD"]);
assert!(shown.contains("agent.txt"), "{shown}");
assert!(shown.contains("specs/lunch/phase-2.md"), "{shown}");
assert!(!shown.contains("mine.txt"), "{shown}");
assert_eq!(git_in(&repo, &["status", "--porcelain"]), "?? mine.txt");
end_the_test(&ctx);
}
#[test]
fn a_phase_whose_start_could_not_list_the_tree_commits_nothing() {
if !harness_ready("no baseline") {
return;
}
let repo = throwaway_repo("no-baseline");
let (ctx, home) = running_loop(&repo, Limits::default());
lock(&ctx.slot).as_mut().unwrap().phase_baseline = None;
finish_phase_tasks(&repo, 2);
std::fs::write(repo.join("agent.txt"), "built").unwrap();
write_session(&home, json!({ "loopOutcome": good_report(2) }));
let head = git_in(&repo, &["rev-parse", "HEAD"]);
assert!(!tick(&ctx), "the commit stops the loop");
assert_eq!(
git_in(&repo, &["rev-parse", "HEAD"]),
head,
"nothing committed"
);
assert_eq!(git_in(&repo, &["diff", "--cached", "--name-only"]), "");
let entry = last_entry_saved(&home, &repo);
assert!(
entry.line.contains(loop_commit::OWN_FILES_UNKNOWN),
"{}",
entry.line
);
}
#[test]
fn a_phase_that_never_opens_its_console_stops_with_that_cause() {
if !git_ready("no session") {
@@ -5260,7 +5592,7 @@ second line"
assert!(md.contains("(a key or certificate)"), "{md}");
assert!(md.contains("## Your own files") && md.contains("`mine.txt`"));
let big = evidence_markdown(&StopCause::UnsafeFiles(vec!["dump.bin".into()]), "l", &rec);
assert!(big.contains("`dump.bin` (over 5 MB)"), "{big}");
assert!(big.contains("`dump.bin` (over 5 MB"), "{big}");
// The line is never sent as a notification for a stop by the person.
assert!(stop_message(&cause, "specs/lunch", 4, "x").is_some());
}
+164 -35
View File
@@ -106,12 +106,26 @@ enum Keep {
/// `run_limited_with` with the part kept chosen, and whether output was dropped.
fn run_capped(
mut cmd: Command,
cmd: Command,
stdin: Option<&str>,
limit: Duration,
keep_stderr: bool,
keep: Keep,
) -> (ToolRun, bool) {
let (run, cut, _) = run_capped_bytes(cmd, stdin.map(str::as_bytes), limit, keep_stderr, keep);
(run, cut)
}
/// `run_capped` that also hands back the kept output as the bytes the child
/// wrote: a path list read from git must not pass through a lossy decode, or a
/// name that is not UTF-8 no longer names its file.
fn run_capped_bytes(
mut cmd: Command,
stdin: Option<&[u8]>,
limit: Duration,
keep_stderr: bool,
keep: Keep,
) -> (ToolRun, bool, Vec<u8>) {
let cut = Arc::new(AtomicBool::new(false));
cmd.env("PATH", crate::node_check::resolved_path());
#[cfg(windows)]
@@ -146,6 +160,7 @@ fn run_capped(
output: format!("could not start: {e}"),
},
false,
Vec::new(),
);
}
};
@@ -162,7 +177,7 @@ fn run_capped(
];
if let (Some(text), Some(mut pipe)) = (stdin, child.stdin.take()) {
// A child that exits before reading closes the pipe: not an error here.
let _ = pipe.write_all(text.as_bytes());
let _ = pipe.write_all(text);
}
let pid = child.id();
let started = Instant::now();
@@ -194,10 +209,8 @@ fn run_capped(
let _ = reader.join();
}
}
let mut output = sink
.lock()
.map(|buf| String::from_utf8_lossy(&buf).into_owned())
.unwrap_or_default();
let raw = sink.lock().map(|buf| buf.clone()).unwrap_or_default();
let mut output = String::from_utf8_lossy(&raw).into_owned();
if timed_out {
if !output.is_empty() && !output.ends_with('\n') {
output.push('\n');
@@ -211,6 +224,7 @@ fn run_capped(
output,
},
cut.load(Ordering::Relaxed),
raw,
)
}
@@ -332,12 +346,13 @@ pub fn specs_mark(project: &Path, spec: &str, phase: u32, to: &str) -> ToolRun {
)
}
/// `commit-msg.mjs --subject <subject> --add-all`: the checked message. The
/// `commit-msg.mjs --subject <subject>`: the checked message (the Loop stages
/// its own files through `git_add_listed`, so no add is asked for). The
/// script's own subject checks are the only ones.
pub fn commit_message(project: &Path, subject: &str) -> Result<String, String> {
let script = script_or_err("commit-msg.mjs")?;
let run = run_limited(
node_script(&script, project, &["--subject", subject, "--add-all"]),
node_script(&script, project, &["--subject", subject]),
None,
QUICK_LIMIT,
);
@@ -366,8 +381,40 @@ fn parse_commit_msg(stdout: &str) -> Result<String, String> {
.unwrap_or_else(|| stdout.trim().to_string()))
}
pub fn git_add_all(project: &Path) -> ToolRun {
run_limited(git(project, &["add", "-A"]), None, QUICK_LIMIT)
/// `git add` of exactly `paths` (relative to the repository's top folder
/// `top`), read from stdin NUL-separated and taken literally: no command line
/// to outgrow, no quoting, and a name such as `[id].tsx` is a file, not a
/// pattern. Nothing to stage is a success.
pub fn git_add_listed(top: &Path, paths: &[GitPath]) -> ToolRun {
if paths.is_empty() {
return ToolRun {
ok: true,
code: Some(0),
output: String::new(),
};
}
let mut list = Vec::new();
for path in paths {
list.extend_from_slice(&path.bytes);
list.push(0);
}
let cmd = git(
top,
&[
"--literal-pathspecs",
"add",
"--pathspec-from-file=-",
"--pathspec-file-nul",
],
);
run_capped_bytes(
cmd,
Some(&list),
QUICK_LIMIT,
true,
Keep::Tail(OUTPUT_LIMIT),
)
.0
}
/// `git commit -F -` with the message on stdin: no shell, nothing quoted.
@@ -406,17 +453,49 @@ pub fn git_add_paths(project: &Path, paths: &[&Path]) -> ToolRun {
run_limited(cmd, None, QUICK_LIMIT)
}
/// A path git printed, relative to the repository's top folder: the bytes as
/// git wrote them (so a name that is not UTF-8 still reaches its file) and the
/// same name made readable, for messages and for comparing with name lists.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GitPath {
pub bytes: Vec<u8>,
pub shown: String,
}
impl GitPath {
pub fn from_bytes(bytes: &[u8]) -> GitPath {
GitPath {
bytes: bytes.to_vec(),
shown: String::from_utf8_lossy(bytes).into_owned(),
}
}
/// The file on disk under `top`. On Unix the name is the exact bytes; git
/// writes UTF-8 names on Windows, where a file name cannot be anything else.
pub fn under(&self, top: &Path) -> PathBuf {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
top.join(std::ffi::OsStr::from_bytes(&self.bytes))
}
#[cfg(not(unix))]
{
top.join(&self.shown)
}
}
}
/// The names of the staged files, as `git diff --cached --name-only -z` prints
/// them: NUL-separated, so no path is quoted.
pub fn git_staged(project: &Path) -> Result<Vec<String>, String> {
/// them: NUL-separated, so no path is quoted, and read as bytes.
pub fn git_staged(project: &Path) -> Result<Vec<GitPath>, String> {
git_staged_capped(project, STAGED_LIST_LIMIT)
}
/// `git_staged` with the size the list may reach. The secret and size gate
/// reads every staged name, so a list over the cap fails closed rather than
/// being checked in part.
fn git_staged_capped(project: &Path, cap: usize) -> Result<Vec<String>, String> {
let (run, cut) = run_capped(
fn git_staged_capped(project: &Path, cap: usize) -> Result<Vec<GitPath>, String> {
let (run, cut, raw) = run_capped_bytes(
git(project, &["diff", "--cached", "--name-only", "-z"]),
None,
QUICK_LIMIT,
@@ -429,13 +508,14 @@ fn git_staged_capped(project: &Path, cap: usize) -> Result<Vec<String>, String>
if cut {
return Err(STAGED_TOO_LONG.to_string());
}
Ok(split_nul(&run.output))
Ok(split_nul(&raw))
}
fn split_nul(text: &str) -> Vec<String> {
text.split('\0')
fn split_nul(bytes: &[u8]) -> Vec<GitPath> {
bytes
.split(|b| *b == 0)
.filter(|name| !name.is_empty())
.map(str::to_string)
.map(GitPath::from_bytes)
.collect()
}
@@ -529,39 +609,67 @@ pub fn git_head_full(project: &Path) -> Option<String> {
/// The paths `git status --porcelain=v1 -z` lists (renames name the new path).
pub fn git_status_porcelain(project: &Path) -> Result<Vec<String>, String> {
let run = run_limited_with(
git(project, &["status", "--porcelain=v1", "-z"]),
Ok(git_changed(project)?
.into_iter()
.map(|path| path.shown)
.collect())
}
/// `git_status_porcelain` with each path kept as git wrote it, relative to the
/// repository's top folder: the list the loop stages from.
pub fn git_changed(project: &Path) -> Result<Vec<GitPath>, String> {
let (run, cut, raw) = run_capped_bytes(
// Untracked files are listed whatever `status.showUntrackedFiles`
// says: with it at `no`, the agent's new files would miss the commit. `all` lists each file,
// not a folder, so a folder that was untracked before the phase never hides or swallows files.
git(
project,
&["status", "--porcelain=v1", "-z", "--untracked-files=all"],
),
None,
QUICK_LIMIT,
false,
Keep::Head(STAGED_LIST_LIMIT),
);
if !run.ok {
return Err(run.output.trim().to_string());
}
Ok(parse_porcelain(&run.output))
// A list cut short would name only some of the files: never stage from it.
if cut {
return Err(STAGED_TOO_LONG.to_string());
}
Ok(porcelain_paths(&raw)
.into_iter()
.map(GitPath::from_bytes)
.collect())
}
/// Read `git status --porcelain=v1 -z`: NUL-separated records of `XY path`, no
/// quoting. A rename or copy record is followed by one more field, the old
/// path, which is skipped (the new path is the one listed).
pub fn parse_porcelain(text: &str) -> Vec<String> {
porcelain_paths(text.as_bytes())
.into_iter()
.map(|path| String::from_utf8_lossy(path).into_owned())
.collect()
}
/// `parse_porcelain` over the bytes git wrote. The two status letters and the
/// space are ASCII, so the path is whatever follows them.
fn porcelain_paths(bytes: &[u8]) -> Vec<&[u8]> {
let mut paths = Vec::new();
let mut fields = text.split('\0');
let mut fields = bytes.split(|b| *b == 0);
while let Some(record) = fields.next() {
let mut chars = record.chars();
let (Some(x), Some(y), Some(' ')) = (chars.next(), chars.next(), chars.next()) else {
continue;
};
let Some(path) = record.get(x.len_utf8() + y.len_utf8() + 1..) else {
let [x, y, b' ', path @ ..] = record else {
continue;
};
if path.is_empty() {
continue;
}
if matches!(x, 'R' | 'C') || matches!(y, 'R' | 'C') {
if matches!(x, b'R' | b'C') || matches!(y, b'R' | b'C') {
fields.next();
}
paths.push(path.to_string());
paths.push(path);
}
paths
}
@@ -682,7 +790,11 @@ mod tests {
git_staged_capped(&repo, 8),
Err(STAGED_TOO_LONG.to_string())
);
let all = git_staged_capped(&repo, 1024).unwrap();
let all: Vec<String> = git_staged_capped(&repo, 1024)
.unwrap()
.into_iter()
.map(|path| path.shown)
.collect();
assert_eq!(all, [".env", "a.txt", "b.txt"]);
let _ = std::fs::remove_dir_all(&repo);
}
@@ -749,11 +861,28 @@ mod tests {
#[test]
fn staged_names_are_split_on_nul() {
assert_eq!(
split_nul("a b.txt\0dir/c.rs\0"),
vec!["a b.txt", "dir/c.rs"]
);
assert!(split_nul("").is_empty());
let shown: Vec<String> = split_nul(b"a b.txt\0dir/c.rs\0")
.into_iter()
.map(|path| path.shown)
.collect();
assert_eq!(shown, vec!["a b.txt", "dir/c.rs"]);
assert!(split_nul(b"").is_empty());
}
#[test]
fn a_name_that_is_not_utf8_keeps_its_bytes() {
let names = split_nul(b"caf\xe9.bin\0ok.txt\0");
assert_eq!(names[0].bytes, b"caf\xe9.bin");
assert_eq!(names[0].shown, "caf\u{fffd}.bin");
// The porcelain reader keeps the bytes too, and still skips a rename's old path.
let paths = porcelain_paths(b"?? caf\xe9.bin\0R new.rs\0old.rs\0");
assert_eq!(paths, vec![&b"caf\xe9.bin"[..], &b"new.rs"[..]]);
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
let file = names[0].under(Path::new("/top"));
assert_eq!(file.as_os_str().as_bytes(), b"/top/caf\xe9.bin");
}
}
#[test]
+119 -21
View File
@@ -17,6 +17,7 @@ use plan2code_app_lib::node_check;
use plan2code_app_lib::project::{self, ProjectDir};
use plan2code_app_lib::quit_prompt::{loop_quit_prompt, quit_prompt, QuitCase};
use plan2code_app_lib::restart_brief;
use plan2code_app_lib::session_reader;
use plan2code_app_lib::settings;
#[cfg(windows)]
use plan2code_app_lib::task_dialog;
@@ -185,10 +186,14 @@ fn open_install_page(id: String) -> Result<(), String> {
// `cmd /c ver` prints e.g. `Microsoft Windows [Version 10.0.26300.1234]`.
fn windows_build() -> Option<u32> {
let out = std::process::Command::new("cmd")
.args(["/c", "ver"])
.output()
.ok()?;
let mut command = std::process::Command::new("cmd");
command.args(["/c", "ver"]);
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
}
let out = command.output().ok()?;
let text = String::from_utf8_lossy(&out.stdout);
let version = text.split("Version ").nth(1)?;
version.split('.').nth(2)?.trim().parse().ok()
@@ -889,13 +894,23 @@ fn console_start(state: State<'_, AppState>) -> Result<serde_json::Value, String
console_start_impl(&state)
}
/// What `console_start` says before the agent has announced any page.
const NO_DASHBOARD_YET: &str = "The agent has not opened the dashboard yet.";
/// The health check runs with the console lock released (the announce thread
/// takes it to follow a new page); a console the person stopped, or one found
/// dead, is opened again on its session, unless a new page was followed
/// meanwhile.
fn console_start_impl(state: &AppState) -> Result<serde_json::Value, String> {
let probe = {
let guard = state.console.lock().map_err(|e| e.to_string())?;
guard.as_ref().ok_or(NO_DASHBOARD_YET)?.probe()
};
let alive = !probe.stopped() && probe.alive();
let mut guard = state.console.lock().map_err(|e| e.to_string())?;
let sup = guard
.as_mut()
.ok_or("The agent has not opened the dashboard yet.")?;
if !sup.health() {
sup.restart_if_dead()?;
let sup = guard.as_mut().ok_or(NO_DASHBOARD_YET)?;
if !alive && sup.probe() == probe {
sup.reopen()?;
}
serde_json::to_value(sup.session()).map_err(|e| e.to_string())
}
@@ -904,23 +919,37 @@ fn console_start_impl(state: &AppState) -> Result<serde_json::Value, String> {
/// dead (started but not answering).
#[tauri::command(async)]
fn console_status(state: State<'_, AppState>) -> serde_json::Value {
let Ok(guard) = state.console.lock() else {
return serde_json::json!({ "state": "none", "url": null });
};
match guard.as_ref() {
Some(sup) if sup.stopped() => serde_json::json!({ "state": "none", "url": null }),
Some(sup) if sup.health() => {
serde_json::json!({ "state": "running", "url": sup.session().url })
console_status_impl(&state)
}
/// The health check runs with the console lock released, as in `console_start`.
fn console_status_impl(state: &AppState) -> serde_json::Value {
let none = serde_json::json!({ "state": "none", "url": null });
let seen = state.console.lock().ok().and_then(|guard| {
guard
.as_ref()
.map(|sup| (sup.probe(), sup.session().url.clone()))
});
match seen {
Some((probe, _)) if probe.stopped() => none,
Some((probe, url)) if probe.health() => {
serde_json::json!({ "state": "running", "url": url })
}
Some(sup) => serde_json::json!({ "state": "dead", "url": sup.session().url }),
None => serde_json::json!({ "state": "none", "url": null }),
Some((_, url)) => serde_json::json!({ "state": "dead", "url": url }),
None => none,
}
}
#[tauri::command]
fn console_stop(state: State<'_, AppState>) -> Result<(), String> {
console_stop_impl(&state)
}
/// Stop the console but keep its supervisor, so a start after a stop opens
/// the same session again instead of finding nothing to start.
fn console_stop_impl(state: &AppState) -> Result<(), String> {
let mut guard = state.console.lock().map_err(|e| e.to_string())?;
if let Some(mut sup) = guard.take() {
if let Some(sup) = guard.as_mut() {
sup.stop()?;
}
Ok(())
@@ -1374,8 +1403,13 @@ fn main() {
let taken =
take_announced(&state, &notice, window_origin(&handle), session_on_disk);
if taken {
// A running loop follows its phase's session from here.
loop_driver::note_page(&state.loop_run, &notice.workflow, &notice.sid);
// A running loop follows its phase's session from here,
// once the agent's `open --loop` has locked it.
let page = session_reader::console_home()
.and_then(|home| session_reader::load(&home, &notice.sid).ok())
.map(|session| session.state)
.unwrap_or(serde_json::Value::Null);
loop_driver::note_page(&state.loop_run, &notice.workflow, &notice.sid, &page);
let _ = handle.emit("console-page", &notice);
} else {
eprintln!(
@@ -1425,6 +1459,7 @@ fn main() {
mod tests {
use super::*;
use std::path::PathBuf;
use std::time::{Duration, Instant};
fn state_for(dir: &str) -> AppState {
AppState {
@@ -1801,6 +1836,69 @@ mod tests {
assert_eq!(event.spec_name, "x");
}
#[test]
fn a_start_after_a_stop_opens_the_same_session_again() {
let Some(sup) = real_console() else { return };
let state = state_for("project-a");
let sid = sup.session().sid.clone();
*state.console.lock().unwrap() = Some(sup);
assert_eq!(console_status_impl(&state)["state"], "running");
console_stop_impl(&state).unwrap();
assert_eq!(console_status_impl(&state)["state"], "none");
assert!(
state.console.lock().unwrap().is_some(),
"the supervisor stays"
);
let session = console_start_impl(&state).expect("a start after a stop works");
assert_eq!(
session["sid"].as_str(),
Some(sid.as_str()),
"the same session"
);
assert_eq!(console_status_impl(&state)["state"], "running");
let _ = state.console.lock().unwrap().take().unwrap().stop();
}
#[test]
fn a_slow_health_check_never_holds_the_console_lock() {
// A server that takes the connection and never answers: the check
// waits out its whole timeout.
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
std::env::set_var(
"PLAN2CODE_CONSOLE_DIR",
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console"),
);
let sup = ConsoleSupervisor::adopt(
PathBuf::from("."),
app_origin().to_string(),
&format!("http://127.0.0.1:{port}/s/slow/"),
"slow",
)
.expect("adopt");
let state = state_for("project-a");
*state.console.lock().unwrap() = Some(sup);
std::thread::scope(|scope| {
let poll = scope.spawn(|| console_status_impl(&state));
// The poll is in its health check by now; the announce thread's
// lock must not wait for it.
std::thread::sleep(Duration::from_millis(300));
let asked = Instant::now();
drop(state.console.lock().unwrap());
assert!(
asked.elapsed() < Duration::from_millis(500),
"the lock waited {:?} on the health check",
asked.elapsed()
);
assert_eq!(poll.join().unwrap()["state"], "dead");
});
drop(listener);
// Leave nothing to stop: the adopted console was never started.
std::mem::forget(state.console.lock().unwrap().take());
}
#[test]
fn teardown_clears_the_console_so_console_start_refuses_not_reconnects() {
let Some(sup) = real_console() else { return };
+15 -9
View File
@@ -37,11 +37,14 @@ pub fn classify(output: &str) -> NodeStatus {
}
pub fn check_node() -> NodeStatus {
match Command::new("node")
.env("PATH", resolved_path())
.arg("--version")
.output()
let mut command = Command::new("node");
command.env("PATH", resolved_path()).arg("--version");
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
}
match command.output() {
Ok(out) if out.status.success() => classify(&String::from_utf8_lossy(&out.stdout)),
_ => NodeStatus::Missing,
}
@@ -226,11 +229,14 @@ pub fn node_binary_path() -> Option<String> {
} else {
("which", "node")
};
let out = Command::new(program)
.env("PATH", resolved_path())
.arg(arg)
.output()
.ok()?;
let mut command = Command::new(program);
command.env("PATH", resolved_path()).arg(arg);
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
}
let out = command.output().ok()?;
if !out.status.success() {
return None;
}
+1 -1
View File
@@ -83,7 +83,7 @@ If no state file is found, the bot starts a fresh run.
1. Detects mode based on presence of `AGENTS.md`
2. Generates an idea (new app or enhancement) via Claude, optionally guided by `--idea` seed
3. Writes `IDEA.md` to the project directory
4. Installs bot-friendly copies of plan2code skills (strips `disable-model-invocation` so sessions can invoke them)
4. Installs bot-friendly copies of five plan2code skills (init, plan, document, implement, finalize), each whole folder with its references and scripts, and strips `disable-model-invocation`; the plan, document and finalize prompts tell the session to open the skill file and follow it (init writes a stub by hand and implement works from the spec directly)
5. Runs each workflow step as a separate Claude Agent SDK session:
- **init** — generates `AGENTS.md` (new-project mode only)
- **plan** — creates plan draft in `specs/<feature>/`
+31
View File
@@ -186,6 +186,37 @@ describe('installSkillsForBot', () => {
expect(content).toContain('name: doc');
});
it('copies the whole skill folder, references and scripts included', () => {
const srcDir = path.join(fakeHome, '.claude', 'skills', 'plan2code-3-implement');
fs.ensureDirSync(path.join(srcDir, 'references', 'web-console', 'notes'));
fs.ensureDirSync(path.join(srcDir, 'scripts'));
fs.writeFileSync(path.join(srcDir, 'SKILL.md'), 'disable-model-invocation: true\n---\nname: impl\n---\nBody');
fs.writeFileSync(path.join(srcDir, 'references', 'implement.md'), 'implement rules');
fs.writeFileSync(path.join(srcDir, 'references', 'web-console', 'notes', 'implement.md'), 'console notes');
fs.writeFileSync(path.join(srcDir, 'scripts', 'specs.mjs'), 'export {};');
installSkillsForBot(projectDir);
const dest = path.join(projectDir, '.claude', 'skills', 'plan2code-3-implement');
expect(fs.readFileSync(path.join(dest, 'references', 'implement.md'), 'utf-8')).toBe('implement rules');
expect(fs.readFileSync(path.join(dest, 'references', 'web-console', 'notes', 'implement.md'), 'utf-8')).toBe('console notes');
expect(fs.readFileSync(path.join(dest, 'scripts', 'specs.mjs'), 'utf-8')).toBe('export {};');
expect(fs.readFileSync(path.join(dest, 'SKILL.md'), 'utf-8')).not.toContain('disable-model-invocation');
});
it('copies only its five skills, not every installed plan2code skill', () => {
for (const name of ['plan2code-init', 'plan2code-git', 'plan2code-quick-task']) {
const dir = path.join(fakeHome, '.claude', 'skills', name);
fs.ensureDirSync(dir);
fs.writeFileSync(path.join(dir, 'SKILL.md'), 'content');
}
installSkillsForBot(projectDir);
const skills = fs.readdirSync(path.join(projectDir, '.claude', 'skills'));
expect(skills).toEqual(['plan2code-init']);
});
it('skips gracefully when source skill does not exist', () => {
// No skills in fakeHome — should not throw
expect(() => installSkillsForBot(projectDir)).not.toThrow();
+10 -6
View File
@@ -33,7 +33,9 @@ const SKILL_MAP: Record<StepName, string> = {
* Install bot-friendly copies of plan2code skills into the project's .claude/skills/.
* The global skills have `disable-model-invocation: true` which prevents the autonomous
* session from invoking them via the Skill tool. We copy them with that flag removed
* so the session can invoke the real workflow prompts instead of guessing.
* so the session can open and follow the real workflow prompts instead of guessing.
* The whole skill folder is copied (its references and scripts too), because a skill
* reads its references and runs its shipped scripts by path from beside SKILL.md.
*/
export function installSkillsForBot(projectDir: string): void {
const userSkillsDir = path.join(
@@ -44,15 +46,17 @@ export function installSkillsForBot(projectDir: string): void {
const projectSkillsDir = path.join(projectDir, '.claude', 'skills');
for (const skillName of Object.values(SKILL_MAP)) {
const srcFile = path.join(userSkillsDir, skillName, 'SKILL.md');
const srcDir = path.join(userSkillsDir, skillName);
const srcFile = path.join(srcDir, 'SKILL.md');
if (!fs.existsSync(srcFile)) continue;
const content = fs.readFileSync(srcFile, 'utf-8');
// Remove the disable-model-invocation line so the bot session can invoke the skill
const patched = content.replace(/^disable-model-invocation:\s*true\n?/m, '');
const destDir = path.join(projectSkillsDir, skillName);
fs.ensureDirSync(destDir);
fs.copySync(srcDir, destDir, { overwrite: true });
// Remove the disable-model-invocation line so the bot session can use the skill
const content = fs.readFileSync(srcFile, 'utf-8');
const patched = content.replace(/^disable-model-invocation:\s*true\n?/m, '');
fs.writeFileSync(path.join(destDir, 'SKILL.md'), patched);
}
}
@@ -24,14 +24,16 @@ describe('buildStepPrompt', () => {
expect(prompt).toContain('/plan2code-init');
});
it('plan prompt includes /plan2code-1-plan skill invocation', () => {
it('plan prompt says to open the skill file and follow it', () => {
const prompt = buildStepPrompt('plan', config);
expect(prompt).toContain('/plan2code-1-plan');
expect(prompt).toContain('Open the skill file .claude/skills/plan2code-1-plan/SKILL.md and follow it');
expect(prompt).not.toContain('Run the /plan2code');
});
it('document prompt includes /plan2code-2-document skill invocation', () => {
it('document prompt says to open the skill file and follow it', () => {
const prompt = buildStepPrompt('document', config);
expect(prompt).toContain('/plan2code-2-document');
expect(prompt).toContain('Open the skill file .claude/skills/plan2code-2-document/SKILL.md and follow it');
expect(prompt).not.toContain('Run the /plan2code');
});
it('implement prompt instructs direct tool usage without skill invocation', () => {
@@ -39,9 +41,10 @@ describe('buildStepPrompt', () => {
expect(prompt).toContain('Do NOT use the Skill tool');
});
it('finalize prompt includes /plan2code-4-finalize skill invocation', () => {
it('finalize prompt says to open the skill file and follow it', () => {
const prompt = buildStepPrompt('finalize', config);
expect(prompt).toContain('/plan2code-4-finalize');
expect(prompt).toContain('Open the skill file .claude/skills/plan2code-4-finalize/SKILL.md and follow it');
expect(prompt).not.toContain('Run the /plan2code');
});
it('plan prompt includes project name and description', () => {
@@ -56,7 +56,7 @@ If IDEA.md does not already exist, create it with the project name and descripti
function buildPlanPrompt(config: BotConfig): string {
return `${AUTONOMOUS_PREAMBLE}
Run the /plan2code-1-plan skill to create a plan for this project.
Open the skill file .claude/skills/plan2code-1-plan/SKILL.md and follow it to create a plan for this project.
Read the IDEA.md file first to understand the project. The project is: ${config.ideaDescription}
@@ -72,7 +72,7 @@ When making decisions during planning:
function buildDocumentPrompt(config: BotConfig): string {
return `${AUTONOMOUS_PREAMBLE}
Run the /plan2code-2-document skill to transform the plan into implementation specs.
Open the skill file .claude/skills/plan2code-2-document/SKILL.md and follow it to transform the plan into implementation specs.
Read the existing plan output in specs/ first to understand what was planned.
@@ -121,7 +121,7 @@ You are a senior software engineer implementing a project phase. Do NOT use the
function buildFinalizePrompt(config: BotConfig): string {
return `${AUTONOMOUS_PREAMBLE}
Run the /plan2code-4-finalize skill to validate and archive the completed project.
Open the skill file .claude/skills/plan2code-4-finalize/SKILL.md and follow it to validate and archive the completed project.
When making decisions:
- Approve all documentation updates
+16 -9
View File
@@ -56,18 +56,25 @@ export function cohortKeyForRun(run: RunMetrics): string {
}
/**
* Backfill missing PromptVersions fields for old run files (pre-v1.1).
* Backfill missing PromptVersions fields for old run files (pre-v1.1): the
* eight prompts every run once recorded are padded with the missing sentinel
* (buildCohortKey ignores it), and any other prompt a run recorded is kept.
*
* One-time regrouping: a run recorded before the collector fingerprinted every
* prompt has fewer entries than a new one, so its cohort key differs and it
* groups as the previous prompt generation.
*/
export function backfillPromptVersions(pv: PromptVersions): PromptVersions {
return {
plan: pv.plan ?? 'sha256:missing',
revise_plan: pv.revise_plan ?? 'sha256:missing',
document: pv.document ?? 'sha256:missing',
implement: pv.implement ?? 'sha256:missing',
finalize: pv.finalize ?? 'sha256:missing',
init: pv.init ?? 'sha256:missing',
init_update: pv.init_update ?? 'sha256:missing',
quick_task: pv.quick_task ?? 'sha256:missing',
plan: 'sha256:missing',
revise_plan: 'sha256:missing',
document: 'sha256:missing',
implement: 'sha256:missing',
finalize: 'sha256:missing',
init: 'sha256:missing',
init_update: 'sha256:missing',
quick_task: 'sha256:missing',
...(pv ?? {}),
};
}
+101
View File
@@ -0,0 +1,101 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { collectPromptVersions, collectStep1, extractMetricsJson, promptKey } from './collector.js';
import { backfillPromptVersions, buildCohortKey } from './aggregator.js';
let root: string;
beforeEach(() => {
root = fs.mkdtempSync(path.join(os.tmpdir(), 'p2c-collector-'));
fs.mkdirSync(path.join(root, 'src'));
});
afterEach(() => {
fs.rmSync(root, { recursive: true, force: true });
});
function prompt(name: string, body: string) {
fs.writeFileSync(path.join(root, 'src', name), body);
}
describe('collectPromptVersions', () => {
it('fingerprints every src/plan2code-*.md prompt in the folder', () => {
prompt('plan2code-1-plan.md', 'plan');
prompt('plan2code-3-implement-review.md', 'implement review');
prompt('plan2code-git.md', 'git');
const versions = collectPromptVersions(root);
expect(Object.keys(versions).sort()).toEqual(['3_implement_review', 'git', 'plan']);
for (const v of Object.values(versions)) expect(v).toMatch(/^sha256:[0-9a-f]{64}$/);
});
it('covers a newly added prompt without a code change', () => {
prompt('plan2code-1-plan.md', 'plan');
const before = collectPromptVersions(root);
prompt('plan2code-brand-new.md', 'a new skill');
const after = collectPromptVersions(root);
expect(before).not.toHaveProperty('brand_new');
expect(after).toHaveProperty('brand_new');
expect(buildCohortKey(after)).not.toBe(buildCohortKey(before));
});
it('ignores files and folders that are not top-level plan2code-*.md prompts', () => {
prompt('plan2code-1-plan.md', 'plan');
prompt('README.md', 'not a prompt');
prompt('plan2code-notes.txt', 'not markdown');
fs.mkdirSync(path.join(root, 'src', 'plan2code-0-pathfinder-references.md'));
expect(Object.keys(collectPromptVersions(root))).toEqual(['plan']);
});
it('keeps the old keys for the eight prompts recorded before, so their hashes stay comparable', () => {
expect(promptKey('plan2code-1-plan.md')).toBe('plan');
expect(promptKey('plan2code-1b-revise-plan.md')).toBe('revise_plan');
expect(promptKey('plan2code-2-document.md')).toBe('document');
expect(promptKey('plan2code-3-implement.md')).toBe('implement');
expect(promptKey('plan2code-4-finalize.md')).toBe('finalize');
expect(promptKey('plan2code-init.md')).toBe('init');
expect(promptKey('plan2code-init-update.md')).toBe('init_update');
expect(promptKey('plan2code-quick-task.md')).toBe('quick_task');
});
it('returns nothing when there is no src folder', () => {
expect(collectPromptVersions(path.join(root, 'nowhere'))).toEqual({});
});
it('groups a run recorded before this change as the previous prompt generation', () => {
prompt('plan2code-1-plan.md', 'plan');
prompt('plan2code-git.md', 'git');
const now = collectPromptVersions(root);
const old = backfillPromptVersions({ plan: now.plan });
expect(buildCohortKey(old)).not.toBe(buildCohortKey(now));
});
});
describe('the shared scrape pattern', () => {
function draft(body: string) {
const specDir = path.join(root, 'spec');
fs.mkdirSync(specDir);
fs.writeFileSync(path.join(specDir, 'PLAN-DRAFT-1.md'), body);
return collectStep1(specDir);
}
it('reads the METRICS_JSON comment', () => {
expect(extractMetricsJson('x <!-- METRICS_JSON {"confidence": 95} --> y')).toEqual({ confidence: 95 });
});
it('reads a breakdown written as label, colon, score', () => {
const m = draft('Requirements: 24\nFeasibility: 23\nIntegration: 22\nRisk: 21\n');
expect(m.confidence_breakdown).toEqual({ requirements: 24, feasibility: 23, integration: 22, risk: 21 });
});
it('reads a breakdown table whose score ends the row', () => {
const m = draft('| Requirements | 24 |\n| Risk | 21/25 |\n');
expect(m.confidence_breakdown).toEqual({ requirements: 24, feasibility: null, integration: null, risk: 21 });
});
it('leaves an ordinary risk-register row alone', () => {
const m = draft('| Risk | 3 | High | Mitigation |\n');
expect(m.confidence_breakdown).toBeNull();
});
});
+49 -18
View File
@@ -16,6 +16,7 @@ import type {
Step4FinalizeMetrics,
UserFeedback,
} from './types.js';
import metricsPattern from './metrics-pattern.json' with { type: 'json' };
// ── Helpers ──────────────────────────────────────────────────────────────────
@@ -44,7 +45,7 @@ function readFileSafe(filePath: string): string | null {
* Returns parsed object or null if not found / invalid.
*/
export function extractMetricsJson(content: string, stepFilter?: string): Record<string, unknown> | null {
const re = /<!--\s*METRICS_JSON\s+(\{[\s\S]*?\})\s*-->/g;
const re = new RegExp(metricsPattern.metricsComment, 'g');
let match: RegExpExecArray | null;
while ((match = re.exec(content)) !== null) {
try {
@@ -96,18 +97,38 @@ function generateRunId(): string {
// ── Prompt version hashing ────────────────────────────────────────────────────
// The prompts recorded before the collector read the folder keep their keys.
const LEGACY_PROMPT_KEYS: Record<string, string> = {
'plan2code-1-plan.md': 'plan',
'plan2code-1b-revise-plan.md': 'revise_plan',
'plan2code-2-document.md': 'document',
'plan2code-3-implement.md': 'implement',
'plan2code-4-finalize.md': 'finalize',
'plan2code-init.md': 'init',
'plan2code-init-update.md': 'init_update',
'plan2code-quick-task.md': 'quick_task',
};
/** The PromptVersions key for a prompt file: its legacy key, else its name without "plan2code-" and ".md", dashes as underscores. */
export function promptKey(fileName: string): string {
return LEGACY_PROMPT_KEYS[fileName]
?? fileName.replace(/^plan2code-/, '').replace(/\.md$/, '').replace(/-/g, '_');
}
/** Fingerprint every src/plan2code-*.md prompt, read from the folder so a new skill is covered at once. */
export function collectPromptVersions(plan2codeRoot: string): PromptVersions {
const srcDir = path.join(plan2codeRoot, 'src');
return {
plan: sha256File(path.join(srcDir, 'plan2code-1-plan.md')),
revise_plan: sha256File(path.join(srcDir, 'plan2code-1b-revise-plan.md')),
document: sha256File(path.join(srcDir, 'plan2code-2-document.md')),
implement: sha256File(path.join(srcDir, 'plan2code-3-implement.md')),
finalize: sha256File(path.join(srcDir, 'plan2code-4-finalize.md')),
init: sha256File(path.join(srcDir, 'plan2code-init.md')),
init_update: sha256File(path.join(srcDir, 'plan2code-init-update.md')),
quick_task: sha256File(path.join(srcDir, 'plan2code-quick-task.md')),
};
let files: string[] = [];
try {
files = fs.readdirSync(srcDir)
.filter(f => /^plan2code-.+\.md$/.test(f) && fs.statSync(path.join(srcDir, f)).isFile())
.sort();
} catch {
return {};
}
const versions: PromptVersions = {};
for (const f of files) versions[promptKey(f)] = sha256File(path.join(srcDir, f));
return versions;
}
// ── Step 1: Plan ──────────────────────────────────────────────────────────────
@@ -184,24 +205,34 @@ export function collectStep1(specDir: string): Step1PlanMetrics {
};
// ── Confidence ──
// The patterns are the shared ones in metrics-pattern.json, by name, like the breakdown below.
const confidenceMatch = (name: string) => {
const p = metricsPattern.confidence.find(c => c.name === name);
return p ? latestDraft.match(new RegExp(p.source, p.flags)) : null;
};
let finalConfidence = parseMetricField('confidence');
if (finalConfidence === null) {
// Fallback: prose scraping — handle bold markdown like **Confidence:** 95%
const confMatch = latestDraft.match(/(?:Overall|Final|Total)?\s*\**[Cc]onfidence\**[:\s*]+(\d{1,3})%/);
const confMatch = confidenceMatch('overall confidence with %');
if (confMatch) {
finalConfidence = parseInt(confMatch[1], 10);
} else {
const tableMatch = latestDraft.match(/[|]\s*[Cc]onfidence\s*[|]\s*(\d{1,3})/);
const tableMatch = confidenceMatch('confidence table cell');
if (tableMatch) finalConfidence = parseInt(tableMatch[1], 10);
}
}
// Confidence breakdown (requirements, feasibility, integration, risk)
let confidenceBreakdown: Step1PlanMetrics['confidence_breakdown'] = null;
const reqMatch = latestDraft.match(/[Rr]equirements?[:\s|]+(\d{1,2})/);
const feasMatch = latestDraft.match(/[Ff]easibility[:\s|]+(\d{1,2})/);
const intMatch = latestDraft.match(/[Ii]ntegration[:\s|]+(\d{1,2})/);
const riskMatch = latestDraft.match(/[Rr]isk[:\s|]+(\d{1,2})/);
// The patterns are the shared ones in metrics-pattern.json (the console's bait scanner reads the same).
const breakdownMatch = (key: string): RegExpMatchArray | null => {
const p = metricsPattern.breakdown.find(b => b.key === key);
return p ? latestDraft.match(new RegExp(p.source, p.flags)) : null;
};
const reqMatch = breakdownMatch('requirements');
const feasMatch = breakdownMatch('feasibility');
const intMatch = breakdownMatch('integration');
const riskMatch = breakdownMatch('risk');
if (reqMatch || feasMatch || intMatch || riskMatch) {
confidenceBreakdown = {
requirements: reqMatch ? parseInt(reqMatch[1], 10) : null,
@@ -596,7 +627,7 @@ export async function collectRun(opts: CollectorOptions): Promise<RunMetrics> {
const runId = generateRunId();
// Get started_at / completed_at from spec directory mtime / iteration.log
// Get started_at / completed_at from the spec directory's birth and modified times
let startedAt: string | null = null;
let completedAt: string | null = null;
try {
@@ -0,0 +1,42 @@
{
"_note": "The shapes plan2code-metrics scrapes from a PLAN-DRAFT: one source for the console's bait scanner (src/web-console/patches.mjs), the skill scripts' SCRAPE (src/skill-scripts/common.mjs) and the collector's copy (plan2code-metrics/src/metrics-pattern.json). scripts/test-web-console-hardening.mjs fails when the copies drift. A label then a number in a table row counts only when the number ends the row.",
"metricsComment": "<!--\\s*METRICS_JSON\\s+(\\{[\\s\\S]*?\\})\\s*-->",
"confidence": [
{
"name": "overall confidence with %",
"source": "(?:Overall|Final|Total)?\\s*\\**[Cc]onfidence\\**[:\\s*]+(\\d{1,3})%",
"flags": ""
},
{
"name": "confidence table cell",
"source": "[|]\\s*[Cc]onfidence\\s*[|]\\s*(\\d{1,3})",
"flags": ""
}
],
"breakdown": [
{
"key": "requirements",
"name": "Requirements",
"source": "[Rr]equirements?(?:[:\\s]+|[ \\t:]*\\|[ \\t:|]*(?=\\d{1,2}(?:\\/\\d+)?[ \\t]*\\|?[ \\t]*$))(\\d{1,2})",
"flags": "m"
},
{
"key": "feasibility",
"name": "Feasibility",
"source": "[Ff]easibility(?:[:\\s]+|[ \\t:]*\\|[ \\t:|]*(?=\\d{1,2}(?:\\/\\d+)?[ \\t]*\\|?[ \\t]*$))(\\d{1,2})",
"flags": "m"
},
{
"key": "integration",
"name": "Integration",
"source": "[Ii]ntegration(?:[:\\s]+|[ \\t:]*\\|[ \\t:|]*(?=\\d{1,2}(?:\\/\\d+)?[ \\t]*\\|?[ \\t]*$))(\\d{1,2})",
"flags": "m"
},
{
"key": "risk",
"name": "Risk",
"source": "[Rr]isk(?:[:\\s]+|[ \\t:]*\\|[ \\t:|]*(?=\\d{1,2}(?:\\/\\d+)?[ \\t]*\\|?[ \\t]*$))(\\d{1,2})",
"flags": "m"
}
]
}
+7 -10
View File
@@ -1,15 +1,12 @@
// All TypeScript interfaces for plan2code-metrics
export interface PromptVersions {
plan: string; // sha256:... plan2code-1-plan.md
revise_plan: string; // plan2code-1b-revise-plan.md
document: string; // plan2code-2-document.md
implement: string; // plan2code-3-implement.md
finalize: string; // plan2code-4-finalize.md
init: string; // plan2code-init.md
init_update: string; // plan2code-init-update.md
quick_task: string; // plan2code-quick-task.md
}
/**
* SHA-256 fingerprint of every src/plan2code-*.md prompt, keyed by name
* (promptKey in collector.ts). The eight prompts recorded before the
* collector read the folder keep their old keys: plan, revise_plan, document,
* implement, finalize, init, init_update, quick_task.
*/
export type PromptVersions = Record<string, string>;
export interface Step1PlanMetrics {
present: boolean;
+91
View File
@@ -0,0 +1,91 @@
// Fails when the console opening paragraph of a skill drifts from the shared one.
//
// Eighteen skills open with the same "web console or terminal?" paragraph. Only
// the workflow name, the notes file and a few skill-specific clauses may differ;
// the shared sentences below must read the same in every one, so a fix to one
// skill's opening cannot silently skip the others. Matching ignores case and
// punctuation (dashes, colons, commas, brackets), never the words.
// Usage: node scripts/check-console-openings.mjs [srcDir] (defaults to ./src)
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
// Shared sentences. `{w}` is the workflow name. A sentence a skill states in its
// own words on purpose is listed in EXEMPT with the reason.
export const SHARED = [
{ id: "first", text: "The FIRST thing you do, before anything else in this file" },
{ id: "ask", text: "**web console** (browser page, suggested) or **terminal**?" },
{ id: "run", text: 'run `node "<D>/console.mjs" open --workflow {w}` before reading' },
{ id: "dir", text: "<D>: references/web-console/ beside this SKILL.md" },
{ id: "dirfile", text: "or the dir in ~/.plan2code/console/console-dir" },
{ id: "read", text: "then read <D>/console.md" },
{ id: "switch", text: "Switchable anytime." },
{ id: "web", text: "If the argument already says which (`--web` or `Use the web console for this session.`), take it and do not ask; drop the flag." },
{ id: "dash", text: "Launched by the dashboard? Its session is already open: resume it (console-launches.md)" },
];
export const EXEMPT = {
// Implement + Review defers to Implementation Mode's own Interface question.
"plan2code-3-implement-review": { ask: "defers to Implementation Mode's Interface question", run: "the question is Implementation Mode's" , switch: "Implementation Mode's Interface section says it" },
// Git runs an instruction in the argument in the terminal at once and has its own hand-off lines.
"plan2code-git": { dash: "also resumes from Commit it now and the Changelog hand-off", first: "opens with the run-at-once rule for an argument" },
};
export function normalize(text) {
return text
.toLowerCase()
.replace(/[\u2014\u2013:;,()\[\]]/g, " ")
.replace(/\s+/g, " ")
.trim();
}
// The paragraph (one line) holding the `open --workflow` command, or null.
export function openingOf(markdown) {
return markdown.split("\n").find((l) => l.includes('console.mjs" open --workflow')) ?? null;
}
export function workflowOf(skill) {
return skill.replace(/^plan2code-/, "").replace(/^\d+b?-/, "");
}
// Returns one message per drift found under srcDir.
export function check(srcDir) {
const problems = [];
const notesDir = path.join(srcDir, "web-console", "notes");
const files = fs
.readdirSync(srcDir)
.filter((f) => /^plan2code-.+\.md$/.test(f))
.sort();
let seen = 0;
for (const file of files) {
const skill = file.replace(/\.md$/, "");
const opening = openingOf(fs.readFileSync(path.join(srcDir, file), "utf8"));
if (!opening) continue; // the dashboard opens its own way
seen++;
const w = workflowOf(skill);
const norm = normalize(opening);
const exempt = EXEMPT[skill] ?? {};
for (const s of SHARED) {
if (exempt[s.id]) continue;
if (!norm.includes(normalize(s.text.replace("{w}", w)))) problems.push(`${file}: shared sentence "${s.id}" differs or is missing (expected: ${s.text.replace("{w}", w)})`);
}
const flows = [...opening.matchAll(/--workflow ([a-z-]+)/g)].map((m) => m[1]);
if (!flows.includes(w) && !exempt.run) problems.push(`${file}: opens --workflow ${flows.join(", ")} instead of ${w}`);
const note = opening.match(/<D>\/notes\/([a-z-]+)\.md/);
if (!note) problems.push(`${file}: names no <D>/notes/<workflow>.md file`);
else if (!fs.existsSync(path.join(notesDir, `${note[1]}.md`))) problems.push(`${file}: notes file ${note[1]}.md is not in src/web-console/notes/`);
}
if (seen !== 18) problems.push(`expected 18 skills with a console opening, found ${seen}`);
return problems;
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const problems = check(process.argv[2] ? path.resolve(process.argv[2]) : path.join(root, "src"));
if (problems.length) {
for (const p of problems) console.error(` FAIL ${p}`);
process.exit(1);
}
console.log("All 18 console openings share their sentences.");
}
+39
View File
@@ -0,0 +1,39 @@
// Fails when a file in .agents-docs/ is larger than the size limit, so a doc
// never grows into one nobody reads whole again. Split it by area instead and
// link the pieces from its index (see AGENTS-architecture.md).
// Usage: node scripts/check-doc-size.mjs [docsDir] [limitBytes]
// The limit is the largest area file (about 54 KB) plus headroom.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
export const DEFAULT_LIMIT = 60000;
// One entry per file over the limit: { file, bytes }.
export function oversize(dir, limit = DEFAULT_LIMIT) {
return fs.readdirSync(dir)
.filter((f) => f.endsWith(".md"))
.map((f) => ({ file: f, bytes: fs.statSync(path.join(dir, f)).size }))
.filter((e) => e.bytes > limit)
.sort((a, b) => a.file.localeCompare(b.file));
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const here = path.dirname(fileURLToPath(import.meta.url));
const dir = process.argv[2] ? path.resolve(process.argv[2]) : path.join(here, "..", ".agents-docs");
const limit = process.argv[3] ? Number(process.argv[3]) : DEFAULT_LIMIT;
if (!Number.isFinite(limit) || limit <= 0) {
console.error(`Bad size limit: ${process.argv[3]}`);
process.exit(2);
}
const big = oversize(dir, limit);
if (big.length) {
console.error(
`Over the ${limit}-byte limit (split each by area and link the pieces from its index):\n` +
big.map((e) => ` ${e.file}: ${e.bytes} bytes`).join("\n"),
);
process.exit(1);
}
console.log(`Every file in .agents-docs/ is within ${limit} bytes.`);
}
+69
View File
@@ -0,0 +1,69 @@
// Fails when a built prompt names an agent product's tool by its product name.
//
// Prompts are read by many agents, and each one calls the same tool something
// else. Prompt text says what to do ("ask with the question tool", "list the
// folder") and never what one product's tool is called. This reads every
// Markdown file in the built skills/ tree, so run it after
// `node install.js --build-skills`.
// Usage: node scripts/check-prompt-wording.mjs [skillsDir] (defaults to ./skills)
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
// Case-sensitive on purpose: "glob" and "grep" in lower case are ordinary words
// and command names, "Glob" and "Grep" as tool names are what this catches.
export const BANNED = [
"AskUserQuestion",
"Glob",
"Grep",
"TodoWrite",
"WebFetch",
"WebSearch",
"NotebookEdit",
"Read tool",
"Write tool",
"Edit tool",
"Bash tool",
"ask_user_question",
];
const PATTERN = new RegExp(`(?<![A-Za-z0-9_])(${BANNED.join("|")})(?![A-Za-z0-9_])`);
function* markdownFiles(dir) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) yield* markdownFiles(full);
else if (entry.name.endsWith(".md")) yield full;
}
}
// Returns [{ file, line, name }] for every banned name found under dir.
export function findBanned(dir) {
const hits = [];
for (const file of markdownFiles(dir)) {
fs.readFileSync(file, "utf8")
.split("\n")
.forEach((text, i) => {
const m = PATTERN.exec(text);
if (m) hits.push({ file: path.relative(dir, file).split(path.sep).join("/"), line: i + 1, name: m[1] });
});
}
return hits;
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const dir = process.argv[2] ? path.resolve(process.argv[2]) : path.join(root, "skills");
if (!fs.existsSync(dir)) {
console.error(` FAIL ${dir} does not exist. Run: node install.js --build-skills`);
process.exit(1);
}
const hits = findBanned(dir);
if (hits.length) {
for (const h of hits) console.error(` FAIL ${h.file}:${h.line} names a product tool: ${h.name}`);
console.error(" Say what to do in neutral words (\"the question tool\", \"list the folder\").");
process.exit(1);
}
console.log("Built prompts name no product tool.");
}
+27
View File
@@ -0,0 +1,27 @@
// Refuse a commit that stages a file named `nul`.
//
// On Windows a stray `> nul` in a Git Bash or Unix-style command (where nul is
// not the null device) writes a real file called `nul`, which Windows tools
// then cannot open, move or delete, and which breaks a checkout there. The
// repo used to hide it with a `nul` line in .gitignore; this pre-commit check
// (run from .husky/pre-commit) refuses it instead, so one never lands.
//
// node scripts/check-staged-nul.mjs exit 1 and name them when any staged
// path is nul (or nul.<ext>)
import { execFileSync } from "node:child_process";
import { pathToFileURL } from "node:url";
/** The paths whose file name is the Windows device name nul, with or without an extension. */
export function nulPaths(paths) {
return paths.filter((p) => /^nul(\.[^/\\]*)?$/i.test(p.split(/[/\\]/).pop()));
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const staged = execFileSync("git", ["diff", "--cached", "--name-only", "--diff-filter=ACR", "-z"], { encoding: "utf8" }).split("\0").filter(Boolean);
const bad = nulPaths(staged);
if (bad.length) {
process.stderr.write(`pre-commit: refusing to commit a file named nul (a Windows device name): ${bad.join(", ")}\nUnstage and delete it: git rm --cached -- <path>, then remove the file.\n`);
process.exit(1);
}
}
+37
View File
@@ -0,0 +1,37 @@
// Fails when a scripts/test-*.mjs file is in neither list of scripts/test-lanes.json,
// is in both, or is named there but missing on disk. Prints the names and exits 1.
// Usage: node scripts/check-test-lanes.mjs [scriptsDir] (the folder defaults to this one)
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
export function checkLanes(dir) {
const lanes = JSON.parse(fs.readFileSync(path.join(dir, "test-lanes.json"), "utf8"));
const fast = lanes.fast || [];
const skip = lanes.skipFast || [];
const onDisk = fs.readdirSync(dir).filter((f) => /^test-.*\.mjs$/.test(f));
const listed = new Set([...fast, ...skip]);
const all = [...fast, ...skip];
return {
duplicates: [...new Set(all.filter((f, i) => all.indexOf(f) !== i && !(fast.includes(f) && skip.includes(f))))].sort(),
unlisted: onDisk.filter((f) => !listed.has(f)).sort(),
both: fast.filter((f) => skip.includes(f)).sort(),
missing: [...listed].filter((f) => !onDisk.includes(f)).sort(),
};
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const dir = process.argv[2] ? path.resolve(process.argv[2]) : path.dirname(fileURLToPath(import.meta.url));
const { unlisted, both, missing, duplicates } = checkLanes(dir);
const out = [];
if (unlisted.length) out.push(`In neither list of test-lanes.json (add each to fast or skipFast): ${unlisted.join(", ")}`);
if (both.length) out.push(`In both lists: ${both.join(", ")}`);
if (duplicates.length) out.push(`Listed twice in one list: ${duplicates.join(", ")}`);
if (missing.length) out.push(`Named in test-lanes.json but not on disk: ${missing.join(", ")}`);
if (out.length) {
console.error(out.join("\n"));
process.exit(1);
}
console.log("test-lanes.json lists every scripts/test-*.mjs once.");
}
+138
View File
@@ -0,0 +1,138 @@
// Writes one version into every file that carries it, so a release never leaves one behind:
// version.json (and its releaseDate), the root package.json, README's "Version X.Y.Z" line, and
// under plan2code-app/: package.json, package-lock.json (two lines), src-tauri/tauri.conf.json,
// src-tauri/Cargo.toml, fake-agent/Cargo.toml and Cargo.lock (the plan2code-app and fake-agent
// entries). It never touches CHANGELOG.md: write its heading by hand, then run this.
// `check-versions.mjs` is the reader of the same places and stays the judge.
//
// node scripts/set-version.mjs <x.y.z> [--date YYYY-MM-DD] [--root <dir>]
//
// The release date defaults to today (local time). Every carrier is read and checked before any is
// written, so a file that has no version leaves the tree as it was. Exit 0 when written, 1 when a
// carrier could not be edited, 2 for bad arguments.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const SEMVER = /^\d+\.\d+\.\d+$/;
const DATE = /^\d{4}-\d{2}-\d{2}$/;
const validDate = (d) => {
if (!DATE.test(d)) return false;
const at = new Date(`${d}T00:00:00Z`);
return !Number.isNaN(at.getTime()) && at.toISOString().slice(0, 10) === d;
};
// Replace the first match of `pattern` (its first group is kept, then the new value, then its
// last group). A text edit, never a JSON round trip, so each file's formatting stays as it was.
function swap(text, pattern, value, what) {
if (!pattern.test(text)) throw new Error(`no ${what} found`);
return text.replace(pattern, (_, before, _old, after = "") => `${before}${value}${after}`);
}
const JSON_VERSION = /^(\s*"version"\s*:\s*")([^"]*)(")/m;
const CARGO_VERSION = /^(\s*version\s*=\s*")([^"]*)(")/m;
// A JSON file's top-level version, checked by parsing the result.
function jsonVersion(text, version, what) {
const out = swap(text, JSON_VERSION, version, `${what} "version"`);
if (JSON.parse(out).version !== version) throw new Error(`the first "version" in ${what} is not the top-level one`);
return out;
}
const lockEntry = (name) => new RegExp(`(^name = "${name}"\\r?\\nversion = ")([^"]*)(")`, "m");
/** Each carrier: its path under the root and how to rewrite its text. */
const CARRIERS = [
{ file: "version.json", edit: (t, v, d) => swap(jsonVersion(t, v, "version.json"), /^(\s*"releaseDate"\s*:\s*")([^"]*)(")/m, d, "releaseDate") },
{ file: "package.json", edit: (t, v) => jsonVersion(t, v, "package.json") },
{ file: "README.md", edit: (t, v) => swap(t, /^(Version )(\d+\.\d+\.\d+)(\b)/m, v, '"Version X.Y.Z" line') },
{ file: "plan2code-app/package.json", edit: (t, v) => jsonVersion(t, v, "package.json") },
{ file: "plan2code-app/src-tauri/tauri.conf.json", edit: (t, v) => jsonVersion(t, v, "tauri.conf.json") },
{
file: "plan2code-app/package-lock.json",
edit: (t, v) => {
// The top-level version, then the one inside packages[""].
let out = jsonVersion(t, v, "package-lock.json");
const at = out.indexOf('"packages"');
if (at < 0) throw new Error('no "packages" block found');
const head = out.slice(0, at);
const tail = swap(out.slice(at), JSON_VERSION, v, 'packages[""] "version"');
out = head + tail;
if (JSON.parse(out).packages?.[""]?.version !== v) throw new Error('packages[""].version was not updated');
return out;
},
},
{ file: "plan2code-app/src-tauri/Cargo.toml", edit: (t, v) => swap(t, CARGO_VERSION, v, "version line") },
{ file: "plan2code-app/fake-agent/Cargo.toml", edit: (t, v) => swap(t, CARGO_VERSION, v, "version line") },
{
file: "plan2code-app/Cargo.lock",
edit: (t, v) => swap(swap(t, lockEntry("plan2code-app"), v, "plan2code-app entry"), lockEntry("fake-agent"), v, "fake-agent entry"),
},
];
function today() {
const d = new Date();
const pad = (n) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}
/**
* Write `version` into every carrier under `root`. Returns `{ ok, written: [file], problems: [string] }`;
* nothing is written unless every carrier edits cleanly.
*/
export function setVersion(root, version, date = today()) {
const problems = [];
const staged = [];
for (const { file, edit } of CARRIERS) {
const full = path.join(root, file);
try {
const before = fs.readFileSync(full, "utf8");
staged.push({ file, full, before, after: edit(before, version, date) });
} catch (error) {
problems.push(`${file}: ${error.code === "ENOENT" ? "file is missing" : error.message}`);
}
}
if (problems.length) return { ok: false, written: [], problems };
const written = [];
try {
for (const { file, full, before, after } of staged) {
if (after !== before) fs.writeFileSync(full, after);
written.push(file);
}
} catch (error) {
// A write failed part way (permissions, a locked file): put back what was already written.
for (const { file, full, before } of staged) if (written.includes(file)) fs.writeFileSync(full, before);
return { ok: false, written: [], problems: [`write failed (${error.code || error.message}); restored the files already written`] };
}
return { ok: true, written, problems };
}
export const CARRIER_FILES = CARRIERS.map((c) => c.file);
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const args = process.argv.slice(2);
const take = (flag) => {
const at = args.indexOf(flag);
if (at < 0) return undefined;
const [, value] = args.splice(at, 2);
return value ?? "";
};
const date = take("--date");
const rootArg = take("--root");
const [version, ...extra] = args;
const usage = "Usage: node scripts/set-version.mjs <x.y.z> [--date YYYY-MM-DD] [--root <dir>]";
if (!version || extra.length || !SEMVER.test(version) || (date !== undefined && !validDate(date)) || rootArg === "") {
console.error(usage);
process.exit(2);
}
const { ok, written, problems } = setVersion(rootArg ? path.resolve(rootArg) : ROOT, version, date);
if (!ok) {
for (const problem of problems) console.error(`CANNOT SET: ${problem}`);
console.error("Nothing was written.");
process.exit(1);
}
for (const file of written) console.log(`${version.padEnd(10)} ${file}`);
console.log(`Wrote ${version} to ${written.length} files. CHANGELOG.md is yours to edit; then run: node scripts/check-versions.mjs`);
}
+77
View File
@@ -0,0 +1,77 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { check, normalize, workflowOf } from "./check-console-openings.mjs";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const SRC = path.join(path.dirname(HERE), "src");
// A copy of the real prompts and notes names, small enough to edit per test.
function copySrc() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-openings-"));
for (const f of fs.readdirSync(SRC)) if (/^plan2code.*\.md$/.test(f)) fs.copyFileSync(path.join(SRC, f), path.join(dir, f));
fs.mkdirSync(path.join(dir, "web-console", "notes"), { recursive: true });
for (const f of fs.readdirSync(path.join(SRC, "web-console", "notes"))) fs.writeFileSync(path.join(dir, "web-console", "notes", f), "");
return dir;
}
function edit(dir, file, from, to) {
const p = path.join(dir, file);
const t = fs.readFileSync(p, "utf8");
assert.ok(t.includes(from), `fixture text missing in ${file}: ${from}`);
fs.writeFileSync(p, t.replace(from, to));
}
test("the real prompts pass", () => {
assert.deepEqual(check(SRC), []);
});
test("a drifted shared sentence is named with its skill", () => {
const dir = copySrc();
edit(dir, "plan2code-review.md", "Switchable anytime.", "You can switch whenever.");
const problems = check(dir);
assert.equal(problems.length, 1);
assert.match(problems[0], /plan2code-review\.md: shared sentence "switch"/);
});
test("punctuation and case alone do not count as drift", () => {
const dir = copySrc();
edit(dir, "plan2code-test.md", "Switchable anytime.", "switchable anytime.");
edit(dir, "plan2code-test.md", "Its session is already open: resume it", "Its session is already open \u2014 resume it");
assert.deepEqual(check(dir), []);
});
test("a wrong workflow name or a missing notes file is reported", () => {
const dir = copySrc();
edit(dir, "plan2code-xray.md", "--workflow xray", "--workflow diagnose");
edit(dir, "plan2code-changelog.md", "<D>/notes/changelog.md", "<D>/notes/nope.md");
const problems = check(dir).join("\n");
assert.match(problems, /plan2code-xray\.md.*shared sentence "run"/);
assert.match(problems, /plan2code-xray\.md: opens --workflow diagnose instead of xray/);
assert.match(problems, /plan2code-changelog\.md: notes file nope\.md is not in src\/web-console\/notes/);
});
test("a skill that loses its opening is caught by the count", () => {
const dir = copySrc();
fs.rmSync(path.join(dir, "plan2code-pr-prep.md"));
assert.match(check(dir).join("\n"), /expected 18 skills with a console opening, found 17/);
});
test("helpers", () => {
assert.equal(normalize("A \u2014 B: (C), D"), "a b c d");
assert.equal(workflowOf("plan2code-1b-revise-plan"), "revise-plan");
assert.equal(workflowOf("plan2code-3-implement-review"), "implement-review");
assert.equal(workflowOf("plan2code-pr-prep"), "pr-prep");
});
test("the CLI exits 1 on drift", () => {
const dir = copySrc();
edit(dir, "plan2code-git.md", "Switchable anytime.", "Whenever.");
const r = spawnSync(process.execPath, [path.join(HERE, "check-console-openings.mjs"), dir], { encoding: "utf8" });
assert.equal(r.status, 1);
assert.match(r.stderr, /plan2code-git\.md/);
});
+54
View File
@@ -0,0 +1,54 @@
import { test, after } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { oversize, DEFAULT_LIMIT } from "./check-doc-size.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
const script = path.join(here, "check-doc-size.mjs");
const made = [];
after(() => {
for (const d of made) fs.rmSync(d, { recursive: true, force: true });
});
function fixture(sizes) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "docsize-"));
made.push(dir);
for (const [name, n] of Object.entries(sizes)) fs.writeFileSync(path.join(dir, name), "x".repeat(n));
return dir;
}
const run = (...args) => spawnSync(process.execPath, [script, ...args], { encoding: "utf8" });
test("files within the limit pass, and a file exactly at it passes", () => {
const dir = fixture({ "a.md": 10, "b.md": 100 });
const r = run(dir, "100");
assert.equal(r.status, 0, r.stderr);
});
test("a file over the limit fails and is named with its size", () => {
const dir = fixture({ "a.md": 10, "big.md": 101 });
const r = run(dir, "100");
assert.equal(r.status, 1);
assert.match(r.stderr, /big\.md: 101 bytes/);
assert.doesNotMatch(r.stderr, /a\.md/);
});
test("only .md files count", () => {
const dir = fixture({ "a.md": 10, "notes.txt": 5000 });
assert.deepEqual(oversize(dir, 100), []);
});
test("a bad limit is refused", () => {
const dir = fixture({ "a.md": 1 });
assert.equal(run(dir, "nope").status, 2);
});
test("every file in .agents-docs/ is within the default limit", () => {
const r = run();
assert.equal(r.status, 0, r.stderr);
assert.equal(DEFAULT_LIMIT, 60000);
});
+51
View File
@@ -0,0 +1,51 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { BANNED, findBanned } from "./check-prompt-wording.mjs";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.dirname(HERE);
function fixture(files) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-wording-"));
for (const [name, text] of Object.entries(files)) {
const full = path.join(dir, name);
fs.mkdirSync(path.dirname(full), { recursive: true });
fs.writeFileSync(full, text);
}
return dir;
}
test("a clean tree has no hits", () => {
const dir = fixture({ "a/SKILL.md": "Ask with the question tool. Run `glob` or grep in a shell.\n" });
assert.deepEqual(findBanned(dir), []);
});
test("every banned name is found, with its file and line", () => {
for (const name of BANNED) {
const dir = fixture({ "x/references/r.md": `fine\nuse ${name} here\n` });
assert.deepEqual(findBanned(dir), [{ file: "x/references/r.md", line: 2, name }], name);
}
});
test("a longer word that contains a banned name is not a hit", () => {
const dir = fixture({ "a.md": "Globals and Grepping and AskUserQuestionnaire\n" });
assert.deepEqual(findBanned(dir), []);
});
test("the CLI exits 1 on a hit and 0 on a clean tree", () => {
const bad = fixture({ "a.md": "never use Glob\n" });
const r = spawnSync(process.execPath, [path.join(HERE, "check-prompt-wording.mjs"), bad], { encoding: "utf8" });
assert.equal(r.status, 1);
assert.match(r.stderr, /a\.md:1 names a product tool: Glob/);
const ok = fixture({ "a.md": "list the folder\n" });
assert.equal(spawnSync(process.execPath, [path.join(HERE, "check-prompt-wording.mjs"), ok]).status, 0);
});
test("the built skills tree names no product tool", { skip: !fs.existsSync(path.join(ROOT, "skills")) }, () => {
assert.deepEqual(findBanned(path.join(ROOT, "skills")), []);
});
+57
View File
@@ -0,0 +1,57 @@
import { test, after } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
const script = path.join(path.dirname(fileURLToPath(import.meta.url)), "check-test-lanes.mjs");
const made = [];
after(() => {
for (const d of made) fs.rmSync(d, { recursive: true, force: true });
});
function fixture(files, lanes) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "lanes-"));
made.push(dir);
for (const f of files) fs.writeFileSync(path.join(dir, f), "");
fs.writeFileSync(path.join(dir, "test-lanes.json"), JSON.stringify(lanes));
return dir;
}
const run = (dir) => spawnSync(process.execPath, [script, dir], { encoding: "utf8" });
test("a complete fixture passes", () => {
const dir = fixture(["test-a.mjs", "test-b.mjs"], { fast: ["test-a.mjs"], skipFast: ["test-b.mjs"] });
const r = run(dir);
assert.equal(r.status, 0, r.stderr);
});
test("an unlisted file fails and is named", () => {
const dir = fixture(["test-a.mjs", "test-b.mjs"], { fast: ["test-a.mjs"], skipFast: [] });
const r = run(dir);
assert.equal(r.status, 1);
assert.match(r.stderr, /test-b\.mjs/);
});
test("a doubly listed file fails and is named", () => {
const dir = fixture(["test-a.mjs"], { fast: ["test-a.mjs"], skipFast: ["test-a.mjs"] });
const r = run(dir);
assert.equal(r.status, 1);
assert.match(r.stderr, /In both lists: test-a\.mjs/);
});
test("a dangling name fails and is named", () => {
const dir = fixture(["test-a.mjs"], { fast: ["test-a.mjs"], skipFast: ["test-gone.mjs"] });
const r = run(dir);
assert.equal(r.status, 1);
assert.match(r.stderr, /not on disk: test-gone\.mjs/);
});
test("a name repeated inside one list fails and is named", () => {
const dir = fixture(["test-a.mjs"], { fast: ["test-a.mjs", "test-a.mjs"], skipFast: [] });
const r = run(dir);
assert.equal(r.status, 1);
assert.match(r.stderr, /Listed twice in one list: test-a.mjs/);
});
+187
View File
@@ -0,0 +1,187 @@
// Tests for the shared console: each skill's forwarding stub (src/web-console-stub/console.mjs)
// and what the build leaves in skills/.
// Run with: node --test scripts/test-console-stub.mjs
//
// The stubs run from the built skills/ tree against a scratch PLAN2CODE_CONSOLE_HOME holding a
// fake shared copy, so nothing here starts a console server or touches ~/.plan2code.
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { createRequire } from "node:module";
import { spawnSync } from "node:child_process";
import { pathToFileURL } from "node:url";
import { ROOT, SKILLS } from "./skill-script-helpers.mjs";
const require = createRequire(import.meta.url);
const HOME = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-console-stub-"));
process.env.HOME = HOME;
process.env.USERPROFILE = HOME;
const { SOURCE_PROMPTS, generateSkillName, CONSOLE_SHARED_DIR } = require(path.join(ROOT, "install.js"));
test.after(() => fs.rmSync(HOME, { recursive: true, force: true }));
const VERSION = JSON.parse(fs.readFileSync(path.join(ROOT, "version.json"), "utf8")).version;
const MESSAGE = "The Plan2Code console is missing or out of date. Run: plan2code update";
const consoleSkills = SOURCE_PROMPTS.filter((p) => (p.additionalReferences || []).some((r) => r.source === "web-console")).map(
(p) => ({ name: generateSkillName(p), target: p.additionalReferences.find((r) => r.source === "web-console").target })
);
// A stand-in shared console: prints the arguments it was given and the exit code asked for.
function fakeConsole({ version = VERSION, pointer = true, entry = true } = {}) {
const home = fs.mkdtempSync(path.join(HOME, "home-"));
const dir = path.join(home, version);
fs.mkdirSync(dir, { recursive: true });
if (entry) {
fs.writeFileSync(
path.join(dir, "console.mjs"),
'console.log(JSON.stringify({ args: process.argv.slice(2), home: process.env.PLAN2CODE_CONSOLE_HOME }));\nprocess.exitCode = Number(process.env.FAKE_EXIT || 0);\n'
);
}
fs.writeFileSync(path.join(dir, "version.txt"), version + "\n");
if (pointer) fs.writeFileSync(path.join(home, "console-dir"), dir + "\n");
return { home, dir };
}
function runStub(skill, home, args = [], env = {}) {
const stub = path.join(SKILLS, skill.name, "references", skill.target, "console.mjs");
return spawnSync(process.execPath, [stub, ...args], {
encoding: "utf8",
env: { ...process.env, PLAN2CODE_CONSOLE_HOME: home, ...env },
});
}
test("every skill that lists the console carries a stub", () => {
assert.ok(consoleSkills.length >= 19, `expected the 19 skills, found ${consoleSkills.length}`);
for (const skill of consoleSkills) {
const stub = path.join(SKILLS, skill.name, "references", skill.target, "console.mjs");
assert.ok(fs.existsSync(stub), `${skill.name} has no stub`);
const text = fs.readFileSync(stub, "utf8");
assert.ok(text.includes(`const VERSION = "${VERSION}";`), `${skill.name}: the version is not baked in`);
assert.ok(!text.includes("__PLAN2CODE_VERSION__"), `${skill.name}: the version token is left in`);
}
});
test("every stub forwards its arguments and exit code to the shared copy", () => {
const { home } = fakeConsole();
for (const skill of consoleSkills) {
const args = ["open", "--workflow", skill.name, "--spec", "specs/x y"];
const ok = runStub(skill, home, args);
assert.equal(ok.status, 0, `${skill.name}: ${ok.stderr}`);
assert.deepEqual(JSON.parse(ok.stdout).args, args, `${skill.name}: arguments`);
const coded = runStub(skill, home, ["wait"], { FAKE_EXIT: "30" });
assert.equal(coded.status, 30, `${skill.name}: the shared copy's exit code`);
assert.equal(coded.stderr, "", `${skill.name}: nothing is added on stderr`);
}
});
test("a missing or stale shared copy prints the one plain line and exits 5, naming no path", () => {
const cases = {
"no console-dir at all": () => fs.mkdtempSync(path.join(HOME, "empty-")),
"a pointer to a folder that is gone": () => {
const { home, dir } = fakeConsole();
fs.rmSync(dir, { recursive: true, force: true });
return home;
},
"a pointer to a source checkout with no version.txt": () => {
const home = fs.mkdtempSync(path.join(HOME, "source-pointer-"));
const source = fs.mkdtempSync(path.join(HOME, "source-"));
fs.writeFileSync(path.join(source, "console.mjs"), "");
fs.writeFileSync(path.join(home, "console-dir"), `${source}\n`);
return home;
},
"a copy of another version": () => fakeConsole({ version: "0.0.1" }).home,
"a copy with no console.mjs": () => fakeConsole({ entry: false }).home,
"an empty pointer": () => {
const home = fs.mkdtempSync(path.join(HOME, "empty-pointer-"));
fs.writeFileSync(path.join(home, "console-dir"), "\n");
return home;
},
};
for (const [what, make] of Object.entries(cases)) {
const home = make();
for (const skill of consoleSkills) {
const r = runStub(skill, home, ["open"]);
assert.equal(r.status, 5, `${what} (${skill.name}): exit code`);
assert.equal(r.stdout, "", `${what} (${skill.name}): stdout`);
assert.equal(r.stderr, MESSAGE + "\n", `${what} (${skill.name}): the line`);
assert.ok(!r.stderr.includes(home) && !/[\\/]/.test(r.stderr), `${what} (${skill.name}): names no path`);
}
}
});
test("a stub finds its own version folder even when console-dir names a console that is not this version", () => {
const { home } = fakeConsole({ pointer: false });
const elsewhere = fs.mkdtempSync(path.join(HOME, "elsewhere-"));
fs.writeFileSync(path.join(home, "console-dir"), `${elsewhere}\n`);
const res = runStub(consoleSkills[0], home, ["status"]);
assert.equal(res.status, 0, res.stderr);
assert.deepEqual(JSON.parse(res.stdout).args, ["status"]);
});
test("a stub finds the copy through console-dir under PLAN2CODE_CONSOLE_HOME and passes the home on", () => {
const { home } = fakeConsole();
const skill = consoleSkills[0];
const r = runStub(skill, home, ["status"], { PLAN2CODE_CONSOLE_HOME: home });
assert.equal(r.status, 0, r.stderr);
assert.equal(JSON.parse(r.stdout).home, home);
});
test("no built skill holds the large console files; the shared copy keeps every game, sound and vendor file", () => {
const forbidden = new Set(["public", "activities", "vendor"]);
const found = [];
const walk = (dir, rel) => {
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
const next = path.join(rel, e.name);
if (e.isDirectory()) {
if (forbidden.has(e.name)) found.push(next);
walk(path.join(dir, e.name), next);
} else if (/\.(mp3|png|svg)$/.test(e.name) || /^(server|routes|files|sessions)\.mjs$/.test(e.name)) found.push(next);
}
};
for (const entry of fs.readdirSync(SKILLS, { withFileTypes: true })) {
if (!entry.isDirectory() || entry.name === CONSOLE_SHARED_DIR) continue;
walk(path.join(SKILLS, entry.name), entry.name);
}
assert.deepEqual(found, [], "console files left inside a skill");
const shared = path.join(SKILLS, CONSOLE_SHARED_DIR, VERSION);
assert.equal(fs.readFileSync(path.join(shared, "version.txt"), "utf8").trim(), VERSION);
const src = path.join(ROOT, "src", "web-console");
const sourceFiles = [];
const collect = (dir, rel) => {
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
const next = rel ? `${rel}/${e.name}` : e.name;
if (e.isDirectory()) collect(path.join(dir, e.name), next);
else sourceFiles.push(next);
}
};
collect(src, "");
for (const rel of sourceFiles) {
const built = path.join(shared, ...rel.split("/"));
assert.ok(fs.existsSync(built), `the shared console lacks ${rel}`);
assert.ok(fs.readFileSync(built).equals(fs.readFileSync(path.join(src, ...rel.split("/")))), `${rel} differs from src/`);
}
assert.ok(fs.existsSync(path.join(shared, "public", "vendor", "codemirror.esm.js")), "codemirror ships");
assert.ok(fs.readdirSync(path.join(shared, "public")).filter((f) => f.endsWith(".mp3")).length >= 3, "every sound ships");
});
test("the shared copy ships a module for every game listed in public/activities.js", async () => {
const { ACTIVITIES } = await import(pathToFileURL(path.join(ROOT, "src", "web-console", "public", "activities.js")).href);
assert.ok(ACTIVITIES.length >= 13, `expected the thirteen games, found ${ACTIVITIES.length}`);
const shared = path.join(SKILLS, CONSOLE_SHARED_DIR, VERSION, "public");
for (const game of ACTIVITIES) {
assert.ok(fs.existsSync(path.join(shared, ...game.module.split("/").filter(Boolean))), `${game.id}: ${game.module} is not in the shared console`);
}
});
test("a skill keeps the markdown the agent reads by path, and notes/", () => {
for (const skill of consoleSkills) {
const dir = path.join(SKILLS, skill.name, "references", skill.target);
for (const file of ["console.md", "building.md", "console-finish.md"]) assert.ok(fs.existsSync(path.join(dir, file)), `${skill.name}: ${file}`);
assert.ok(fs.existsSync(path.join(dir, "notes", "implement.md")), `${skill.name}: notes/implement.md`);
}
});
+15
View File
@@ -0,0 +1,15 @@
// Runs the fast test lane: the files listed under `fast` in scripts/test-lanes.json,
// through node-test.mjs so its cap of one file per spare core applies.
// Usage: node scripts/test-fast.mjs (or: npm run test:fast)
import { spawnSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const here = path.dirname(fileURLToPath(import.meta.url));
const lanes = JSON.parse(fs.readFileSync(path.join(here, "test-lanes.json"), "utf8"));
const files = lanes.fast.map((name) => path.join(here, name));
const r = spawnSync(process.execPath, [path.join(here, "node-test.mjs"), ...files], { cwd: process.cwd(), stdio: "inherit" });
process.exit(r.status ?? 1);
+36
View File
@@ -12,7 +12,9 @@ import path from "node:path";
import { execFileSync } from "node:child_process";
import { tmp, write, gitInit, gitIn, copyFixture, slashed, fixtureCleanup } from "./skill-script-helpers.mjs";
import {
GIT_TIMEOUT_MS,
countPending,
git,
gitFloor,
parseRemoteUrl,
parseStatusV2,
@@ -409,3 +411,37 @@ test("snapshot: a 300-branch repo reads in under 5 seconds", () => {
assert.equal(s.branches.length, 301);
assert.ok(took < 5000, `took ${took} ms`);
});
// A git that never returns (a stuck credential helper, hook or network drive)
// used to hold the console server's only thread for good. The alias stands in
// for one: real git, running a command that just sleeps.
test("git() gives up on a hanging git: 10 seconds by default, or the caller's limit", () => {
const repo = tmp("git-hang");
const hang = (ms) => ["-c", `alias.hang=!node -e "setTimeout(() => {}, ${ms})"`, "hang"];
assert.equal(GIT_TIMEOUT_MS, 10000);
let t = Date.now();
const quick = git(hang(30000), repo, { timeout: 500 });
assert.equal(quick.ok, false);
assert.match(quick.err, /did not finish within 0\.5s/);
assert.ok(Date.now() - t < 8000, "the caller's limit applies");
t = Date.now();
const byDefault = git(hang(14000), repo);
const took = Date.now() - t;
assert.equal(byDefault.ok, false);
assert.match(byDefault.err, /did not finish within 10s/);
assert.ok(took >= 9000 && took < 13500, `the default limit applies (took ${took}ms)`);
});
// A repository whose status fails (here a corrupt index; a status past git()'s
// time limit fails the same way) has an unknown tree: snapshot says so
// instead of drawing an empty, clean-looking board.
test("snapshot reports an error, not a clean tree, when git status fails in a repository", () => {
const { repo } = repoWithCommit("status-fails");
fs.writeFileSync(path.join(repo, ".git", "index"), "not an index");
const snap = snapshot(repo);
assert.equal(snap.repo, true);
assert.ok(snap.error, "the failure is reported");
assert.equal(snap.changes, undefined, "no change list is drawn from an empty status");
});
+105
View File
@@ -500,3 +500,108 @@ test("app declined: the no is remembered next to the pieces, and needs a record
installer.recordInstalled("launcher");
assert.deepEqual(installer.readInstallRecord().skipped, ["app"], "other writes keep the decline");
});
test("shared console install: the new version is placed, old versions go, and every other entry is left byte-identical", () => {
const SHARED = path.join(ROOT, "skills", installer.CONSOLE_SHARED_DIR, VERSION, "console.mjs");
if (!fs.existsSync(SHARED)) spawnSync(process.execPath, [INSTALL, "--build-skills"], { stdio: "ignore" });
const home = installer.consoleHomeDir();
assert.equal(home, path.join(HOME, ".plan2code", "console"), "the default home is under the temp HOME");
fs.rmSync(home, { recursive: true, force: true });
const put = (rel, body) => {
const p = path.join(home, ...rel.split("/"));
fs.mkdirSync(path.dirname(p), { recursive: true });
fs.writeFileSync(p, body);
return p;
};
put("2.9.9/console.mjs", "old");
put("2.9.9/public/core.js", "old");
put("10.0.0/console.mjs", "an older or newer version folder goes too");
put(`${VERSION}/stale.txt`, "a leftover inside the folder being replaced");
const kept = {
"sessions/20261108-101010-aaaaaa/state.json": '{"a":1}',
"sessions/20261108-101010-aaaaaa/shots/x.png": "png",
"looks.json": '{"theme":"dark"}',
"workspaces.json": "{}",
"subagents.json": "[]",
"runtime/x.json": "{}",
"notes.txt": "not ours",
"3.0/keep.txt": "not a version folder",
};
for (const [rel, body] of Object.entries(kept)) put(rel, body);
const lines = [];
const log = console.log;
console.log = (...a) => lines.push(a.join(" "));
let ok;
try {
ok = installer.installSharedConsole({ quiet: false });
} finally {
console.log = log;
}
assert.equal(ok, true);
assert.equal(fs.existsSync(path.join(home, "2.9.9")), false, "an old version folder is gone");
assert.equal(fs.existsSync(path.join(home, "10.0.0")), false, "every other version folder is gone");
assert.ok(fs.existsSync(path.join(home, VERSION, "console.mjs")), "the new version is present");
assert.equal(fs.readFileSync(path.join(home, VERSION, "version.txt"), "utf8").trim(), VERSION);
assert.equal(fs.existsSync(path.join(home, VERSION, "stale.txt")), false, "the folder is replaced, not merged");
assert.equal(fs.readFileSync(path.join(home, "console-dir"), "utf8").trim(), path.join(home, VERSION));
for (const [rel, body] of Object.entries(kept)) {
assert.equal(fs.readFileSync(path.join(home, ...rel.split("/")), "utf8"), body, rel + " is untouched");
}
assert.ok(lines.some((line) => line.includes("Removed old console 2.9.9")), lines.join("\n"));
// A second run changes nothing it should not.
assert.equal(installer.installSharedConsole({ quiet: true }), true);
assert.equal(fs.readFileSync(path.join(home, "looks.json"), "utf8"), kept["looks.json"]);
assert.ok(fs.existsSync(path.join(home, VERSION, "console.mjs")));
});
test("shared console install: sweep false keeps old versions until sweepOldConsoles runs", () => {
const SHARED = path.join(ROOT, "skills", installer.CONSOLE_SHARED_DIR, VERSION, "console.mjs");
if (!fs.existsSync(SHARED)) spawnSync(process.execPath, [INSTALL, "--build-skills"], { stdio: "ignore" });
const home = installer.consoleHomeDir();
fs.rmSync(home, { recursive: true, force: true });
fs.mkdirSync(path.join(home, "2.9.9"), { recursive: true });
fs.writeFileSync(path.join(home, "2.9.9", "console.mjs"), "old");
fs.writeFileSync(path.join(home, "2.9.9", "version.txt"), "2.9.9\n");
assert.equal(installer.installSharedConsole({ quiet: true, sweep: false }), true);
assert.ok(fs.existsSync(path.join(home, "2.9.9", "console.mjs")), "a failed skills add leaves the old version for the old stubs");
assert.ok(fs.existsSync(path.join(home, VERSION, "console.mjs")), "the new version is placed");
installer.sweepOldConsoles({ quiet: true });
assert.equal(fs.existsSync(path.join(home, "2.9.9")), false, "swept once skills add worked");
assert.ok(fs.existsSync(path.join(home, VERSION, "console.mjs")), "the current version stays");
});
test("shared console install: a missing build fails plainly and removes nothing", () => {
const home = installer.consoleHomeDir();
fs.mkdirSync(home, { recursive: true });
fs.writeFileSync(path.join(home, "looks.json"), "{}");
const errors = [];
const error = console.error;
console.error = (...a) => errors.push(a.join(" "));
try {
// An empty folder stands in for a build that did not happen; the real build is never touched.
const empty = fs.mkdtempSync(path.join(HOME, "no-build-"));
assert.equal(installer.installSharedConsole({ quiet: true, source: empty }), false);
} finally {
console.error = error;
}
assert.ok(errors.join("\n").includes("Could not install the shared console"));
assert.ok(fs.existsSync(path.join(home, "looks.json")), "what was there stays");
});
test("the skills CLI is pinned to one exact version, and every doc line that runs it names that version", () => {
const source = fs.readFileSync(INSTALL, "utf8");
const pinned = source.match(/const SKILLS_CLI_VERSION = '(\d+\.\d+\.\d+)';/);
assert.ok(pinned, "install.js pins SKILLS_CLI_VERSION to an exact x.y.z");
assert.ok(source.includes("npx --yes skills@${SKILLS_CLI_VERSION}"), "SKILLS_CLI runs the pinned version");
assert.ok(!/npx (--yes )?skills( |')/.test(source), "no unpinned `npx skills` in install.js");
for (const doc of ["README.md", ".agents-docs/AGENTS-development-commands.md"]) {
const text = fs.readFileSync(path.join(ROOT, doc), "utf8");
assert.ok(!/npx (--yes )?skills (add|list|remove|--version)/.test(text), `${doc} has an unpinned \`npx skills\` command`);
for (const m of text.matchAll(/npx (?:--yes )?skills@(\d+\.\d+\.\d+)/g)) {
assert.equal(m[1], pinned[1], `${doc} names skills@${m[1]}, install.js pins ${pinned[1]}`);
}
}
});
+122
View File
@@ -0,0 +1,122 @@
{
"fast": [
"test-agent-lookup.mjs",
"test-agents-file.mjs",
"test-app-meter.mjs",
"test-browser-helper.mjs",
"test-check-console-openings.mjs",
"test-check-doc-size.mjs",
"test-check-prompt-wording.mjs",
"test-check-test-lanes.mjs",
"test-check-versions.mjs",
"test-getting-started.mjs",
"test-git-repo.mjs",
"test-install-update.mjs",
"test-line-endings.mjs",
"test-script-changelog.mjs",
"test-script-coverage.mjs",
"test-script-finalize.mjs",
"test-script-git.mjs",
"test-script-pathfinder.mjs",
"test-script-pr-prep.mjs",
"test-script-run-check.mjs",
"test-script-test-commands.mjs",
"test-script-test-map.mjs",
"test-script-test-match.mjs",
"test-script-xray.mjs",
"test-set-version.mjs",
"test-skill-scripts.mjs",
"test-skill-test-runs.mjs",
"test-us-english.mjs",
"test-web-console-agents-doc.mjs",
"test-web-console-git-board.mjs",
"test-web-console-send-state.mjs",
"test-web-console-shape.mjs",
"test-web-console-skills.mjs",
"test-web-console-spec-states.mjs",
"test-web-console-state.mjs",
"test-web-console-strengths.mjs",
"test-web-console-tones.mjs"
],
"skipFast": [
"test-console-stub.mjs",
"test-console-wire-budgets.mjs",
"test-fast.mjs",
"test-launcher.mjs",
"test-standalone-check.mjs",
"test-web-console-activities-bounce-cars.mjs",
"test-web-console-activities-bounce-game.mjs",
"test-web-console-activities-bounce.mjs",
"test-web-console-activities-flock.mjs",
"test-web-console-activities-ghoul-arms.mjs",
"test-web-console-activities-ghoul-banister.mjs",
"test-web-console-activities-ghoul-bog.mjs",
"test-web-console-activities-ghoul-bones.mjs",
"test-web-console-activities-ghoul-bonestair.mjs",
"test-web-console-activities-ghoul-bossintro.mjs",
"test-web-console-activities-ghoul-carnival.mjs",
"test-web-console-activities-ghoul-cart.mjs",
"test-web-console-activities-ghoul-chapel.mjs",
"test-web-console-activities-ghoul-dice.mjs",
"test-web-console-activities-ghoul-ending.mjs",
"test-web-console-activities-ghoul-eye.mjs",
"test-web-console-activities-ghoul-frozen.mjs",
"test-web-console-activities-ghoul-gameover.mjs",
"test-web-console-activities-ghoul-graveyard.mjs",
"test-web-console-activities-ghoul-grounds.mjs",
"test-web-console-activities-ghoul-gurney.mjs",
"test-web-console-activities-ghoul-hearse.mjs",
"test-web-console-activities-ghoul-heart.mjs",
"test-web-console-activities-ghoul-intro.mjs",
"test-web-console-activities-ghoul-lantern.mjs",
"test-web-console-activities-ghoul-marrow.mjs",
"test-web-console-activities-ghoul-mat.mjs",
"test-web-console-activities-ghoul-mine.mjs",
"test-web-console-activities-ghoul-mower.mjs",
"test-web-console-activities-ghoul-pew.mjs",
"test-web-console-activities-ghoul-retry.mjs",
"test-web-console-activities-ghoul-ride.mjs",
"test-web-console-activities-ghoul-sanatorium.mjs",
"test-web-console-activities-ghoul-sled.mjs",
"test-web-console-activities-ghoul-story.mjs",
"test-web-console-activities-ghoul-tray.mjs",
"test-web-console-activities-ghoul-village.mjs",
"test-web-console-activities-ghoul-wagon.mjs",
"test-web-console-activities-ghoul.mjs",
"test-web-console-activities-rapids.mjs",
"test-web-console-activities.mjs",
"test-web-console-chat-stress.mjs",
"test-web-console-chat.mjs",
"test-web-console-concurrency.mjs",
"test-web-console-embed.mjs",
"test-web-console-git.mjs",
"test-web-console-handoffs.mjs",
"test-web-console-hardening.mjs",
"test-web-console-in-app.mjs",
"test-web-console-lifecycle.mjs",
"test-web-console-logic.mjs",
"test-web-console-loop.mjs",
"test-web-console-notepad.mjs",
"test-web-console-page-activities.mjs",
"test-web-console-page-ask.mjs",
"test-web-console-page-cards.mjs",
"test-web-console-page-dashboard.mjs",
"test-web-console-page-git.mjs",
"test-web-console-page-help.mjs",
"test-web-console-page-loop.mjs",
"test-web-console-page-notepad.mjs",
"test-web-console-page-prefs.mjs",
"test-web-console-page-send.mjs",
"test-web-console-page-session.mjs",
"test-web-console-page-setup.mjs",
"test-web-console-page-workspace.mjs",
"test-web-console-pointers.mjs",
"test-web-console-qa.mjs",
"test-web-console-server.mjs",
"test-web-console-session.mjs",
"test-web-console-source.mjs",
"test-web-console-speed.mjs",
"test-web-console-subagents.mjs",
"test-web-console-workspace.mjs"
]
}
+68 -15
View File
@@ -140,7 +140,7 @@ function writeCache(box, latest, ageMs = 0) {
test("launcher: Claude Code gets the prompt first, then bypassPermissions and the forwarded args", (t) => {
const box = sandbox(["claude"]);
t.after(box.cleanup);
const result = box.run(["--verbose"]);
const result = box.run(["--bypass-permissions", "--verbose"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("claude"), ["/plan2code", "--permission-mode", "bypassPermissions", "--verbose"]);
assert.match(result.stdout, new RegExp(`Claude Code ${NOTICE}`));
@@ -149,7 +149,7 @@ test("launcher: Claude Code gets the prompt first, then bypassPermissions and th
test("launcher: Devin keeps its args ahead of the -- and the prompt", (t) => {
const box = sandbox(["devin"]);
t.after(box.cleanup);
const result = box.run(["--verbose"]);
const result = box.run(["--bypass-permissions", "--verbose"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("devin"), ["--permission-mode", "bypass", "--verbose", "--", "/plan2code"]);
});
@@ -157,7 +157,7 @@ test("launcher: Devin keeps its args ahead of the -- and the prompt", (t) => {
test("launcher: Codex gets the bypass flag, the forwarded args, then the $plan2code prompt", (t) => {
const box = sandbox(["codex"]);
t.after(box.cleanup);
const result = box.run(["--verbose"]);
const result = box.run(["--bypass-permissions", "--verbose"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("codex"), ["--dangerously-bypass-approvals-and-sandbox", "--verbose", "$plan2code"]);
});
@@ -177,6 +177,59 @@ test("launcher: --keep-permissions keeps every built-in's permission prompts, an
}
});
test("launcher: with no terminal and no flag every built-in keeps its permission prompts", (t) => {
const box = sandbox(["claude", "devin", "codex"]);
t.after(box.cleanup);
const expected = {
claude: ["/plan2code", "--verbose"],
devin: ["--verbose", "--", "/plan2code"],
codex: ["--verbose", "$plan2code"],
};
for (const [cli, args] of Object.entries(expected)) {
const result = box.run(["--cli", cli, "--verbose"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf(cli), args, cli);
assert.doesNotMatch(result.stdout, /off\?/, cli);
}
});
test("launcher: --bypass-permissions turns every built-in's prompts off with no terminal, and is never forwarded", (t) => {
const box = sandbox(["claude", "devin", "codex"]);
t.after(box.cleanup);
const expected = {
claude: ["/plan2code", "--permission-mode", "bypassPermissions", "--verbose"],
devin: ["--permission-mode", "bypass", "--verbose", "--", "/plan2code"],
codex: ["--dangerously-bypass-approvals-and-sandbox", "--verbose", "$plan2code"],
};
for (const [cli, args] of Object.entries(expected)) {
const result = box.run(["--cli", cli, "--bypass-permissions", "--verbose"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf(cli), args, cli);
}
// --keep-permissions wins when both are given.
assert.equal(box.run(["--cli", "claude", "--bypass-permissions", "--keep-permissions"]).status, 0);
assert.deepEqual(box.argsOf("claude"), ["/plan2code"]);
});
test("launcher: the keyboard question names what the flag drops, and Codex's names its sandbox", () => {
const { bypassQuestion } = require(LAUNCHER);
const claude = bypassQuestion({ id: "claude", label: "Claude Code", bypassArgs: ["--permission-mode", "bypassPermissions"] });
assert.equal(claude.heading, "Turn Claude Code's permission prompts off?");
assert.equal(claude.prompt, "Turn permission prompts off?");
assert.match(claude.detail, /without asking \(--permission-mode bypassPermissions\)/);
assert.doesNotMatch(claude.detail, /sandbox/);
assert.equal(claude.hint, "Type n to keep the permission prompts, or press Enter to turn them off.");
const codex = bypassQuestion({ id: "codex", label: "Codex", bypassArgs: ["--dangerously-bypass-approvals-and-sandbox"] });
assert.equal(codex.heading, "Turn Codex's approval prompts and its sandbox off?");
assert.equal(codex.prompt, "Turn approval prompts and its sandbox off?");
assert.match(codex.detail, /outside its sandbox \(--dangerously-bypass-approvals-and-sandbox\)/);
assert.equal(codex.hint, "Type n to keep the approval prompts and its sandbox, or press Enter to turn them off.");
// A custom agent gets the plain wording, with its own arguments.
const goose = bypassQuestion({ id: "goose", label: "Goose", bypassArgs: ["--bypass"] });
assert.equal(goose.heading, "Turn Goose's permission prompts off?");
assert.match(goose.detail, /\(--bypass\)/);
});
test("launcher: --cli codex picks Codex when it is installed beside another CLI", (t) => {
const box = sandbox(["claude", "codex"]);
t.after(box.cleanup);
@@ -200,7 +253,7 @@ test("launcher: Codex takes a forwarded --model ahead of the $plan2code prompt,
const result = box.run(["--cli", "codex", "--model", "x"]);
assert.equal(result.status, 0, result.stderr);
assert.doesNotMatch(result.stdout, new RegExp(NOTICE));
assert.deepEqual(box.argsOf("codex"), ["--dangerously-bypass-approvals-and-sandbox", "--model", "x", "$plan2code"]);
assert.deepEqual(box.argsOf("codex"), ["--model", "x", "$plan2code"]);
});
test("launcher: Codex's -m counts as a model already chosen", (t) => {
@@ -209,7 +262,7 @@ test("launcher: Codex's -m counts as a model already chosen", (t) => {
const result = box.run(["--cli", "codex", "-m", "x"]);
assert.equal(result.status, 0, result.stderr);
assert.doesNotMatch(result.stdout, new RegExp(NOTICE));
assert.deepEqual(box.argsOf("codex"), ["--dangerously-bypass-approvals-and-sandbox", "-m", "x", "$plan2code"]);
assert.deepEqual(box.argsOf("codex"), ["-m", "x", "$plan2code"]);
});
test("launcher: hasModelFlag reads -m as a model only for Codex", () => {
@@ -241,7 +294,7 @@ test("launcher: a forwarded --model skips the model notice", (t) => {
const result = box.run(args);
assert.equal(result.status, 0, result.stderr);
assert.doesNotMatch(result.stdout, new RegExp(NOTICE));
assert.deepEqual(box.argsOf("claude"), ["/plan2code", "--permission-mode", "bypassPermissions", ...args]);
assert.deepEqual(box.argsOf("claude"), ["/plan2code", ...args]);
}
});
@@ -270,7 +323,7 @@ test("launcher: --cli picks the CLI and is never forwarded; the pick is merged i
for (const args of [["--cli", "devin"], ["--cli=DEVIN"]]) {
const result = box.run(args);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("devin"), ["--permission-mode", "bypass", "--", "/plan2code"]);
assert.deepEqual(box.argsOf("devin"), ["--", "/plan2code"]);
}
assert.equal(box.argsOf("claude"), null);
assert.deepEqual(JSON.parse(fs.readFileSync(box.stateFile, "utf8")), { lastFolder: box.home, lastCli: "devin" });
@@ -393,7 +446,7 @@ test("launcher: a forwarded argument with a space and a cmd metacharacter arrive
t.after(box.cleanup);
const result = box.run(["--append-system-prompt", "a b&c"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("claude"), ["/plan2code", "--permission-mode", "bypassPermissions", "--append-system-prompt", "a b&c"]);
assert.deepEqual(box.argsOf("claude"), ["/plan2code", "--append-system-prompt", "a b&c"]);
});
test("launcher: the CLI's non-zero exit code is passed through", (t) => {
@@ -533,7 +586,7 @@ test("launcher: a piped run prints no escape codes, with or without NO_COLOR", (
// The desktop app hand-off. The stand-in app is found through PLAN2CODE_APP; "no display" is
// only something a Linux run can ask for, since Windows and macOS always count as having one.
const NO_DISPLAY = { DISPLAY: "", WAYLAND_DISPLAY: "" };
const CLASSIC_ARGS = ["/plan2code", "--permission-mode", "bypassPermissions"];
const CLASSIC_ARGS = ["/plan2code"];
test("launcher app: with no app installed the agent starts exactly as before", (t) => {
const box = sandbox(["claude"]);
@@ -759,13 +812,13 @@ test("launcher agents: --cli <custom id> starts it with args, the model through
const box = sandbox(["claude", "goose"]);
t.after(box.cleanup);
writeAgents(box, goose());
const result = box.run(["--cli", "goose", "--model", "m1", "--verbose"]);
const result = box.run(["--cli", "goose", "--bypass-permissions", "--model", "m1", "--verbose"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("goose"), ["--yes", "/plan2code", "--model", "m1", "--bypass", "--verbose"]);
assert.equal(box.argsOf("claude"), null);
assert.equal(JSON.parse(fs.readFileSync(box.stateFile, "utf8")).lastCli, "goose");
// No model chosen and no models flag: the model arguments are left out.
assert.equal(box.run(["--cli=goose"]).status, 0);
assert.equal(box.run(["--cli=goose", "--bypass-permissions"]).status, 0);
assert.deepEqual(box.argsOf("goose"), ["--yes", "/plan2code", "--bypass"]);
// --keep-permissions leaves bypassArgs out.
assert.equal(box.run(["--cli=goose", "--keep-permissions"]).status, 0);
@@ -903,7 +956,7 @@ const leadRun = (id) => builtin(id).install[OS_KEY][0].run;
test("launcher list: the menu and launch come from the sandboxed agents.json + agent-lookup.mjs", (t) => {
const box = sandbox(["claude", "devin", "codex"], { installed: "0.0.0" });
t.after(box.cleanup);
const result = box.run(["--cli", "devin", "--verbose"]);
const result = box.run(["--cli", "devin", "--bypass-permissions", "--verbose"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("devin"), ["--permission-mode", "bypass", "--verbose", "--", "/plan2code"]);
// The menu's order and shape come from the list: --cli errors list the same ids.
@@ -916,9 +969,9 @@ test("launcher list: a forwarded --model fills {model} in place; Codex's -m forw
const box = sandbox(["claude", "codex"], { installed: "0.0.0" });
t.after(box.cleanup);
assert.equal(box.run(["--cli", "claude", "--model", "opus"]).status, 0);
assert.deepEqual(box.argsOf("claude"), ["/plan2code", "--permission-mode", "bypassPermissions", "--model", "opus"]);
assert.deepEqual(box.argsOf("claude"), ["/plan2code", "--model", "opus"]);
assert.equal(box.run(["--cli", "codex", "-m", "x"]).status, 0);
assert.deepEqual(box.argsOf("codex"), ["--dangerously-bypass-approvals-and-sandbox", "-m", "x", "$plan2code"]);
assert.deepEqual(box.argsOf("codex"), ["-m", "x", "$plan2code"]);
});
test("launcher list: the last-used notice names the gone agent and the pick, on a terminal only", () => {
@@ -940,7 +993,7 @@ test("launcher list: a missing agent-lookup.mjs falls back to the built-in list"
t.after(box.cleanup);
const result = box.run([]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("claude"), ["/plan2code", "--permission-mode", "bypassPermissions"]);
assert.deepEqual(box.argsOf("claude"), ["/plan2code"]);
});
test("launcher list: with no agent and no terminal it prints this OS's install steps and exits 127", (t) => {
+26
View File
@@ -84,3 +84,29 @@ test("--hook fixes the file a Write or Edit names, and nothing outside the repo"
for (const input of ["", "not json", "{}"]) assert.equal(run(dir, ["--hook"], input).status, 0, `never fails the tool call (${JSON.stringify(input)})`);
});
test("the pre-commit hook refuses a staged file named nul, and .gitignore no longer hides one", async () => {
const { nulPaths } = await import("./check-staged-nul.mjs");
assert.deepEqual(nulPaths(["nul", "src/NUL", "docs/nul.txt", "null.md", "src/nullable.js", "annul", "a/b/Nul.log"]), ["nul", "src/NUL", "docs/nul.txt", "a/b/Nul.log"]);
assert.match(fs.readFileSync(path.join(HERE, "..", ".husky", "pre-commit"), "utf8"), /^node scripts\/check-staged-nul\.mjs$/m);
assert.ok(!/^nul$/m.test(fs.readFileSync(path.join(HERE, "..", ".gitignore"), "utf8")), "the check replaces the ignore line");
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-nul-"));
try {
const g = (...a) => execFileSync("git", ["-C", dir, ...a], { encoding: "utf8", stdio: "pipe" });
g("init", "-q");
fs.writeFileSync(path.join(dir, "ok.txt"), "ok\n");
g("add", "ok.txt");
const check = () => spawnSync(process.execPath, [path.join(HERE, "check-staged-nul.mjs")], { cwd: dir, encoding: "utf8" });
assert.equal(check().status, 0, "an ordinary file passes");
// Staged through the index, with no file on disk: Windows cannot create
// one, and git there refuses the path unless protectNTFS is off.
const blob = execFileSync("git", ["-C", dir, "hash-object", "-w", "--stdin"], { input: "", encoding: "utf8" }).trim();
g("-c", "core.protectNTFS=false", "update-index", "--add", "--cacheinfo", `100644,${blob},sub/nul.txt`);
const refused = check();
assert.equal(refused.status, 1);
assert.match(refused.stderr, /refusing to commit a file named nul.*sub\/nul\.txt/);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
+12
View File
@@ -1043,3 +1043,15 @@ test("the git prompt never instructs a forbidden command, stays under 20,000 cha
assert.ok(prompt.includes(name), `the prompt names ${name}`);
}
});
test("commit-msg has no add-everything option: --add-all is refused, and no prompt, reference or script names it", () => {
const r = runScript("plan2code-git", "commit-msg.mjs", ["--subject", "Fix", "--add-all"]);
assert.equal(r.code, 2, r.stdout);
assert.equal(r.json.error, "unknown-flag");
// Every source a skill ships (prompts, references, scripts and the console)
// and the desktop app, whose Loop runs the script too.
const walk = (dir) => fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(dir, e.name)) : /\.(md|mjs|js|rs)$/.test(e.name) ? [path.join(dir, e.name)] : []));
const sources = [...walk(path.join(ROOT, "src")), ...walk(path.join(ROOT, "plan2code-app", "src-tauri", "src"))];
const found = sources.filter((f) => !/[\\/]public[\\/]vendor[\\/]/.test(f) && fs.readFileSync(f, "utf8").includes("--add-all"));
assert.deepEqual(found.map((f) => path.relative(ROOT, f)), [], "--add-all is retired: stage the work's own files with --files");
});
+174 -16
View File
@@ -25,7 +25,7 @@ const MAP = `${B}
# Map: audit-export
*Decisions live in \`questions/\` — one file each. This file is just the index.*
*Decisions live in \`questions/\`, one file each. This file is just the index.*
**Status:** Working
**Updated:** 2026-08-01
@@ -43,7 +43,7 @@ A locked plan for exporting audit events.
<!-- Rebuilt from questions/ every session. -->
- [x] [Codebase context](./questions/00-codebase-context.md) — Node and Postgres; a long gist
- [x] [Codebase context](./questions/00-codebase-context.md): Node and Postgres; a long gist
that wraps onto a second line. *(2026-08-01)*
- [ ] [Export format](./questions/01-export-format.md)
- [ ] [Row-count
@@ -89,11 +89,11 @@ test("pathfinder reconcile: files win, dates backfill, stale claims reset, rows
assert.deepEqual(r.json.refire.map((x) => x.nn), ["02"], "research with no Research complete line is re-fired");
assert.equal(r.json.refire[0].partialEvidence, true);
const map = read(root, `${pf}/map.md`);
assert.match(map, /- \[x\] \[Codebase context\]\(\.\/questions\/00-codebase-context\.md\) — Node and Postgres; a long gist\n that wraps onto a second line\. \*\(2026-08-01\)\*/, "an unchanged row keeps its own wrapped text");
assert.match(map, /- \[x\] \[Export format\]\(\.\/questions\/01-export-format\.md\) — CSV with a BOM\. \*\(2026-08-02\)\*/);
assert.match(map, /- \[x\] \[Codebase context\]\(\.\/questions\/00-codebase-context\.md\): Node and Postgres; a long gist\n that wraps onto a second line\. \*\(2026-08-01\)\*/, "an unchanged row keeps its own wrapped text");
assert.match(map, /- \[x\] \[Export format\]\(\.\/questions\/01-export-format\.md\): CSV with a BOM\. \*\(2026-08-02\)\*/);
assert.match(map, /- \[ \] \[Row-count\n ceiling\]\(\.\/questions\/02-row-count-ceiling\.md\)/, "a wrapped link is still one row");
assert.match(map, /- \[!\] \[Delivery channel\]\(\.\/questions\/04-delivery-channel\.md\) — Blocked by 02/);
assert.match(map, /- \[-\] \[SIEM push\]\(\.\/questions\/05-siem-push\.md\) — out of scope, see below/);
assert.match(map, /- \[!\] \[Delivery channel\]\(\.\/questions\/04-delivery-channel\.md\): Blocked by 02/);
assert.match(map, /- \[-\] \[SIEM push\]\(\.\/questions\/05-siem-push\.md\): out of scope, see below/);
assert.ok(!map.includes("09-gone"), "a row with no file is dropped");
assert.match(map, /<!-- Rebuilt from questions\/ every session\. -->/);
const q1 = read(root, `${pf}/questions/01-export-format.md`);
@@ -132,13 +132,13 @@ test("pathfinder frontier, claim, resolve, rule-out", () => {
assert.equal(res.code, 0, res.stderr);
assert.deepEqual(res.json.unblocked, [{ nn: "04", name: "Delivery channel" }]);
const map = read(root, `${pf}/map.md`);
assert.match(map, /- \[x\] \[Row-count ceiling\]\(\.\/questions\/02-row-count-ceiling\.md\) — 2M rows at the 99th percentile\. \*\(2026-08-03\)\*/);
assert.match(map, /- \[x\] \[Row-count ceiling\]\(\.\/questions\/02-row-count-ceiling\.md\): 2M rows at the 99th percentile\. \*\(2026-08-03\)\*/);
assert.match(map, /- \[ \] \[Delivery channel\]\(\.\/questions\/04-delivery-channel\.md\)\n/, "the Blocked by tail goes with the [!] marker");
assert.match(map, /^\*\*Updated:\*\* 2026-08-03$/m);
const ro = P("rule-out", "audit-export", "03", "--reason", "testing is owned elsewhere");
assert.equal(ro.code, 0, ro.stderr);
assert.match(read(root, `${pf}/questions/03-testing-posture.md`), /State: out-of-scope[\s\S]*## Question\n\nOut of scope: testing is owned elsewhere/);
assert.match(read(root, `${pf}/map.md`), /## Out of scope\n\n- Redesign of the schema\.\n- \[Testing posture\]\(\.\/questions\/03-testing-posture\.md\) — testing is owned elsewhere/);
assert.match(read(root, `${pf}/map.md`), /## Out of scope\n\n- Redesign of the schema\.\n- \[Testing posture\]\(\.\/questions\/03-testing-posture\.md\): testing is owned elsewhere/);
assert.equal(P("rule-out", "audit-export", "04").code, 2, "--reason is required");
assert.equal(P("rule-out", "audit-export", "00", "--reason", "x").code, 5, "a resolved decision is not ruled out");
});
@@ -156,7 +156,7 @@ test("pathfinder trail: exact footer for forms A, B and C", () => {
" ● done · ◉ here · ○ open · ⊘ blocked · ⊝ out of scope · ⚑ destination · ~1 fog",
" 1 Codebase context ✔ · 2 Export format ✔ · 3 Row-count ceiling · 4 Testing posture ◀ here",
" 5 Delivery channel (blocked:3) · 6 SIEM push (out of scope)",
" Confidence: not yet — Feasibility still needs work.",
" Confidence: not yet, Feasibility still needs work.",
"",
"WAITING ON YOU · answer here, in this conversation:",
"Q1 Types · Q2 Cadence",
@@ -266,7 +266,7 @@ test("pathfinder brief-data: range filtering, frontier notes, plain sections", (
assert.deepEqual(full.waiting, [{ name: "Delivery channel", waitingOn: ["Row-count ceiling"] }]);
assert.deepEqual(full.fog, ["How far back an export may reach."]);
assert.deepEqual(full.ruledOut, ["Redesign of the schema."]);
assert.equal(full.confidence, "Confidence: not yet — Feasibility still needs work.");
assert.equal(full.confidence, "Confidence: not yet, Feasibility still needs work.");
const since = P("brief-data", "audit-export", "--range", "since:2026-08-02").json;
assert.deepEqual(since.decided.map((d) => d.name), ["Export format"]);
assert.deepEqual(P("brief-data", "audit-export", "--range", "2026-08-01..2026-08-01").json.decided.map((d) => d.name), ["Codebase context"]);
@@ -304,7 +304,7 @@ test("pathfinder reconcile: an unrepairable file is skipped and named, nothing h
test("pathfinder reconcile: rows stay in place among grouping lines, a re-opened row loses its gist, stray claims clear", () => {
const { root, pf } = mapFixture();
const mp = path.join(root, pf, "map.md");
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8").replace("- [ ] [Export format]", "### Group two\n\n- [x] [Export format]").replace("- [ ] [Export format](./questions/01-export-format.md)", "- [x] [Export format](./questions/01-export-format.md) — old gist *(2026-07-01)*"));
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8").replace("- [ ] [Export format]", "### Group two\n\n- [x] [Export format]").replace("- [ ] [Export format](./questions/01-export-format.md)", "- [x] [Export format](./questions/01-export-format.md): old gist *(2026-07-01)*"));
fs.writeFileSync(path.join(root, pf, "questions/01-export-format.md"), q("Export format", { claimed: "2026-08-02 10:00" }));
const r = runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["reconcile", "audit-export", "--root", root]);
assert.ok(r.json.repairs.some((x) => x.nn === "01" && x.repair === "stray-claim-cleared"));
@@ -366,10 +366,10 @@ test("pathfinder brief-data: calendar dates only, no future since, no NNs or lin
assert.equal(P("brief-data", "audit-export", "--range", "since:2026-13-99").json.error, "bad-date");
assert.equal(P("brief-data", "audit-export", "--range", "since:2026-09-01").code, 2);
const mp = path.join(root, pf, "map.md");
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8").replace("- Redesign of the schema.", "- [SIEM push](./questions/05-siem-push.md) — not ours.\n- Nothing yet."));
fs.writeFileSync(mp, fs.readFileSync(mp, "utf8").replace("- Redesign of the schema.", "- [SIEM push](./questions/05-siem-push.md): not ours.\n- Nothing yet."));
fs.writeFileSync(path.join(root, pf, "questions/04-delivery-channel.md"), q("Delivery channel", { blocked: "09" }));
const j = P("brief-data", "audit-export", "--range", "full").json;
assert.deepEqual(j.ruledOut, ["SIEM push — not ours."]);
assert.deepEqual(j.ruledOut, ["SIEM push: not ours."]);
assert.deepEqual(j.waiting.find((w) => w.name === "Delivery channel").waitingOn, ["a question that no longer exists"]);
});
@@ -445,15 +445,15 @@ test("pathfinder: an author's sub-bullet under a row survives resolve, rule-out
.replace("- [ ] [Delivery channel](./questions/04-delivery-channel.md)", "- [ ] [Delivery channel](./questions/04-delivery-channel.md)\n - note: depends on the volume\n and wraps"));
P("reconcile", "audit-export");
let map = read(root, `${pf}/map.md`);
assert.match(map, /- \[!\] \[Delivery channel\]\(\.\/questions\/04-delivery-channel\.md\) — Blocked by 02\n - note: depends on the volume\n and wraps\n/, "kept under a regenerated [!] row");
assert.match(map, /- \[!\] \[Delivery channel\]\(\.\/questions\/04-delivery-channel\.md\): Blocked by 02\n - note: depends on the volume\n and wraps\n/, "kept under a regenerated [!] row");
P("claim", "audit-export", "03");
fs.appendFileSync(path.join(root, pf, "questions/03-testing-posture.md"), "\n## Answer\n\nUnit.\n\n**Gist:** Unit tests only.\n");
assert.equal(P("resolve", "audit-export", "03").code, 0);
map = read(root, `${pf}/map.md`);
assert.match(map, /- \[x\] \[Testing posture\]\(\.\/questions\/03-testing-posture\.md\) — Unit tests only\. \*\(2026-08-03\)\*\n - note: ask Dana first\n/, "kept on resolve");
assert.match(map, /- \[x\] \[Testing posture\]\(\.\/questions\/03-testing-posture\.md\): Unit tests only\. \*\(2026-08-03\)\*\n - note: ask Dana first\n/, "kept on resolve");
assert.equal(P("rule-out", "audit-export", "04", "--reason", "not ours").code, 0);
map = read(root, `${pf}/map.md`);
assert.match(map, /- \[-\] \[Delivery channel\]\(\.\/questions\/04-delivery-channel\.md\) — out of scope, see below\n - note: depends on the volume\n and wraps\n/, "kept on rule-out");
assert.match(map, /- \[-\] \[Delivery channel\]\(\.\/questions\/04-delivery-channel\.md\): out of scope, see below\n - note: depends on the volume\n and wraps\n/, "kept on rule-out");
assert.deepEqual(P("frontier", "audit-export").json.drift, []);
});
@@ -540,3 +540,161 @@ test("pathfinder lint: the chart.md map template lints clean", () => {
assert.equal(l.code, 0, JSON.stringify(l.json.problems));
assert.deepEqual([l.json.errors, l.json.warnings], [0, 0], JSON.stringify(l.json.problems));
});
/* ============================================== separators, init and add */
// U+2014, built from its code so this file carries none: maps written before
// the ": " separator used it between a row's link and its tail.
const EM = String.fromCharCode(0x2014);
test("pathfinder: a map written the old way (em dash tails) still reads, and nothing the script writes has an em dash", () => {
const { root, pf } = mapFixture();
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
const mp = path.join(root, pf, "map.md");
const oldRow00 = `- [x] [Codebase context](./questions/00-codebase-context.md) ${EM} Node and Postgres; a long gist\n that wraps onto a second line. *(2026-08-01)*`;
const oldRow04 = `- [!] [Delivery channel](./questions/04-delivery-channel.md) ${EM} Blocked by 02`;
const OLD = MAP
.replace(", one file each", ` ${EM} one file each`)
.replace(/- \[x\] \[Codebase context\][^\n]*\n[^\n]*\n/, `${oldRow00}\n`)
.replace("- [ ] [Testing posture](./questions/03-testing-posture.md)", `- [x] [Testing posture](./questions/03-testing-posture.md) ${EM} an old gist *(2026-07-01)*`)
.replace("- [ ] [Delivery channel](./questions/04-delivery-channel.md)", `${oldRow04}\n- [-] [SIEM push](./questions/05-siem-push.md) ${EM} out of scope, see below`)
.replace("- [ ] [Gone question](./questions/09-gone.md)\n", "")
.replace("- Redesign of the schema.", `- [SIEM push](./questions/05-siem-push.md) ${EM} not ours.\n- Nothing yet.`);
fs.writeFileSync(mp, OLD);
// Every old row is found by its checkbox and link: drift is about markers only.
const before = P("frontier", "audit-export").json;
assert.ok(!before.drift.some((d) => /no map row|no question file|appears/.test(d)), JSON.stringify(before.drift));
const r = P("reconcile", "audit-export");
assert.equal(r.code, 0, r.stderr);
let map = read(root, `${pf}/map.md`);
assert.ok(map.includes(`${oldRow00}\n`), "an unchanged row keeps the author's words, old separator and all");
assert.ok(map.includes(`${oldRow04}\n`), "a [!] row that stays [!] is kept as written");
assert.match(map, /- \[x\] \[Export format\]\(\.\/questions\/01-export-format\.md\): CSV with a BOM\. \*\(2026-08-02\)\*\n/, "a row turning [x] is written with the new separator");
assert.match(map, /- \[ \] \[Testing posture\]\(\.\/questions\/03-testing-posture\.md\)\n/, "a re-opened row drops its old em dash tail");
assert.deepEqual(P("frontier", "audit-export").json.drift, []);
assert.equal(P("reconcile", "audit-export").json.mapWritten, false, "stable on an old map");
fs.appendFileSync(path.join(root, pf, "questions/02-row-count-ceiling.md"), "\n## Answer\n\nFacts.\n\n**Gist:** 2M rows.\n");
assert.equal(P("resolve", "audit-export", "02").code, 0);
assert.equal(P("rule-out", "audit-export", "03", "--reason", "owned elsewhere").code, 0);
map = read(root, `${pf}/map.md`);
assert.match(map, /- \[ \] \[Delivery channel\]\(\.\/questions\/04-delivery-channel\.md\)\n/, "the old Blocked by tail goes with the [!] marker");
assert.match(map, /- \[-\] \[Testing posture\]\(\.\/questions\/03-testing-posture\.md\): out of scope, see below\n/);
assert.match(map, /- \[Testing posture\]\(\.\/questions\/03-testing-posture\.md\): owned elsewhere\n/);
const oldLines = new Set(OLD.split("\n"));
const written = map.split("\n").filter((l) => !oldLines.has(l));
assert.ok(written.length > 0);
assert.deepEqual(written.filter((l) => l.includes(EM)), [], "no line the script wrote carries an em dash");
const brief = P("brief-data", "audit-export", "--range", "full").json;
assert.deepEqual(brief.ruledOut, [`SIEM push ${EM} not ours.`, "Testing posture: owned elsewhere"], "old and new out-of-scope lines both read; the placeholder is skipped");
assert.ok(!brief.confidence.includes(EM), brief.confidence);
const trail = P("trail", "audit-export", "--form", "A", "--text").stdout;
assert.ok(!trail.includes(EM), trail);
const src = fs.readFileSync(path.join(SKILLS, "plan2code-0-pathfinder", "scripts", "pathfinder.mjs"), "utf8");
assert.ok(!src.includes(EM), "pathfinder.mjs holds no em dash; a reader of old maps spells it \\u2014");
});
test("pathfinder gate: the PLAN-DRAFT status line is byte-exact with the one specs.mjs reads", () => {
const { root } = mapFixture();
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
P("reconcile", "audit-export");
const line = P("gate", "audit-export").json.planDraftStatus;
const m = /^\*\*Status:\*\* (.+)$/.exec(line || "");
assert.ok(m, `gate prints the **Status:** line: ${line}`);
const status = m[1];
assert.match(status, /^[\x20-\x7e]+$/, "plain ASCII: an en dash or a smart character breaks the match");
const specs = fs.readFileSync(path.join(ROOT, "src", "skill-scripts", "specs.mjs"), "utf8");
const decl = /const DRAFT_STATUSES = \[([^\]]*)\]/.exec(specs);
assert.ok(decl, "specs.mjs still declares DRAFT_STATUSES");
const statuses = [...decl[1].matchAll(/"([^"\\]*)"/g)].map((x) => x[1]);
assert.ok(statuses.includes(status), `"${status}" is not in specs.mjs DRAFT_STATUSES: ${JSON.stringify(statuses)}`);
assert.ok(fs.readFileSync(path.join(ROOT, "src", "plan2code-1-plan.md"), "utf8").includes(`Status "${status}": Resume at Phase 4`), "Plan resumes from the same string");
assert.ok(fs.readFileSync(path.join(SKILLS, "plan2code-0-pathfinder", "references", "handoff.md"), "utf8").includes(line), "handoff.md quotes the same line");
});
test("pathfinder init and add: the map and every question type from the templates, lint-clean, with their refusals", () => {
const root = tmp("pfi");
const pf = "specs/audit-export/pathfinder";
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
const INIT = ["--destination", "A locked plan for exporting audit events as one file.", "--scores", "10,8,12,9", "--fog", "How far back an export may reach."];
assert.equal(P("init", "Audit_Export", ...INIT).json.error, "bad-idea-name");
assert.equal(P("add", "audit-export", "--name", "Export format", "--question", "Which format?").json.error, "reserved-00", "00 is the codebase context");
// Chart Step 3: the codebase context, written before there is a map.
const c = P("add", "audit-export", "--name", "Codebase context", "--type", "legwork-afk", "--question", "What does the codebase provide?");
assert.equal(c.code, 0, c.stderr);
assert.deepEqual([c.json.nn, c.json.file, c.json.mapRow, c.json.nextNN], ["00", `${pf}/questions/00-codebase-context.md`, null, "01"]);
assert.match(c.json.next, /init/);
assert.equal(read(root, `${pf}/questions/00-codebase-context.md`), [B, "", "# Codebase context", "", "Type: legwork · AFK", "State: open", "Blocked by: none", "Claimed: none", "Resolved: none", "Locked: no", "", "## Question", "", "What does the codebase provide?", "", "## Evidence", ""].join("\n"));
// Chart Step 5: init.
assert.equal(P("init", "audit-export", "--scores", "1,1,1,1", "--fog", "x").code, 2, "--destination is required");
assert.equal(P("init", "audit-export", "--destination", "d", "--scores", "10,8,30,9", "--fog", "x").json.error, "bad-scores");
assert.equal(P("init", "audit-export", "--destination", "d", "--scores", "10,8,12,9").json.error, "no-fog", "no fog is the off-ramp, not a map");
assert.equal(P("init", "audit-export", "--destination", "d", "--scores", "10,8,12,9", "--fog", "[ ] decide x").json.error, "checkbox", "init refuses a checkbox as add does");
assert.equal(P("init", "audit-export", "--destination", "d", "--scores", "10,8,12,9", "--fog", "x", "--rule", "TASK_COMPLETE").json.error, "loop-token", "init refuses a loop token as add does");
const dry = P("init", "audit-export", ...INIT, "--dry-run");
assert.deepEqual([dry.code, dry.json.mapWritten, fs.existsSync(path.join(root, pf, "map.md"))], [0, false, false], "--dry-run writes nothing");
const i = P("init", "audit-export", ...INIT, "--rule", "Dana reviews compliance text.", "--out", "Schema redesign: the write path is untouched.");
assert.equal(i.code, 0, i.stderr);
assert.deepEqual([i.json.status, i.json.agentsAbsent, i.json.indexed], ["Charting", true, [{ nn: "00", name: "Codebase context", marker: "[ ]" }]]);
let map = read(root, `${pf}/map.md`);
assert.ok(map.startsWith(`${B}\n\n# Map: audit-export\n`), map);
assert.match(map, /^\*\*Status:\*\* Charting\n\*\*Updated:\*\* 2026-08-03\n\*\*Confidence:\*\* Requirements-clarity 10\/25 · Feasibility-technical 8\/25 · Integration-points 12\/25 · Risk-assessment 9\/25\n/m);
assert.match(map, /## Destination\n\nA locked plan for exporting audit events as one file\.\n/);
assert.match(map, /<!-- Standing[\s\S]*?-->\n\n- \*\*Backend:\*\* local\n- `AGENTS\.md` is absent\.\n- One question _file_ at a time;[\s\S]*\n- Dana reviews compliance text\.\n\n## Glossary/, "Backend first, then AGENTS.md as found on disk, the standing rules, then --rule");
assert.match(map, /## Question Checklist\n\n<!--[\s\S]*?-->\n\n- \[ \] \[Codebase context\]\(\.\/questions\/00-codebase-context\.md\)\n\n## Not yet specified/, "a question written before the map is indexed");
assert.match(map, /-->\n\n- How far back an export may reach\.\n\n## Out of scope\n\n<!--[\s\S]*?-->\n\n- Schema redesign: the write path is untouched\.\n$/);
assert.ok(!map.includes(EM), "init writes no em dash");
assert.equal(P("init", "audit-export", ...INIT).json.error, "map-exists", "never overwrites a map");
// Chart Step 6: one question of each type, in dependency order.
const types = [["Export format", "grill", "grill · HITL"], ["Row-count ceiling", "research", "research · AFK"], ["Delivery sketch", "sketch", "sketch · HITL"], ["Ask legal", "legwork-hitl", "legwork · HITL"], ["Load figures", "legwork · AFK", "legwork · AFK"]];
const extra = { "Row-count ceiling": ["--evidence", "audit_events is partitioned monthly.", "--recommended", "Cap at 2M rows."], "Delivery sketch": ["--blocked-by", "2", "--locked"] };
types.forEach(([name, flag, type], n) => {
const a = P("add", "audit-export", "--name", name, "--type", flag, "--question", `What about ${name}?`, ...(extra[name] || []));
assert.equal(a.code, 0, a.stderr);
assert.deepEqual([a.json.nn, a.json.type, a.json.mapWritten, a.json.nextNN], [`0${n + 1}`, type, true, `0${n + 2}`], name);
});
assert.equal(read(root, `${pf}/questions/02-row-count-ceiling.md`).split("## Question\n")[1], "\nWhat about Row-count ceiling?\n\nRecommended answer to react to: Cap at 2M rows.\n\n## Evidence\n\n- audit_events is partitioned monthly.\n");
assert.match(read(root, `${pf}/questions/03-delivery-sketch.md`), /Type: sketch · HITL\nState: open\nBlocked by: 02\nClaimed: none\nResolved: none\nLocked: yes\n/);
map = read(root, `${pf}/map.md`);
assert.match(map, /- \[ \] \[Codebase context\]\(\.\/questions\/00-codebase-context\.md\)\n- \[ \] \[Export format\]\(\.\/questions\/01-export-format\.md\)\n- \[ \] \[Row-count ceiling\]\(\.\/questions\/02-row-count-ceiling\.md\)\n- \[!\] \[Delivery sketch\]\(\.\/questions\/03-delivery-sketch\.md\): Blocked by 02\n- \[ \] \[Ask legal\]\(\.\/questions\/04-ask-legal\.md\)\n- \[ \] \[Load figures\]\(\.\/questions\/05-load-figures\.md\)\n\n## Not yet specified/);
assert.match(map, /^\*\*Next NN:\*\* 06$/m);
// Refusals, and a dry run that writes nothing.
const refused = (args, code, error, why) => {
const x = P("add", "audit-export", ...args);
assert.deepEqual([x.code, x.json.error], [code, error], why);
};
refused(["--name", "export FORMAT", "--question", "Again?"], 5, "duplicate", "one file per decision");
refused(["--name", "Codebase context", "--slug", "codebase-context-two", "--question", "Again?"], 5, "duplicate", "the same name under another file name");
const bare = tmp("pfr");
write(bare, "specs/odd/pathfinder/questions/01-first.md", q("First"));
const late = runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["add", "odd", "--name", "Codebase context", "--question", "What?", "--root", bare]);
assert.deepEqual([late.code, late.json.error], [5, "reserved-name"], "codebase-context is 00 only");
refused(["--name", "Odd", "--type", "legwork", "--question", "Which?"], 2, "bad-type", "legwork names its mode");
refused(["--name", "Odd", "--question", "Which?", "--blocked-by", "09"], 3, "no-blocker", "a blocker must exist");
refused(["--name", "Odd", "--question", "Which?\n- [ ] a checkbox"], 5, "checkbox", "plain bullets only");
refused(["--name", "Odd", "--question", "Done. TASK_COMPLETE"], 5, "loop-token", "loop tokens never land under specs/");
refused(["--name", "Odd"], 2, "missing-question", "--question is required");
refused(["--name", "Odd", "--slug", "Not Kebab", "--question", "Which?"], 2, "bad-slug", "the file name is kebab-case");
const mapBefore = read(root, `${pf}/map.md`);
const d = P("add", "audit-export", "--name", "Retention", "--question", "How long?", "--dry-run");
assert.deepEqual([d.code, d.json.nn, d.json.dryRun, d.json.mapWritten], [0, "06", true, false]);
assert.ok(!fs.existsSync(path.join(root, pf, "questions/06-retention.md")), "add --dry-run writes no file");
assert.equal(read(root, `${pf}/map.md`), mapBefore, "nor the map");
// Chart Step 7: the index already agrees with the files, and lint accepts all of it.
const r = P("reconcile", "audit-export");
assert.deepEqual([r.json.repairs, r.json.mapChanges, r.json.mapWritten], [[], [], false], JSON.stringify(r.json));
const l = P("lint", "audit-export");
assert.equal(l.code, 0, JSON.stringify(l.json.problems));
assert.deepEqual([l.json.errors, l.json.warnings], [0, 0], JSON.stringify(l.json.problems));
});
test("pathfinder --help lists init and add", () => {
const h = runScript("plan2code-0-pathfinder", "pathfinder.mjs", ["--help"]);
assert.equal(h.code, 0);
assert.match(h.stdout, /node pathfinder\.mjs init <map>/);
assert.match(h.stdout, /node pathfinder\.mjs add <map>/);
});
+154
View File
@@ -0,0 +1,154 @@
// Tests for scripts/set-version.mjs, the one writer of the version carriers.
// Run with: node --test scripts/test-set-version.mjs
//
// Every run works on a scratch copy of the carriers (plus CHANGELOG.md, which check-versions reads
// and the script leaves to a person), never on the real tree.
import test, { after } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { checkVersions } from "./check-versions.mjs";
import { CARRIER_FILES } from "./set-version.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(here, "..");
const SET = path.join(here, "set-version.mjs");
const made = [];
after(() => {
for (const d of made) fs.rmSync(d, { recursive: true, force: true });
});
function scratch() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "setver-"));
made.push(dir);
for (const file of [...CARRIER_FILES, "CHANGELOG.md"]) {
const to = path.join(dir, file);
fs.mkdirSync(path.dirname(to), { recursive: true });
fs.copyFileSync(path.join(ROOT, file), to);
}
return dir;
}
const read = (dir, file) => fs.readFileSync(path.join(dir, file), "utf8");
const run = (...args) => spawnSync(process.execPath, [SET, ...args], { encoding: "utf8" });
// A person writes the changelog heading; the script never does.
function writeHeading(dir, version) {
const file = path.join(dir, "CHANGELOG.md");
fs.writeFileSync(file, fs.readFileSync(file, "utf8").replace(/^##\s+v?\d+\.\d+\.\d+/m, `## v${version}`));
}
const changedLines = (a, b) => {
const x = a.split("\n");
const y = b.split("\n");
assert.equal(x.length, y.length, "the line count does not change");
return x.filter((line, i) => line !== y[i]).length;
};
test("it names all the carriers, and the tree's own versions agree before the test starts", () => {
assert.equal(CARRIER_FILES.length, 9);
assert.ok(checkVersions(ROOT).ok, checkVersions(ROOT).problems.join("\n"));
});
test("after it runs, check-versions passes on the scratch copy", () => {
const dir = scratch();
const before = Object.fromEntries(CARRIER_FILES.map((f) => [f, read(dir, f)]));
const r = run("9.8.7", "--date", "2030-01-02", "--root", dir);
assert.equal(r.status, 0, r.stderr);
writeHeading(dir, "9.8.7");
const check = checkVersions(dir);
assert.deepEqual(check.problems, []);
assert.ok(check.versions.every((v) => v.version === "9.8.7"));
assert.match(read(dir, "version.json"), /"releaseDate": "2030-01-02"/);
assert.match(read(dir, "README.md"), /^Version 9\.8\.7\b/m);
// Only the version lines changed: the carriers keep their formatting.
const expected = {
"version.json": 2, "package.json": 1, "README.md": 1, "plan2code-app/package.json": 1,
"plan2code-app/src-tauri/tauri.conf.json": 1, "plan2code-app/package-lock.json": 2,
"plan2code-app/src-tauri/Cargo.toml": 1, "plan2code-app/fake-agent/Cargo.toml": 1, "plan2code-app/Cargo.lock": 2,
};
for (const f of CARRIER_FILES) assert.equal(changedLines(before[f], read(dir, f)), expected[f], f);
});
test("a second run for another version replaces the first, and the date defaults to today", () => {
const dir = scratch();
assert.equal(run("1.2.3", "--root", dir).status, 0);
assert.equal(run("1.2.4", "--root", dir).status, 0);
writeHeading(dir, "1.2.4");
assert.deepEqual(checkVersions(dir).problems, []);
const { releaseDate } = JSON.parse(read(dir, "version.json"));
const d = new Date();
const today = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
assert.equal(releaseDate, today);
});
test("a Cargo.lock with CRLF line endings is still edited, and keeps them", () => {
const dir = scratch();
const lock = path.join(dir, "plan2code-app/Cargo.lock");
fs.writeFileSync(lock, fs.readFileSync(lock, "utf8").replace(/\n/g, "\r\n"));
assert.equal(run("4.5.6", "--root", dir).status, 0);
writeHeading(dir, "4.5.6");
assert.deepEqual(checkVersions(dir).problems, []);
assert.ok(read(dir, "plan2code-app/Cargo.lock").includes("\r\n"));
});
test("it never touches CHANGELOG.md", () => {
const dir = scratch();
const before = read(dir, "CHANGELOG.md");
assert.equal(run("7.7.7", "--root", dir).status, 0);
assert.equal(read(dir, "CHANGELOG.md"), before);
});
test("a missing carrier fails, names it, and writes nothing", () => {
const dir = scratch();
fs.rmSync(path.join(dir, "plan2code-app/fake-agent/Cargo.toml"));
const before = Object.fromEntries(CARRIER_FILES.filter((f) => !f.includes("fake-agent/")).map((f) => [f, read(dir, f)]));
const r = run("6.6.6", "--root", dir);
assert.equal(r.status, 1);
assert.match(r.stderr, /fake-agent\/Cargo\.toml: file is missing/);
assert.match(r.stderr, /Nothing was written/);
for (const [f, text] of Object.entries(before)) assert.equal(read(dir, f), text, `${f} is unchanged`);
});
test("a carrier with no version in it fails and writes nothing", () => {
const dir = scratch();
fs.writeFileSync(path.join(dir, "README.md"), "# Plan2Code\n\nNo version line here.\n");
const r = run("6.6.6", "--root", dir);
assert.equal(r.status, 1);
assert.match(r.stderr, /README\.md: no "Version X\.Y\.Z" line found/);
assert.match(read(dir, "version.json"), /"version": "[^"]+"/);
assert.ok(!read(dir, "version.json").includes("6.6.6"));
});
test("bad arguments exit 2 and write nothing", () => {
const dir = scratch();
for (const args of [[], ["3.0"], ["v3.0.1"], ["3.0.1-beta"], ["3.0.1", "extra"], ["3.0.1", "--date", "yesterday"], ["3.0.1", "--root"]]) {
const r = run(...args, ...(args.includes("--root") ? [] : ["--root", dir]));
assert.equal(r.status, 2, `${args.join(" ")}: ${r.stderr}`);
assert.match(r.stderr, /Usage: node scripts\/set-version\.mjs/);
}
assert.ok(!read(dir, "version.json").includes("3.0.1"));
});
test("an impossible date is refused", () => {
const dir = scratch();
const r = run("3.0.1", "--date", "2030-99-99", "--root", dir);
assert.equal(r.status, 2);
assert.equal(run("3.0.1", "--date", "2030-02-30", "--root", dir).status, 2);
assert.equal(run("3.0.1", "--date", "2028-02-29", "--root", dir).status, 0);
});
test("a write that fails part way puts back the files already written", () => {
const dir = scratch();
const last = path.join(dir, "plan2code-app/Cargo.lock");
fs.chmodSync(last, 0o444);
const before = Object.fromEntries(CARRIER_FILES.map((f) => [f, read(dir, f)]));
const r = run("5.5.5", "--root", dir);
fs.chmodSync(last, 0o644);
if (r.status === 0) return; // running as a user who can write a read-only file: nothing to test
assert.equal(r.status, 1);
assert.match(r.stderr, /restored the files already written/);
for (const f of CARRIER_FILES) assert.equal(read(dir, f), before[f], `${f} is back as it was`);
});
+125 -7
View File
@@ -9,17 +9,21 @@ import path from "node:path";
import { spawnSync } from "node:child_process";
import { ROOT, SKILLS, NOW, runScript, tmp, write, read, gitInit, phase } from "./skill-script-helpers.mjs";
// skills/ also holds _console, the shared console build: not a skill.
const skillNames = () => fs.readdirSync(SKILLS).filter((name) => !name.startsWith("_"));
/* ================================================================ install */
test("npm test runs every scripts/test-*.mjs file, and names none that is missing", () => {
const command = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8")).scripts.test;
const listed = [...command.matchAll(/scripts\/(test-[\w-]+\.mjs)/g)].map((m) => m[1]).sort();
const onDisk = fs.readdirSync(path.join(ROOT, "scripts")).filter((f) => /^test-[\w-]+\.mjs$/.test(f)).sort();
// test-fast.mjs runs the fast lane (npm run test:fast); it is a runner, not a test file.
const onDisk = fs.readdirSync(path.join(ROOT, "scripts")).filter((f) => /^test-[\w-]+\.mjs$/.test(f) && f !== "test-fast.mjs").sort();
assert.deepEqual(listed, onDisk);
});
test("every skill with scripts ships common.mjs and version.json; dashboard ships none", () => {
const withScripts = fs.readdirSync(SKILLS).filter((s) => fs.existsSync(path.join(SKILLS, s, "scripts")));
const withScripts = skillNames().filter((s) => fs.existsSync(path.join(SKILLS, s, "scripts")));
assert.ok(withScripts.length >= 11, `expected most skills to carry scripts, got ${withScripts.join(", ")}`);
for (const s of withScripts) {
for (const f of ["common.mjs", "version.json"]) assert.ok(fs.existsSync(path.join(SKILLS, s, "scripts", f)), `${s}/scripts/${f}`);
@@ -41,7 +45,7 @@ test("the Handoff skill writes through the console's handoff new, with no folder
});
test("every script a SKILL.md (or a reference it ships) runs exists beside it, and answers --help", () => {
for (const skill of fs.readdirSync(SKILLS)) {
for (const skill of skillNames()) {
const dir = path.join(SKILLS, skill);
const texts = [];
const walk = (d) => {
@@ -78,7 +82,7 @@ test("scripts are self-contained: built-ins and siblings only", () => {
}
// 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)) {
for (const skill of skillNames()) {
const dir = path.join(SKILLS, skill, "scripts");
if (!fs.existsSync(dir)) continue;
for (const f of fs.readdirSync(dir).filter((n) => n.endsWith(".mjs"))) {
@@ -159,6 +163,58 @@ test("specs list: a diagnosis Quick Task marked Fixed is a fixed bug", () => {
assert.equal(bug.detail, "bug fixed");
});
// The seven cases where the dashboard scan and specs.mjs once disagreed
// (recorded in the hardening spec's Phase 5 notes; the same cases are in
// test-web-console-spec-states.mjs). Each is a spec folder and the
// [state, detail, finalizeReady] both must now report.
const DESYNC_CHECKLIST = (...marks) => `# Overview\n\n## Phase Checklist\n\n${marks.map((m, i) => `- [${m}] [Phase ${i + 1}: Step ${i + 1}](./phase-${i + 1}.md)`).join("\n")}\n`;
const DESYNC_PHASE = (n, lines) => `# Phase ${n}: Step ${n}\n\n**Status:** In Progress\n\n## Tasks\n\n${lines.join("\n")}\n\n## Acceptance Criteria\n\n- It works\n`;
const DESYNC_CASES = {
"blocked-reasoned": {
files: { "overview.md": DESYNC_CHECKLIST("x"), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One", "- [!] **Task 1.2:** Two", " > BLOCKED: needs admin access. User action: create the app."]) },
want: ["building", "1 of 2 tasks done, 1 blocked", true],
},
"unknown-marker": {
files: { "overview.md": DESYNC_CHECKLIST("/"), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One", "- [~] **Task 1.2:** Two"]) },
want: ["building", "1 of 2 tasks done", false],
},
"row-without-file": {
files: { "overview.md": DESYNC_CHECKLIST("x", " "), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One", "- [x] **Task 1.2:** Two"]) },
want: ["building", "2 of 2 tasks done, Phase 2 not written up", false],
},
"phase-without-tasks": {
files: { "overview.md": DESYNC_CHECKLIST("x", " "), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One"]), "phase-2.md": DESYNC_PHASE(2, ["To be written."]) },
want: ["building", "1 of 1 tasks done, Phase 2 not written up", false],
},
"stale-duplicate": {
files: { "overview.md": DESYNC_CHECKLIST("x"), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One"]), "phase-1-old.md": DESYNC_PHASE(1, ["- [ ] **Task 1.1:** One", "- [ ] **Task 1.2:** Two"]) },
want: ["built", "all tasks done", false],
},
"not-a-phase-file": {
files: { "overview.md": DESYNC_CHECKLIST("x"), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One"]), "phase-notes.md": "# Notes\n\n- [ ] Ask about colors\n" },
want: ["built", "all tasks done", false],
},
"blocked-bare": {
files: { "overview.md": DESYNC_CHECKLIST("x"), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One", "- [!] **Task 1.2:** Two"]) },
want: ["building", "1 of 2 tasks done, 1 blocked", false],
},
};
test("specs: list and status agree with the dashboard scan on the seven desync cases", () => {
const root = tmp("desync");
for (const [name, c] of Object.entries(DESYNC_CASES)) for (const [file, text] of Object.entries(c.files)) write(root, `specs/${name}/${file}`, text);
const S = (...a) => runScript("plan2code-3-implement", "specs.mjs", [...a, "--root", root]);
const list = S("list");
assert.equal(list.code, 0, list.stderr);
for (const [name, c] of Object.entries(DESYNC_CASES)) {
const row = list.json.specs.find((s) => s.name === name);
const st = S("status", name);
assert.equal(st.code, 0, st.stderr);
assert.deepEqual([row.state, row.detail, Boolean(row.finalizeReady)], c.want, `${name}: specs.mjs list (the dashboard scan)`);
assert.deepEqual([st.json.state, st.json.stateDetail, st.json.finalizeReady], c.want, `${name}: specs.mjs status`);
}
});
test("specs status: checklist formats, groups, task markers, numbering, totals, checks", () => {
const root = specFixture();
const r = runScript("plan2code-3-implement", "specs.mjs", ["status", "specs/lunch-vote/overview.md", "--root", root]);
@@ -310,6 +366,7 @@ test("specs mark: transitions, the no-reset rule, dry-run and idempotence", () =
assert.match(read(root, "specs/lunch-vote/overview.md"), /- \[ \] \*\*Phase 3/, "dry-run writes nothing");
assert.equal(S("mark", "lunch-vote", "--phase", "3", "--to", "in-progress").code, 0);
assert.match(read(root, "specs/lunch-vote/overview.md"), /- \[\/\] \*\*Phase 3 — Web UI\*\* — see/, "only the marker changes");
assert.match(read(root, "specs/lunch-vote/phase-3.md"), /^\*\*Status:\*\* In Progress$/m, "in-progress writes the phase file's Status line too");
assert.equal(S("mark", "lunch-vote", "--phase", "3", "--to", "in-progress").json.changed, false);
const reset = S("mark", "lunch-vote", "--phase", "3", "--to", "open");
assert.equal(reset.code, 5);
@@ -366,11 +423,11 @@ test("commit-msg: the two -m flags on any branch, subject rules", () => {
g("add", "-A");
g("commit", "-q", "-m", "init");
const C = (...a) => runScript("plan2code-review", "commit-msg.mjs", a, { cwd: repo });
const ok = C("--subject", "Add the export endpoint", "--add-all");
const ok = C("--subject", "Add the export endpoint", "--files", "src/export.js");
assert.equal(ok.code, 0, ok.stderr);
assert.equal(ok.json.ticket, undefined);
assert.equal(ok.json.branch, undefined);
assert.equal(ok.json.command, 'git add -A && git commit -m "Add the export endpoint" -m "AI Assisted"');
assert.equal(ok.json.command, 'git add -- src/export.js && git commit -m "Add the export endpoint" -m "AI Assisted"');
assert.equal(ok.json.message, "Add the export endpoint\n\nAI Assisted");
assert.equal(C("--subject", "x".repeat(101)).code, 4);
assert.equal(C("--subject", 'say "hi"').code, 4);
@@ -438,6 +495,22 @@ test("agent-files: detect, apply only what was chosen, rules folders, idempotent
/* ============================================================== agents-md.mjs */
test("agents-md: Init's first run warns once that a gitignored specs--completed/ is not backed up", () => {
const root = tmp("notices");
const I = () => runScript("plan2code-init", "agents-md.mjs", ["inspect", "--root", root]).json;
assert.deepEqual(I().notices, [], "no .gitignore, nothing to say");
for (const line of ["specs--completed/", "/specs--completed", "specs*"]) {
write(root, ".gitignore", `node_modules\nspecs/\n${line}\n`);
assert.deepEqual(I().notices.map((n) => n.code), ["specs-not-backed-up"], line);
}
assert.match(I().notices[0].message, /not backed up/);
write(root, ".gitignore", "node_modules\nspecs/\n");
assert.deepEqual(I().notices, [], "only specs/ ignored: archives are committed");
write(root, ".gitignore", "specs--completed/\n");
write(root, "AGENTS.md", "# AGENTS.md\n\n## Project Overview\n\nA thing.\n");
assert.equal(I().notices, undefined, "once AGENTS.md exists (Init Update), it is not said again");
});
test("agents-md: structure, budget, orphans, broken links, inline rules", () => {
const root = tmp("agentsmd");
write(root, "AGENTS.md", [
@@ -581,6 +654,35 @@ test("specs check: a well-formed spec passes", () => {
assert.deepEqual(r.json.problems, []);
});
test("specs check: the format rules warn on an unmarked spec and fail one carrying the format marker", () => {
const root = cleanSpec(specFixture());
write(
root,
"specs/clean/phase-1.md",
phase(1, "x", [["x", "1.1"], ["!", "1.2"], ["!", "1.3"], [" ", "1.4"], [" ", "1.5"]])
.replace("**Status:** x\n", "")
.replace("**Task 1.3:** Do 1.3", "**Task 1.3:** Do 1.3\n > BLOCKED: needs admin. User action: grant it.")
.replace("**Task 1.4:** Do 1.4", "**Task 1.4:** Change `src/app.js:42` to retry")
.replace("**Task 1.5:** Do 1.5", "**Task 1.5:** Change `src/app.js:~42` (approximate) to retry")
.replace("## Acceptance Criteria", "## Notes\n\n- [ ] Ask about colors\n\n## Acceptance Criteria")
);
const C = () => runScript("plan2code-2-document", "specs.mjs", ["check", "clean", "--root", root]);
const codes = (r) => r.json.problems.filter((p) => p.file === "specs/clean/phase-1.md").map((p) => [p.level, p.code]);
const old = C();
assert.equal(old.code, 0, old.stdout);
assert.equal(old.json.format, null);
assert.deepEqual(codes(old), [["warn", "no-status"], ["warn", "notes-checkbox"], ["warn", "bare-blocked"], ["warn", "line-reference"]], "an unmarked spec only warns; the reasoned blocker and the ~ reference pass");
write(root, "specs/clean/overview.md", read(root, "specs/clean/overview.md") + "\n<!-- plan2code-format: 2 -->\n");
const marked = C();
assert.equal(marked.code, 4, marked.stdout);
assert.equal(marked.json.format, 2);
assert.deepEqual(codes(marked), [["error", "no-status"], ["error", "notes-checkbox"], ["error", "bare-blocked"], ["error", "line-reference"]]);
assert.match(marked.json.problems.find((p) => p.code === "bare-blocked").message, /Task 1\.2/);
assert.match(marked.json.problems.find((p) => p.code === "line-reference").message, /Task 1\.4/);
// The clean phase file passes the same rules under the marker.
assert.ok(!marked.json.problems.some((p) => p.file === "specs/clean/phase-2.md"));
});
test("specs check: a bad task line, a checklist row with no phase file, a loop token and a bare metric word each fail", () => {
const root = cleanSpec(specFixture());
write(root, "specs/clean/overview.md", read(root, "specs/clean/overview.md") + "- [ ] [Phase 3: Docs](./phase-3.md)\n");
@@ -869,6 +971,23 @@ test("specs mark: a plain or bold Status: line is updated; a missing one is repo
assert.match(read(root, "specs/lunch-vote/overview.md"), /- \[x\] \[Phase 2: API\]/);
});
test("specs archive: a copy that does not match the source by name and size keeps the source", () => {
const root = specFixture();
const S = (env, ...a) => runScript("plan2code-4-finalize", "specs.mjs", [...a, "--root", root], { env });
const bad = S({ PLAN2CODE_ARCHIVE_FAULT: "truncate" }, "archive", "lunch-vote");
assert.equal(bad.code, 4, bad.stdout);
assert.equal(bad.json.error, "copy-unverified");
assert.match(bad.json.message, /PLAN-DRAFT-20260801\.md is \d+ bytes, not \d+/, "the short file is named with both sizes");
assert.ok(fs.existsSync(path.join(root, "specs/lunch-vote/phase-4.md")), "the source stays when the copy is short");
assert.match(bad.json.next, /Delete the partial specs--completed\/lunch-vote\//);
// The same move through the copy path, intact, removes the source.
fs.rmSync(path.join(root, "specs--completed/lunch-vote"), { recursive: true });
const good = S({ PLAN2CODE_ARCHIVE_FAULT: "copy" }, "archive", "lunch-vote");
assert.equal(good.code, 0, good.stdout);
assert.equal(good.json.sourceRemoved, true);
assert.ok(!fs.existsSync(path.join(root, "specs/lunch-vote")));
});
test("specs: only a folder directly under specs/ is a spec; archive verification fails loudly", () => {
const root = specFixture();
write(root, "src/app.js", "x\n");
@@ -901,7 +1020,6 @@ test("commit-msg: @ and - paths are quoted, git add ends its options, risky subj
assert.equal(files.json.add, "git add -- '@types/x.d.ts' '-weird.md' src/a@b.js");
assert.equal(files.json.commit, 'git commit -m "Fix" -m "AI Assisted"');
assert.equal(files.json.command, `${files.json.add} && ${files.json.commit}`);
assert.equal(C("--subject", "Fix", "--add-all").json.add, "git add -A");
const bare = C("--subject", "Fix").json;
assert.equal(bare.add, null);
assert.equal(bare.command, bare.commit);
+43 -6
View File
@@ -9,10 +9,10 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { execFileSync, spawn } from "node:child_process";
import { execFileSync, spawn, spawnSync } from "node:child_process";
import http from "node:http";
import { meterView } from "../src/web-console/public/meter.js";
import { STATE_LOCK_FILE } from "../src/web-console/files.mjs";
import { STATE_LOCK_FILE, lockStale } from "../src/web-console/files.mjs";
import { cwdHash, readLedger, repoRoots } from "../src/web-console/sessions.mjs";
import { validate } from "../src/web-console/patches.mjs";
import { WORKSPACE_FILE } from "../src/web-console/workspace.mjs";
@@ -241,6 +241,34 @@ test("a lock left by a writer that died is broken rather than waited on for good
}
});
// Age alone used to break a lock: a writer slowed past LOCK_STALE_MS by a busy
// machine lost its lock to the next writer, and both wrote. The holder's pid
// decides now; age only breaks a lock that names no live holder.
test("a lock whose holder is still running is kept past the stale age; age breaks only an unnamed one", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-lock-"));
const lock = path.join(dir, STATE_LOCK_FILE);
const holder = spawn(process.execPath, ["-e", "setTimeout(() => {}, 60000)"], { stdio: "ignore", windowsHide: true });
try {
await new Promise((r) => holder.once("spawn", r));
const old = new Date(Date.now() - 60000);
fs.writeFileSync(lock, String(holder.pid));
fs.utimesSync(lock, old, old);
assert.equal(lockStale(lock), false, "a live holder keeps its lock, however old");
holder.kill();
await new Promise((r) => (holder.exitCode !== null || holder.signalCode ? r() : holder.once("exit", r)));
assert.equal(lockStale(lock), true, "a gone holder frees it");
fs.writeFileSync(lock, "");
assert.equal(lockStale(lock), false, "an unnamed young lock is a holder mid-create");
fs.utimesSync(lock, old, old);
assert.equal(lockStale(lock), true, "an unnamed old lock is a crash left behind");
} finally {
holder.kill();
fs.rmSync(dir, { recursive: true, force: true });
}
});
// A young handle and a live pid are what a server that died a minute ago
// leaves behind for any process to inherit. Only /health is proof.
test("stop never kills a live process that does not answer /health as ours", () => {
@@ -345,7 +373,7 @@ test("wait reads --seconds 6s as six seconds, not as nothing", () => {
}
});
test("only open leaves the console-dir pointer; status, help and a bad command do not", () => {
test("only an installed console's open leaves the console-dir pointer; status, help, a bad command and a source checkout's open do not", () => {
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-pointer-"));
const env = { PLAN2CODE_CONSOLE_HOME: home, PLAN2CODE_MODELS_DIR: path.join(home, "plan2code") };
const pointer = path.join(home, "console-dir");
@@ -356,9 +384,18 @@ test("only open leaves the console-dir pointer; status, help and a bad command d
const usage = cli(["nope"], { env, expectFail: true });
assert.match(usage.stderr, /keep/, "the usage line names every command");
assert.equal(fs.existsSync(pointer), false);
const opened = cli(["open", "--no-open"], { env });
assert.equal(fs.readFileSync(pointer, "utf8").trim(), path.join(ROOT, "src", "web-console"));
cli(["stop", "--session", opened.json.sid, "--force"], { env });
// A source checkout never points every skill stub at itself.
const fromSource = cli(["open", "--no-open"], { env });
assert.equal(fs.existsSync(pointer), false, "a source checkout leaves no pointer");
cli(["stop", "--session", fromSource.json.sid, "--force"], { env });
// An installed console (a version folder) does.
const installed = path.join(home, "9.9.9");
fs.cpSync(path.join(ROOT, "src", "web-console"), installed, { recursive: true });
const res = spawnSync(process.execPath, [path.join(installed, "console.mjs"), "open", "--no-open"], { env: { ...ENV, ...env }, encoding: "utf8", cwd: ROOT });
assert.equal(res.status, 0, res.stderr);
assert.equal(fs.readFileSync(pointer, "utf8").trim(), installed);
const sid = JSON.parse(res.stdout.trim().split(/\r?\n/)[0]).sid;
spawnSync(process.execPath, [path.join(installed, "console.mjs"), "stop", "--session", sid, "--force"], { env: { ...ENV, ...env }, encoding: "utf8", cwd: ROOT });
} finally {
fs.rmSync(home, { recursive: true, force: true });
}
+130 -3
View File
@@ -7,6 +7,7 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { spawn, spawnSync } from "node:child_process";
import { pathToFileURL } from "node:url";
import { parseArgs } from "../src/web-console/files.mjs";
import { BASE, cli, consoleSession, cookieFor, ENV, HOME, payload, ROOT } from "./web-console-test-helpers.mjs";
@@ -102,7 +103,7 @@ test("a token that starts with -- survives the trip to the server", async () =>
windowsHide: true,
});
assert.equal(res.status, 2, `refused: ${JSON.stringify(tokenArgs)}`);
assert.match(res.stderr, /--token=<token> is required/);
assert.match(res.stderr, /a token is required/);
}
const child = spawn(process.execPath, [SERVER_JS, `--session=${dir}`, "--token=--dashy", `--project=${dir}`], {
@@ -120,8 +121,8 @@ test("a token that starts with -- survives the trip to the server", async () =>
});
child.on("exit", () => reject(new Error("server exited before it was ready")));
});
assert.ok(ready.url.endsWith("/s/--dashy/"));
const res = await fetch(ready.url, { redirect: "manual" });
assert.equal(ready.url, `http://127.0.0.1:${ready.port}/`, "the ready line carries no token");
const res = await fetch(`${ready.url}s/--dashy/`, { redirect: "manual" });
assert.equal(res.status, 302);
assert.ok(res.headers.get("set-cookie").startsWith(`p2c_console_${ready.port}=--dashy;`));
} finally {
@@ -129,6 +130,56 @@ test("a token that starts with -- survives the trip to the server", async () =>
}
});
// The command line of a process is readable by anyone on the machine (ps,
// Task Manager), and server.log is the server's stdout. Neither may carry the
// session token: `open` hands it over in a one-shot file the server deletes.
function commandLineOf(pid) {
const res =
process.platform === "win32"
? spawnSync("powershell", ["-NoProfile", "-Command", `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`], {
encoding: "utf8",
windowsHide: true,
})
: spawnSync("ps", ["-o", "args=", "-p", String(pid)], { encoding: "utf8" });
return String(res.stdout || "");
}
test("the session token is in neither the server's arguments nor server.log", async () => {
const s = consoleSession(["--file", payload("token-off-argv.json", BASE)]);
try {
const token = s.opened.url.match(/\/s\/([^/]+)\//)[1];
let handle = null;
const runtime = path.join(HOME, "runtime");
for (const bucket of fs.readdirSync(runtime)) {
const file = path.join(runtime, bucket, s.sid + ".json");
if (fs.existsSync(file)) handle = JSON.parse(fs.readFileSync(file, "utf8"));
}
assert.ok(handle?.pid, "the server wrote its handle");
assert.equal(handle.token, token, "the server took the token open made");
const args = commandLineOf(handle.pid);
assert.match(args, /server\.mjs/, "read the server's own command line");
assert.match(args, /--token-file=server-token-/);
assert.ok(!args.includes(token), "the token is not on the command line");
const log = fs.readFileSync(path.join(s.session, "server.log"), "utf8");
assert.match(log, /"ready"/, "the server logged its ready line");
assert.ok(!log.includes(token), "the token is not in server.log");
assert.deepEqual(
fs.readdirSync(s.session).filter((f) => f.startsWith("server-token-")),
[],
"the one-shot token file is gone once read"
);
// The page still signs in with it.
const res = await fetch(s.base + "/state", { headers: { cookie: cookieFor(s.base, token), connection: "close" } });
assert.equal(res.status, 200);
await res.arrayBuffer();
} finally {
cli(["stop", "--session", s.sid, "--force"]);
}
});
test("a cancel that could not be written answers 500 and tells nobody", async () => {
const s = consoleSession(["--file", payload("cancel-500.json", BASE)]);
try {
@@ -226,3 +277,79 @@ test("an image block outside the session's shots folder, or not an image, is ref
cli(["stop", "--session", s.sid, "--force"]);
}
});
// A route callback that threw used to run twice (readBody's catch fed the
// throw back in as a parse error) or leave the request hanging (readRaw). It
// now answers once with 400, runs once, and the throw still reaches the
// process's uncaughtException handler, which the real server logs. Run in a
// child so that rethrow lands on a handler like the server's, not the runner's.
test("a route callback that throws answers once with 400 and runs once", () => {
const routes = path.join(ROOT, "src", "web-console", "routes.mjs");
const script = `
import http from "node:http";
import { readBody, readRaw } from ${JSON.stringify(pathToFileURL(routes).href)};
const caught = [];
process.on("uncaughtException", (e) => caught.push(e.message));
const calls = { body: 0, raw: 0 };
const server = http.createServer((req, res) => {
if (req.url === "/body") return readBody(req, res, () => { calls.body++; throw new Error("body boom"); });
if (req.url === "/half") return readBody(req, res, () => { calls.body++; res.writeHead(200); res.write("x"); throw new Error("half boom"); });
return readRaw(req, res, 1024, () => { calls.raw++; throw new Error("raw boom"); });
});
server.listen(0, "127.0.0.1", async () => {
const base = "http://127.0.0.1:" + server.address().port;
const out = {};
for (const p of ["/body", "/raw", "/half"]) {
const r = await fetch(base + p, { method: "POST", body: p === "/raw" ? "bytes" : "{}" });
out[p] = { status: r.status, text: await r.text() };
}
await new Promise((r) => setTimeout(r, 50));
process.stdout.write(JSON.stringify({ out, calls, caught }));
server.close();
});
`;
const res = spawnSync(process.execPath, ["--input-type=module", "-e", script], { encoding: "utf8", timeout: 15000, windowsHide: true });
assert.equal(res.status, 0, res.stderr);
const { out, calls, caught } = JSON.parse(res.stdout);
assert.equal(out["/body"].status, 400);
assert.match(out["/body"].text, /bad request/);
assert.equal(out["/raw"].status, 400);
assert.deepEqual([out["/half"].status, out["/half"].text], [200, "x"], "a started answer is ended, not answered twice");
assert.deepEqual(calls, { body: 2, raw: 1 }, "each callback ran once");
assert.deepEqual(caught.sort(), ["body boom", "half boom", "raw boom"], "every throw still reaches the process handler");
});
// ── The metrics scrape pattern: one shared source, no drift ──────────────────
test("the bait scanner, the skill scripts and the collector read one metrics pattern", async () => {
const { SCRAPE } = await import("../src/skill-scripts/common.mjs");
const shared = JSON.parse(fs.readFileSync(path.join(ROOT, "src", "web-console", "metrics-pattern.json"), "utf8"));
const collectorCopy = fs.readFileSync(path.join(ROOT, "plan2code-metrics", "src", "metrics-pattern.json"), "utf8");
assert.equal(
collectorCopy,
fs.readFileSync(path.join(ROOT, "src", "web-console", "metrics-pattern.json"), "utf8"),
"plan2code-metrics/src/metrics-pattern.json must be a byte-for-byte copy of src/web-console/metrics-pattern.json",
);
const bySource = (re) => `${re.source}/${re.flags}`;
const scripts = new Map(SCRAPE.map((s) => [s.name, bySource(s.re)]));
for (const c of shared.confidence) assert.equal(scripts.get(c.name), `${c.source}/${c.flags}`, `skill scripts' "${c.name}" drifted from the shared pattern`);
for (const b of shared.breakdown) assert.equal(scripts.get(`bare ${b.name} + number`), `${b.source}/${b.flags}`, `skill scripts' ${b.name} pattern drifted from the shared pattern`);
assert.equal(SCRAPE.length, shared.confidence.length + shared.breakdown.length);
});
test("an ordinary table row that pairs Risk with a number is accepted, the real scrape shapes are refused", async () => {
const { proseProblems } = await import("../src/web-console/patches.mjs");
for (const ok of [
"| Risk | 3 | High |",
"| Requirements | 7 | Medium | Owner |",
"| R2 | Slow build | A risk to the plan | High |",
"Risk-assessment 22/25",
]) {
assert.deepEqual(proseProblems(ok), [], ok);
}
for (const bad of ["Risk: 3", "Risk 3", "Requirements 22 of 25", "| Requirements | 24 |", "| Integration | 23/25 |", "- Feasibility: 23"]) {
const found = proseProblems(bad);
assert.equal(found.length, 1, bad);
assert.match(found[0], /metrics collector scrapes that pattern/);
}
});
+42
View File
@@ -9,6 +9,7 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import http from "node:http";
import { spawn } from "node:child_process";
// The page's pure answer-shaping logic. app.js itself cannot be imported here
// (it touches `document` at module scope and starts a session on import), which
// is exactly why this lives in its own file.
@@ -24,8 +25,10 @@ import {
} from "../src/web-console/public/answers.js";
import { WORKFLOWS } from "../src/web-console/public/skills.js";
import {
ENV,
HOME,
MODELS_DIR,
ROOT,
cookieFor,
cli,
payload,
@@ -1251,3 +1254,42 @@ test("a finish posted while stopWarning is set is refused naming stopWarning, an
cli(["stop", "--session", opened.json.sid, "--force"]);
}
});
// The four-hour cap used to exit with answers nobody had collected, stranding
// the person's send. A pending result now holds the server past the cap; once
// a wait collects it (consumedAt), the cap applies again. A control server
// with a collected result shows when a 20s tick has passed.
test("a pending result holds the server past its lifetime cap; once collected it exits", async () => {
const SERVER_JS = path.join(ROOT, "src", "web-console", "server.mjs");
const start = (label, consumed) => {
const dir = fs.mkdtempSync(path.join(HOME, `max-life-${label}-`));
fs.writeFileSync(path.join(dir, "state.json"), JSON.stringify({ sid: path.basename(dir), phase: "collecting" }));
const result = { actions: [{ i: "q1", type: "answer", kind: "choice", k: "A" }], reply: "Export format: a", ...(consumed ? { consumedAt: new Date().toISOString() } : {}) };
fs.writeFileSync(path.join(dir, "result.json"), JSON.stringify(result));
const child = spawn(process.execPath, [SERVER_JS, `--session=${dir}`, "--token=t", `--project=${dir}`, "--max-life-ms=300"], {
env: ENV,
stdio: "ignore",
windowsHide: true,
});
const exited = new Promise((r) => child.once("exit", r));
return { dir, child, exited, gone: false };
};
const held = start("held", false);
const control = start("control", true);
held.exited.then(() => (held.gone = true));
try {
// The control exits on the first tick past its cap...
await Promise.race([control.exited, new Promise((_, no) => setTimeout(() => no(new Error("the control server never hit its cap")), 45000))]);
assert.match(fs.readFileSync(path.join(control.dir, "events.ndjson"), "utf8"), /"reason":"max-life"/);
// ...and that same tick left the held server running.
assert.equal(held.gone, false, "a pending result keeps the server past its cap");
const file = path.join(held.dir, "result.json");
fs.writeFileSync(file, JSON.stringify({ ...JSON.parse(fs.readFileSync(file, "utf8")), consumedAt: new Date().toISOString() }));
await Promise.race([held.exited, new Promise((_, no) => setTimeout(() => no(new Error("the collected server never exited")), 45000))]);
assert.match(fs.readFileSync(path.join(held.dir, "events.ndjson"), "utf8"), /"reason":"max-life"/);
} finally {
held.child.kill();
control.child.kill();
}
});
+46
View File
@@ -83,6 +83,52 @@ test("a Quick question typed in Ask reaches the agent under chat, and the agent'
assert.match(await textOf(s.page.locator(".ask-counter")), /1/);
});
// What a person hears break: every redraw rewrote the Ask log and the footer
// summary, both live regions, so a screen reader read the whole conversation
// and the summary again on each agent post or tick, not only what was new.
test("a redraw leaves the Ask log and the footer summary untouched, and a new message only appends its row", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await openAsk(s);
await askQuestion(s, "Where does the export live?");
const [asked] = messages(collect(s));
s.post({ chat: { replies: [{ id: "r1", re: asked.seq, conversation: 1, md: "It lives in `exports/`." }] } });
await s.page.locator(".ask-row.agent").getByText("It lives in").waitFor();
await settled(s.page, ".ask-list");
// Count every change inside both live regions from here on, and tag the rows on the page.
await s.page.evaluate(() => {
window.__live = { list: 0, footer: 0 };
const list = document.querySelector(".ask-list");
for (const row of list.children) row.__kept = true;
new MutationObserver((records) => (window.__live.list += records.length)).observe(list, {
subtree: true,
childList: true,
attributes: true,
characterData: true,
});
new MutationObserver((records) => (window.__live.footer += records.length)).observe(document.getElementById("footer-summary"), {
subtree: true,
childList: true,
attributes: true,
characterData: true,
});
});
// An agent post that changes nothing in the log or the summary redraws the page all the same:
// the new document gets its tab, and the Ask tab stays open on the same list.
s.post({ docs: [{ id: "notes", title: "Export notes", blocks: [{ id: "b1", state: "settled", md: "Nothing yet." }] }] });
await s.page.locator("nav").getByRole("button", { name: "Export notes" }).waitFor();
await settled(s.page, "#main");
assert.equal(await s.page.evaluate(() => [...document.querySelector(".ask-list").children].every((row) => row.__kept)), true, "the Ask tab shows the same rows");
assert.deepEqual(await s.page.evaluate(() => window.__live), { list: 0, footer: 0 }, "the redraw rewrote a live region");
// A second question appends one row; the two already there stay the same nodes.
await askQuestion(s, "And the importer?");
await s.page.locator(".ask-row.person").getByText("And the importer?").waitFor();
const rows = await s.page.evaluate(() => [...document.querySelector(".ask-list").children].map((row) => Boolean(row.__kept)));
assert.deepEqual(rows, [true, true, false], "only the new message's row is new");
});
// What a person sees break: a prompt the agent wrote for a new conversation with no
// Copy button, or one that tells them to "paste it into the Ask tab" as though it
// were a terminal command.
+50
View File
@@ -408,6 +408,36 @@ test("on a sign-off card, approve and yes are outlined in the accent until picke
assert.notEqual(await outlineOf(card.getByRole("button", { name: "Not yet" })), accent);
});
// What a person hears break: a screen reader names the verdicts on a sign-off
// card but never says which one is picked.
test("a sign-off card's verdicts expose aria-pressed, kept in step with each click", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "implement" });
const card = await ask(s, {
id: "so1",
kind: "review",
title: "Sign off",
body: "Read it.",
verdicts: [{ id: "approve", label: "Approve this phase" }, { id: "changes", label: "I want changes" }],
});
const approve = card.getByRole("button", { name: "Approve this phase" });
const changes = card.getByRole("button", { name: "I want changes" });
const pressed = async () => [await approve.getAttribute("aria-pressed"), await changes.getAttribute("aria-pressed")];
assert.deepEqual(await pressed(), ["false", "false"], "nothing picked yet");
await approve.click();
await s.page.waitForFunction(() => document.querySelector("#btn-send:not(:disabled)"));
assert.deepEqual(await pressed(), ["true", "false"], "approve picked");
assert.equal(await card.getByRole("button", { name: "Approve this phase", pressed: true }).count(), 1);
await changes.click();
await s.page.waitForFunction(() => document.querySelector('[data-item="so1"] button[aria-pressed="true"]')?.textContent.includes("I want changes"));
assert.deepEqual(await pressed(), ["false", "true"], "the pick moved to changes");
await changes.click();
await s.page.waitForFunction(() => !document.querySelector('[data-item="so1"] button[aria-pressed="true"]'));
assert.deepEqual(await pressed(), ["false", "false"], "a second click takes the pick back");
});
// What a person sees break: Skip this one turns into a full-size button, or
// the quick answer under a note box does.
test("Skip this one and a comment box's quick answer are the same small accent button", async (t) => {
@@ -666,6 +696,26 @@ test("Clear on a one-answer question takes back the pick and the words, and a se
assert.equal(await clear.count(), 0, "a sent card cannot be cleared");
});
// What a person sees break: on a question taller than the window, Clear sat at
// the card's foot, out of sight until the options were scrolled past.
test("Clear on a tall question reads \"Clear answer\" and stays on screen while the options scroll", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
await s.page.setViewportSize({ width: 1280, height: 520 });
const options = Array.from({ length: 14 }, (_, i) => opt(String.fromCharCode(65 + i), `Choice ${i + 1}`));
const card = await ask(s, { id: "c1", kind: "choice", title: "Which", body: "Which one?", options });
const clear = card.getByRole("button", { name: "Clear your answer to this question" });
assert.equal((await clear.innerText()).trim(), "Clear answer");
assert.equal(await clear.locator("svg").count(), 1, "an icon leads the label");
const visible = () => clear.evaluate((b) => {
const c = b.getBoundingClientRect();
const card = b.closest(".card").getBoundingClientRect();
return c.top >= card.top && c.bottom <= card.bottom + 1 && c.bottom <= window.innerHeight;
});
assert.equal(await visible(), true, "in view with the card scrolled to the top");
await scrollCard(card, "end");
assert.equal(await visible(), true, "still in view at the foot of the card");
});
// What a person sees break: a note typed on a card is dropped by the verdict,
// or is lost when the verdict comes first.
test("a note's comment field rides along with the answer, typed before or after the pick", async (t) => {
+25
View File
@@ -671,6 +671,31 @@ test("Cleanup scans the console home and lists an old session folder with its si
assert.equal(await s.page.locator("#cleanup-delete").isHidden(), true);
});
// The server refuses to delete a completed spec git does not track as it
// stands, so the list shows it apart as kept, never as something to delete.
test("Cleanup lists an untracked completed spec as kept, out of the total and out of Delete", async (t) => {
noSavedLooks(t);
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
const spec = path.join(s.project, "specs--completed", "old-spec");
fs.mkdirSync(spec, { recursive: true });
fs.writeFileSync(path.join(spec, "overview.md"), "x".repeat(2000));
backdate(path.join(spec, "overview.md"));
backdate(spec);
await s.page.click("#btn-looks");
await s.page.click("#prefs-tab-system");
await s.page.click("#cleanup-scan");
const list = s.page.locator("#cleanup-list");
const kept = list.locator(".cleanup-kept").filter({ hasText: "old-spec" });
await kept.waitFor();
assert.match(await textOf(kept), /specs--completed\/old-spec\/\s*kept: git does not track it as it stands/);
assert.equal(await list.locator(".cleanup-row:not(.cleanup-kept)").filter({ hasText: "old-spec" }).count(), 0, "not listed to delete");
const summary = list.locator(".cleanup-summary");
if (await summary.count()) assert.doesNotMatch(await textOf(summary), /completed spec/, "not counted in the summary");
assert.match(await textOf(s.page.locator("#cleanup-status")), /1 old completed spec is kept: git does not track it as it stands\./);
assert.equal(fs.existsSync(spec), true);
});
/* ------------------------------------------------------------- the tabs */
const tabNames = async (s) => (await s.page.locator("#prefs-tabs [role=tab] .prefs-tab-label").allInnerTexts()).map((x) => x.trim());
+92 -3
View File
@@ -37,6 +37,8 @@ import {
terminalLine,
} from "../src/web-console/sessions.mjs";
import { validate } from "../src/web-console/patches.mjs";
// Scrubs this process's git config, so the Cleanup fixtures and git-repo.mjs agree.
import { gitInit } from "./skill-script-helpers.mjs";
import { joinedCss } from "./css-helpers.mjs";
import {
ROOT,
@@ -439,6 +441,13 @@ test("cleanup finds old sessions and strays in both folders, and keeps every pro
];
stray(path.join(consoleDir, "p1.json"), "12345");
put(path.join(consoleDir, "runtime", "x.json"));
// The shared console install, one folder per version, however old: never a stray.
const installed = stray(path.join(consoleDir, "3.0.4", "console.mjs"), "x");
backdate(path.dirname(installed));
kept.push(installed);
// A folder that is not a version stays a stray.
backdate(put(path.join(consoleDir, "3.0", "x.txt")));
backdate(path.join(consoleDir, "3.0"));
backdate(put(path.join(plan2code, "console-dev", "sessions", "x.txt"), "abc"));
backdate(path.join(plan2code, "console-dev"));
// An old folder with a file rewritten just now: the folder's own mtime
@@ -463,6 +472,7 @@ test("cleanup finds old sessions and strays in both folders, and keeps every pro
const opts = { consoleDir, plan2codeDir: plan2code, skipSid: "20250801-101010-bbbbbb" };
const { items, bytes } = await cleanupFindings(opts);
assert.deepEqual(items.map((i) => i.id).sort(), [
"console:3.0",
"console:looks.json.456.tmp",
"console:p1.json",
"root:console-dev",
@@ -478,7 +488,7 @@ test("cleanup finds old sessions and strays in both folders, and keeps every pro
// A console running from another home never reaches the folder above it.
const elsewhere = await cleanupFindings({ ...opts, plan2codeDir: path.join(plan2code, "other") });
assert.deepEqual(elsewhere.items.map((i) => i.where).sort(), ["console", "console", "session"]);
assert.deepEqual(elsewhere.items.map((i) => i.where).sort(), ["console", "console", "console", "session"]);
// Only ids a fresh scan still finds are removed; anything else is ignored.
const done = await removeCleanup(
@@ -510,6 +520,8 @@ test("cleanup lists the project's completed specs untouched for 30 days, and rem
return p;
};
fs.mkdirSync(consoleDir, { recursive: true });
fs.mkdirSync(project, { recursive: true });
const g = gitInit(project);
const opts = { consoleDir, plan2codeDir: path.join(base, "home"), skipSid: "x", project };
// No specs--completed/ at all is just nothing to list.
@@ -523,6 +535,9 @@ test("cleanup lists the project's completed specs untouched for 30 days, and rem
put(path.join(completed, "touched-spec", "overview.md"));
backdate(put(path.join(completed, "README.md")));
backdate(put(path.join(project, "specs", "live-spec", "overview.md")));
// Committed, so Cleanup may delete it (an untracked one is refused: see the next test).
g("add", "specs--completed/old-spec");
g("commit", "-q", "-m", "archive old-spec");
const { items } = await cleanupFindings(opts);
assert.deepEqual(items.map((i) => i.id), ["completed:old-spec"]);
@@ -544,6 +559,78 @@ test("cleanup lists the project's completed specs untouched for 30 days, and rem
}
});
test("cleanup refuses a completed spec git does not track, says why, and still deletes a tracked one and everything else", async () => {
const base = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-cleanup-guard-"));
const home = path.join(base, "home");
const consoleDir = path.join(home, "console");
const project = path.join(base, "project");
const completed = path.join(project, "specs--completed");
try {
const put = (p, body = "{}") => {
fs.mkdirSync(path.dirname(p), { recursive: true });
fs.writeFileSync(p, body);
return p;
};
const oldSpec = (name, file = "overview.md") => {
backdate(put(path.join(completed, name, file), "abc"));
backdate(path.join(completed, name));
};
fs.mkdirSync(consoleDir, { recursive: true });
fs.mkdirSync(project, { recursive: true });
const g = gitInit(project);
// The default: Init gitignores the archive, so only a forced add tracks a spec.
put(path.join(project, ".gitignore"), "specs--completed/\n");
oldSpec("tracked-spec");
oldSpec("untracked-spec");
oldSpec("partly-spec");
oldSpec("edited-spec");
g("add", ".gitignore");
g("add", "-f", "specs--completed/tracked-spec", "specs--completed/partly-spec", "specs--completed/edited-spec");
g("commit", "-q", "-m", "archive");
// A file added after the commit: git could not give it back.
oldSpec("partly-spec", "notes.md");
// A tracked file edited after the commit: git could give back only the old text.
backdate(put(path.join(completed, "edited-spec", "overview.md"), "edited"));
backdate(path.join(completed, "edited-spec"));
// Not a spec: removed as before, in the same call.
backdate(put(path.join(consoleDir, "stray.json")));
const opts = { consoleDir, plan2codeDir: home, skipSid: "x", project };
const ids = ["completed:tracked-spec", "completed:untracked-spec", "completed:partly-spec", "completed:edited-spec", "console:stray.json"];
assert.deepEqual((await cleanupFindings(opts)).items.map((i) => i.id).sort(), [...ids].sort(), "the scan still lists all of them");
const done = await removeCleanup(ids, opts);
assert.deepEqual(done.removed.sort(), ["completed:tracked-spec", "console:stray.json"]);
assert.deepEqual(done.refused.sort(), ["completed:edited-spec", "completed:partly-spec", "completed:untracked-spec"]);
assert.deepEqual(done.failed, []);
assert.equal(fs.existsSync(path.join(completed, "tracked-spec")), false, "a tracked spec is deleted");
assert.equal(fs.existsSync(path.join(consoleDir, "stray.json")), false);
for (const name of ["untracked-spec", "partly-spec", "edited-spec"]) assert.ok(fs.existsSync(path.join(completed, name, "overview.md")), name + " is kept");
assert.ok(fs.existsSync(path.join(completed, "partly-spec", "notes.md")));
assert.match(done.refusal, /^Kept 3 completed specs git does not track as they stand, so deleting them would lose them for good: /);
assert.ok(done.refusal.includes("specs--completed/untracked-spec/"), done.refusal);
assert.ok(done.refusal.includes("specs--completed/partly-spec/"), done.refusal);
assert.ok(done.refusal.includes("specs--completed/edited-spec/"), done.refusal);
assert.equal(fs.readFileSync(path.join(completed, "edited-spec", "overview.md"), "utf8"), "edited", "the uncommitted edit survives");
assert.equal(done.refusal.includes("specs--completed/tracked-spec/"), false, "the deleted spec is not named");
// A project that is not a repository at all: nothing there is tracked.
const loose = path.join(base, "loose");
backdate(put(path.join(loose, "specs--completed", "only-spec", "overview.md")));
backdate(path.join(loose, "specs--completed", "only-spec"));
const alone = await removeCleanup(["completed:only-spec"], { ...opts, project: loose });
assert.deepEqual(alone.removed, []);
assert.deepEqual(alone.refused, ["completed:only-spec"]);
assert.equal(alone.refusal, "Kept specs--completed/only-spec/: git does not track it as it stands, so deleting it would lose it for good. Commit it first, or delete it yourself once it is backed up.");
assert.ok(fs.existsSync(path.join(loose, "specs--completed", "only-spec")));
// Nothing refused: no line.
assert.equal((await removeCleanup([], opts)).refusal, "");
} finally {
fs.rmSync(base, { recursive: true, force: true });
}
});
test("User Preferences: wider, its body scrolls and the button bar stays put, without touching dialogs that borrow .looks", () => {
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
const css = joinedCss();
@@ -871,9 +958,11 @@ test("/app.css is the style files joined in CSS_ORDER with the accent rules last
// The skills the build writes carry public/styles/ with every file in CSS_ORDER,
// and a console started from that tree serves the same /app.css as this one.
test("the built skills tree serves the same /app.css as the source console", async (t) => {
test("the built shared console serves the same /app.css as the source console", async (t) => {
const { CSS_ORDER, asset } = await import("../src/web-console/static.mjs");
const built = path.join(ROOT, "skills", "plan2code", "references", "web-console");
// The console is built once, as skills/_console/<version>/, and every skill forwards to it.
const version = JSON.parse(fs.readFileSync(path.join(ROOT, "version.json"), "utf8")).version;
const built = path.join(ROOT, "skills", "_console", version);
// npm test builds first; a bare run of this file may not have.
if (!fs.existsSync(path.join(built, "console.mjs"))) return t.skip("skills/ is not built: run npm run build:skills");
for (const f of CSS_ORDER) assert.ok(fs.existsSync(path.join(built, "public", "styles", f)), `the build is missing public/styles/${f}`);
+3 -2
View File
@@ -39,7 +39,7 @@ import { DEFAULT_LOOKS, looks, resetLooks } from "../src/web-console/public/look
import { ROLE_NOT_SET } from "../src/web-console/public/starters.js";
import { RED_AT, YELLOW_AT } from "../src/web-console/public/meter.js";
import { REMOTE_FOLD } from "../src/web-console/public/git-board.js";
import { readLedger, SESSION_MAX_AGE_MS, sweepUploads, UPLOAD_MAX_AGE_MS } from "../src/web-console/sessions.mjs";
import { readLedger, SERVER_MAX_LIFE_MS, SESSION_MAX_AGE_MS, sweepUploads, UPLOAD_MAX_AGE_MS } from "../src/web-console/sessions.mjs";
import { applyPatch, validate } from "../src/web-console/patches.mjs";
import { joinedCss } from "./css-helpers.mjs";
import {
@@ -897,7 +897,8 @@ const helpFacts = () => ({
adriftMinutes: sourceConst("public/selectors.js", /const ADRIFT_MS = ([^;]+);/, "ADRIFT_MS") / 60000,
maxUploadMb: sourceConst("public/uploads.js", /const MAX_UPLOAD_BYTES = ([^;]+);/, "MAX_UPLOAD_BYTES") / 1024 / 1024,
idleMinutes: sourceConst("server.mjs", /const IDLE_MS = Number\(args\[[^\]]+\] \|\| ([^)]+)\)/, "IDLE_MS") / 60000,
maxLifeHours: sourceConst("server.mjs", /const MAX_LIFE_MS = Number\(args\[[^\]]+\] \|\| ([^)]+)\)/, "MAX_LIFE_MS") / 3600000,
// server.mjs and stop share this one constant (sessions.mjs).
maxLifeHours: SERVER_MAX_LIFE_MS / 3600000,
closedTabMinutes: sourceConst("server.mjs", /\(IDLE_MS - ([^)]+)\)/, "the closed-tab shutdown") / 60000,
accentCount: Object.keys(ACCENTS).length,
// The one fact quoted as several numbers: each span holds one of the widths.
+40 -7
View File
@@ -1,5 +1,6 @@
// Web console tests, the shape of the source: no console file grows past
// 3,000 lines, and the files lib.mjs split into stand on their own.
// 3,000 lines, the files lib.mjs split into stand on their own, and the
// light theme's faintest ink meets WCAG AA contrast.
// Run with: node --test scripts/test-web-console-shape.mjs
import test from "node:test";
@@ -293,11 +294,19 @@ test("shape: CSS_ORDER names every file in public/styles/ once, and none is serv
for (const rel of SERVABLE) assert.ok(!rel.startsWith("styles/") && !CSS_ORDER.includes(rel), `${rel} must not be served on its own`);
});
// The files table in AGENTS-architecture.md gives every console file a row,
// The files tables in the AGENTS-architecture-*.md area files give every console file a row,
// so a contributor finds where a job lives without searching. A row's first
// cell names the file by its path under src/web-console/ (backticked; one cell
// may name several files, joined by "·").
const ARCHITECTURE_DOC = path.join(ROOT, ".agents-docs", "AGENTS-architecture.md");
const DOCS_DIR = path.join(ROOT, ".agents-docs");
// Every architecture file (the index and its area files): the tables run across several.
function architectureMarkdown() {
return fs.readdirSync(DOCS_DIR)
.filter((f) => /^AGENTS-architecture(-[a-z-]+)?\.md$/.test(f))
.sort()
.map((f) => fs.readFileSync(path.join(DOCS_DIR, f), "utf8"))
.join("\n");
}
// The paths the files table names, from the first cell of each table row.
function tableFiles(markdown) {
@@ -315,11 +324,11 @@ function undocumented(dir, markdown) {
const named = tableFiles(markdown);
return sourceFiles(dir)
.filter((p) => !named.has(p))
.map((p) => `${p} has no row in the files table of AGENTS-architecture.md: add one with its one-line job`);
.map((p) => `${p} has no row in the files tables of the AGENTS-architecture area files: add one with its one-line job`);
}
test("shape: every console file has a row in the files table of AGENTS-architecture.md", () => {
const problems = undocumented(CONSOLE_DIR, fs.readFileSync(ARCHITECTURE_DOC, "utf8"));
test("shape: every console file has a row in the files tables of the AGENTS-architecture area files", () => {
const problems = undocumented(CONSOLE_DIR, architectureMarkdown());
assert.deepEqual(problems, []);
});
@@ -331,7 +340,7 @@ test("shape: the docs-table check names a file with no row, and passes one that
fs.writeFileSync(path.join(dir, "public", "b.js"), "");
const table = "| File | Role |\n|---|---|\n| `a.mjs` | the first |\n";
assert.deepEqual(undocumented(dir, table), [
"public/b.js has no row in the files table of AGENTS-architecture.md: add one with its one-line job",
"public/b.js has no row in the files tables of the AGENTS-architecture area files: add one with its one-line job",
]);
assert.deepEqual(undocumented(dir, `${table}| \`public/b.js\` · \`x.js\` | the second |\n`), []);
} finally {
@@ -384,3 +393,27 @@ test("shape: the redraw-safe check names a locator's style read and scroll, and
].join("\n");
assert.deepEqual(racyPageReads("x.mjs", fine), []);
});
// The WCAG 2 contrast ratio of two "#rrggbb" colors.
function contrastRatio(a, b) {
const lum = (hex) => {
const [r, g, bl] = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255).map((v) => (v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4));
return 0.2126 * r + 0.7152 * g + 0.0722 * bl;
};
const [hi, lo] = [lum(a), lum(b)].sort((x, y) => y - x);
return (hi + 0.05) / (lo + 0.05);
}
test("shape: the light theme's faintest ink, --ink-3, reads at 4.5:1 or better on --bg", () => {
const css = fs.readFileSync(path.join(CONSOLE_DIR, "public", "styles", "tokens.css"), "utf8");
// The first :root block is the light theme; the dark ones sit under their own selectors.
const light = css.match(/^:root \{([^}]*)\}/m);
assert.ok(light, "tokens.css opens with a :root block");
const token = (name) => {
const m = light[1].match(new RegExp(`--${name}:\\s*(#[0-9a-fA-F]{6})\\s*;`));
assert.ok(m, `--${name} is a #rrggbb color in the light :root block`);
return m[1];
};
const ratio = contrastRatio(token("ink-3"), token("bg"));
assert.ok(ratio >= 4.5, `--ink-3 ${token("ink-3")} on --bg ${token("bg")} is ${ratio.toFixed(2)}:1, under 4.5:1`);
});
+96 -4
View File
@@ -8,11 +8,13 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { SPEC_STATES as TABLE, stateFor } from "../src/web-console/public/spec-states.js";
import { SKILLS } from "../src/web-console/public/skills.js";
import { SKILL_CATALOG, cardAvailability, defaultSpec, launchVariant } from "../src/web-console/public/answers.js";
import { scanProject } from "../src/web-console/scan.mjs";
import { MARKERS, TASK_LINE_RE, TASK_ID_RE, CHECKBOX_RE, STATUS_RE, statusOf, countTasks } from "../src/web-console/spec-files.mjs";
import { MARKERS, TASK_LINE_RE, TASK_ID_RE, CHECKBOX_RE, STATUS_RE, statusOf, countTasks, deriveSpecState, pickPhaseFiles } from "../src/web-console/spec-files.mjs";
// The task pattern specs.mjs used before spec-files.mjs: TASK_ID_RE must take
// a `-` task line apart into the same groups.
@@ -68,10 +70,11 @@ test("spec files: countTasks() counts task lines only when there are any, every
"- [ ] It works",
"- [x] It is fast",
].join("\r\n");
assert.deepEqual(countTasks(phase), { done: 1, assumed: 1, open: 3, total: 5 });
// [~] is an unknown marker: not done, so it counts as open.
assert.deepEqual(countTasks(phase), { done: 1, assumed: 1, open: 3, blocked: 1, bare: 1, total: 6 });
const older = "# Phase 1\n\n- [x] Make it\n- [ ] Ship it\n- [?] Check it\n";
assert.deepEqual(countTasks(older), { done: 1, assumed: 1, open: 1, total: 3 });
assert.deepEqual(countTasks(""), { done: 0, assumed: 0, open: 0, total: 0 });
assert.deepEqual(countTasks(older), { done: 1, assumed: 1, open: 1, blocked: 0, bare: 0, total: 3 });
assert.deepEqual(countTasks(""), { done: 0, assumed: 0, open: 0, blocked: 0, bare: 0, total: 0 });
});
// What the picker labels each state and which card each state lights, as
@@ -487,6 +490,95 @@ test("the scan: an assumed task counts as done and is named, and numbered task l
}
});
// The seven cases where the dashboard scan and specs.mjs once disagreed
// (recorded in the hardening spec's Phase 5 notes; the same cases are in
// test-skill-scripts.mjs). Each is a spec folder and the
// [state, detail, finalizeReady] both must now report.
const DESYNC_CHECKLIST = (...marks) => `# Overview\n\n## Phase Checklist\n\n${marks.map((m, i) => `- [${m}] [Phase ${i + 1}: Step ${i + 1}](./phase-${i + 1}.md)`).join("\n")}\n`;
const DESYNC_PHASE = (n, lines) => `# Phase ${n}: Step ${n}\n\n**Status:** In Progress\n\n## Tasks\n\n${lines.join("\n")}\n\n## Acceptance Criteria\n\n- It works\n`;
const DESYNC_CASES = {
"blocked-reasoned": {
files: { "overview.md": DESYNC_CHECKLIST("x"), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One", "- [!] **Task 1.2:** Two", " > BLOCKED: needs admin access. User action: create the app."]) },
want: ["building", "1 of 2 tasks done, 1 blocked", true],
},
"unknown-marker": {
files: { "overview.md": DESYNC_CHECKLIST("/"), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One", "- [~] **Task 1.2:** Two"]) },
want: ["building", "1 of 2 tasks done", false],
},
"row-without-file": {
files: { "overview.md": DESYNC_CHECKLIST("x", " "), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One", "- [x] **Task 1.2:** Two"]) },
want: ["building", "2 of 2 tasks done, Phase 2 not written up", false],
},
"phase-without-tasks": {
files: { "overview.md": DESYNC_CHECKLIST("x", " "), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One"]), "phase-2.md": DESYNC_PHASE(2, ["To be written."]) },
want: ["building", "1 of 1 tasks done, Phase 2 not written up", false],
},
"stale-duplicate": {
files: { "overview.md": DESYNC_CHECKLIST("x"), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One"]), "phase-1-old.md": DESYNC_PHASE(1, ["- [ ] **Task 1.1:** One", "- [ ] **Task 1.2:** Two"]) },
want: ["built", "all tasks done", false],
},
"not-a-phase-file": {
files: { "overview.md": DESYNC_CHECKLIST("x"), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One"]), "phase-notes.md": "# Notes\n\n- [ ] Ask about colors\n" },
want: ["built", "all tasks done", false],
},
"blocked-bare": {
files: { "overview.md": DESYNC_CHECKLIST("x"), "phase-1.md": DESYNC_PHASE(1, ["- [x] **Task 1.1:** One", "- [!] **Task 1.2:** Two"]) },
want: ["building", "1 of 2 tasks done, 1 blocked", false],
},
};
const SPECS_SCRIPT = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "src", "skill-scripts", "specs.mjs");
test("the scan: the dashboard and specs.mjs status report the same state on the seven desync cases", () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-spec-desync-"));
try {
for (const [name, c] of Object.entries(DESYNC_CASES))
for (const [rel, text] of Object.entries(c.files)) {
fs.mkdirSync(path.join(root, "specs", name), { recursive: true });
fs.writeFileSync(path.join(root, "specs", name, rel), text);
}
const by = Object.fromEntries(scanProject(root).specs.map((sp) => [sp.name, sp]));
for (const [name, c] of Object.entries(DESYNC_CASES)) {
assert.deepEqual([by[name].state, by[name].detail, Boolean(by[name].finalizeReady)], c.want, `${name}: the dashboard scan`);
const r = spawnSync(process.execPath, [SPECS_SCRIPT, "status", name, "--root", root], { encoding: "utf8" });
assert.equal(r.status, 0, r.stderr);
const st = JSON.parse(r.stdout);
assert.deepEqual([st.state, st.stateDetail, st.finalizeReady], c.want, `${name}: specs.mjs status`);
}
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
test("deriveSpecState: blocked tasks keep a spec building, and finalizeReady needs a reason on each", () => {
const phase = (lines) => [{ number: 1, text: `# Phase 1\n\n${lines.join("\n")}\n` }];
const ready = deriveSpecState({ phases: phase(["- [x] **Task 1.1:** One", "- [!] **Task 1.2:** Two Blocked: no key yet", "- [!] **Task 1.3:** Three", " Reason: waiting on legal"]) });
assert.deepEqual([ready.state, ready.detail, ready.finalizeReady, ready.blocked, ready.bare], ["building", "1 of 3 tasks done, 2 blocked", true, 2, 0]);
const open = deriveSpecState({ phases: phase(["- [x] **Task 1.1:** One", "- [!] **Task 1.2:** Two", " > BLOCKED: no key.", "- [ ] **Task 1.3:** Three"]) });
assert.deepEqual([open.state, open.finalizeReady], ["building", false], "an open task left keeps Finalize dark");
// A reason belongs to its own task: the next task's line does not lend one.
const borrowed = deriveSpecState({ phases: phase(["- [x] **Task 1.1:** One", "- [!] **Task 1.2:** Two", "- [x] **Task 1.3:** Blocked: on purpose"]) });
assert.deepEqual([borrowed.bare, borrowed.finalizeReady], [1, false]);
assert.equal(deriveSpecState({ phases: phase(["- [!] **Task 1.1:** One", " > BLOCKED: no key."]) }).state, "documented", "nothing done yet is still documented");
// An approved phase with no task lines is not waiting to be written up.
const approved = deriveSpecState({ overview: "## Phase Checklist\n\n- [x] Phase 1: One\n- [x] Phase 2: Two\n", phases: [...phase(["- [x] **Task 1.1:** One"]), { number: 2, text: "# Phase 2\n" }] });
assert.deepEqual([approved.state, approved.unwritten], ["built", []]);
});
test("pickPhaseFiles: one file per phase number, the exact phase-N.md first, the rest listed as extra", () => {
const picked = pickPhaseFiles(["phase-2-old.md", "phase-2.md", "phase-1-setup.md", "phase-notes.md", "overview.md", "phase-10.md"]);
assert.deepEqual([...picked.entries()].sort((a, b) => a[0] - b[0]), [[1, "phase-1-setup.md"], [2, "phase-2.md"], [10, "phase-10.md"]]);
assert.deepEqual([...picked.extra.entries()], [[2, ["phase-2-old.md"]]]);
});
test("card rules: Finalize lights for a building spec only when the scan says finalizeReady", () => {
const entry = SKILL_CATALOG.find((e) => e.skill === "plan2code-4-finalize");
const spec = (extra) => ({ dir: "specs/x", name: "x", state: "building", ...extra });
assert.equal(cardAvailability(entry, SCAN, spec({ finalizeReady: true })).on, true);
assert.equal(cardAvailability(entry, SCAN, spec({})).on, false);
assert.equal(cardAvailability(entry, SCAN, { dir: "specs/x", name: "x", state: "documented", finalizeReady: true }).on, false, "only a building spec");
});
test("the scan: planChange is true for a waiting Plan change brief, and absent once it is applied or dropped", () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-spec-brief-"));
const notes = (line) => "# Phase 1\n\n- [x] **Task 1.1:** One\n- [ ] **Task 1.2:** Two\n\n## Notes\n\n### Paused 2026-10-27\n" + line + "\n\n## Phase Completion Summary\n";
+20 -3
View File
@@ -412,8 +412,25 @@ test("a launch, a dashboard press, Commit it now and Update CHANGELOG first each
test("the built skills name the skill file to follow after a hop", async () => {
const builtCli = path.join(ROOT, "skills", "plan2code", "references", "web-console", "console.mjs");
if (!fs.existsSync(builtCli)) return;
// The built console.mjs is a stub that forwards to the shared install, so
// point it at the console this build produced, in a throwaway console home.
const sharedRoot = path.join(ROOT, "skills", "_console");
const sharedVersion = fs.existsSync(sharedRoot) ? fs.readdirSync(sharedRoot)[0] : undefined;
if (!sharedVersion) return;
const stubHome = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-speed-home-"));
fs.writeFileSync(path.join(stubHome, "console-dir"), path.join(sharedRoot, sharedVersion));
// A shared console finds skill files in the agent skills store under the home folder.
const storeHome = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-speed-store-"));
const storeSkill = (name) => {
const dir = path.join(storeHome, ".agents", "skills", name);
fs.mkdirSync(dir, { recursive: true });
fs.copyFileSync(path.join(ROOT, "skills", name, "SKILL.md"), path.join(dir, "SKILL.md"));
return path.join(dir, "SKILL.md");
};
const reviewFile = storeSkill("plan2code-review");
const handoffFile = storeSkill("plan2code-handoff");
const run = (args) => {
const res = spawnSync(process.execPath, [builtCli, ...args], { env: ENV, encoding: "utf8", cwd: ROOT });
const res = spawnSync(process.execPath, [builtCli, ...args], { env: { ...ENV, PLAN2CODE_CONSOLE_HOME: stubHome, HOME: storeHome, USERPROFILE: storeHome }, encoding: "utf8", cwd: ROOT });
return { ...res, json: JSON.parse(res.stdout.trim().split("\n").pop()) };
};
const opened = run(["open", "--no-open", "--workflow", "dashboard"]).json;
@@ -428,7 +445,7 @@ test("the built skills name the skill file to follow after a hop", async () => {
});
assert.equal(res.status, 200);
const got = run(["wait", "--session", opened.sid, "--seconds", "10"]).json;
assert.equal(got.skillFile, path.join(ROOT, "skills", "plan2code-review", "SKILL.md"));
assert.equal(got.skillFile, reviewFile);
assert.equal(got.handoffSkill, undefined, "a launch is not a handoff stop");
const stopRes = await fetch(`${m[1]}/submit`, {
method: "POST",
@@ -437,7 +454,7 @@ test("the built skills name the skill file to follow after a hop", async () => {
});
assert.equal(stopRes.status, 200);
const stopped = run(["wait", "--session", opened.sid, "--seconds", "10"]).json;
assert.equal(stopped.handoffSkill, path.join(ROOT, "skills", "plan2code-handoff", "SKILL.md"), "a handoff stop in a built skill names the Handoff skill file");
assert.equal(stopped.handoffSkill, handoffFile, "a handoff stop in a built skill names the Handoff skill file");
} finally {
run(["stop", "--session", opened.sid, "--force"]);
}
+57 -18
View File
@@ -18,8 +18,15 @@
* that agent (marked `(last used)`), or keeps the agent's own last-used model when none is
* recorded, and `--model` (or Codex's `-m`) skips the question. Right after the agent is chosen, when it has a
* flag for skipping permission prompts (every built-in does; a custom agent only with bypassArgs),
* it asks whether to turn them off, Yes by default; `--keep-permissions` answers no, and with no
* terminal to ask on they are off. Any other arguments are forwarded to the CLI.
* it asks at a keyboard, on every launch, whether to turn them off, Yes by default and nothing
* remembered (Codex's question also names its sandbox, which the flag turns off too).
*
* Permission flags (never forwarded to the CLI):
* --bypass-permissions turn the agent's permission prompts off without asking; the only way
* a run with no terminal (a script, a pipe) starts with them off
* --keep-permissions keep the prompts on without asking (if both are given, this wins)
* With no terminal to ask on and neither flag, the prompts stay on. Any other arguments are
* forwarded to the CLI.
* Self-contained, Node built-ins only, with one exception: the shared agent list and lookup
* rule (agents.json and agent-lookup.mjs, installed beside this file in ~/.plan2code/bin/) are
* loaded by dynamic import inside chooseCli() so the command, the web console and the desktop
@@ -64,6 +71,7 @@ const PICK_FOLDER_FLAG = '--pick-folder';
const CLI_FLAG = '--cli';
const CLASSIC_FLAG = '--classic';
const KEEP_PERMISSIONS_FLAG = '--keep-permissions';
const BYPASS_PERMISSIONS_FLAG = '--bypass-permissions';
// Where install.js puts the desktop app, and the one file in it the launcher starts.
// PLAN2CODE_APP names a different executable (the tests start a stand-in this way).
const APP_DIR = path.join(os.homedir(), '.plan2code', 'app');
@@ -1069,21 +1077,50 @@ async function chooseCli(requested, { fromShortcut } = {}) {
}
/**
* Whether to start the agent with permission prompts off. Asked only for an agent that has a flag
* for it (a custom agent may have none), with Yes as the default; `--keep-permissions` answers no
* without asking, and with no terminal to ask on the prompts are off.
* What turning the prompts off drops, in the words the keyboard question uses: Codex's flag also
* turns off its sandbox, so its question names both.
*/
async function chooseBypass(cli, keep) {
function bypassDrops(cli) {
return cli.id === 'codex' ? 'approval prompts and its sandbox' : 'permission prompts';
}
/**
* The keyboard question's lines for an agent with a bypass flag: the heading, the line naming
* what the flag drops, the prompt, and the hint after an answer it cannot read.
*/
function bypassQuestion(cli) {
const drops = bypassDrops(cli);
return {
heading: `Turn ${cli.label}'s ${drops} off?`,
detail:
cli.id === 'codex'
? `It would read, edit and run commands in this project without asking, outside its sandbox (${cli.bypassArgs.join(' ')}).`
: `It would read, edit and run commands in this project without asking (${cli.bypassArgs.join(' ')}).`,
prompt: `Turn ${drops} off?`,
hint: `Type n to keep the ${drops}, or press Enter to turn them off.`,
};
}
/**
* Whether to start the agent with permission prompts off. Asked only for an agent that has a flag
* for it (a custom agent may have none), on every launch at a keyboard, with Yes as the default
* and no answer remembered. `--keep-permissions` answers no and `--bypass-permissions` answers yes
* without asking. With no terminal to ask on the prompts stay on unless `--bypass-permissions`
* was passed: a run nobody watches never drops them silently.
*/
async function chooseBypass(cli, { keep = false, bypass = false } = {}) {
if (!cli.bypassArgs || !cli.bypassArgs.length || keep) return false;
if (!process.stdin.isTTY) return true;
if (bypass) return true;
if (!process.stdin.isTTY) return false;
const question = bypassQuestion(cli);
console.log('');
console.log(c.bright(`Turn ${cli.label}'s permission prompts off?`));
console.log(c.dim(`It would read, edit and run commands in this project without asking (${cli.bypassArgs.join(' ')}).`));
console.log(c.bright(question.heading));
console.log(c.dim(question.detail));
for (;;) {
const answer = (await ask(`Prompts off? ${c.green('[Y/n]')}: `)).trim().toLowerCase();
const answer = (await ask(`${question.prompt} ${c.green('[Y/n]')}: `)).trim().toLowerCase();
if (!answer || answer === 'y' || answer === 'yes') return true;
if (answer === 'n' || answer === 'no') return false;
console.log(c.yellow('Type n to keep the prompts, or press Enter to turn them off.'));
console.log(c.yellow(question.hint));
}
}
@@ -1546,10 +1583,12 @@ async function launch() {
}
const fromShortcut = argv.includes(PICK_FOLDER_FLAG);
const classic = argv.includes(CLASSIC_FLAG);
const keepPermissions = argv.includes(KEEP_PERMISSIONS_FLAG);
const { cli: requestedCli, rest: extraArgs } = takeCliFlag(
argv.filter((arg) => arg !== PICK_FOLDER_FLAG && arg !== CLASSIC_FLAG && arg !== KEEP_PERMISSIONS_FLAG)
);
const permissions = {
keep: argv.includes(KEEP_PERMISSIONS_FLAG),
bypass: argv.includes(BYPASS_PERMISSIONS_FLAG),
};
const ownFlags = new Set([PICK_FOLDER_FLAG, CLASSIC_FLAG, KEEP_PERMISSIONS_FLAG, BYPASS_PERMISSIONS_FLAG]);
const { cli: requestedCli, rest: extraArgs } = takeCliFlag(argv.filter((arg) => !ownFlags.has(arg)));
printIntro();
await releaseNotice();
@@ -1599,7 +1638,7 @@ async function launch() {
// terminal flow (asked late if the app fails to start). An agent the setup page started runs
// in this terminal even with the app installed: the waiting setup tab is owed the hand-over.
const app = !setup && !classic && hasDisplay() ? findApp() : null;
let bypass = app ? null : await chooseBypass(cli, keepPermissions);
let bypass = app ? null : await chooseBypass(cli, permissions);
if (!cwdSettled) {
const picked = await projectCwd(fromShortcut);
@@ -1622,7 +1661,7 @@ async function launch() {
console.log(`Opened the Plan2Code app in ${c.cyan(cwd)} ${c.dim('(run `plan2code --classic` to stay in this terminal)')}`);
return process.exit(0);
}
if (bypass === null) bypass = await chooseBypass(cli, keepPermissions);
if (bypass === null) bypass = await chooseBypass(cli, permissions);
const args = cli.args(extraArgs, { bypass });
const options = { cwd, stdio: 'inherit', ...(cli.fullPath ? { fromFullPath: true } : {}) };
@@ -1659,4 +1698,4 @@ async function launch() {
// Run only when invoked directly; requiring the file (the tests do) is load-only.
if (require.main === module) launch();
module.exports = { normalizeAgents, buildArgs, parseRegQueryValue, expandPercentVars, addSavedWindowsPath, customClis, resolveCustomCommand, runnableClis, listModels, mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject, lastUsedNotice, leadInstall, installLine, findConsoleMjs, runSetupFlow, projectCwd };
module.exports = { bypassQuestion, normalizeAgents, buildArgs, parseRegQueryValue, expandPercentVars, addSavedWindowsPath, customClis, resolveCustomCommand, runnableClis, listModels, mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject, lastUsedNotice, leadInstall, installLine, findConsoleMjs, runSetupFlow, projectCwd };
+11 -5
View File
@@ -146,6 +146,8 @@ Two disciplines keep this file useful:
Record what you could **not** determine as an explicit gap. Gaps at recon time are often the first real fog bullets.
On `local`, `node "<S>/pathfinder.mjs" add specs/<idea>/pathfinder --name "Codebase context" --type legwork-afk --question "<what the recon establishes>"` writes the file (it refuses any other name as `00`); append the `## Answer` below to it, and Step 7's `reconcile` marks it resolved and dates it. Without the script, write the whole file by hand.
### The literal file
```markdown
@@ -398,6 +400,8 @@ Write the four dimension labels **hyphenated exactly as shown** — `Requirement
Say once, at Step 5: *"This map lives in gitignored `specs/` — local to you, not shared. `git add -f` it to track it."*
On `local`, write it with `node "<S>/pathfinder.mjs" init specs/<idea>/pathfinder --destination "<agreed lines>" --scores R,F,I,K --fog "<bullet>"` (one `--fog` per bullet; `--rule` adds a project ground rule, `--out` an out-of-scope line). It writes this structure at its Step 5 state: the banner, `**Status:** Charting`, the scores in the hyphenated form, the comments, `**Backend:** local` and the `AGENTS.md` line as found on disk, the standing ground rules, the fog, and a row for each question file already written. It refuses to overwrite a map and refuses a map with no fog (the off-ramp below). The template is the fallback when the script cannot run, and the reference for what `init` writes.
```markdown
> Pathfinder planning note - decisions, not implementation work. Archive with the spec; do not delete.
@@ -467,12 +471,12 @@ plan, not at shipped code. Continuous streaming to external systems is not on th
[-] out of scope. Resolved rows carry the one-line gist from the question's Answer,
then the Resolved: date in italics — briefs filter on these dates. -->
- [x] [Codebase context](./questions/00-codebase-context.md) — Node/Express/Knex/React with a BullMQ-to-S3 export precedent; `audit_events` is 180M rows partitioned monthly, no `actor_id` index, `requireAdmin` has no tenant scoping. *(2026-08-03)*
- [x] [Export format](./questions/01-export-format.md) — CSV with a UTF-8 BOM and RFC 4180 quoting, plus a sidecar SHA-256 manifest; JSONL rejected because recipients open these in Excel. *(2026-08-03)*
- [x] [Codebase context](./questions/00-codebase-context.md): Node/Express/Knex/React with a BullMQ-to-S3 export precedent; `audit_events` is 180M rows partitioned monthly, no `actor_id` index, `requireAdmin` has no tenant scoping. *(2026-08-03)*
- [x] [Export format](./questions/01-export-format.md): CSV with a UTF-8 BOM and RFC 4180 quoting, plus a sidecar SHA-256 manifest; JSONL rejected because recipients open these in Excel. *(2026-08-03)*
- [/] [Row-count ceiling](./questions/02-row-count-ceiling.md)
- [ ] [Export authorization](./questions/03-export-authorization.md)
- [!] [Delivery channel](./questions/05-delivery-channel.md) — Blocked by 02
- [-] [SIEM push connector](./questions/06-siem-push-connector.md) — out of scope, see below
- [!] [Delivery channel](./questions/05-delivery-channel.md): Blocked by 02
- [-] [SIEM push connector](./questions/06-siem-push-connector.md): out of scope, see below
## Not yet specified
@@ -497,7 +501,7 @@ plan, not at shipped code. Continuous streaming to external systems is not on th
<!-- Work consciously ruled past the destination. Never graduates; returns only if the
destination is redrawn, and then as a fresh effort. One line each: gist plus why. -->
- [SIEM push connector](./questions/06-siem-push-connector.md) — scheduled push to Splunk or
- [SIEM push connector](./questions/06-siem-push-connector.md): scheduled push to Splunk or
similar. The destination ends at an operator-initiated export; anything continuous is a
different effort with a different owner.
- Redesign of the `audit_events` schema. The write path is untouched by this destination;
@@ -515,6 +519,8 @@ Six contiguous `Key: value` lines after the H1. Not YAML. No frontmatter delimit
`## Question` is written at charting. `## Answer` is appended only when the question resolves. `## Evidence` holds sources, links, and artifacts, and a `research` subagent writes into it during Chart Step 8 without deciding anything.
On `local`, `node "<S>/pathfinder.mjs" add specs/<idea>/pathfinder --name "<name>" --question "<text>"` writes an open question in this shape and adds its map row: `NN` is `nextNN`, `--type` is `grill` (the default), `research`, `sketch`, `legwork-hitl` or `legwork-afk`, plus `--blocked-by "02, 04"`, `--locked`, `--recommended "<answer to react to>"` and one `--evidence` per bullet. Add the rest of the `## Question` detail (sub-decisions, why it is locked) to the file afterwards. It refuses a name already on the map and a `Blocked by:` number with no file. The templates below are the fallback when the script cannot run.
### An open question
```markdown
@@ -343,7 +343,7 @@ If a decision survives all six with no answer, it is not ready to leave the map.
| Drip-feeding one probe at a time | Twelve open questions on the map, one probe per response, the human gives up on session four | Batch up to three independent probes. On a charted map the human's round trips are the scarce resource, not your token budget. |
| Losing a probe the human skipped | Sent three, got two back, moved on and never mentioned the third | Diff the batch. Lead the next turn with what came back empty, restated in full. |
| A batch of naked questions | Three one-liners with no recommendations and no why-it-matters | Every probe in a batch carries its own recommendation and its own stake. Otherwise you have offloaded the thinking, not the round trips. |
| Asking in prose when the tool exists | Numbered Q blocks or a loose "which one?" despite AskUserQuestion being available | Put every answer control in the structured UI. Use descriptions for trade-offs and `Other` for composition. Prose may provide context or an artifact immediately before the tool, never the question itself. |
| Asking in prose when the tool exists | Numbered Q blocks or a loose "which one?" despite the question tool being available | Put every answer control in the structured UI. Use descriptions for trade-offs and `Other` for composition. Prose may provide context or an artifact immediately before the tool, never the question itself. |
| Flattening a gnarly probe into labels | An architectural decision reduced to three option labels with no useful descriptions | Keep the tool, not the flattening: put the real trade-off in each description, preserve `Other`, and recap the reasoning before recording. |
| Treating an artifact as an excuse for prose | An ASCII UI followed by "thoughts?" | Show the artifact, then invoke the structured tool with pointed reaction probes naming the rows/elements. |
| Retreating to prose over a fixable batch | Two probes collide on the short header, or one label bundles three answers | Rename the headers; split the bundled probe. Reshape the batch, never the decision. |
@@ -101,7 +101,7 @@ Pathfinder writes `specs/<idea>/PLAN-DRAFT-<YYYYMMDD>.md` with the header line:
`**Status:** Phase 3 Complete - Resume at Phase 4`
`/plan2code-1-plan` **already recognizes that exact string.** Its "Check for Existing Progress" block, which runs before Phase 1, reads:
(`gate` prints this line as `planDraftStatus`: copy it from there.) `/plan2code-1-plan` **already recognizes that exact string.** Its "Check for Existing Progress" block, which runs before Phase 1, reads:
`- Status "Phase 3 Complete - Resume at Phase 4": Resume at Phase 4`
@@ -114,7 +114,7 @@ Consequences of that being a literal string match:
- The file must be named `PLAN-DRAFT-<YYYYMMDD>.md` and live directly in `specs/<idea>/`. `PLAN-DRAFT-*.md` is a reserved name inside `pathfinder/` — never write it there.
- Use the date in `gate`'s `planDraftPath` (it reads the clock). Do not guess it. On `github` (no `gate`), take today's date from the shell and check `ls specs/<idea>/` for an existing draft.
**Discovery is shell-only.** `specs/` is gitignored, so Glob silently returns nothing and every downstream skill would report "no PLAN-DRAFT found". Use `ls specs/` and `ls specs/<idea>/` (Bash) or `Get-ChildItem specs/` (PowerShell) — the same rule 1-plan and `/plan2code-2-document` follow when they look for the file you are about to write.
**Discovery is shell-only.** `specs/` is gitignored, so a file search silently returns nothing and every downstream skill would report "no PLAN-DRAFT found". Use `ls specs/` and `ls specs/<idea>/` (Bash) or `Get-ChildItem specs/` (PowerShell) — the same rule 1-plan and `/plan2code-2-document` follow when they look for the file you are about to write.
**Do not append `## Planning Metrics` or any metrics comment.** Pathfinder is not a metered step. 1-plan's Phase 7 owns that block and will add it when it finishes the plan. Do not emit any of the completion tokens listed in the skill's Rules anywhere under `specs/`.
@@ -411,7 +411,7 @@ Nothing to commit — `specs/` is gitignored. Say so once, then stop.
| Symptom | Cause | Fix |
|---|---|---|
| 1-plan starts at Phase 1 and re-asks for requirements | The status string does not match byte for byte | Compare against the quoted line above; watch for en dashes and casing |
| 1-plan cannot find the draft at all | Glob was used to discover `specs/` | Shell only: `ls specs/` |
| 1-plan cannot find the draft at all | A file search was used to discover `specs/` | Shell only: `ls specs/` |
| `/plan2code-2-document` asks which of two drafts to use | The replace-in-place bullet was dropped from the footer | Merge the two drafts into the pathfinder-dated one, delete the other, restore the footer |
| The finished plan is missing requirements the map decided | The verification bullet was dropped from the footer | Re-derive 2.1 and 2.2 from the resolved answers, restore the footer |
| Metrics report a planning confidence nobody scored | A percent sign, or a bare dimension word followed by a number, reached the file | Hyphenate the dimension labels and drop the percent sign |
@@ -40,8 +40,8 @@ Each question file carries six contiguous `Key: value` lines after its H1 — NO
## Markers and blocking
**Map markers**, rebuilt from the files every session: `[ ]` open — **these rows ARE the frontier** · `[/]` claimed · `[x]` resolved · `[!]` open but blocked · `[-]` out of scope. Resolved rows carry the gist plus the `Resolved:` date in italics: `— <gist> *(YYYY-MM-DD)*`.
**Map markers**, rebuilt from the files every session: `[ ]` open — **these rows ARE the frontier** · `[/]` claimed · `[x]` resolved · `[!]` open but blocked · `[-]` out of scope. Resolved rows carry the gist plus the `Resolved:` date in italics, after a colon: `[x] [<name>](./questions/<file>): <gist> *(YYYY-MM-DD)*`. A map written before this format has an em dash there; both read the same, since a row is its checkbox and link.
`scripts/pathfinder.mjs` implements exactly these rules (`reconcile` rebuilds the markers, `frontier` computes blocking, `lint` checks the schema), so this file is the reference for reading its output and for writing a question file. Apply the rules by hand only when the script cannot run.
`scripts/pathfinder.mjs` implements exactly these rules (`init` writes the map, `add` writes a question file and its row, `reconcile` rebuilds the markers, `frontier` computes blocking, `lint` checks the schema), so this file is the reference for reading its output and for writing a question file by hand. Apply the rules by hand only when the script cannot run.
**Unblocked** ⟺ every `NN` in `Blocked by:` is `resolved`. **Stranded:** a blocker gone `out-of-scope` never resolves — the question is not merely blocked. Re-frame its `## Question` to drop the dependency, or rule it out too. Never leave it sitting.
@@ -521,7 +521,7 @@ The map row it produces — gist, then the `Resolved:` date in italics:
1. **Re-read `## Not yet specified` in full.** Every bullet, every session, after every resolution. Not the ones you remember — you are assuming no memory of prior sessions, and the bullet that graduates is usually the one you forgot was there.
2. **Ask of each bullet: did the answer just make this sharp?** Can you now write a `## Question` paragraph a stranger could act on, without "we'll need to figure out" anywhere in it?
3. **If yes, write the question file NOW** — in this same session, before Work Step 9. Its `NN` is `frontier`'s `nextNN` (max existing + 1, from the directory, never reused). Fill all six schema lines, with `Blocked by:` wired in the same pass. `reconcile` then adds its `[ ]` or `[!]` row to `## Question Checklist`.
3. **If yes, write the question file NOW** — in this same session, before Work Step 9. Its `NN` is `frontier`'s `nextNN` (max existing + 1, from the directory, never reused). Fill all six schema lines, with `Blocked by:` wired in the same pass. `reconcile` then adds its `[ ]` or `[!]` row to `## Question Checklist`. On `local`, `node "<S>/pathfinder.mjs" add specs/<idea>/pathfinder --name "<name>" --question "<text>" [--type ...] [--blocked-by "NN"]` does all of this in one step (chart.md, the question-file template); write the file by hand only when the script cannot run.
4. **DELETE the bullet from `## Not yet specified`.** Immediately, in the same edit as writing the file.
5. **If no, leave the bullet alone** — untouched, not reworded into something that merely sounds sharper.
6. **Re-check the counts.** One fog patch may graduate into three questions, or into none. Both are normal. A patch that graduates into three was written at the right coarseness; a patch that graduates into exactly one every time was probably a question all along.
+314 -21
View File
@@ -6,8 +6,9 @@
// each row carries, which questions are on the frontier, which are blocked or
// stranded, what NN comes next, what the Trail Footer looks like, which
// clearing checks pass, which dates fall in a brief's range. This script
// computes all of it and performs the bookkeeping writes (reconcile, claim,
// resolve, rule out), so the agent spends its attention on the decisions.
// computes all of it and performs the bookkeeping writes (init, add,
// reconcile, claim, resolve, rule out), so the agent spends its attention on
// the decisions.
//
// It never writes an ## Answer, never decides a question, never scores
// confidence. Those stay with the agent and the human.
@@ -20,6 +21,28 @@ const USAGE = `
pathfinder.mjs: Pathfinder map bookkeeping. JSON on stdout (trail: --text prints the footer itself).
<map> is specs/<idea>/pathfinder, specs/<idea>, <idea>, or a path to map.md.
node pathfinder.mjs init <map> --destination "<one or two lines>" --scores R,F,I,K
--fog "<bullet>" [--fog ...] [--rule "<ground rule>" ...]
[--out "<out-of-scope line>" ...] [--dry-run]
Chart Step 5: writes map.md from the template (creating the idea folder
and questions/): **Status:** Charting, the destination, the ground rules
(Backend local, AGENTS.md as found on disk, the standing rules, then each
--rule), the fog, an index of any question files already written.
--scores are the four confidence scores out of 25, in order
Requirements-clarity, Feasibility-technical, Integration-points,
Risk-assessment. Refuses an existing map, and a map with no --fog (no fog
is the Step 4 off-ramp: no map).
node pathfinder.mjs add <map> --name "<question name>" --question "<text>"
[--type grill|research|sketch|legwork-hitl|legwork-afk]
[--blocked-by "02, 04"] [--locked] [--recommended "<text>"]
[--evidence "<line>" ...] [--slug <kebab-name>] [--dry-run]
Chart Steps 3 and 6, Work Step 8: writes questions/NN-<slug>.md from the
template (NN is nextNN, State open, the type defaults to grill) and adds
its row to the map when one exists. Refuses a name already used, 00 for
anything but codebase-context (and that name at any other NN), a
checkbox or loop token in the text; a Blocked by: NN must exist.
node pathfinder.mjs reconcile <map> [--dry-run]
Work Step 2. Files win: an ## Answer under a non-resolved State becomes
resolved; a missing Resolved: date is backfilled from Claimed: (today if
@@ -62,7 +85,8 @@ pathfinder.mjs: Pathfinder map bookkeeping. JSON on stdout (trail: --text prints
The Clearing Gate's mechanical checks and the handoff preflight: zero
[ ] [/] [!] rows, empty fog, a Gist on every resolved answer, an existing
PLAN-DRAFT to update in place, the four hard caps, the map's scores >= 18.
Lists what stays your judgment.
Lists what stays your judgment, and prints the PLAN-DRAFT's byte-exact
**Status:** line (planDraftStatus).
node pathfinder.mjs lint <map>
Standing rules: loop tokens anywhere under specs/<idea>/, checkboxes or
@@ -84,6 +108,25 @@ const SCHEMA_KEYS = ["Type", "State", "Blocked by", "Claimed", "Resolved", "Lock
const TYPES = ["grill · HITL", "research · AFK", "sketch · HITL", "legwork · HITL", "legwork · AFK"];
const STATES = ["open", "claimed", "resolved", "out-of-scope"];
const GLYPH = { x: "●", "/": "◉", " ": "○", "!": "⊘", "-": "⊝" };
// What sits between a row's link and its tail (gist, blocker, out-of-scope
// note) and between an ## Out of scope link and its reason. Maps written
// before it carried an em dash there; rows are found by checkbox and link, so
// both read the same.
const SEP = ": ";
// The PLAN-DRAFT hand-off status /plan2code-1-plan resumes from, byte for byte
// (DRAFT_STATUSES in specs.mjs reads the same string; a test holds them equal).
const PLAN_DRAFT_STATUS = "Phase 3 Complete - Resume at Phase 4";
// Written as the ground rules of every map init creates, after the Backend and
// AGENTS.md lines (chart.md's map template carries the same ones).
const STANDING_RULES = [
"One question _file_ at a time; the fork-menu between decisions; a fresh session recommended after ~3. `research` questions may run as parallel subagents.",
"Every user-facing question uses the structured question tool when available; probes batch at most three. Prose Q blocks are fallback only when the tool is unavailable.",
"Questions are put to the human in plain English. Technical terms only where the term is the decision.",
"HITL questions are answered by the human in their own words. Never self-answered.",
"No new runtime dependency is assumed without a `research` question backing it.",
"Sketches are throwaway and live only under `pathfinder/sketch-NN/`.",
];
const KEBAB = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
const DIMENSIONS = [
{ key: "Requirements-clarity", word: "Requirements" },
{ key: "Feasibility-technical", word: "Feasibility" },
@@ -93,14 +136,22 @@ const DIMENSIONS = [
/* ------------------------------------------------------------- locating */
function locate(root, arg) {
/**
* The map's folders from the <map> argument. `create` (init, add) accepts an
* idea folder that does not exist yet, as long as its name is kebab-case: the
* command writing the first file creates it.
*/
function locate(root, arg, { create = false } = {}) {
if (!arg) fail(EXIT.USAGE, "missing-map", "Name the map: specs/<idea>/pathfinder, specs/<idea>, or <idea>.", "Example: node pathfinder.mjs frontier specs/audit-export/pathfinder");
let p = arg.replace(/\\/g, "/").replace(/\/+$/, "");
if (/\/map\.md$/i.test(p)) p = p.replace(/\/map\.md$/i, "");
let abs = path.isAbsolute(p) ? p : p.includes("/") ? path.join(root, p) : path.join(root, "specs", p);
if (path.basename(abs) !== "pathfinder") abs = path.join(abs, "pathfinder");
const ideaDir = path.dirname(abs);
if (!isDir(ideaDir)) fail(EXIT.NOT_FOUND, "no-idea", `No idea folder at ${rel(root, ideaDir)}.`, "Check the idea name with `ls specs/` (shell, not Glob: specs/ is gitignored).");
if (!isDir(ideaDir)) {
if (!create) fail(EXIT.NOT_FOUND, "no-idea", `No idea folder at ${rel(root, ideaDir)}.`, "Check the idea name with `ls specs/` (shell, not a file search: specs/ is gitignored).");
if (!KEBAB.test(path.basename(ideaDir))) fail(EXIT.USAGE, "bad-idea-name", `"${path.basename(ideaDir)}" is not a kebab-case idea name.`, "Use lowercase words joined by hyphens, for example audit-log-export.");
}
return { root, pf: abs, ideaDir, idea: path.basename(ideaDir), mapPath: path.join(abs, "map.md"), qDir: path.join(abs, "questions"), relPf: rel(root, abs) };
}
@@ -204,7 +255,7 @@ function parseQuestion(file, text) {
// Consequences under any of the names the playbooks use: a grill's
// "Consequences", a research answer's "What this implies", or a stated
// "breaks if reversed" for a locked decision.
hasConsequences: answer ? /\*\*(Consequences|What this implies)\b|^#{2,6}\s*(Consequences|What this implies)\b|^\s*Consequences\s*[:—-]|\bif (this is |it is )?reversed\b|breaks if reversed/im.test(answer.body) : false,
hasConsequences: answer ? /\*\*(Consequences|What this implies)\b|^#{2,6}\s*(Consequences|What this implies)\b|^\s*Consequences\s*[:\u2014-]|\bif (this is |it is )?reversed\b|breaks if reversed/im.test(answer.body) : false,
hasEvidence: hasContent(evidence),
researchComplete: evidence ? (evidence.body.match(/\*\*Research complete:\*\*\s*(\d{4}-\d{2}-\d{2})/) || [])[1] || null : null,
questionText: question ? stripComments(question.body).trim() : "",
@@ -346,10 +397,10 @@ function rowFor(q, byNN, nameOverride) {
const link = `- [${q.marker}] [${name}](./questions/${q.file})`;
if (q.marker === "x") {
const date = q.resolved ? ` *(${q.resolved})*` : "";
return q.gist ? `${link} — ${q.gist}${date}` : `${link}${date}`;
return q.gist ? `${link}${SEP}${q.gist}${date}` : `${link}${date}`;
}
if (q.marker === "!") return `${link} — Blocked by ${openBlockers(q, byNN).join(", ")}`;
if (q.marker === "-") return `${link} — out of scope, see below`;
if (q.marker === "!") return `${link}${SEP}Blocked by ${openBlockers(q, byNN).join(", ")}`;
if (q.marker === "-") return `${link}${SEP}out of scope, see below`;
return link;
}
@@ -365,11 +416,11 @@ function updateRow({ lines: block, rowLines, extra, m }, q, byNN, regenerate) {
if (regenerate || !m) return [rowFor(q, byNN, name), ...extra];
const oldMarker = m[1];
if (oldMarker === q.marker) return block;
const hasSuffix = /^\s*—/.test(m[4]);
if (q.marker === "x" && !(oldMarker === "x" && hasSuffix)) return [rowFor(q, byNN, name), ...extra];
if (q.marker === "!" || q.marker === "-" || oldMarker === "!" || oldMarker === "-" || oldMarker === "x") {
// The tail ("— Blocked by", "— out of scope", a resolved row's gist and
// date) belongs to the old marker.
// A marker change that adds a tail ([x] gist and date, [!] blocker, [-]
// note) or drops one (whatever follows an old [x], [!] or [-] link, in
// either separator) writes the row fresh. The tail itself is never parsed:
// the checkbox and the link are what make it a row.
if (["x", "!", "-"].includes(q.marker) || ["x", "!", "-"].includes(oldMarker)) {
return [rowFor(q, byNN, name), ...extra];
}
return [rowLines[0].replace(/\[(.)\]/, `[${q.marker}]`), ...rowLines.slice(1), ...extra];
@@ -596,6 +647,244 @@ function drift(questions, map) {
return d;
}
/* ------------------------------------------------------- init and add */
// The chart.md templates, in code: init and add write these, and the
// templates in the references stay as the fallback for when the script
// cannot run. The comments are written for the next session.
const MAP_COMMENTS = {
status: [
"<!-- Status: Charting while the map is being built (Chart Steps 1-6) -> Working once the",
" checklist is indexed (Chart Step 7) -> Cleared only when the Clearing Gate passes.",
" A fresh session routes on this line, so it must be correct before the session ends. -->",
],
nextNN: [
"<!-- Next NN: the number the next new question file takes. Kept by the script (reconcile",
" adds it at Chart Step 7 and every write command raises it); it never goes down, so a",
" deleted question's number is never reused. Never edit it by hand. -->",
],
confidence: [
"<!-- Confidence: four dimensions, each scored out of 25, re-scored at every resolution.",
" The Clearing Gate requires all four at 18/25 or better. Score against evidence. -->",
],
destination: [
"<!-- Settled at Chart Step 2 and quoted as agreed. Every question is measured against it:",
" in scope or past the edge, still needed or now moot. Change it only with the human",
" present: a silent redraw invalidates every scope call already made. -->",
],
groundRules: [
"<!-- Standing constraints for every session on this map. Read before choosing a question,",
" obeyed while resolving it. Nothing here is re-asked. The Backend line comes first, then",
" AGENTS.md: \"- `AGENTS.md` exists and governs.\" or, when it is missing, exactly",
" \"- `AGENTS.md` is absent.\" (the handoff then routes to /plan2code-init first). -->",
],
glossary: [
"<!-- Terms this effort uses precisely, as a table: | Term | Meaning here | Avoid |.",
" Prevents two sessions meaning different things by the same word. -->",
],
checklist: [
"<!-- Rebuilt from questions/ every session: the files are ground truth, this is an index.",
" [ ] open (the frontier) · [/] claimed · [x] resolved · [!] open but blocked",
" [-] out of scope. Resolved rows carry the one-line gist from the question's Answer,",
" then the Resolved: date in italics; briefs filter on these dates. -->",
],
fog: [
"<!-- The fog: in-scope areas you can see but cannot yet phrase as a question. Graduates into",
" question files as answers land, and the graduated bullet is deleted from here.",
" Do NOT pre-slice these into question-sized pieces: one bullet may become three",
" questions, or none. Nothing already decided, already a question, or out of scope. -->",
],
outOfScope: [
"<!-- Work consciously ruled past the destination. Never graduates; returns only if the",
" destination is redrawn, and then as a fresh effort. One line each: gist plus why. -->",
],
};
const bulletsOf = (list) => (list || []).map((s) => s.trim()).filter(Boolean).map((s) => `- ${s}`);
function parseScores(v) {
const nums = String(v || "").split(/[\s,]+/).filter(Boolean);
if (nums.length !== 4 || nums.some((n) => !/^\d{1,2}$/.test(n) || Number(n) > 25)) {
fail(EXIT.USAGE, "bad-scores", `--scores needs four whole numbers from 0 to 25${v ? `, not "${v}"` : ""}.`, "Order: Requirements-clarity, Feasibility-technical, Integration-points, Risk-assessment. Example: --scores 12,9,14,10 (charting scores are low by construction).");
}
return nums.map(Number);
}
async function cmdInit(loc, args) {
const dry = !!args["dry-run"];
if (fs.existsSync(loc.mapPath)) fail(EXIT.REFUSED, "map-exists", `${loc.relPf}/map.md already exists; init never overwrites a map.`, "Resume it instead: run reconcile (Work Step 2), or frontier to see where it stands.");
const destination = (args.destination || "").trim();
if (!destination) fail(EXIT.USAGE, "missing-destination", "--destination is required: the one or two lines settled at Chart Step 2.", 'Example: --destination "A locked plan for exporting a filtered range of audit events as one file."');
const scores = parseScores(args.scores);
const fog = bulletsOf(args.fog);
if (!fog.length) fail(EXIT.REFUSED, "no-fog", "No --fog: a map with nothing in ## Not yet specified is the Chart Step 4 off-ramp, not a map.", "Pass each fog bullet as --fog, or take the off-ramp: create no map, keep the codebase context, hand it to /plan2code-1-plan.");
const agentsAbsent = !fs.existsSync(path.join(loc.root, "AGENTS.md"));
const rules = [
"- **Backend:** local",
agentsAbsent ? "- `AGENTS.md` is absent." : "- `AGENTS.md` exists and governs. Its conventions are not re-litigated by any question here.",
...STANDING_RULES.map((r) => `- ${r}`),
...bulletsOf(args.rule),
];
const outOfScope = bulletsOf(args.out);
// The same two refusals add applies: a checkbox line or a loop token never lands in a map.
for (const t of [destination, ...fog, ...bulletsOf(args.rule), ...outOfScope]) {
if (/^\s*[-*] \[.\]/m.test(t)) fail(EXIT.REFUSED, "checkbox", "A map never holds a checkbox line (the loop and metrics read checkboxes).", "Use plain bullets.");
const tok = t.match(LOOP_TOKENS);
if (tok) fail(EXIT.REFUSED, "loop-token", `${tok[0]} is a reserved loop completion token; it never belongs under specs/.`, "Reword it.");
}
const [r, f, i, k] = scores;
const lines = [
BANNER,
"",
`# Map: ${loc.idea}`,
"",
"*Decisions live in `questions/`, one file each. This file is just the index.*",
"",
"**Status:** Charting",
`**Updated:** ${isoDate()}`,
`**Confidence:** Requirements-clarity ${r}/25 · Feasibility-technical ${f}/25 · Integration-points ${i}/25 · Risk-assessment ${k}/25`,
"",
...MAP_COMMENTS.status, "",
...MAP_COMMENTS.nextNN, "",
...MAP_COMMENTS.confidence, "",
"## Destination", "", destination, "", ...MAP_COMMENTS.destination, "",
"## Ground rules", "", ...MAP_COMMENTS.groundRules, "", ...rules, "",
"## Glossary", "", ...MAP_COMMENTS.glossary, "",
"## Question Checklist", "", ...MAP_COMMENTS.checklist, "",
"## Not yet specified", "", ...MAP_COMMENTS.fog, "", ...fog, "",
"## Out of scope", "", ...MAP_COMMENTS.outOfScope, ...(outOfScope.length ? ["", ...outOfScope] : []),
];
let mapText = lines.join("\n") + "\n";
// Question files written before the map (the Step 3 codebase context) get
// their rows now, so the index starts out agreeing with the files.
const questions = loadQuestions(loc);
const byNN = derive(questions);
if (questions.length) mapText = rebuildChecklist(mapText, questions, byNN).text;
if (!dry) {
fs.mkdirSync(loc.qDir, { recursive: true });
fs.writeFileSync(loc.mapPath, mapText);
}
out({
ok: true,
map: `${loc.relPf}/map.md`,
status: "Charting",
agentsAbsent,
indexed: questions.map((q) => ({ nn: q.nn, name: q.name, marker: `[${q.marker}]` })),
nextNN: nextNN(loc, questions),
dryRun: dry,
mapWritten: !dry,
next: "Write each question with add (Chart Step 6), then reconcile, set **Status:** Working and lint (Chart Step 7).",
});
}
const TYPE_WORDS = { grill: "grill · HITL", research: "research · AFK", sketch: "sketch · HITL" };
/** --type as written in a file ("legwork · AFK") or typed ("legwork-afk", "research"); grill by default. */
function parseType(v) {
if (v === undefined) return TYPES[0];
const key = String(v).toLowerCase().replace(/[·\s_-]+/g, "-").replace(/^-+|-+$/g, "");
const type = TYPES.find((t) => t.toLowerCase().replace(/[·\s]+/g, "-") === key) || TYPE_WORDS[key];
if (!type) fail(EXIT.USAGE, "bad-type", `--type "${v}" is not a question type.`, "Use grill, research, sketch, legwork-hitl or legwork-afk (questions.md: Type meanings).");
return type;
}
function slugOf(name) {
return name
.normalize("NFKD")
.replace(/\p{M}/gu, "")
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 60)
.replace(/-+$/, "");
}
async function cmdAdd(loc, args) {
const dry = !!args["dry-run"];
const name = (args.name || "").trim();
if (!name) fail(EXIT.USAGE, "missing-name", "--name is required: the question's name, its H1 and its map row.", 'Example: --name "Export authorization"');
if (/[\r\n]/.test(name)) fail(EXIT.USAGE, "bad-name", "--name is one line.", "Put the detail in --question.");
const question = (args.question || "").trim();
if (!question) fail(EXIT.USAGE, "missing-question", "--question is required: the ## Question text, phrased sharply.", 'Example: --question "Who may run an audit-log export, and over whose events?"');
const type = parseType(args.type);
const slug = args.slug !== undefined ? String(args.slug) : slugOf(name);
if (!KEBAB.test(slug)) fail(EXIT.USAGE, "bad-slug", args.slug !== undefined ? `--slug "${slug}" is not kebab-case.` : `"${name}" gives no usable file name.`, "Pass --slug with lowercase words joined by hyphens.");
const recommended = (args.recommended || "").trim();
const evidence = bulletsOf(args.evidence);
for (const t of [name, question, recommended, ...evidence]) {
if (/^\s*[-*] \[.\]/m.test(t)) fail(EXIT.REFUSED, "checkbox", "A question file never holds a checkbox line (the loop and metrics read checkboxes).", "Use plain bullets.");
const tok = t.match(LOOP_TOKENS);
if (tok) fail(EXIT.REFUSED, "loop-token", `${tok[0]} is a reserved loop completion token; it never belongs under specs/.`, "Reword it.");
}
const questions = loadQuestions(loc);
const byNN = derive(questions);
const same = questions.find((q) => q.file.replace(/^\d+-/, "") === `${slug}.md` || q.name.toLowerCase() === name.toLowerCase());
if (same) fail(EXIT.REFUSED, "duplicate", `${same.file} already holds "${same.name}"; one file per decision.`, "Work in that file, or name this question apart from it (--name, or --slug for the file name).");
const nn = nextNN(loc, questions);
if (nn === "00" && slug !== "codebase-context") fail(EXIT.REFUSED, "reserved-00", `This would be question 00, and 00 is always 00-codebase-context.md.`, 'Add the codebase context first (Chart Step 3): --name "Codebase context" --type legwork-afk.');
if (nn !== "00" && slug === "codebase-context") fail(EXIT.REFUSED, "reserved-name", `codebase-context is question 00's name; this would be ${nn}-codebase-context.md.`, "Name this question for its own decision.");
const blockedBy = args["blocked-by"] === undefined ? [] : parseBlockers(String(args["blocked-by"]));
const missing = blockedBy.filter((b) => !byNN.has(b));
if (missing.length) fail(EXIT.NOT_FOUND, "no-blocker", `Blocked by ${missing.join(", ")}, which ${missing.length === 1 ? "is not a question" : "are not questions"} in questions/.`, "Name blockers by an existing NN (frontier lists them); a blocker is written before what it blocks.");
const file = `${nn}-${slug}.md`;
const full = path.join(loc.qDir, file);
if (fs.existsSync(full)) fail(EXIT.REFUSED, "exists", `questions/${file} already exists.`, "Run reconcile, then frontier for the next NN.");
const text = [
BANNER,
"",
`# ${name}`,
"",
`Type: ${type}`,
"State: open",
`Blocked by: ${blockedBy.length ? blockedBy.join(", ") : "none"}`,
"Claimed: none",
"Resolved: none",
`Locked: ${args.locked ? "yes" : "no"}`,
"",
"## Question",
"",
question,
...(recommended ? ["", `Recommended answer to react to: ${recommended}`] : []),
"",
"## Evidence",
...(evidence.length ? ["", ...evidence] : []),
].join("\n") + "\n";
if (!dry) {
fs.mkdirSync(loc.qDir, { recursive: true });
fs.writeFileSync(full, text);
}
const q = { ...parseQuestion(full, text), path: full };
const all = [...questions, q];
const byNNAfter = derive(all);
const after = String(parseInt(nn, 10) + 1).padStart(2, "0");
const original = readText(loc.mapPath);
let mapRow = null;
let mapWritten = false;
if (original !== null) {
const mapText = rebuildChecklist(original, all, byNNAfter).text;
mapRow = rowFor(q, byNNAfter);
mapWritten = saveMap(loc, original, mapText, after, dry);
}
out({
ok: true,
nn,
name,
file: rel(loc.root, full),
type,
state: "open",
marker: `[${q.marker}]`,
blockedBy,
locked: !!args.locked,
mapRow,
dryRun: dry,
mapWritten,
nextNN: after,
...(original === null ? { next: "No map yet: init writes it at Chart Step 5 and indexes this file." } : {}),
});
}
/* ----------------------------------------------------------- commands */
async function cmdReconcile(loc, args) {
@@ -805,7 +1094,7 @@ async function cmdRuleOut(loc, args) {
q.state = "out-of-scope";
const byNN = derive(questions);
mapText = rebuildChecklist(mapText, questions, byNN).text;
const line = `- [${q.name}](./questions/${q.file}) — ${reason}`;
const line = `- [${q.name}](./questions/${q.file})${SEP}${reason}`;
const mapNl = eol(mapText);
const lines = mapText.split(/\r?\n/);
const at = lines.findIndex((l) => /^## +Out of scope\s*$/i.test(l));
@@ -834,7 +1123,7 @@ function confidenceLine(scores) {
const vals = DIMENSIONS.map((d) => ({ word: d.word, v: scores[d.word] }));
if (vals.some((x) => x.v === null)) return null;
const low = vals.filter((x) => x.v < 18).map((x) => x.word);
if (low.length) return `Confidence: not yet — ${low.join(", ")} still ${low.length === 1 ? "needs" : "need"} work.`;
if (low.length) return `Confidence: not yet, ${low.join(", ")} still ${low.length === 1 ? "needs" : "need"} work.`;
const border = vals.filter((x) => x.v < 20).map((x) => x.word);
if (border.length) return `Confidence: solid, but ${border.join(", ")} ${border.length === 1 ? "is" : "are"} borderline.`;
return "Confidence: solid.";
@@ -1000,6 +1289,7 @@ async function cmdGate(loc) {
caps,
existingPlanDraft: drafts.length ? drafts.map((n) => rel(loc.root, path.join(loc.ideaDir, n))) : null,
planDraftPath: drafts.length ? rel(loc.root, path.join(loc.ideaDir, drafts.sort().at(-1))) : `${rel(loc.root, loc.ideaDir)}/PLAN-DRAFT-${isoDate().replace(/-/g, "")}.md`,
planDraftStatus: `**Status:** ${PLAN_DRAFT_STATUS}`,
agentsAbsent: map.agentsAbsent,
initFirst: needsInit(loc, map),
judgment: [
@@ -1215,7 +1505,8 @@ async function cmdBriefData(loc, args) {
decided,
// Link markup dropped (a brief has no links); placeholder bullets ("None yet.") skipped.
// A link text may hold one level of brackets ("Retention [legal] hold").
ruledOut: map.outOfScope.map((b) => b.replace(/\[((?:[^[\]]|\[[^\]]*\])+)\]\([^)]*\)/g, "$1")).filter((b) => !/^(none|nothing)\b[^—:]*\.?$/i.test(b.trim())),
// A placeholder has no separator after it (an em dash in maps written before SEP).
ruledOut: map.outOfScope.map((b) => b.replace(/\[((?:[^[\]]|\[[^\]]*\])+)\]\([^)]*\)/g, "$1")).filter((b) => !/^(none|nothing)\b[^\u2014:]*\.?$/i.test(b.trim())),
ready,
waiting,
fog: map.fog,
@@ -1230,12 +1521,14 @@ async function cmdBriefData(loc, args) {
run(USAGE, async (argv) => {
const args = parseArgs(argv, {
booleans: ["dry-run", "text", "heavy"],
values: ["root", "form", "reason", "range", "resolved-this-session"],
lists: ["item"],
booleans: ["dry-run", "text", "heavy", "locked"],
values: ["root", "form", "reason", "range", "resolved-this-session", "destination", "scores", "name", "question", "type", "blocked-by", "recommended", "slug"],
lists: ["item", "fog", "rule", "out", "evidence"],
});
const cmd = args._[0];
const commands = {
init: cmdInit,
add: cmdAdd,
reconcile: cmdReconcile,
frontier: cmdFrontier,
claim: cmdClaim,
@@ -1247,6 +1540,6 @@ run(USAGE, async (argv) => {
"brief-data": cmdBriefData,
};
if (!commands[cmd]) fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", `Commands: ${Object.keys(commands).join(", ")}. Run with --help.`);
const loc = locate(path.resolve(args.root || "."), args._[1]);
const loc = locate(path.resolve(args.root || "."), args._[1], { create: cmd === "init" || cmd === "add" });
await commands[cmd](loc, args);
});
+10 -10
View File
@@ -6,13 +6,13 @@ Start all PATHFINDER MODE responses with '🧭 [PATHFINDER: Chart - Step X: Name
Pathfinder, not architect. An idea has arrived too big or unclear to plan. Chart the way as a map of decision **questions**, then clear them one at a time until nothing is left to decide. Hand off to `/plan2code-1-plan`.
Read references/grilling.md
Read references/grilling.md at the first question you grill (Chart Step 2, or a `grill` question in Work), not before: the intent gate, backend choice and a brief never need it.
> Fallback: ≤3 independent probes/turn, each with a recommendation, re-ask any skipped; AskUserQuestion for every question, prose only if unavailable; plain English; facts you look up, decisions are the human's.
> Fallback: ≤3 independent probes/turn, each with a recommendation, re-ask any skipped; the question tool for every question, prose only if unavailable; plain English; facts you look up, decisions are the human's.
## Interface
The FIRST thing you do, before anything else in this file — before Step 0: ask **web console** (suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow pathfinder` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/pathfinder.md. Switchable anytime. `--web` or `Use the web console for this session.` in the argument answers it; drop the flag. Dashboard-launched? Resume its open session (console-launches.md), then Step 0.
The FIRST thing you do, before anything else in this file — before Step 0: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow pathfinder` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/pathfinder.md. 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 Step 0.
## Backend
@@ -51,7 +51,7 @@ Load `./AGENTS.md` if it exists — its conventions govern; never re-ask what it
## Auto-Discovery and Mode Selection
⚠️ `specs/` is gitignored: NEVER use Glob; list it with `ls specs/` or `Get-ChildItem specs/`.
⚠️ `specs/` is gitignored: NEVER use a file-search tool; list it with `ls specs/` or `Get-ChildItem specs/`.
**Brief/recap/minutes asked?** → read references/brief.md: `reconcile`, then `brief-data --range <range>` (`github`: its brief section), write plain-English `briefs/brief-<YYYYMMDD>.md` from the output, STOP. Never resolves.
@@ -80,13 +80,13 @@ Read references/chart.md
> Fallback: confirm the outcome with the human FIRST; only then grill the destination, then breadth-first; write the map and one question per sharp decision.
0. `[Chart - Step 0: Intent Gate]` **Before creating anything**, use AskUserQuestion for the outcome and WAIT: **chart a map** (foggy — Step 1), **`/plan2code-1-plan`** (clear — STOP), **`/plan2code-quick-task`** (tiny — STOP). HITL, never self-select "chart".
0. `[Chart - Step 0: Intent Gate]` **Before creating anything**, use the question tool for the outcome and WAIT: **chart a map** (foggy — Step 1), **`/plan2code-1-plan`** (clear — STOP), **`/plan2code-quick-task`** (tiny — STOP). HITL, never self-select "chart".
1. `[Chart - Step 1: Name and backend]` Only after the gate says "chart." Confirm the kebab-case idea name, then ask — HITL, never self-picked — **local files or GitHub Issues?** Recommend `local` for solo work; offer `github` only if preflight passes, naming the repo's visibility. THEN the first write.
2. `[Chart - Step 2: Destination]` Grill until it is one or two lines. It fixes scope — settle it first.
3. `[Chart - Step 3: Recon]` Explore the codebase; record codebase context, resolved on the spot, `legwork · AFK`. On `github` hold it until Step 6 so a Step 4 off-ramp leaves no litter. Unfamiliar code? `/plan2code-xray` explains an area first.
3. `[Chart - Step 3: Recon]` Explore the codebase; record codebase context, resolved on the spot, `legwork · AFK` (`local`: `add` writes `00`, then its `## Answer`). On `github` hold it until Step 6 so a Step 4 off-ramp leaves no litter. Unfamiliar code? `/plan2code-xray` explains an area first.
4. `[Chart - Step 4: Map the frontier]` Grill again **breadth-first**: fan out, never deep on one thread. Surface the open decisions and what is takeable now.
5. `[Chart - Step 5: Create the map]` `**Status:** Charting`, Destination, Ground rules (backend first), an empty index, the fog in `## Not yet specified`. Say once where it lives and who sees it.
6. `[Chart - Step 6: Write the questions]` One per decision you can phrase sharply NOW, dependency order, `Blocked by:` filled the same pass — on `github`, create all first, wire edges second. The rest stays fog. Testing is not charted here: `/plan2code-1-plan` Phase 1 asks it.
5. `[Chart - Step 5: Create the map]` `**Status:** Charting`, Destination, Ground rules (backend first), an empty index, the fog in `## Not yet specified` (`local`: `init` writes it). Say once where it lives and who sees it.
6. `[Chart - Step 6: Write the questions]` One per decision you can phrase sharply NOW, dependency order, `Blocked by:` filled the same pass (`local`: `add` each) — on `github`, create all first, wire edges second. The rest stays fog. Testing is not charted here: `/plan2code-1-plan` Phase 1 asks it.
7. `[Chart - Step 7: Index]` `local`: `reconcile` fills `## Question Checklist` from the files (every missing row, with its marker). Either backend: set `**Status:** Working`. `local`: then `lint`.
8. `[Chart - Step 8: Fire research]` One subagent per `research` question, in parallel. Each writes only its `## Evidence`, never decides. **Wait for all** (they die with the terminal), then Session End.
@@ -110,7 +110,7 @@ Assume NO memory of any prior session.
5. `[Work - Step 5: Zoom]` Read the claimed question in full, plus any closed question it references. Obey `## Ground rules`.
6. `[Work - Step 6: Resolve]` Route by type per the resolve playbook. HITL needs the human's own words.
7. `[Work - Step 7: Record]` Write `## Answer`: the decision, what was rejected and why, consequences, a one-line `**Gist:**` last. Sources under `## Evidence`. Mark it resolved, dated today, index the gist + date on the map, bump `**Updated:**` (`local`: `resolve <NN>` does all four; its `unblocked` list feeds the menu).
8. `[Work - Step 8: Graduate]` Fog now sharp? Write those questions (`local`: numbered from `nextNN`, then `reconcile` to index them), delete the graduated bullets. Past the destination? Rule it out of scope, one line in `## Out of scope` (`local`: `rule-out <NN> --reason "<why>"`; handle anything it reports `stranded`). Invalidated? Re-frame or rule out.
8. `[Work - Step 8: Graduate]` Fog now sharp? Write those questions (`local`: `add` numbers and indexes each), delete the graduated bullets. Past the destination? Rule it out of scope, one line in `## Out of scope` (`local`: `rule-out <NN> --reason "<why>"`; handle anything it reports `stranded`). Invalidated? Re-frame or rule out.
9. `[Work - Step 9: Menu]` Run The Clearing Gate. Not cleared: fork-menu (Form C; resolve.md §Cadence) — pick → Step 4, stop → Session End.
## The Clearing Gate
@@ -130,7 +130,7 @@ Score the four dimensions (handoff.md rubric) and write them to the map's `**Con
## Trail Footer
Read references/trail.md
Read references/trail.md before the first footer (your first response once the map exists), not before.
> Fallback: once the map exists, end every response with a marker path (`●` done · `◉` here · `○` open · `⊘` blocked · `⊝` out of scope) `START`→`⚑`, a named legend, a plain-English confidence note, then ONE closer: asking → Form B, `WAITING ON YOU`, no command; menu → Form C, `NEXT UP` + `OR START FRESH`; session end → Form A, `NEXT STEP` + resume command with `--web` (map issue URL on `github`).
+6 -7
View File
@@ -8,7 +8,7 @@ Senior software architect and technical PM. Analyze requirements critically, ask
## Interface
The FIRST thing you do, before anything else in this file — before the AGENTS.md check, before looking for a draft: ask **web console** (suggested — far easier for sign-offs with a non-engineer) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow plan` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/plan.md. `--web` or `Use the web console for this session.` in the argument answers it; drop the flag. Dashboard-launched? Resume its open session (console-launches.md), then the AGENTS.md check.
The FIRST thing you do, before anything else in this file — before the AGENTS.md check, before looking for a draft: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow plan` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md and <D>/notes/plan.md. Switchable anytime. The console is far easier for sign-offs with a non-engineer. 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 the AGENTS.md check.
## Project Context (BLOCKING)
@@ -57,7 +57,7 @@ Keep with you: every question, confidence score, decision and sign-off, Phases 3
### Check for Existing Progress
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:
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/` (a file search 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" or "Escalated from Test - Resume at Phase 2": Acknowledge, verify requirements, skip to Phase 2
- Status "Draft" or "Complete": Ask user how to proceed
@@ -119,7 +119,7 @@ After confirmation, proceed with analysis:
>
> Say 'skip testing' to omit."
Default if skipped: Phase Testing `None`, Full Suite `Never`.
Question skipped or unanswered: infer the posture from `AGENTS.md`'s `## Test map` (else its test commands): tests exist → Phase Testing `Targeted per phase`, Full Suite `Offered at Finalize`; none found → `None`, `Never`. Say what you inferred and from what in the sign-off's Testing line. 'skip testing' said outright still writes `None` and `Never`.
7. Report confidence score
8. **Requirements Sign-Off:**
@@ -131,7 +131,7 @@ After confirmation, proceed with analysis:
> **Non-Functional:**
> NFR-1: [req]
> ...
> **Testing:** [types, phase testing, full suite, approach, or None]
> **Testing:** [types, phase testing, full suite, approach, or None; "inferred from the test map" when you chose it]
>
> **Confirm:** Complete and accurate? (approved / needs changes)
@@ -298,11 +298,10 @@ When complete (PLAN-DRAFT created), tell user:
> ╲│ ★ │╱
> │ ◡ │ Planning done! Ready for documentation!
> ╰┬─┬╯
> =============================================
> NEXT STEP: Start a NEW conversation then run:
> `/plan2code-2-document --web`
> ```"
In the terminal, end with `NEXT STEP: /plan2code-2-document --web` in a NEW conversation. The web console's finish carries it, so print nothing there.
## Abort / Recovery
- **Abort:** Confirm with user, list files needing cleanup, stop workflow
+4 -15
View File
@@ -27,7 +27,7 @@ The FIRST thing you do, before anything else in this file — before Step 1, bef
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-1b-revise-plan/scripts/` globally). Run from the project root; each prints one JSON object, and on a non-zero exit `next` says what to do. They only ever touch `specs/`.
- `node "<S>/specs.mjs" list`: the active specs (it reads gitignored `specs/`, where Glob silently finds nothing).
- `node "<S>/specs.mjs" list`: the active specs (it reads gitignored `specs/`, where a file search silently finds nothing).
- `node "<S>/specs.mjs" status <spec>`: phases, task counts by marker, `checks`, `pending`.
- `node "<S>/specs.mjs" mark <spec> --phase <N> --to open`: re-open a completed phase in overview.md.
@@ -195,21 +195,10 @@ Report and resolve issues (every `error` in `checks` included), then rerun `stat
│ ◡ │ All revised! Ready to continue!
╰┬─┬╯
╔═══════════════════════════════════════════════════════════════════╗
║ REVISION COMPLETE ║
╠═══════════════════════════════════════════════════════════════════╣
║ ║
║ Specs have been updated. To continue implementation: ║
║ ║
║ 1. Start a NEW conversation ║
║ 2. Use command: /plan2code-3-implement --web ║
║ 3. Provide path: specs/<feature-name>/overview.md ║
║ ║
║ The command will auto-detect the next Phase to implement. ║
║ ║
╚═══════════════════════════════════════════════════════════════════╝
```
In the terminal, end with `REVISION COMPLETE: start a NEW conversation and run /plan2code-3-implement --web with specs/<feature-name>/overview.md` (it finds the next phase itself). The web console's finish carries it, so print nothing there.
### STEP 6: Revision Cleanup
`🔄 [REVISION] Step 6: Revision Cleanup`
@@ -250,4 +239,4 @@ Work summary — tell user: change type, tasks added/modified/removed, phases re
Returning context: Revised specs in `specs/<feature-name>/`. Run `/plan2code-3-implement --web` in a new conversation to continue implementation.
**On the web console:** specs change only at Step 3, so stopping before then saves nothing. The finish command is `/plan2code-3-implement specs/<feature-name>/overview.md` when revised, or the revise-plan command on an abort. The closing box above is printed to a terminal the browser user is not watching.
**On the web console:** specs change only at Step 3, so stopping before then saves nothing. The finish command is `/plan2code-3-implement specs/<feature-name>/overview.md` when revised, or the revise-plan command on an abort.
+6 -9
View File
@@ -8,7 +8,7 @@ Technical writer transforming planning documents into precise, complete implemen
## Interface
The FIRST thing you do, before anything else — before Auto-Discovery: ask **web console** (suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow document` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir; `--spec` once known), then read <D>/console.md and <D>/notes/document.md. Switchable anytime. `--web` or `Use the web console for this session.` in the argument answers it; drop the flag. Dashboard-launched? Resume its open session (console-launches.md), then Auto-Discovery.
The FIRST thing you do, before anything else in this file — before Auto-Discovery: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow document` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir; `--spec` once known), then read <D>/console.md and <D>/notes/document.md. 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 Auto-Discovery.
## Scripts
@@ -38,7 +38,7 @@ Keep with you: the breakdown, the task writing and every question. Strength and
## Auto-Discovery
`specs/` is gitignored, so Glob silently finds nothing there; `specs.mjs` reads it directly.
`specs/` is gitignored, so a file search silently finds nothing there; `specs.mjs` reads it directly.
**Before asking user for input:**
@@ -103,7 +103,7 @@ Line numbers may only appear as SUPPLEMENTAL context alongside a semantic refere
3. **Analyze** planning document thoroughly
4. **Identify** phase boundaries by dependencies and deliverables
5. **Use existing** `specs/<feature-name>/` directory
6. **Write** `overview.md` first, copying from PLAN-DRAFT:
6. **Write** `overview.md` first (header with the format marker, see Templates), copying from PLAN-DRAFT:
- Summary (from Executive Summary)
- Phase Checklist (Implementation Phases), directly under Summary
- Parallel Execution Groups (filled in step 8)
@@ -183,7 +183,7 @@ Use kebab-case for feature name (e.g., `user-authentication`).
### overview.md
Header: Title, Created date, Source (PLAN-DRAFT path), Status on its own line as `**Status:** <value>` (Not Started | In Progress | Complete).
Header: Title, Created date, Source (PLAN-DRAFT path), Status on its own line as `**Status:** <value>` (Not Started | In Progress | Complete), then the format marker on its own line, `<!-- plan2code-format: 2 -->` (it makes `specs.mjs check` hold this spec to the current format rules as errors).
Sections, in this order: Summary (from Executive Summary), Phase Checklist, Parallel Execution Groups table (from analysis), Tech Stack table (exact copy from PLAN-DRAFT), Architecture (Pattern + Component Overview table), Risks and Mitigations table, Success Criteria checklist, Quick Reference (Key Files, Environment Variables, External Dependencies), Completion Summary (filled during finalization).
@@ -245,13 +245,10 @@ Paste the `comment` from `specs.mjs metrics specs/<feature-name> --step document
╲│ ★ │╱
│ ◡ │ Specs are ready! Time to build!
╰┬─┬╯
============================================
NEXT STEP: Start a NEW conversation and run:
`/plan2code-3-implement-review --web`
Or use `/plan2code-3-implement --web` for implementation without the review gate.
```
In the terminal, end with `NEXT STEP: start a NEW conversation and run /plan2code-3-implement-review --web` (or `/plan2code-3-implement --web` for implementation without the review gate). The web console's finish carries it, so print nothing there.
## Abort Handling
If user says "abort", "cancel", "start over":
+3 -25
View File
@@ -45,35 +45,13 @@ State:
> 🔬 [Review Mode] Implementation complete; reviewing before sign-off.
Read references/review.md
Read references/review.md and references/review-in-build.md
Run Review Mode with this explicit scope:
- Scope is **Focused**.
- Review the exact phase change set tracked in Stage 1, including any relevant tests and documentation changed for the phase.
- Use overview.md and the active phase file for spec-compliance context; they do not broaden scope to other phases.
- Read related callers, dependencies, and project files when needed to verify a finding, but do not turn them into unrelated review targets.
- Review all changed files completely and apply the full focused-review depth required by Review Mode.
- Review Mode's helper rule applies: a fresh helper runs the analysis when available, at the strength `helper-strength.md` gives for the phase's review (standard and high, or strongest and high when the phase touches security, auth or data), this session verifies every finding, and the Stage 4 report carries the Reviewed by line. The helper's brief carries the phase's `phase-X.md` and its change set only, never Stage 1's work notes.
Override Review Mode's completion and session-end behavior:
1. Do not provide commit instructions or next-conversation routing.
2. Do not ask the user to approve the review or commit.
3. If there are findings, present Review Mode's normal `H`, `A`, and `S` fix options and wait for the user's choice.
4. If there are zero findings, proceed directly to Stage 4.
5. If the user explicitly declines or defers findings, preserve them as unresolved and proceed to Stage 4.
Run Review Mode as `references/review-in-build.md` says, over the exact phase change set tracked in Stage 1 (including the relevant tests and documentation changed for the phase). Findings go to the person as Review Mode's `H`, `A` and `S` options; zero findings go straight to Stage 4, and declined or deferred findings stay unresolved.
## Stage 3: Resolve Findings
When the user selects fixes, follow Review Mode's Post-Fix Flow to plan, apply, and verify them.
- Add every review-fix file to the phase change set.
- Re-read every file modified by a fix and check for introduced issues.
- Update the Phase Completion Summary if a fix materially changes the implementation summary or test results.
- Do not mark the phase complete and do not ask for approval during fix processing.
- Ignore Review Mode's `Reply approved to commit` instruction; selected-fix verification transitions directly to Stage 4.
- When selected fixes are verified, preserve any unselected findings as unresolved and proceed to Stage 4.
When the user selects fixes, apply and verify them as `references/review-in-build.md` says (Fixing). Every review-fix file joins the phase change set. Selected-fix verification goes straight to Stage 4 with any unselected findings kept as unresolved; do not mark the phase complete or ask for approval here.
## Stage 4: Final Implementation Sign-Off
+5 -5
View File
@@ -16,7 +16,7 @@ The FIRST thing you do, before anything else in this file — before reading a s
- `node "<S>/specs.mjs" status <spec>`: the Phase Checklist, parallel groups, every phase's task counts by marker, goal, the phase-selection verdict (`next`) and consistency `checks`.
- `node "<S>/specs.mjs" mark <spec> --phase <N> --to in-progress|done`: the overview checkbox (and on `done`, the phase file's Status line). It refuses to reset `[/]` to `[ ]`.
- `node "<S>/commit-msg.mjs" --subject "<subject>" --add-all`: the commit command (`<subject>`, then `AI Assisted`).
- `node "<S>/commit-msg.mjs" --subject "<subject>" --files <path> ...`: the commit command for the phase's own files (`<subject>`, then `AI Assisted`).
## Rules
@@ -32,7 +32,7 @@ The FIRST thing you do, before anything else in this file — before reading a s
## Required Context
Needs the spec files. `specs/` is gitignored, so never search it with Glob; the script reads the disk directly and never looks in `specs--completed/`.
Needs the spec files. `specs/` is gitignored, so never search it with a file search; the script reads the disk directly and never looks in `specs--completed/`.
**Option 1: User provides an overview.md path** → `specs.mjs status <that path>`.
@@ -78,7 +78,7 @@ Before acting on `ask-resume` or `choose`, read the Notes of each `[/]` phase on
### Manual Check-Off
`next.tasks` lists each open task (`id`, `marker`, `text`, `detail` with any BLOCKED / User action note). The spec is not built, and Finalize stays unavailable on the dashboard, until each is `[x]`. Say so in one line, then ask about them **one at a time**, in order:
`next.tasks` lists each open task (`id`, `marker`, `text`, `detail` with any BLOCKED / User action note). The spec is not built until each is `[x]`; Finalize stays unavailable on the dashboard until then, or until the only ones left are `[!]` tasks that each carry a written reason (`status`'s `finalizeReady`). Say so in one line, then ask about them **one at a time**, in order:
1. Show the task: id, `text`, and what `detail` says the person must do or check.
2. Ask: "Is this done? (yes / not yet)". Console: a `confirm` item (`yesLabel` "Done, check it off", `noLabel` "Not yet"), posted with `--wait`, a new id per task.
@@ -147,7 +147,7 @@ After all tasks:
4. Use Completion Report Format
5. Do NOT mark phase `[x]` until user says "approved"
6. Address issues before re-requesting sign-off
7. On "review": run the code review BEFORE sign-off — Review Mode (references/review.md in the installed skill, src/plan2code-review.md in this repo), scope fixed to exactly this phase's change set, no commit instructions; its helper rule and Reviewed by line still apply. Apply the fixes the user picks, update the report, then request sign-off again. The phase stays `[/]` throughout.
7. On "review": run the code review BEFORE sign-off as `references/review-in-build.md` says, over exactly this phase's change set. Apply the fixes the user picks, update the report, then request sign-off again. The phase stays `[/]` throughout.
8. **Show me it working** (on "show me"; offered, never required): read how to start and view the app from `AGENTS.md` (Commands). Missing: work it out from the project (`package.json` scripts, `Makefile`, `README`), and once it worked offer the line for `AGENTS.md`; cannot work it out: ask the person. Start it, look at the change (a browser tool's screenshot when available, otherwise the command's output), stop what you started, and add one line to the Phase Completion Summary: what was run and what was seen. Screenshots go on the web console page only, never under `specs/`. Then request sign-off again.
## Issue Handling
@@ -207,7 +207,7 @@ On user "approved":
| Phase X: [Name] | Y | [One-sentence goal] |
| Phase X+1: [Name] | Z | [One-sentence goal] |
5. Write a one-line subject for the phase, then give the user the `command` from `commit-msg.mjs --subject "<subject>" --add-all`. It enforces the format: subject ≤100 chars and EXACTLY TWO -m flags (subject, `AI Assisted`), no body. If a phase spec file contains a longer commit-message template, use only its subject line. The diff is the body; the PR is the explanation. On Windows PowerShell 5.1 (no `&&`), give `add` and `commit` as two commands instead.
5. Write a one-line subject for the phase, then give the user the `command` from `commit-msg.mjs --subject "<subject>" --files <path> ...`, one `--files` per file the phase created or changed. It enforces the format: subject ≤100 chars and EXACTLY TWO -m flags (subject, `AI Assisted`), no body. If a phase spec file contains a longer commit-message template, use only its subject line. The diff is the body; the PR is the explanation. On Windows PowerShell 5.1 (no `&&`), give `add` and `commit` as two commands instead.
6. **If more phases:** "NEXT STEP: Start NEW conversation and run: `/plan2code-3-implement specs/<feature>/overview.md --web`"
7. **If final phase:** "NEXT STEP: Start NEW conversation and run: `/plan2code-4-finalize --web`"
8. Mention `/plan2code-1b-revise-plan --web` option
@@ -1,6 +1,6 @@
# Community Feedback Submission (STEP 6.5 detail)
> Loaded by `src/plan2code-4-finalize.md` STEP 6.5. This file has no character limit (see `AGENTS-architecture.md` Reference Files).
> Loaded by `src/plan2code-4-finalize.md` STEP 6.5. This file has no character limit (see `AGENTS-architecture-install.md` Reference Files).
Everything in the payload is read from files, so a script builds it: the metrics from the `METRICS_JSON` comments the pipeline already wrote, the task counts from the phase files, your Step 5 answers from overview.md's `## User Feedback` table, the installed version, and a sha256 prefix of each prompt. Your part is the two judgment counts, the preview, and the user's approval.
@@ -14,7 +14,11 @@ import os from "node:os";
import path from "node:path";
import crypto from "node:crypto";
import { execFileSync, spawn } from "node:child_process";
import { EXIT, HERE, fail, out, parseArgs, run, readText, isDir, rel, compactDate, clock, version, phaseFiles } from "./common.mjs";
import { EXIT, HERE, fail, out, parseArgs, run, readText, isDir, rel, compactDate, clock, version, consoleModule } from "./common.mjs";
// The phase-file pick specs.mjs and the dashboard use (the console's
// spec-files.mjs), bound in run() before any command.
let pickPhaseFiles;
const USAGE = `
feedback-payload.mjs: build and submit the community feedback payload. JSON on stdout.
@@ -115,7 +119,7 @@ function parseFeedbackTable(overview) {
function phaseTasks(dir) {
const c = { total: 0, complete: 0, assumed: 0, blocked: 0 };
// The same files specs.mjs reads: a stale sibling like phase-1-old.md is not counted.
for (const n of phaseFiles(dir).values()) {
for (const n of pickPhaseFiles(fs.readdirSync(dir)).values()) {
for (const line of (readText(path.join(dir, n)) || "").split(/\r?\n/)) {
// The same task line specs.mjs counts: 2.3, 3.6a, or a named 1.T.
const m = line.match(/^\s*[-*] \[(.)\]\s+\*\*Task\s+\d+\.(?:\d+|[A-Za-z]+)[a-z]*\b/);
@@ -371,6 +375,7 @@ async function cmdSubmit(args) {
}
run(USAGE, async (argv) => {
({ pickPhaseFiles } = await consoleModule("spec-files.mjs"));
const args = parseArgs(argv, { booleans: ["dry-run", "truncate"], values: ["root", "out", "from"], lists: ["set"] });
const cmd = args._[0];
if (cmd === "build") return cmdBuild(args);
+5 -5
View File
@@ -8,7 +8,7 @@ QA engineer and technical lead performing rigorous final validation. Verify spec
## Interface
The FIRST thing you do, before anything else in this file — before the Required Context check, before Step 1: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow finalize` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir; `--spec specs/<feature-name>` if known, else post `specDir` later), then read <D>/console.md and <D>/notes/finalize.md; the audit options, the final review, the doc-update approval and every cleanup confirmation go through it. Switchable anytime. `--web` or `Use the web console for this session.` in the argument answers it; drop the flag. Dashboard-launched? Resume its open session (console-launches.md), then the Required Context check.
The FIRST thing you do, before anything else in this file — before the Required Context check, before Step 1: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow finalize` before reading (<D>: references/web-console/ beside this SKILL.md, or the dir in ~/.plan2code/console/console-dir; `--spec specs/<feature-name>` if known, else post `specDir` later), then read <D>/console.md and <D>/notes/finalize.md; the audit options, the final review, the doc-update approval and every cleanup confirmation 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 the Required Context check.
## Scripts
@@ -36,7 +36,7 @@ The FIRST thing you do, before anything else in this file — before the Require
### Required Context
Need all implementation spec files. If the user hasn't named the spec, run `specs.mjs list` (it reads gitignored `specs/` directly, where Glob silently finds nothing, and never offers `specs--completed/`, which holds archives only). Exactly one active spec → use it.
Need all implementation spec files. If the user hasn't named the spec, run `specs.mjs list` (it reads gitignored `specs/` directly, where a file search silently finds nothing, and never offers `specs--completed/`, which holds archives only). Exactly one active spec → use it.
If multiple active spec folders exist or nothing provided, ask user for:
1. The entire `specs/<feature-name>/` directory: `overview.md` and all `phase-X.md` files
@@ -209,11 +209,12 @@ Add this summary to `overview.md` under `## Completion Summary`.
|----------|-----------|--------|
| `AGENTS.md` + `.agents-docs/*` | Commands/architecture/gotchas changed; stale paths | Update ALL applicable files (agent voice) |
| `README.md` | New features, setup, API docs | Update if feature affects usage |
| `CHANGELOG.md` | Version history | Add entry for feature |
| `.env.example` | Environment variables | Add new required vars |
| `API.md` / human docs | API documentation | Update with new endpoints |
| `CLAUDE.md` | AI assistant context | Update if patterns changed |
The CHANGELOG is the Changelog skill's job (the web console's finish offers it): Finalize writes no entry.
Route each fact per tier voice (agent vs human) — never copy text across tiers; cut redundancy.
Report: table of documents needing updates with proposed changes. List each document with specific additions.
@@ -323,7 +324,6 @@ Paste the `comment` from `specs.mjs metrics <spec's current path: specs--complet
- `specs/<feature-name>/overview.md` - Added completion summary
- [each file a Step 2.5 fix changed, if any]
- `README.md` - [if updated]
- `CHANGELOG.md` - [if updated]
### Archived Files
[List all files moved to specs--completed/<feature-name>/]
@@ -374,7 +374,7 @@ If you discovered undocumented commands, dependency quirks, gotchas (>5min cost)
(Step 7 already delivered the completion summary — don't repeat it.)
Suggested commit (only if Step 2.5 fixes landed or README, CHANGELOG, or other tracked docs were updated): the `command` from `commit-msg.mjs --subject "chore: finalize and archive <feature-name>"`. When the console finish prints it, the finish also carries `"commit": true`, so the finished screen offers **Commit it now**.
Suggested commit (only if Step 2.5 fixes landed or README or other tracked docs were updated): the `command` from `commit-msg.mjs --subject "chore: finalize and archive <feature-name>"`. When the console finish prints it, the finish also carries `"commit": true`, so the finished screen offers **Commit it now**.
Returning context: Feature complete. Specs archived to `specs--completed/<feature-name>/`.
+5 -1
View File
@@ -185,8 +185,12 @@ async function prHosts() {
return (await consoleModule("settings.mjs")).readPrHosts();
}
// A status that failed (or ran past git()'s time limit) is an unknown tree,
// never a clean one: a plan built on it would offer to commit nothing.
function readStatus(root) {
return R.parseStatusV2(g(["status", "--porcelain=v2", "-z", "--branch", "--untracked-files=normal"], root, { raw: true }).out);
const res = g(["status", "--porcelain=v2", "-z", "--branch", "--untracked-files=normal"], root, { raw: true });
if (!res.ok) fail(EXIT.CRASH, "status-failed", `git status failed: ${res.err || "no message"}`, "Run git status yourself to see why, then try again.");
return R.parseStatusV2(res.out);
}
// The commit flow's lists and letters: a conflicted file only under conflicted.
+2 -2
View File
@@ -26,7 +26,7 @@ Determine it like this:
2. **Present it to the user for confirmation before writing the file.** If you
inferred a candidate, show it and ask them to confirm or correct it. If you
genuinely can't infer one, ask them to tell you what the next agent should do.
Use `AskUserQuestion` (offer your inferred task as the recommended option) or
Use the question tool (offer your inferred task as the recommended option) or
a plain question — either is fine.
3. **Do not write the document until the user has confirmed or supplied the next
task.** This gate is mandatory even when your inference feels obviously
@@ -50,7 +50,7 @@ The dashboard lists the handoff for this checkout until it is picked up, and old
## If this touched a plan2code spec
`specs/` is gitignored — Glob/Grep and file search silently skip it. If the
`specs/` is gitignored — file search and text search silently skip it. If the
conversation worked inside `specs/<feature>/`, confirm the exact state before
writing with `node "<S>/specs.mjs" status specs/<feature>` (`<S>` is `scripts/` beside this SKILL.md: `~/.agents/skills/plan2code-handoff/scripts/` globally), which reads the disk:
+1 -1
View File
@@ -30,7 +30,7 @@ The FIRST thing you do, before anything else in this file — before the Awarene
## Awareness Context
Before making any updates, orient yourself to current project state: read `AGENTS.md` and `README.md`, list `src/` directory, run `ls specs/` (not Glob — gitignored) to read any active spec overview, and locate the human-docs tree (`docs/` or equivalent — don't assume).
Before making any updates, orient yourself to current project state: read `AGENTS.md` and `README.md`, list `src/` directory, run `ls specs/` (not a file search — gitignored) to read any active spec overview, and locate the human-docs tree (`docs/` or equivalent — don't assume).
## Helpers
+1 -1
View File
@@ -20,7 +20,7 @@ The FIRST thing you do, before anything else in this file — before exploring t
`<S>` is `scripts/` beside this SKILL.md (`~/.agents/skills/plan2code-init/scripts/` globally). Run from the project root; each prints one JSON object, and on a non-zero exit `next` says what to do.
- `node "<S>/agents-md.mjs" inspect`: does AGENTS.md exist, its line count against 500, `structure` (`progressive` or `single-file`), sections, `.agents-docs/` files, broken links, orphans. Run it first.
- `node "<S>/agents-md.mjs" inspect`: does AGENTS.md exist, its line count against 500, `structure` (`progressive` or `single-file`), sections, `.agents-docs/` files, broken links, orphans. Run it first. Any `notices` it returns (such as `specs--completed/` being gitignored, so finished specs are not backed up): tell the user once, in your closing summary.
- `node "<S>/agents-md.mjs" filename "<Section Name>"`: a section's detail file name, its `Details:` link line and its two header lines.
- `node "<S>/agent-files.mjs" detect` / `apply <id> ... [--dry-run]`: AI Agent File Sync (below).
+1 -1
View File
@@ -161,6 +161,6 @@ Ready to implement? (yes / modify / escalate / abort)
## Session End
Work summary — tell user: task name, plan delivered (or PLAN-DRAFT created if escalated). After a build, offer: "Reply `show me` to see it running." **Show me it working** (offered, never required): start the app as `AGENTS.md` Commands says (missing: work it out from `package.json` scripts, `Makefile` or `README` and, once it worked, offer the line for `AGENTS.md`; else ask), look at the change (a browser tool's screenshot, else the command's output), stop what you started, and add one line to the work summary: what was run and what was seen. Screenshots go on the web console page only.
Work summary — tell user: task name, plan delivered (or PLAN-DRAFT created if escalated). After a build, offer: "Reply `show me` to see it running." A review the person asks for after the build runs as `references/review-in-build.md` says. **Show me it working** (offered, never required): start the app as `AGENTS.md` Commands says (missing: work it out from `package.json` scripts, `Makefile` or `README` and, once it worked, offer the line for `AGENTS.md`; else ask), look at the change (a browser tool's screenshot, else the command's output), stop what you started, and add one line to the work summary: what was run and what was seen. Screenshots go on the web console page only.
**On the web console:** after a build, keep waiting for the review button's answer before you stop.
@@ -5,7 +5,7 @@ Principles to reason from, not a lookup table — adapt; when a case doesn't fit
cleanly, say what you verified and ask.
- **Plan2Code Workflow Pipeline:** `/plan2code-1-plan` → `PLAN-*` files · `/plan2code-2-document` → `overview.md` + `phase-*.md` (the "spec docs") in `specs/<feature>/` · `/plan2code-3-implement` → checks off phase tasks, one phase per run · `/plan2code-4-finalize` → archives to `specs--completed/`.
- **Find specs (any OS/shell):** `specs/` is gitignored, and search tools (Glob/Grep/project search) skip gitignored paths on many platforms — an empty search result is not evidence either way. Use `node "<S>/specs.mjs" list` (`<S>`: see Review Mode → Scripts) (feature dir unknown, or to see what is archived in `completed`) and `node "<S>/specs.mjs" status <spec>`: they read the disk directly. Its fields map onto the routing below: `planDrafts` with no `overview` · `overview` with no phases · each phase's `tasks.open` · a name in `completed`. If the script cannot run, read the expected files directly — file reads see gitignored paths. Conclude "no specs" only after `list` or a failed direct read.
- **Find specs (any OS/shell):** `specs/` is gitignored, and search tools (file search, text search, project search) skip gitignored paths on many platforms — an empty search result is not evidence either way. Use `node "<S>/specs.mjs" list` (`<S>`: see Review Mode → Scripts) (feature dir unknown, or to see what is archived in `completed`) and `node "<S>/specs.mjs" status <spec>`: they read the disk directly. Its fields map onto the routing below: `planDrafts` with no `overview` · `overview` with no phases · each phase's `tasks.open` · a name in `completed`. If the script cannot run, read the expected files directly — file reads see gitignored paths. Conclude "no specs" only after `list` or a failed direct read.
- **Reconcile three signals:** session context (what this conversation was doing — a fresh session may have none), user intent (what they asked reviewed), the disk check above. Disk wins on state; context wins on intent and on disk silence; no context → intent + disk decide.
- **plan2code artifact reviewed (a plan, the spec docs, phases) — route on the reviewed feature's own `specs/<feature>/` state (another feature's specs prove nothing here), to the earliest unmet stage, suggesting only a step whose input exists:**
- `PLAN-*` without `overview.md` → `/plan2code-2-document`
+4 -4
View File
@@ -42,7 +42,7 @@ Three levels -- auto-detected, always respect explicit user override:
| **Branch** | "review my changes", or picked when asked | Branch changes vs main |
| **Full** | "full review" or names a subsystem | Entire codebase/subsystem |
**Detection:** 1) User prompt wins. 2) Conversation context = `focused`. 3) Scope already decided by a host workflow (a build's review, `building-review.md`) = use it. 4) Standalone with nothing named = scan, then ask (Step 1). Never default to `branch` silently. Ambiguous? Ask.
**Detection:** 1) User prompt wins. 2) Conversation context = `focused`. 3) Scope already decided by a host workflow (a build's review: `references/review-in-build.md`, `building-review.md`) = use it. 4) Standalone with nothing named = scan, then ask (Step 1). Never default to `branch` silently. Ambiguous? Ask.
**Thoroughness:** Scope controls WHAT is reviewed, not HOW DEEPLY. Every review is thorough.
@@ -52,7 +52,7 @@ Three levels -- auto-detected, always respect explicit user override:
## Process
**Pre-flight:** Check AGENTS.md — use conventions if found, note if missing. Determine review target from user prompt or conversation context. If neither provides clear signal, scan and use `ask_user_question` (Step 1) — never guess.
**Pre-flight:** Check AGENTS.md — use conventions if found, note if missing. Determine review target from user prompt or conversation context. If neither provides clear signal, scan and use the question tool (Step 1) — never guess.
**Reference files:** Companion files loaded via Read directives. Fallback rules inline if unavailable.
@@ -62,10 +62,10 @@ Three levels -- auto-detected, always respect explicit user override:
1. **User prompt** — use it.
2. **Conversation context** — recent work? Those artifacts. Scope: `focused`.
3. **Standalone, nothing named** — do not assume a target. Do a quick scan (no file reading): `review-scope.mjs`, `specs.mjs list`, recent commits. Then ask what to review (`ask_user_question`; a `choice` on the console, scope questions up front), offering only options the scan supports, each with its size: the branch's changes vs base (files, ~lines, `commits`), uncommitted changes only (when any), a spec/plan under `specs/` (when any), a named subsystem or full codebase, or specific files/folders (free text via Other). Recommend the likeliest first. Nothing found (`empty: true`, no specs)? Ask for files or a subsystem. Use the answer as the scope, then continue.
3. **Standalone, nothing named** — do not assume a target. Do a quick scan (no file reading): `review-scope.mjs`, `specs.mjs list`, recent commits. Then ask what to review (the question tool; a `choice` on the console, scope questions up front), offering only options the scan supports, each with its size: the branch's changes vs base (files, ~lines, `commits`), uncommitted changes only (when any), a spec/plan under `specs/` (when any), a named subsystem or full codebase, or specific files/folders (free text via Other). Recommend the likeliest first. Nothing found (`empty: true`, no specs)? Ask for files or a subsystem. Use the answer as the scope, then continue.
4. **Scan details** — `review-scope.mjs` diffs the branch against its base (`main`, else `master`, or `--base`) plus staged, unstaged and untracked changes: `files`, `counts`, `commits`, `mix`, `batchByRisk`. `empty: true` or exit 3 `not-a-repo`? Ask user what to review. Exit 3 `no-base`? Rerun with `--base <trunk>`, asking which branch is the trunk if unclear.
**Classify review type** from context (auto-detect; use `ask_user_question` only if ambiguous):
**Classify review type** from context (auto-detect; use the question tool only if ambiguous):
| Signal | Type | Prioritize |
|--------|------|-------------|
+31
View File
@@ -0,0 +1,31 @@
# Review Inside a Build
> Read by Review, Implement, Implement + Review and Quick Task when a review runs inside a build: before a phase is signed off, or after a quick task is built. Never invoked as a skill. The web console's `building-review.md` adds only what the page does differently.
Run Review Mode (`references/review.md`, or this skill's own SKILL.md in Review) with these rules. They win over Review Mode's own scope questions, completion and session-end steps.
## Scope
- Scope is **Focused** and already decided. Do not ask about it.
- The change set is exact: files created or modified in this build (the phase or the quick task), the artifacts its tasks name, and the tests and docs changed for it. Unrelated working-tree changes are not in it.
- `overview.md` and the phase file give spec-compliance context. They never widen the scope to other phases.
- Read callers, dependencies and project files when you need them to verify a finding. They are not review targets.
- Review every changed file completely, at the full Focused depth Review Mode requires.
## Who reviews
A fresh helper runs the analysis when your tool can start one and helpers are not switched off, at the strength `references/helper-strength.md` gives (standard and high; strongest and high when the change touches security, auth or data). This session verifies every finding. The report carries the Reviewed by line. The helper's brief holds the phase file (when there is one) and the change set only, never the build's work notes.
## Ending the review
- No commit instructions, no next-conversation routing, and no request to approve the review or a commit. Ignore Review Mode's `Reply approved to commit`.
- Findings: offer Review Mode's `H`, `A` and `S` fix options and wait. Zero findings: go straight back to the build's report. Findings the person declines or defers stay as unresolved.
## Fixing
Follow Review Mode's Post-Fix Flow. Add every fixed file to the change set, re-read each one and check it for new problems, and run the tests that cover the fixes (`references/test-runs.md`). Update the completion summary only when a fix changes what it says. Choosing fixes is never approval.
## Back to the build
- The phase stays `[/]` and no checkbox moves. Only the build's own sign-off prompt, asked after the review, can approve.
- The final report adds **Review Results** (scope, files reviewed, the Reviewed by line, totals by severity, fixes applied) and **Unresolved Review Findings** (a short numbered list, or `None`), and its Verify section includes the fix checks.
- A quick task has no sign-off: its summary carries the same review results and the commit command for the task and its fixes together.
Loaded 100 of 130 files, more files were not shown because too many files have changed in this diff. Show more