diff --git a/.agents-docs/AGENTS-architecture.md b/.agents-docs/AGENTS-architecture.md index 80c3dd9..f4bd210 100644 --- a/.agents-docs/AGENTS-architecture.md +++ b/.agents-docs/AGENTS-architecture.md @@ -271,25 +271,25 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web | `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` 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` | The finale's first ride's room (`MAT_ROOM`, data, read by `core/ghoul-rooms.js`, in `FINALE.rooms` once `ready`) | -| `public/activities/ghoul-rush/rides/mat/ghoul-mat.js` | The finale's first ride, Down the Hatch (`MAT`, a pack in `PACKS`): surfing the WELCOME mat down the House's throat | -| `public/activities/ghoul-rush/rides/mat/ghoul-mat-draw.js` | Down the Hatch's drawing: `LOOKS`, `VOICES`, `LOSE_WORDS`, `LOSE_SOUNDS` and `matArt(d)` | -| `public/activities/ghoul-rush/rides/mat/ghoul-sfx-mat.js` | Down the Hatch's own sounds as data (`MAT_SFX`), merged by `ghoul-sfx.js` | -| `public/activities/ghoul-rush/stages/marrow/ghoul-dollhouse-room.js` | The finale's second kill's room (`DOLLHOUSE_ROOM`, data, in `FINALE.rooms` once `ready`) | -| `public/activities/ghoul-rush/stages/marrow/ghoul-marrow-eye.js` | The finale's second kill, Every Room at Once (`EYE`, a pack in `PACKS`): the Eye in the dollhouse, shades of the keepers YOU beat, the lurch | -| `public/activities/ghoul-rush/stages/marrow/ghoul-marrow-eye-draw.js` | Every Room at Once's drawing: `LOOKS`, `VOICES`, `LOSE_WORDS`, `LOSE_SOUNDS` and `eyeArt(d)` (shades through `d.bossArt`) | -| `public/activities/ghoul-rush/stages/marrow/ghoul-sfx-marrow-eye.js` | Every Room at Once's own sounds as data (`EYE_SFX`), merged by `ghoul-sfx.js` | -| `public/activities/ghoul-rush/rides/bonestair/ghoul-bonestair-room.js` | The finale's second ride's room (`BONESTAIR_ROOM`, data, in `FINALE.rooms` once `ready`) | -| `public/activities/ghoul-rush/rides/bonestair/ghoul-bonestair.js` | The finale's second ride, The Bone Stair (`BONESTAIR`, a pack in `PACKS`): down the stair ahead of the collapse | -| `public/activities/ghoul-rush/rides/bonestair/ghoul-bonestair-draw.js` | The Bone Stair's drawing: `LOOKS`, `VOICES`, `LOSE_WORDS`, `LOSE_SOUNDS` and `bonestairArt(d)` | -| `public/activities/ghoul-rush/rides/bonestair/ghoul-sfx-bonestair.js` | The Bone Stair's own sounds as data (`BONESTAIR_SFX`), merged by `ghoul-sfx.js` | -| `public/activities/ghoul-rush/stages/marrow/ghoul-pit-room.js` | The finale's last kill's room (`PIT_ROOM`, data, in `FINALE.rooms` once `ready`) | -| `public/activities/ghoul-rush/stages/marrow/ghoul-marrow-heart.js` | The finale's last kill, The Heart of Marrow (`HEART`, a pack in `PACKS`): the beat, the ribs, HOLD FIRE (`round.flood` stops the blaster in `fire()`) | -| `public/activities/ghoul-rush/stages/marrow/ghoul-marrow-heart-draw.js` | The Heart of Marrow's drawing: `LOOKS`, `VOICES`, `LOSE_WORDS`, `LOSE_SOUNDS` and `heartArt(d)` | -| `public/activities/ghoul-rush/stages/marrow/ghoul-sfx-marrow-heart.js` | The Heart of Marrow's own sounds as data (`HEART_SFX`), merged by `ghoul-sfx.js` | -| `public/activities/ghoul-rush/story/ghoul-ending.js` | The ending once the House is dead (phase `ending`, shaped like `ghoul-story.js`): `beginEnding` (from `finish` in `ghoul-run.js`), `stepEnding`, `takeEnding`, `pressEnding`, `releaseEnding`, `skipEnding`, `ENDING_TRACK`; it wins the run at its end | -| `public/activities/ghoul-rush/story/ghoul-ending-draw.js` | The ending's drawing: `endingArt(d)` hands back `{ card, react }`, plugged into `drawScene` and `react` | -| `public/activities/ghoul-rush/story/ghoul-sfx-ending.js` | The ending's own sounds and music as data (`ENDING_SFX`), merged by `ghoul-sfx.js` | +| `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). | diff --git a/install.js b/install.js index 9c87cd0..fbc6ae9 100644 --- a/install.js +++ b/install.js @@ -143,7 +143,7 @@ const SOURCE_PROMPTS = [ displayName: 'Init Mode', description: 'Generate AGENTS.md file for project-specific guidance', isUtility: true, - scripts: ['agents-md.mjs', 'agent-files.mjs'], + scripts: ['agents-md.mjs', 'agent-files.mjs', 'test-map.mjs', 'glob.mjs'], additionalReferences: [ { source: 'web-console', target: 'web-console' }, { source: 'shared-references/helper-strength.md', target: 'helper-strength.md' } @@ -156,7 +156,7 @@ const SOURCE_PROMPTS = [ displayName: 'Init Update Mode', description: 'Update existing AGENTS.md with new learnings', isUtility: true, - scripts: ['agents-md.mjs', 'agent-files.mjs', 'commit-msg.mjs'], + scripts: ['agents-md.mjs', 'agent-files.mjs', 'commit-msg.mjs', 'test-map.mjs', 'glob.mjs'], additionalReferences: [ { source: 'web-console', target: 'web-console' }, { source: 'shared-references/helper-strength.md', target: 'helper-strength.md' } diff --git a/package.json b/package.json index c28659d..dd73545 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,7 @@ "fix:eol": "node scripts/fix-line-endings.mjs", "play": "node scripts/play.mjs", "pretest": "node scripts/fix-line-endings.mjs", - "test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-pointers.mjs scripts/test-console-wire-budgets.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-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-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-skill-test-runs.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-agent-lookup.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-activities.mjs scripts/test-web-console-page-setup.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs" + "test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-test-map.mjs scripts/test-script-test-match.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-pointers.mjs scripts/test-console-wire-budgets.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-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-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-skill-test-runs.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-agent-lookup.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-activities.mjs scripts/test-web-console-page-setup.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs" }, "devDependencies": { "gpt-tokenizer": "2.9.0", diff --git a/scripts/test-script-test-map.mjs b/scripts/test-script-test-map.mjs new file mode 100644 index 0000000..2634403 --- /dev/null +++ b/scripts/test-script-test-map.mjs @@ -0,0 +1,290 @@ +// Tests for the shared test-map.mjs (shipped in plan2code-init) and glob.mjs. +// +// See skill-script-helpers.mjs for how these run. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { runScript, tmp, write, read } from "./skill-script-helpers.mjs"; +import { toPosix, globToRegExp, matchGlob, unsupported } from "../src/skill-scripts/glob.mjs"; + +const T = (cwd, args) => runScript("plan2code-init", "test-map.mjs", args, { cwd }); + +const TABLE = "| Area | Paths | Run | Shared |\n|---|---|---|---|\n| Launcher | `src/launcher/**` | `node --test scripts/test-launcher.mjs` | no |\n"; + +function project(agents, files = {}) { + const dir = tmp("test-map"); + if (agents !== null) write(dir, "AGENTS.md", agents); + for (const [rel, content] of Object.entries(files)) write(dir, rel, content); + return dir; +} + +function rowsFile(dir, rows) { + return write(dir, "rows.json", JSON.stringify(rows)); +} + +const NEW_TABLE = + "| Area | Paths | Run | Shared |\n|---|---|---|---|\n| Console | `src/web-console/**`, `scripts/test-web-console-*.mjs` | `node --test scripts/test-web-console-logic.mjs` | no |\n| Helpers | `scripts/*-helpers.mjs` | `npm test` | yes |\n"; + +const ROWS = [ + { area: "Console", paths: ["src/web-console/**", "scripts/test-web-console-*.mjs"], run: "node --test scripts/test-web-console-logic.mjs", shared: false }, + { area: "Helpers", paths: ["scripts/*-helpers.mjs"], run: "npm test", shared: true }, +]; + +/* ------------------------------------------------------------------ read */ + +test("test-map read: a table in AGENTS.md", () => { + const dir = project(`# Project\n\n## Test map\n\nWhich checks cover what.\n\n${TABLE}\n## Next\n\nMore.\n`); + const r = T(dir, ["read"]); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json, { + ok: true, + found: true, + source: "AGENTS.md", + rows: [{ area: "Launcher", paths: ["src/launcher/**"], run: "node --test scripts/test-launcher.mjs", shared: false }], + problems: [], + }); +}); + +test("test-map read: a section linking to .agents-docs/AGENTS-test-map.md reads that file", () => { + const dir = project("# P\n\n## Test map\n\nDetails: [Test map](./.agents-docs/AGENTS-test-map.md)\n", { + ".agents-docs/AGENTS-test-map.md": `# Test map\n\n> Part of [AGENTS.md](../AGENTS.md).\n\nSee [other](./AGENTS-other.md).\n\n${TABLE}`, + ".agents-docs/AGENTS-other.md": `# Other\n\n${TABLE.replace("Launcher", "Wrong")}`, + }); + const r = T(dir, ["read"]); + assert.equal(r.code, 0, r.stderr); + assert.equal(r.json.source, ".agents-docs/AGENTS-test-map.md"); + assert.equal(r.json.rows.length, 1); + assert.equal(r.json.rows[0].area, "Launcher", "follows exactly one link, never a link from the linked file"); + const bare = project("## Test map\n\nSee [map](.agents-docs/AGENTS-test-map.md).\n", { ".agents-docs/AGENTS-test-map.md": TABLE }); + assert.equal(T(bare, ["read"]).json.source, ".agents-docs/AGENTS-test-map.md", "the ](.agents-docs/...) form works too"); +}); + +test("test-map read and write: a link outside .agents-docs/ is a problem, and write refuses", () => { + const dir = project("## Test map\n\nSee [map](./docs/test-map.md).\n", { "docs/test-map.md": TABLE }); + const r = T(dir, ["read"]); + assert.equal(r.code, 0, r.stderr); + assert.equal(r.json.found, true); + assert.deepEqual(r.json.rows, []); + assert.match(r.json.problems[0], /outside \.agents-docs\//); + rowsFile(dir, ROWS); + const w = T(dir, ["write", "--rows", "rows.json"]); + assert.equal(w.code, 5); + assert.equal(w.json.error, "link-outside"); +}); + +test("test-map read: headers in any order and case, extra columns ignored", () => { + const dir = project("## Test Map\n\n| run | SHARED | Notes | paths | area |\n|:---|---|---|---|---:|\n| `npm t` | Yes | x | `a/**`, b/*.js , `c/{d,e}.ts` | Core |\n"); + const r = T(dir, ["read"]); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json.rows, [{ area: "Core", paths: ["a/**", "b/*.js", "c/{d,e}.ts"], run: "npm t", shared: true }]); + assert.deepEqual(r.json.problems, []); +}); + +test("test-map read: a missing Run column is a problem and no rows are returned", () => { + const dir = project("## Test map\n\n| Area | Paths | Shared |\n|---|---|---|\n| A | `a/**` | no |\n"); + const r = T(dir, ["read"]); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json.rows, []); + assert.match(r.json.problems[0], /no Run column/); +}); + +test("test-map read: Shared values, unsupported globs and escaped pipes", () => { + const dir = project( + "## Test map\n\n| Area | Paths | Run | Shared |\n|---|---|---|---|\n| One | `a/**` | `x \\| y` | Yes |\n| Two | b/** | y | no |\n| Three | c/** | z | maybe |\n| Four | `src/[ab]/*.js`, `ok/**` | w | NO |\n| Five | `src/[ab]/*.js` | v | no |\n" + ); + const r = T(dir, ["read"]); + assert.equal(r.code, 0, r.stderr); + const [one, two, three, four, five] = r.json.rows; + assert.equal(one.shared, true); + assert.equal(one.run, "x | y", "an escaped pipe stays inside its cell"); + assert.equal(two.shared, false); + assert.equal(three.shared, false); + assert.deepEqual(four.paths, ["ok/**"], "the unsupported glob is dropped from the row"); + assert.equal(four.shared, false); + assert.deepEqual(five.paths, [], "a row left with no paths"); + assert.equal(r.json.problems.length, 3); + assert.ok(r.json.problems.some((p) => /Row 3 \(Three\).*"maybe"/.test(p))); + assert.ok(r.json.problems.some((p) => /Row 4 \(Four\).*src\/\[ab\]\/\*\.js/.test(p))); +}); + +test("test-map read: a table inside a code fence is ignored, and so is a heading there", () => { + const fenced = project("# P\n\n```md\n## Test map\n\n" + TABLE + "```\n"); + assert.equal(T(fenced, ["read"]).json.found, false, "a heading inside a fence is not the section"); + const dir = project("## Test map\n\n```\n" + TABLE + "```\n\n" + TABLE.replace("Launcher", "Real")); + const r = T(dir, ["read"]); + assert.equal(r.code, 0, r.stderr); + assert.equal(r.json.rows.length, 1); + assert.equal(r.json.rows[0].area, "Real"); +}); + +test("test-map read: no heading is found: false; no AGENTS.md is exit 3", () => { + const r = T(project("# P\n\n## Commands\n\nnpm test\n"), ["read"]); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json, { ok: true, found: false, source: null, rows: [], problems: [] }); + const none = T(project(null), ["read"]); + assert.equal(none.code, 3); + assert.equal(none.json.error, "no-agents-md"); +}); + +/* ----------------------------------------------------------------- write */ + +// Every line of `before` outside the table is in `after`, in order and unchanged. +function outsideTableUnchanged(before, after) { + const strip = (t) => t.split("\n").filter((l) => !/^\|/.test(l)); + const b = strip(before); + const a = strip(after); + let i = 0; + for (const line of a) if (line === b[i]) i++; + assert.equal(i, b.length, "every line outside the table is kept"); +} + +function roundTrip(dir) { + const r = T(dir, ["read"]); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json.rows, ROWS); + assert.deepEqual(r.json.problems, []); +} + +test("test-map write: no heading appends a Test map section", () => { + const before = "# P\n\n## Commands\n\nnpm test\n"; + const dir = project(before); + rowsFile(dir, ROWS); + const w = T(dir, ["write", "--rows", "rows.json"]); + assert.equal(w.code, 0, w.stderr); + assert.deepEqual(w.json, { ok: true, written: true, source: "AGENTS.md", dryRun: false }); + const after = read(dir, "AGENTS.md"); + assert.ok(after.startsWith(before), "the old text is untouched"); + assert.equal( + after.slice(before.length), + "\n## Test map\n\n| Area | Paths | Run | Shared |\n|---|---|---|---|\n| Console | `src/web-console/**`, `scripts/test-web-console-*.mjs` | `node --test scripts/test-web-console-logic.mjs` | no |\n| Helpers | `scripts/*-helpers.mjs` | `npm test` | yes |\n" + ); + roundTrip(dir); +}); + +test("test-map write: a heading with no table gets one after its first paragraph", () => { + const before = "# P\n\n## Test map\n\nWhich checks cover\nwhich files.\n\nA second paragraph.\n\n## Next\n\nMore.\n"; + const dir = project(before); + rowsFile(dir, ROWS); + assert.equal(T(dir, ["write", "--rows", "rows.json"]).code, 0); + const after = read(dir, "AGENTS.md"); + assert.match(after, /which files\.\n\n\| Area \| Paths \| Run \| Shared \|\n[\s\S]*\| yes \|\n\nA second paragraph\./); + outsideTableUnchanged(before, after); + roundTrip(dir); + const bare = project("## Test map\n\n## Next\n"); + rowsFile(bare, ROWS); + assert.equal(T(bare, ["write", "--rows", "rows.json"]).code, 0); + assert.match(read(bare, "AGENTS.md"), /^## Test map\n\n\| Area [\s\S]*\| yes \|\n\n## Next\n$/, "directly under a heading with no paragraph"); +}); + +test("test-map write: an existing table is replaced in place, every other line byte-identical", () => { + const before = `# P\n\nIntro.\n\n## Test map\n\nWhich checks.\n\n${TABLE}| Old | \`old/**\` | \`x\` | no |\n\nAfter the table.\n\n## Next\n\nMore.\n`; + const dir = project(before); + rowsFile(dir, ROWS); + assert.equal(T(dir, ["write", "--rows", "rows.json"]).code, 0); + const after = read(dir, "AGENTS.md"); + assert.equal(after, before.replace(`${TABLE}| Old | \`old/**\` | \`x\` | no |\n`, NEW_TABLE), "only the table changed"); + roundTrip(dir); + const again = T(dir, ["write", "--rows", "rows.json"]); + assert.equal(again.json.written, false, "unchanged rows write nothing"); +}); + +test("test-map write: a CRLF AGENTS.md keeps its line endings", () => { + const before = `# P\r\n\r\n## Test map\r\n\r\nWhich checks.\r\n\r\n${TABLE.replace(/\n/g, "\r\n")}\r\n## Next\r\n\r\nMore.\r\n`; + const dir = project(before); + rowsFile(dir, ROWS); + assert.equal(T(dir, ["write", "--rows", "rows.json"]).code, 0); + const after = read(dir, "AGENTS.md"); + assert.ok(!/[^\r]\n/.test(after), "every line ends in CRLF"); + assert.equal(after, before.replace(TABLE.replace(/\n/g, "\r\n"), NEW_TABLE.replace(/\n/g, "\r\n")), "only the table changed"); + roundTrip(dir); +}); + +test("test-map write: a linked file's table is replaced there, AGENTS.md untouched", () => { + const agents = "# P\n\n## Test map\n\nDetails: [Test map](./.agents-docs/AGENTS-test-map.md)\n"; + const linked = `# Test map\n\n> Part of [AGENTS.md](../AGENTS.md).\n\n${TABLE}\nTrailing note.\n`; + const dir = project(agents, { ".agents-docs/AGENTS-test-map.md": linked }); + rowsFile(dir, ROWS); + const w = T(dir, ["write", "--rows", "rows.json"]); + assert.equal(w.code, 0, w.stderr); + assert.equal(w.json.source, ".agents-docs/AGENTS-test-map.md"); + assert.equal(read(dir, "AGENTS.md"), agents); + outsideTableUnchanged(linked, read(dir, ".agents-docs/AGENTS-test-map.md")); + roundTrip(dir); +}); + +test("test-map write: --dry-run writes nothing", () => { + const before = "# P\n"; + const dir = project(before); + rowsFile(dir, ROWS); + const w = T(dir, ["write", "--rows", "rows.json", "--dry-run"]); + assert.equal(w.code, 0, w.stderr); + assert.deepEqual(w.json, { ok: true, written: false, source: "AGENTS.md", dryRun: true }); + assert.equal(read(dir, "AGENTS.md"), before); +}); + +test("test-map write: invalid rows are exit 4 with the row index; no AGENTS.md is exit 3", () => { + const dir = project("# P\n"); + rowsFile(dir, [ROWS[0], { area: "B", paths: [], run: "x" }]); + const w = T(dir, ["write", "--rows", "rows.json"]); + assert.equal(w.code, 4); + assert.equal(w.json.row, 1); + assert.equal(read(dir, "AGENTS.md"), "# P\n"); + const none = project(null); + rowsFile(none, ROWS); + assert.equal(T(none, ["write", "--rows", "rows.json"]).code, 3); + assert.ok(!fs.existsSync(path.join(none, "AGENTS.md"))); + assert.equal(T(dir, ["write"]).code, 2, "--rows is required"); +}); + +/* ------------------------------------------------------------------ glob */ + +test("glob: ** at the start, middle and end", () => { + assert.ok(matchGlob("**/test/**", "test/a.js")); + assert.ok(matchGlob("**/test/**", "a/b/test/c/d.js")); + assert.ok(matchGlob("**/*.md", "README.md")); + assert.ok(matchGlob("**/*.md", "docs/x/y.md")); + assert.ok(matchGlob("src/**/a.js", "src/a.js")); + assert.ok(matchGlob("src/**/a.js", "src/x/y/a.js")); + assert.ok(!matchGlob("src/**/a.js", "src/xa.js")); + assert.ok(matchGlob("src/**", "src/a.js")); + assert.ok(matchGlob("src/**", "src/x/y/a.js")); + assert.ok(!matchGlob("src/**", "srcx/a.js")); + assert.ok(matchGlob("**", "any/thing.js")); +}); + +test("glob: * and ? stay inside one folder; a bare name matches only at the root", () => { + assert.ok(matchGlob("src/*.js", "src/a.js")); + assert.ok(!matchGlob("src/*.js", "src/x/a.js")); + assert.ok(matchGlob("src/?.js", "src/a.js")); + assert.ok(!matchGlob("src/?.js", "src/ab.js")); + assert.ok(!matchGlob("src/?.js", "src//.js")); + assert.ok(matchGlob("package.json", "package.json")); + assert.ok(!matchGlob("package.json", "a/package.json")); + assert.ok(matchGlob("**/package.json", "a/package.json")); +}); + +test("glob: {a,b} alternation, literal dots and parentheses", () => { + assert.ok(matchGlob("src/*.{js,ts}", "src/a.ts")); + assert.ok(matchGlob("{lib,src}/**", "lib/x.js")); + assert.ok(!matchGlob("src/*.{js,ts}", "src/a.tsx")); + assert.ok(!matchGlob("a.js", "axjs"), "a dot is literal"); + assert.ok(matchGlob("docs/(old)/a+b.md", "docs/(old)/a+b.md"), "parentheses and + are literal"); + assert.ok(!matchGlob("docs/(old)/a+b.md", "docs/old/aab.md")); + assert.ok(globToRegExp("a.js") instanceof RegExp); +}); + +test("glob: Windows backslash input and unsupported syntax", () => { + assert.equal(toPosix("src\\a\\b.js"), "src/a/b.js"); + assert.equal(toPosix("./src/a.js"), "src/a.js"); + assert.ok(matchGlob("src/**", "src\\a\\b.js")); + assert.ok(matchGlob("src\\*.js", "src/a.js")); + assert.match(unsupported("src/[ab]/*.js"), /character classes/); + assert.match(unsupported("!src/**"), /negation/); + assert.match(unsupported("{a,{b,c}}"), /nested/); + assert.match(unsupported("src/***"), /\*\*\*/); + assert.equal(unsupported("src/**/*.{js,ts}"), null); + assert.ok(!matchGlob("src/[ab].js", "src/a.js"), "an unsupported glob matches nothing"); + assert.throws(() => globToRegExp("src/[ab].js")); +}); diff --git a/scripts/test-script-test-match.mjs b/scripts/test-script-test-match.mjs new file mode 100644 index 0000000..1409a43 --- /dev/null +++ b/scripts/test-script-test-match.mjs @@ -0,0 +1,291 @@ +// Tests for the shared test-match.mjs. +// +// No skill ships test-match.mjs yet, so these run it from src/skill-scripts/, +// where common.mjs, glob.mjs, test-map.mjs and review-scope.mjs sit beside it. +// See skill-script-helpers.mjs for the fixtures and the scrubbed git config. + +import { test, after } from "node:test"; +import assert from "node:assert/strict"; +import path from "node:path"; +import { spawnSync, execFileSync } from "node:child_process"; +import { ROOT, NOW, scrubbedEnv, tmp, write, gitInit, gitIn, copyFixture, fixtureCleanup } from "./skill-script-helpers.mjs"; + +after(fixtureCleanup); + +const SCRIPT = path.join(ROOT, "src", "skill-scripts", "test-match.mjs"); +const SCOPE = path.join(ROOT, "src", "skill-scripts", "review-scope.mjs"); + +function runShared(args, { cwd, input } = {}) { + const r = spawnSync(process.execPath, [SCRIPT, ...args], { cwd: cwd || ROOT, encoding: "utf8", input, env: scrubbedEnv({ PLAN2CODE_NOW: NOW }) }); + let json = null; + try { + json = JSON.parse(r.stdout); + } catch {} + return { code: r.status, json, stdout: r.stdout, stderr: r.stderr }; +} + +// A commit with pinned author and committer dates. +function commitAt(dir, date, msg, files = {}) { + for (const [rel, content] of Object.entries(files)) write(dir, rel, content); + const env = { ...process.env, GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date }; + execFileSync("git", ["add", "-A"], { cwd: dir, env, stdio: "pipe" }); + execFileSync("git", ["commit", "-q", "-m", msg], { cwd: dir, env, stdio: "pipe" }); +} + +const MAP = `# Project + +## Test map + +| Area | Paths | Run | Shared | +|---|---|---|---| +| Launcher | \`src/launcher/**\` | \`node --test scripts/test-launcher.mjs\` | no | +| Console | \`src/web-console/**\`, \`src/launcher/shared.js\` | \`node --test tests/console\` | yes | +`; + +// One repo for covers and nearest: a test map, and tests found by name, +// by mirrored folder and by imports (JS, Python, Go). +function matchRepo() { + return copyFixture("match", "match", (dir) => { + gitInit(dir); + commitAt(dir, "2026-07-01T12:00:00Z", "Start", { + "AGENTS.md": MAP, + "package.json": "{}\n", + "src/launcher/a.js": "a\n", + "src/launcher/shared.js": "s\n", + "src/web-console/x.js": "x\n", + "tests/console/server.test.js": "t\n", + "tests/console/page.test.js": "t\n", + "src/app/util.js": "u\n", + "src/app/util.test.js": "t\n", + "src/app/other.test.js": "t\n", + "tests/app/mirror.test.js": "t\n", + "tests/app/second.test.js": "t\n", + "src/widget/button.js": "b\n", + "src/widget/__tests__/button.js": "t\n", + "src/lib/math.js": "m\n", + "src/lib/alias.js": "al\n", + "src/pkgdir/index.js": "i\n", + "tests/calc.test.js": 'import { add } from "../src/lib/math";\nconst p = require("../src/pkgdir");\nimport x from "@/lib/alias";\nimport fs from "node:fs";\n', + "pkg/__init__.py": "", + "pkg/mod.py": "def thing(): pass\n", + "tests/test_calc.py": "from pkg.mod import thing\n", + "go.mod": "module example.com/m\n\ngo 1.21\n", + "gosrc/util/u.go": "package util\n", + "gotests/check_test.go": 'package gotests\n\nimport (\n\t"testing"\n\tu "example.com/m/gosrc/util"\n)\n', + "fixtures/sample.json": "{}\n", + "test/helpers/setup.js": "h\n", + }); + }); +} + +/* ---------------------------------------------------------------- covers */ + +test("test-match covers: map rows, shared hits, hints and the fallback rules", () => { + const dir = matchRepo(); + const files = ["src/launcher/a.js", "src/launcher/shared.js", "src/web-console/x.js", "src/app/util.js", "src/widget/button.js", "src/lib/math.js", "src/pkgdir/index.js", "src/lib/alias.js", "pkg/mod.py", "gosrc/util/u.go", "package.json", "fixtures/sample.json", "test/helpers/setup.js"]; + const r = runShared(["covers", "--files", files.join(",")], { cwd: dir }); + assert.equal(r.code, 0, r.stderr); + assert.equal(r.json.mapFound, true); + assert.deepEqual(r.json.matched, [ + { area: "Launcher", run: "node --test scripts/test-launcher.mjs", shared: false, files: ["src/launcher/a.js", "src/launcher/shared.js"] }, + { area: "Console", run: "node --test tests/console", shared: true, files: ["src/launcher/shared.js", "src/web-console/x.js"] }, + ]); + const un = Object.fromEntries(r.json.unmatched.map((u) => [u.file, u])); + assert.deepEqual(Object.keys(un).sort(), files.slice(3).sort(), "every file no row covers is unmatched"); + assert.deepEqual(un["src/app/util.js"], { file: "src/app/util.js", tests: ["src/app/util.test.js"], method: "name" }); + assert.deepEqual(un["src/widget/button.js"], { file: "src/widget/button.js", tests: ["src/widget/__tests__/button.js"], method: "folder" }); + assert.deepEqual(un["src/lib/math.js"], { file: "src/lib/math.js", tests: ["tests/calc.test.js"], method: "imports" }, "an extensionless relative import"); + assert.deepEqual(un["src/pkgdir/index.js"], { file: "src/pkgdir/index.js", tests: ["tests/calc.test.js"], method: "imports" }, "a folder import resolves to its index"); + assert.deepEqual(un["src/lib/alias.js"], { file: "src/lib/alias.js", tests: [], method: null }, "an @/ alias is never guessed"); + assert.deepEqual(un["pkg/mod.py"], { file: "pkg/mod.py", tests: ["tests/test_calc.py"], method: "imports" }); + assert.deepEqual(un["gosrc/util/u.go"], { file: "gosrc/util/u.go", tests: ["gotests/check_test.go"], method: "imports" }, "a Go import through go.mod"); + assert.deepEqual(r.json.sharedHits, [ + { file: "src/launcher/shared.js", why: "row" }, + { file: "src/web-console/x.js", why: "row" }, + { file: "package.json", why: "config" }, + { file: "fixtures/sample.json", why: "fixture" }, + { file: "test/helpers/setup.js", why: "test-helper" }, + ]); +}); + +test("test-match covers: Windows-style --files input", () => { + const dir = matchRepo(); + const r = runShared(["covers", "--files", "src\\launcher\\a.js"], { cwd: dir }); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json.matched[0].files, ["src/launcher/a.js"]); +}); + +test("test-match covers --stdin: real review-scope.mjs output", () => { + const dir = matchRepo(); + gitIn(dir)("checkout", "-q", "-b", "feature"); + commitAt(dir, "2026-07-02T12:00:00Z", "Change", { "src/launcher/a.js": "a2\n" }); + write(dir, "src/app/util.js", "u2\n"); + const scope = spawnSync(process.execPath, [SCOPE], { cwd: dir, encoding: "utf8", env: scrubbedEnv() }); + assert.equal(scope.status, 0, scope.stderr); + const r = runShared(["covers", "--stdin"], { cwd: dir, input: scope.stdout }); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json.matched.map((m) => m.area), ["Launcher"]); + assert.deepEqual(r.json.unmatched, [{ file: "src/app/util.js", tests: ["src/app/util.test.js"], method: "name" }]); + assert.equal(runShared(["covers", "--stdin"], { cwd: dir, input: "not json" }).code, 2); + assert.equal(runShared(["covers"], { cwd: dir }).code, 2); +}); + +test("test-match covers: no test map leaves every file unmatched, still exit 0", () => { + const dir = tmp("match-nomap"); + write(dir, "a.js", "a\n"); + write(dir, "a.test.js", "t\n"); + const r = runShared(["covers", "--files", "a.js,b.js"], { cwd: dir }); + assert.equal(r.code, 0, r.stderr); + assert.equal(r.json.mapFound, false); + assert.deepEqual(r.json.matched, []); + assert.deepEqual(r.json.unmatched, [ + { file: "a.js", tests: ["a.test.js"], method: "name" }, + { file: "b.js", tests: [], method: null }, + ]); +}); + +/* ------------------------------------------------------------------ gaps */ + +// Untested files changed on pinned dates: c newest, then a (two commits) and +// b (one) on the same day, then old (outside the 90-day window). +function gapsRepo() { + return copyFixture("gaps", "gaps", (dir) => { + gitInit(dir); + commitAt(dir, "2026-01-01T12:00:00Z", "Old", { "src/old.js": "o\n", "src/d.js": "d\n", "src/d.test.js": "t\n", "src/types.d.ts": "x\n", "specs/x/a.js": "s\n", "vendor/v.js": "v\n", "README.md": "r\n" }); + commitAt(dir, "2026-07-01T12:00:00Z", "A", { "src/a.js": "a1\n" }); + commitAt(dir, "2026-07-20T12:00:00Z", "A and B", { "src/a.js": "a2\n", "src/b.js": "b1\n" }); + commitAt(dir, "2026-07-25T12:00:00Z", "C", { "src/sub/c.js": "c1\n" }); + }); +} + +test("test-match gaps --scope all: untested source files ranked by last change, then churn", () => { + const dir = gapsRepo(); + const r = runShared(["gaps", "--scope", "all"], { cwd: dir }); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json.gaps, [ + { file: "src/sub/c.js", area: null, runner: null, commits90d: 1, lastTouched: "2026-07-25" }, + { file: "src/a.js", area: null, runner: null, commits90d: 2, lastTouched: "2026-07-20" }, + { file: "src/b.js", area: null, runner: null, commits90d: 1, lastTouched: "2026-07-20" }, + { file: "src/old.js", area: null, runner: null, commits90d: 0, lastTouched: null }, + ]); + assert.equal(r.json.scope, "all"); + assert.equal(r.json.scanned, 5, "tests, .d.ts, specs/, vendor/ and docs are not source files"); + assert.equal(r.json.covered, 1); + assert.equal(r.json.capped, false); +}); + +test("test-match gaps --scope path and --scope branch", () => { + const dir = gapsRepo(); + const p = runShared(["gaps", "--scope", "path", "--path", "src/sub"], { cwd: dir }); + assert.equal(p.code, 0, p.stderr); + assert.deepEqual(p.json.gaps.map((x) => x.file), ["src/sub/c.js"]); + assert.equal(runShared(["gaps", "--scope", "path"], { cwd: dir }).code, 2, "--scope path needs --path"); + + gitIn(dir)("checkout", "-q", "-b", "feature"); + commitAt(dir, "2026-07-30T12:00:00Z", "Feature", { "src/feat.js": "f\n", "src/feat2.js": "g\n" }); + write(dir, "src/new.js", "n\n"); + const b = runShared(["gaps", "--scope", "branch"], { cwd: dir }); + assert.equal(b.code, 0, b.stderr); + assert.deepEqual(b.json.gaps, [ + { file: "src/feat.js", area: null, runner: null, commits90d: 1, lastTouched: "2026-07-30" }, + { file: "src/feat2.js", area: null, runner: null, commits90d: 1, lastTouched: "2026-07-30" }, + { file: "src/new.js", area: null, runner: null, commits90d: 0, lastTouched: null }, + ]); +}); + +test("test-match gaps: a non-git folder walks the tree; --scope branch is exit 3", () => { + const dir = tmp("match-nogit"); + write(dir, "src/a.js", "a\n"); + write(dir, "node_modules/x/i.js", "x\n"); + const r = runShared(["gaps", "--scope", "all"], { cwd: dir }); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json.gaps, [{ file: "src/a.js", area: null, runner: null, commits90d: null, lastTouched: null }]); + const b = runShared(["gaps", "--scope", "branch"], { cwd: dir }); + assert.equal(b.code, 3); + assert.equal(b.json.error, "not-a-repo"); + assert.equal(runShared(["gaps"], { cwd: dir }).code, 2); +}); + +test("test-match gaps: any matching row with a run covers a file; a row without one only names its area", () => { + const dir = tmp("match-rows"); + write(dir, "AGENTS.md", "## Test map\n\n| Area | Paths | Run | Shared |\n|---|---|---|---|\n| Source | `src/**` | | no |\n| X | `src/x.js` | `npm t` | no |\n"); + write(dir, "src/x.js", "x\n"); + write(dir, "src/y.js", "y\n"); + write(dir, "src/m.ts", "m\n"); + write(dir, "src/m.test.mts", "t\n"); + const r = runShared(["gaps", "--scope", "all"], { cwd: dir }); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json.gaps, [{ file: "src/y.js", area: "Source", runner: null, commits90d: null, lastTouched: null }]); + assert.equal(r.json.covered, 2, "x.js by the second row, m.ts by its .mts test"); +}); + +test("test-match gaps: capped at 2,000 source files", () => { + const dir = tmp("match-cap"); + for (let i = 0; i < 2005; i++) write(dir, `src/f${String(i).padStart(4, "0")}.js`, "x\n"); + const r = runShared(["gaps", "--scope", "all"], { cwd: dir }); + assert.equal(r.code, 0, r.stderr); + assert.equal(r.json.capped, true); + assert.equal(r.json.scanned, 2000); + assert.equal(r.json.gaps.length, 2000); + assert.equal(r.json.gaps.at(-1).file, "src/f1999.js", "the first 2,000 by path"); +}); + +/* --------------------------------------------------------------- nearest */ + +test("test-match nearest: own tests, then the same folder, then the mirrored folder, at most 3", () => { + const dir = matchRepo(); + const r = runShared(["nearest", "--file", "src/app/util.js"], { cwd: dir }); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json, { ok: true, file: "src/app/util.js", tests: ["src/app/util.test.js", "src/app/other.test.js", "tests/app/mirror.test.js"] }); + const m = runShared(["nearest", "--file", "src/app/new.js"], { cwd: dir }); + assert.deepEqual(m.json.tests, ["src/app/other.test.js", "src/app/util.test.js", "tests/app/mirror.test.js"]); + assert.equal(runShared(["nearest"], { cwd: dir }).code, 2); +}); + +test("test-match nearest: the area's run path, then the nearest by shared folders", () => { + const dir = matchRepo(); + const r = runShared(["nearest", "--file", "src/web-console/x.js"], { cwd: dir }); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json.tests.slice(0, 2), ["tests/console/page.test.js", "tests/console/server.test.js"], "the Console row's run names tests/console"); + assert.equal(r.json.tests.length, 3); + const deep = runShared(["nearest", "--file", "src/widget/deep/z.js"], { cwd: dir }); + assert.equal(deep.json.tests[0], "src/widget/__tests__/button.js", "the test file sharing the most folders"); +}); + +/* ------------------------------------------------- the project's own map */ + +test("test-match covers: AGENTS.md's Targeted tests first table, saved as a test map", () => { + const dir = tmp("match-targeted"); + write( + dir, + "AGENTS.md", + `## Test map + +| Area | Paths | Run | Shared | +|---|---|---|---| +| Activities | \`src/web-console/public/activities/**\`, \`src/web-console/public/tones.js\`, \`src/web-console/public/music.js\` | \`node --test scripts/test-web-console-tones.mjs scripts/test-web-console-activities.mjs\` | no | +| Music prototype | \`prototypes/music/**\` | \`node prototypes/music/check.cjs\` | no | +| Web console area | \`src/web-console/**\` | \`node --test scripts/test-web-console-logic.mjs\` | no | +| Launcher | \`src/launcher/**\` | \`node --test scripts/test-launcher.mjs\` | no | +| Skill script | \`src/skill-scripts/**\`, \`src/plan2code-*-scripts/**\` | \`node --test scripts/test-skill-scripts.mjs\` | no | +| Workflow prompt | \`src/plan2code-*.md\` | \`node scripts/validate-char-count.js\` | no | +| Docs | \`**/*.md\` | \`node --test scripts/test-us-english.mjs scripts/test-line-endings.mjs\` | no | +` + ); + const samples = { + Activities: "src/web-console/public/activities/snake.js", + "Music prototype": "prototypes/music/ghoul/index.html", + "Web console area": "src/web-console/routes.mjs", + Launcher: "src/launcher/plan2code.js", + "Skill script": "src/plan2code-git-scripts/git.mjs", + "Workflow prompt": "src/plan2code-3-implement.md", + Docs: ".readme/web-console.md", + }; + const r = runShared(["covers", "--files", Object.values(samples).join(",")], { cwd: dir }); + assert.equal(r.code, 0, r.stderr); + assert.deepEqual(r.json.unmatched, []); + for (const [area, file] of Object.entries(samples)) { + const row = r.json.matched.find((m) => m.area === area); + assert.ok(row && row.files.includes(file), `${area} covers ${file}`); + } +}); diff --git a/scripts/test-skill-scripts.mjs b/scripts/test-skill-scripts.mjs index 2fc9fe6..f3b6ba8 100644 --- a/scripts/test-skill-scripts.mjs +++ b/scripts/test-skill-scripts.mjs @@ -70,11 +70,23 @@ test("scripts are self-contained: built-ins and siblings only", () => { for (const f of fs.readdirSync(dir).filter((n) => n.endsWith(".mjs"))) { const t = fs.readFileSync(path.join(dir, f), "utf8"); for (const m of t.matchAll(/^import .* from "([^"]+)";$/gm)) { - assert.ok(m[1].startsWith("node:") || m[1] === "./common.mjs", `${f} imports ${m[1]}`); + const sibling = /^\.\/[\w-]+\.mjs$/.test(m[1]) && fs.existsSync(path.join(dir, m[1])); + assert.ok(m[1].startsWith("node:") || m[1] === "./common.mjs" || sibling, `${f} imports ${m[1]}`); } assert.ok(!/[\u0000-\u0008]/.test(t), `${f} contains a control character (an escape lost in an edit?)`); } } + // A sibling import ships with its importer: every skill that carries a + // script also carries each ./x.mjs it imports. + for (const skill of fs.readdirSync(SKILLS)) { + const dir = path.join(SKILLS, skill, "scripts"); + if (!fs.existsSync(dir)) continue; + for (const f of fs.readdirSync(dir).filter((n) => n.endsWith(".mjs"))) { + for (const m of fs.readFileSync(path.join(dir, f), "utf8").matchAll(/^import .* from "(\.\/[^"]+)";$/gm)) { + assert.ok(fs.existsSync(path.join(dir, m[1])), `${skill}/scripts/${f} imports ${m[1]}, which the skill does not ship`); + } + } + } }); /* ================================================================ specs.mjs */ diff --git a/src/skill-scripts/glob.mjs b/src/skill-scripts/glob.mjs new file mode 100644 index 0000000..79f25aa --- /dev/null +++ b/src/skill-scripts/glob.mjs @@ -0,0 +1,109 @@ +// glob.mjs: the small glob subset the test map uses, as RegExps. +// +// A library, no CLI. The test map's Paths cells hold globs, and every script +// that reads them (test-map.mjs, test-match.mjs) matches them the same way: +// +// ** any number of path segments, including none +// * any characters except / +// ? one character except / +// {a,b} alternation, no nesting +// +// Everything else is literal. unsupported() names anything outside the subset +// so the test map can report it instead of matching it wrongly. Paths are +// forward-slash normalized; on Windows both sides are lower-cased, as file +// names there are case-insensitive. + +const FOLD = process.platform === "win32"; +const fold = (s) => (FOLD ? s.toLowerCase() : s); + +/** Backslashes to /, a leading ./ dropped. */ +export function toPosix(p) { + return String(p).replace(/\\/g, "/").replace(/^(\.\/)+/, ""); +} + +/** A reason string for a glob outside the subset, or null when it is supported. */ +export function unsupported(glob) { + const g = String(glob); + if (!g.trim()) return "empty glob"; + if (/[[\]]/.test(g)) return "character classes ([...]) are not supported"; + if (g.startsWith("!")) return "negation (!) is not supported"; + if (g.includes("***")) return "*** is not a glob; use ** for any folders"; + let depth = 0; + for (const ch of g) { + if (ch === "{") { + if (++depth > 1) return "nested braces are not supported"; + } else if (ch === "}") { + if (--depth < 0) return "a } has no matching {"; + } + } + if (depth !== 0) return "a { has no matching }"; + return null; +} + +const escape = (s) => s.replace(/[.+^$()|\\/]/g, "\\$&"); + +// One alternative's text (no braces) to RegExp source. +function plain(text) { + let src = ""; + for (let i = 0; i < text.length; i++) { + const ch = text[i]; + if (ch === "*") { + if (text[i + 1] === "*") { + const before = i === 0 || text[i - 1] === "/"; + const after = i + 2 === text.length || text[i + 2] === "/"; + if (before && after) { + if (text[i + 2] === "/") { + src += "(?:[^/]*/)*"; // **/ : any folders, including none + i += 2; + } else if (i > 0) { + src = src.replace(/\\\/$/, "") + "(?:/.*)?"; // /** at the end: the folder and everything in it + i += 1; + } else { + src += ".*"; // a lone ** + i += 1; + } + continue; + } + i += 1; // ** inside a segment reads as * + } + src += "[^/]*"; + } else if (ch === "?") src += "[^/]"; + else src += escape(ch); + } + return src; +} + +/** The glob as an anchored RegExp. Throws on a glob unsupported() rejects. */ +export function globToRegExp(glob) { + const why = unsupported(glob); + if (why) throw new Error(`Unsupported glob "${glob}": ${why}`); + const g = fold(toPosix(glob)); + let src = ""; + let i = 0; + while (i < g.length) { + const open = g.indexOf("{", i); + if (open === -1) { + src += g.slice(i); + break; + } + src += g.slice(i, open); + const close = g.indexOf("}", open); + src += `\u0000${g.slice(open + 1, close)}\u0001`; + i = close + 1; + } + // Brace groups are marked with \0 ... \1 so the text around them converts + // as one piece (a ** next to a brace still sees its neighbors). + const parts = src.split(/(\u0000[^\u0001]*\u0001)/); + let out = ""; + for (const part of parts) { + if (part.startsWith("\u0000")) out += `(?:${part.slice(1, -1).split(",").map(plain).join("|")})`; + else out += plain(part); + } + return new RegExp(`^${out}$`); +} + +/** Does the path match the glob? Unsupported globs match nothing. */ +export function matchGlob(glob, p) { + if (unsupported(glob)) return false; + return globToRegExp(glob).test(fold(toPosix(p))); +} diff --git a/src/skill-scripts/test-map.mjs b/src/skill-scripts/test-map.mjs new file mode 100644 index 0000000..0d89c08 --- /dev/null +++ b/src/skill-scripts/test-map.mjs @@ -0,0 +1,323 @@ +#!/usr/bin/env node +// test-map.mjs: read and write the project test map. +// +// The test map is one Markdown table under a `## Test map` heading in +// AGENTS.md, or in .agents-docs/AGENTS-test-map.md behind one link from that +// section: `| Area | Paths | Run | Shared |`. It tells pr-prep and test which +// checks cover which files. Parsing it, validating its globs and rewriting it +// without touching any other line are mechanical, so they live here; what goes +// in the rows is the agent's call. + +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { EXIT, fail, out, parseArgs, run, readText, writeIfChanged, eol } from "./common.mjs"; +import { toPosix, unsupported } from "./glob.mjs"; + +const USAGE = ` +test-map.mjs: the project test map (## Test map in AGENTS.md). JSON on stdout. + + node test-map.mjs read [--root ] + The table's rows: { area, paths[], run, shared }, read from AGENTS.md + or from the one .agents-docs/ file its Test map section links to. + found is false when AGENTS.md has no ## Test map heading. problems lists + what could not be read (a missing column, an unsupported glob, a Shared + value that is not yes or no, a link outside .agents-docs/). + + node test-map.mjs write --rows [--dry-run] [--root ] + Write the table from a JSON array of { area, paths: [..], run, shared }. + An existing table is replaced in place, a heading with no table gets + one, and no heading appends a ## Test map section to AGENTS.md. Every + line outside the table stays byte-identical. + +Globs: ** (any folders), * and ? (within one folder), {a,b}. Anything else is +a problem and matches nothing. + +Exit: 0 ok (check "found") · 2 bad arguments · 3 no AGENTS.md, or no --rows +file · 4 invalid rows · 5 refused: the section links outside .agents-docs/. +`; + +const HEADING = /^## +test map\s*$/i; +const FENCE = /^\s*(```|~~~)/; +const COLUMNS = ["area", "paths", "run", "shared"]; + +/** Split text into lines, keeping track of which sit inside a code fence. */ +function linesOf(text) { + const lines = text.split(/\r?\n/); + let inFence = false; + const fenced = lines.map((l) => { + if (FENCE.test(l)) { + inFence = !inFence; + return true; + } + return inFence; + }); + return { lines, fenced }; +} + +/** The Test map section: heading line index and body [start, end) line range. */ +function findSection(lines, fenced) { + const at = lines.findIndex((l, i) => !fenced[i] && HEADING.test(l)); + if (at === -1) return null; + let end = lines.length; + for (let i = at + 1; i < lines.length; i++) { + if (!fenced[i] && /^#{1,2} /.test(lines[i])) { + end = i; + break; + } + } + return { heading: at, start: at + 1, end }; +} + +const isRow = (l) => /^\s*\|/.test(l); +const isSeparator = (l) => /^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)*\|?\s*$/.test(l); + +/** The first table between start and end, outside fences: [start, end) or null. */ +function findTable(lines, fenced, start, end) { + for (let i = start; i < end - 1; i++) { + if (fenced[i] || !isRow(lines[i]) || !isSeparator(lines[i + 1])) continue; + let j = i + 2; + while (j < end && !fenced[j] && isRow(lines[j])) j++; + return { start: i, end: j }; + } + return null; +} + +/** Cells of one table row; `\|` stays inside its cell as `|`. */ +function cellsOf(line) { + let s = line.trim(); + if (s.startsWith("|")) s = s.slice(1); + if (s.endsWith("|") && !s.endsWith("\\|")) s = s.slice(0, -1); + const cells = []; + let cur = ""; + for (let i = 0; i < s.length; i++) { + if (s[i] === "\\" && s[i + 1] === "|") { + cur += "|"; + i++; + } else if (s[i] === "|") { + cells.push(cur.trim()); + cur = ""; + } else cur += s[i]; + } + cells.push(cur.trim()); + return cells; +} + +const unquote = (s) => (s.length >= 2 && s.startsWith("`") && s.endsWith("`") ? s.slice(1, -1).trim() : s); + +/** A Paths cell split on commas outside braces and backticks. */ +function splitPaths(cell) { + const parts = []; + let cur = ""; + let depth = 0; + let tick = false; + for (const ch of cell) { + if (ch === "`") tick = !tick; + else if (!tick && ch === "{") depth++; + else if (!tick && ch === "}") depth = Math.max(0, depth - 1); + if (ch === "," && depth === 0 && !tick) { + parts.push(cur); + cur = ""; + } else cur += ch; + } + parts.push(cur); + return parts.map((p) => unquote(p.trim())).filter(Boolean); +} + +/** Rows and problems from the table's lines. */ +function parseTable(lines, table) { + const problems = []; + const header = cellsOf(lines[table.start]).map((c) => c.toLowerCase()); + const index = Object.fromEntries(COLUMNS.map((c) => [c, header.indexOf(c)])); + const missing = COLUMNS.filter((c) => index[c] === -1); + if (missing.length) { + const names = missing.map((c) => c[0].toUpperCase() + c.slice(1)); + return { rows: [], problems: [`The test map table has no ${names.join(", ")} column${names.length > 1 ? "s" : ""}; no rows were read`] }; + } + const rows = []; + for (let i = table.start + 2; i < table.end; i++) { + const cells = cellsOf(lines[i]); + if (cells.every((c) => !c)) continue; + const n = rows.length + 1; + const area = cells[index.area] || ""; + const label = `Row ${n}${area ? ` (${area})` : ""}`; + const paths = []; + for (const glob of splitPaths(cells[index.paths] || "")) { + const why = unsupported(glob); + if (why) problems.push(`${label}: path "${glob}" was dropped: ${why}`); + else paths.push(toPosix(glob)); + } + const sharedCell = (cells[index.shared] || "").trim(); + const yes = /^yes$/i.test(sharedCell); + if (!yes && !/^no$/i.test(sharedCell)) problems.push(`${label}: Shared is "${sharedCell}", not yes or no; read as no`); + rows.push({ area, paths, run: unquote(cells[index.run] || ""), shared: yes }); + } + return { rows, problems }; +} + +/** + * The first relative .md link in the section body. `docs` is the path under + * .agents-docs/ when it points there, else `outside` holds the target. + */ +function linkIn(lines, fenced, start, end) { + for (let i = start; i < end; i++) { + if (fenced[i]) continue; + for (const m of lines[i].matchAll(/\]\(([^)\s]+)\)/g)) { + const target = m[1].replace(/#.*$/, ""); + if (/^[a-z][a-z0-9+.-]*:/i.test(target) || !/\.md$/i.test(target)) continue; + const norm = path.posix.normalize(toPosix(target)); + if (/^\.agents-docs\/[^/]+\.md$/i.test(norm)) return { docs: norm }; + return { outside: target }; + } + } + return null; +} + +/** + * The test map of the project at `root`. Never throws for a missing map: + * `agentsMd` false means there is no AGENTS.md, `found` false no heading. + * `file` is the absolute path the table lives in (or would be written to). + */ +export function readTestMap(root) { + const agentsFile = path.join(root, "AGENTS.md"); + const text = readText(agentsFile); + if (text === null) return { agentsMd: false, found: false, source: null, rows: [], problems: [] }; + const { lines, fenced } = linesOf(text); + const section = findSection(lines, fenced); + if (!section) return { agentsMd: true, found: false, source: null, rows: [], problems: [] }; + const link = linkIn(lines, fenced, section.start, section.end); + if (link && link.outside) { + return { agentsMd: true, found: true, source: "AGENTS.md", rows: [], linkOutside: link.outside, problems: [`The Test map section links to ${link.outside}, outside .agents-docs/; no table was read`] }; + } + if (link && link.docs) { + const file = path.join(root, link.docs); + const linked = readText(file); + if (linked === null) return { agentsMd: true, found: true, source: link.docs, file, rows: [], problems: [`The Test map section links to ${link.docs}, which does not exist`] }; + const l = linesOf(linked); + const table = findTable(l.lines, l.fenced, 0, l.lines.length); + if (!table) return { agentsMd: true, found: true, source: link.docs, file, rows: [], problems: [`${link.docs} has no table`] }; + return { agentsMd: true, found: true, source: link.docs, file, ...parseTable(l.lines, table) }; + } + const table = findTable(lines, fenced, section.start, section.end); + if (!table) return { agentsMd: true, found: true, source: "AGENTS.md", file: agentsFile, rows: [], problems: ["The Test map section has no table"] }; + return { agentsMd: true, found: true, source: "AGENTS.md", file: agentsFile, ...parseTable(lines, table) }; +} + +const cell = (s) => String(s).replace(/\|/g, "\\|"); + +/** The table's lines for `rows`. */ +export function renderTable(rows) { + return [ + "| Area | Paths | Run | Shared |", + "|---|---|---|---|", + ...rows.map((r) => `| ${cell(r.area)} | ${r.paths.map((p) => `\`${cell(p)}\``).join(", ")} | \`${cell(r.run)}\` | ${r.shared ? "yes" : "no"} |`), + ]; +} + +function validRows(data) { + if (!Array.isArray(data)) fail(EXIT.INVALID, "invalid-rows", "The rows file must hold a JSON array of { area, paths, run, shared }.", "Fix the rows file and run write again."); + return data.map((r, i) => { + const bad = (what) => fail(EXIT.INVALID, "invalid-rows", `Row ${i} ${what}.`, "Fix the rows file and run write again.", { row: i }); + if (!r || typeof r !== "object") bad("is not an object"); + if (typeof r.area !== "string" || !r.area.trim()) bad("has no area"); + if (typeof r.run !== "string" || !r.run.trim()) bad("has no run command"); + if (!Array.isArray(r.paths) || !r.paths.length || r.paths.some((p) => typeof p !== "string" || !p.trim())) bad("has no paths"); + return { area: r.area.trim(), paths: r.paths.map((p) => toPosix(p.trim())), run: r.run.trim(), shared: r.shared === true }; + }); +} + +// Insert `table` into `lines` at index `at`, with a blank line before it and +// one after it unless one is already there. +function insertAt(lines, at, table) { + const after = at < lines.length && lines[at] !== "" ? [""] : []; + return [...lines.slice(0, at), "", ...table, ...after, ...lines.slice(at)]; +} + +/** The new text of a file whose Test map section (or whole body) gets `table`. */ +function placeIn(text, table, { linked }) { + const nl = eol(text); + const { lines, fenced } = linesOf(text); + if (linked) { + const t = findTable(lines, fenced, 0, lines.length); + if (t) return [...lines.slice(0, t.start), ...table, ...lines.slice(t.end)].join(nl); + const trimmed = text.replace(/(\r?\n)*$/, ""); + return `${trimmed}${nl}${nl}${table.join(nl)}${nl}`; + } + const section = findSection(lines, fenced); + if (!section) { + const lead = text === "" || text.endsWith("\n") ? "" : nl; + return `${text}${lead}${nl}## Test map${nl}${nl}${table.join(nl)}${nl}`; + } + const t = findTable(lines, fenced, section.start, section.end); + if (t) return [...lines.slice(0, t.start), ...table, ...lines.slice(t.end)].join(nl); + // After the heading's first paragraph, or right under the heading. + let i = section.start; + while (i < section.end && lines[i].trim() === "") i++; + let at = section.start; + if (i < section.end && !fenced[i] && !/^#/.test(lines[i])) { + while (i < section.end && lines[i].trim() !== "") i++; + at = i; + } + return insertAt(lines, at, table).join(nl); +} + +function write(root, rowsFile, dryRun) { + const raw = readText(path.resolve(rowsFile)); + if (raw === null) fail(EXIT.NOT_FOUND, "no-rows-file", `No rows file at ${rowsFile}.`, "Write the rows as a JSON array to a file and pass its path to --rows."); + let data; + try { + data = JSON.parse(raw); + } catch (err) { + fail(EXIT.INVALID, "invalid-rows", `The rows file is not JSON: ${err.message}`, "Fix the rows file and run write again."); + } + const rows = validRows(data); + const map = readTestMap(root); + if (!map.agentsMd) fail(EXIT.NOT_FOUND, "no-agents-md", `No AGENTS.md in ${root}.`, "Create AGENTS.md first (Init), then write the test map."); + if (map.linkOutside) fail(EXIT.REFUSED, "link-outside", `The Test map section links to ${map.linkOutside}, outside .agents-docs/.`, "Point the link at .agents-docs/AGENTS-test-map.md, or remove it, then write again."); + const table = renderTable(rows); + const linked = map.source && map.source !== "AGENTS.md"; + let file; + let next; + if (linked) { + file = map.file; + const current = readText(file); + next = + current === null + ? ["# Test map", "", "> Part of [AGENTS.md](../AGENTS.md): which checks cover which files.", "", ...table, ""].join(eol(readText(path.join(root, "AGENTS.md")) || "\n")) + : placeIn(current, table, { linked: true }); + } else { + file = path.join(root, "AGENTS.md"); + next = placeIn(readText(file), table, { linked: false }); + } + const source = linked ? map.source : "AGENTS.md"; + const written = dryRun ? false : writeIfChanged(file, next); + return { ok: true, written, source, dryRun: !!dryRun }; +} + +async function main(argv) { + const args = parseArgs(argv, { values: ["root", "rows"], booleans: ["dry-run"] }); + const root = path.resolve(args.root || "."); + const cmd = args._[0]; + if (cmd === "read") { + const map = readTestMap(root); + if (!map.agentsMd) fail(EXIT.NOT_FOUND, "no-agents-md", `No AGENTS.md in ${root}.`, "There is no test map to read; offer to create AGENTS.md (Init)."); + out({ ok: true, found: map.found, source: map.source, rows: map.rows, problems: map.problems }); + return; + } + if (cmd === "write") { + if (!args.rows) fail(EXIT.USAGE, "missing-rows", "write needs --rows .", "Run with --help for usage."); + out(write(root, args.rows, args["dry-run"])); + return; + } + fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", "Commands: read, write. Run with --help."); +} + +// Run as a script; imported (by test-match.mjs), do nothing. +const isMain = (() => { + try { + return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url)); + } catch { + return false; + } +})(); +if (isMain) run(USAGE, main); diff --git a/src/skill-scripts/test-match.mjs b/src/skill-scripts/test-match.mjs new file mode 100644 index 0000000..e27d2cc --- /dev/null +++ b/src/skill-scripts/test-match.mjs @@ -0,0 +1,589 @@ +#!/usr/bin/env node +// test-match.mjs: files to tests, in both directions. +// +// pr-prep asks which checks cover a branch's changed files; test asks which +// source files no test covers, and which existing tests to read for style. +// Both answers come from the same rules, in the same order: the project's +// test map first, then name, folder and import matching. Anything these rules +// cannot settle (a path alias, a bare package name) is left unmatched for the +// agent to judge, never guessed. + +import fs from "node:fs"; +import path from "node:path"; +import { execFileSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { EXIT, HERE, fail, out, parseArgs, run, readText, isDir, now } from "./common.mjs"; +import { toPosix, matchGlob } from "./glob.mjs"; +import { readTestMap } from "./test-map.mjs"; + +const USAGE = ` +test-match.mjs: match files to tests, both ways. JSON on stdout. + + node test-match.mjs covers (--files | --stdin) [--root ] + Changed files to the checks that cover them. --stdin takes + review-scope.mjs JSON (files[].path). matched: test map rows that cover + at least one file, in table order. unmatched: { file, tests, method } + for every file no row covers; tests and method come from the name, + folder and import rules (method null when nothing was found). + sharedHits: { file, why }: why is "row" (a Shared: yes row) or a hint + for the agent to judge ("config", "test-helper", "fixture"). + + node test-match.mjs gaps --scope branch|all|path [--path

] [--base ] [--root

] + Source files no test covers: { file, area, runner, commits90d, + lastTouched }, newest first, then by commits in the last 90 days. + branch: the files review-scope.mjs reports; all: every tracked file; + path: every file under --path. Capped at 2,000 source files (capped). + + node test-match.mjs nearest --file [--root ] + Up to 3 existing test files to read for the project's test style. + +Exit: 0 ok · 2 bad arguments · 3 not a git repository (gaps --scope branch). +`; + +/* ------------------------------------------------------------- files */ + +const SKIP_DIRS = new Set(["node_modules", ".git", "dist", "build", "vendor", "target", ".venv"]); +const TEST_DIRS = new Set(["test", "tests", "__tests__", "spec"]); +const CODE_EXT = new Set(["js", "mjs", "cjs", "ts", "tsx", "jsx", "py", "go", "rs", "java", "kt", "cs", "rb", "php", "swift"]); +const SOURCE_SKIP = new Set(["node_modules", "vendor", "dist", "build", "target", ".venv", "specs", "specs--completed"]); +const CAP = 2000; + +const fold = (s) => (process.platform === "win32" ? s.toLowerCase() : s); +const extOf = (p) => (path.posix.extname(p).slice(1) || "").toLowerCase(); +const baseOf = (p) => path.posix.basename(p); +const dirOf = (p) => { + const d = path.posix.dirname(p); + return d === "." ? "" : d; +}; +const segs = (d) => (d ? d.split("/") : []); + +function git(root, args) { + try { + return execFileSync("git", ["-c", "core.quotePath=false", ...args], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 256 * 1024 * 1024 }); + } catch { + return null; + } +} + +const inGit = (root) => git(root, ["rev-parse", "--show-toplevel"]) !== null; + +function walk(root) { + const found = []; + const visit = (dir, relDir) => { + let entries; + try { + entries = fs.readdirSync(dir, { withFileTypes: true }); + } catch { + return; + } + for (const e of entries) { + const r = relDir ? `${relDir}/${e.name}` : e.name; + if (e.isDirectory()) { + if (!SKIP_DIRS.has(e.name)) visit(path.join(dir, e.name), r); + } else if (e.isFile()) found.push(r); + } + }; + visit(root, ""); + return found; +} + +// Every file in the project, once per run: tracked plus untracked files git +// does not ignore, or a walk outside git. Paths relative to root. +const fileLists = new Map(); +function allFiles(root) { + if (!fileLists.has(root)) { + let list; + if (inGit(root)) { + const tracked = (git(root, ["ls-files"]) || "").split("\n"); + const untracked = (git(root, ["ls-files", "--others", "--exclude-standard"]) || "").split("\n"); + list = [...new Set([...tracked, ...untracked].filter(Boolean))].filter((f) => fs.existsSync(path.join(root, f))); + } else list = walk(root); + fileLists.set(root, list.map(toPosix).sort()); + } + return fileLists.get(root); +} + +/** Is this path a test file by name or by folder? */ +export function isTestFile(p) { + const file = toPosix(p); + const base = baseOf(file); + if (/\.(test|spec)\.[^./]+$/i.test(base)) return true; + if (/^test_.+\.py$/i.test(base) || /_test\.py$/i.test(base) || /_test\.go$/i.test(base)) return true; + if (/Tests?\.(java|kt|cs)$/.test(base)) return true; + return segs(dirOf(file)).some((s) => TEST_DIRS.has(s)); +} + +/** The project's test files with a code extension. */ +export function listTestFiles(root) { + return allFiles(root).filter((f) => isTestFile(f) && (CODE_EXT.has(extOf(f)) || JS_EXT.has(extOf(f)))); +} + +/* ------------------------------------------------------- name and folder */ + +// A file's name without its extension and without test markers: +// foo.test.js, test_foo.py, foo_test.go and FooTests.cs all give "foo"/"Foo". +function stemOf(p) { + const base = baseOf(p); + const dot = base.lastIndexOf("."); + let stem = dot > 0 ? base.slice(0, dot) : base; + stem = stem.replace(/\.(test|spec)$/i, ""); + if (/^test_/i.test(stem) && extOf(p) === "py") stem = stem.slice(5); + stem = stem.replace(/_test$/i, ""); + if (/^(java|kt|cs)$/.test(extOf(p))) stem = stem.replace(/Tests?$/, ""); + return stem; +} + +function nameMatch(source, test) { + const ext = extOf(source); + const stem = stemOf(source); + const base = baseOf(test); + const tdot = base.lastIndexOf("."); + const tname = tdot > 0 ? base.slice(0, tdot) : base; + const same = (a, b) => fold(a) === fold(b); + if (ext === "py") return extOf(test) === "py" && (same(tname, `test_${stem}`) || same(tname, `${stem}_test`)); + if (ext === "go") return same(test, `${dirOf(source) ? `${dirOf(source)}/` : ""}${stem}_test.go`); + if (ext === "cs" || ext === "java" || ext === "kt") return extOf(test) === ext && (same(tname, `${stem}Tests`) || same(tname, `${stem}Test`)); + return same(tname, `${stem}.test`) || same(tname, `${stem}.spec`); +} + +// Does the test file sit in a test folder that mirrors the source file's +// folder? src/a/b.js mirrors to src/a/__tests__/, tests/a/, test/src/a/ and +// the like: the part of the path before the test folder must be an ancestor of +// the source, and the part after it the rest of the source's folder (with a +// leading src/ or lib/ optional). +function mirrors(source, test) { + const sd = segs(dirOf(source)).map(fold); + const td = segs(dirOf(test)).map(fold); + const k = td.findIndex((s) => TEST_DIRS.has(s)); + if (k === -1) return false; + const prefix = td.slice(0, k); + const rest = td.slice(k + 1); + if (prefix.some((s, i) => sd[i] !== s)) return false; + const remaining = sd.slice(prefix.length); + const eq = (a, b) => a.length === b.length && a.every((s, i) => s === b[i]); + if (eq(remaining, rest)) return true; + return (remaining[0] === "src" || remaining[0] === "lib") && eq(remaining.slice(1), rest); +} + +const folderMatch = (source, test) => mirrors(source, test) && fold(stemOf(source)) === fold(stemOf(test)); + +/* --------------------------------------------------------------- imports */ + +const JS_EXT = new Set(["js", "mjs", "cjs", "ts", "tsx", "jsx", "mts", "cts"]); +const JS_TRY = ["", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx"]; +const JS_PATTERNS = [ + /\bimport\s+(?:[\w*{}\s,$]+?\s+from\s+)?["']([^"'\n]+)["']/g, + /\bexport\s+[\w*{}\s,$]+?\s+from\s+["']([^"'\n]+)["']/g, + /\brequire\s*\(\s*["']([^"'\n]+)["']\s*\)/g, + /\bimport\s*\(\s*["']([^"'\n]+)["']\s*\)/g, +]; + +const isFile = (p) => { + try { + return fs.statSync(p).isFile(); + } catch { + return false; + } +}; + +// Repo-relative path for `p` (already posix, relative to root), or null when +// it climbs out of the project. +const inside = (p) => { + const n = path.posix.normalize(p); + return n === ".." || n.startsWith("../") || path.posix.isAbsolute(n) ? null : n; +}; + +function resolveJs(root, test, spec) { + if (!spec.startsWith("./") && !spec.startsWith("../")) return []; + const target = inside(path.posix.join(dirOf(test) || ".", spec)); + if (!target) return []; + for (const ext of JS_TRY) if (isFile(path.join(root, target + ext))) return [target + ext]; + for (const ext of JS_TRY.slice(1)) if (isFile(path.join(root, `${target}/index${ext}`))) return [`${target}/index${ext}`]; + return []; +} + +function resolvePyModule(root, bases, dotted) { + const rel = dotted.split(".").filter(Boolean).join("/"); + if (!rel) return []; + for (const base of bases) { + const p = inside(base ? `${base}/${rel}` : rel); + if (!p) continue; + if (isFile(path.join(root, `${p}.py`))) return [`${p}.py`]; + if (isFile(path.join(root, `${p}/__init__.py`))) return [`${p}/__init__.py`]; + } + return []; +} + +function pythonImports(root, test, text) { + const found = []; + const own = dirOf(test); + for (const m of text.matchAll(/^[ \t]*import[ \t]+([\w.]+(?:[ \t]*,[ \t]*[\w.]+)*)/gm)) { + for (const name of m[1].split(",")) found.push(...resolvePyModule(root, ["", own], name.trim())); + } + for (const m of text.matchAll(/^[ \t]*from[ \t]+(\.*)([\w.]*)[ \t]+import[ \t]+\(?([\w\s,]+)/gm)) { + const dots = m[1].length; + const mod = m[2]; + const names = m[3].split(",").map((s) => s.trim().split(/\s+/)[0]).filter(Boolean); + let bases; + if (dots) { + let base = own; + for (let i = 1; i < dots; i++) base = dirOf(base); + bases = [base]; + } else bases = ["", own]; + if (mod) found.push(...resolvePyModule(root, bases, mod)); + for (const n of names) found.push(...resolvePyModule(root, bases, mod ? `${mod}.${n}` : n)); + } + return found; +} + +// The module path and folder of the go.mod nearest to `file`, walking up. +const goMods = new Map(); +function goModFor(root, file) { + let dir = dirOf(file); + for (;;) { + const key = `${root}\0${dir}`; + if (!goMods.has(key)) { + const text = readText(path.join(root, dir, "go.mod")); + const m = text && text.match(/^module\s+(\S+)/m); + goMods.set(key, m ? { module: m[1], dir } : null); + } + if (goMods.get(key)) return goMods.get(key); + if (!dir) return null; + dir = dirOf(dir); + } +} + +// Go imports name packages: the result is folders, prefixed "dir:". +function goImports(root, test, text) { + const mod = goModFor(root, test); + if (!mod) return []; + const specs = []; + for (const m of text.matchAll(/^\s*import\s+(?:[\w.]+\s+)?"([^"]+)"/gm)) specs.push(m[1]); + for (const m of text.matchAll(/^\s*import\s*\(([\s\S]*?)\)/gm)) { + for (const l of m[1].matchAll(/(?:^|\n)\s*(?:[\w.]+\s+)?"([^"]+)"/g)) specs.push(l[1]); + } + const found = []; + for (const s of specs) { + if (s !== mod.module && !s.startsWith(`${mod.module}/`)) continue; + const sub = s.slice(mod.module.length).replace(/^\//, ""); + const dir = inside([mod.dir, sub].filter(Boolean).join("/") || "."); + if (dir) found.push(`dir:${dir === "." ? "" : dir}`); + } + return found; +} + +// Source path (or "dir:" for Go) to the test files that import it, +// built once per root from every test file. +const importIndexes = new Map(); +function importIndex(root, testFiles) { + if (importIndexes.has(root)) return importIndexes.get(root); + const index = new Map(); + const add = (target, test) => { + const k = fold(target); + if (!index.has(k)) index.set(k, new Set()); + index.get(k).add(test); + }; + for (const test of testFiles) { + const ext = extOf(test); + if (!JS_EXT.has(ext) && ext !== "py" && ext !== "go") continue; + const text = readText(path.join(root, test)); + if (text === null || text.length > 2 * 1024 * 1024) continue; + if (JS_EXT.has(ext)) { + for (const re of JS_PATTERNS) for (const m of text.matchAll(re)) for (const t of resolveJs(root, test, m[1])) add(t, test); + } else if (ext === "py") for (const t of pythonImports(root, test, text)) add(t, test); + else for (const t of goImports(root, test, text)) add(t, test); + } + importIndexes.set(root, index); + return index; +} + +/** + * The tests that cover `file` after the test map: by name, then by mirrored + * folder, then by imports. `{ tests, method }`, method null when none did. + */ +export function findTests(root, file, testFiles = listTestFiles(root)) { + const f = toPosix(file); + const others = testFiles.filter((t) => fold(t) !== fold(f)); + const byName = others.filter((t) => nameMatch(f, t)); + if (byName.length) return { tests: byName, method: "name" }; + const byFolder = others.filter((t) => folderMatch(f, t)); + if (byFolder.length) return { tests: byFolder, method: "folder" }; + const index = importIndex(root, testFiles); + const hits = new Set([...(index.get(fold(f)) || [])]); + if (extOf(f) === "go" && !isTestFile(f)) for (const t of index.get(fold(`dir:${dirOf(f)}`)) || []) hits.add(t); + hits.delete(f); + if (hits.size) return { tests: [...hits].sort(), method: "imports" }; + return { tests: [], method: null }; +} + +/* ---------------------------------------------------------------- covers */ + +const CONFIG_NAMES = new Set(["package.json", "package-lock.json", "pnpm-lock.yaml", "yarn.lock", "jsconfig.json", "pytest.ini", "pyproject.toml", "setup.cfg", "tox.ini", "go.mod", "go.sum", "cargo.toml", "makefile", "directory.build.props"]); + +/** A shared-ground hint for a file the agent should judge, or null. */ +export function hintFor(file) { + const f = toPosix(file); + const base = baseOf(f); + const lower = base.toLowerCase(); + const dirs = segs(dirOf(f)); + if (CONFIG_NAMES.has(lower) || /^tsconfig.*\.json$/i.test(base) || /\.config\.(js|cjs|mjs|ts)$/i.test(base) || /^\.babelrc/i.test(base) || /\.csproj$/i.test(base)) return "config"; + if (dirs.some((d) => ["fixtures", "__fixtures__", "testdata"].includes(d))) return "fixture"; + if (dirs.some((d) => ["helpers", "test-utils", "testutils", "support"].includes(d))) return "test-helper"; + if (/helpers/i.test(base) && /\.(js|mjs|ts|py|go)$/i.test(base) && dirs.some((d) => TEST_DIRS.has(d))) return "test-helper"; + return null; +} + +const rowMatches = (row, file) => row.paths.some((g) => matchGlob(g, file)); + +function covers(root, files) { + const map = readTestMap(root); + const rows = map.found ? map.rows : []; + const matched = rows.map((r) => ({ area: r.area, run: r.run, shared: r.shared, files: [] })); + const unmatched = []; + const sharedHits = []; + let testFiles; + for (const file of files) { + let hit = false; + let sharedRow = false; + rows.forEach((r, i) => { + if (!rowMatches(r, file)) return; + hit = true; + matched[i].files.push(file); + if (r.shared) sharedRow = true; + }); + if (!hit) { + testFiles ||= listTestFiles(root); + const { tests, method } = findTests(root, file, testFiles); + unmatched.push({ file, tests, method }); + } + const why = sharedRow ? "row" : hintFor(file); + if (why) sharedHits.push({ file, why }); + } + return { ok: true, mapFound: map.found, matched: matched.filter((m) => m.files.length), unmatched, sharedHits }; +} + +function readStdin() { + try { + return fs.readFileSync(0, "utf8"); + } catch { + return ""; + } +} + +/* ------------------------------------------------------------------ gaps */ + +/** + * The branch's changed files, relative to root: review-scope.mjs's list when + * it ships beside this script, else the same git commands it runs. + */ +export function branchFiles(root, base) { + const top = git(root, ["rev-parse", "--show-toplevel"]); + if (top === null) fail(EXIT.NOT_FOUND, "not-a-repo", `${root} is not inside a git repository.`, "Use --scope all or --scope path, or ask which files to look at."); + const prefix = (git(root, ["rev-parse", "--show-prefix"]) || "").trim(); + let list; + const scope = path.join(HERE, "review-scope.mjs"); + if (fs.existsSync(scope)) { + let stdout; + try { + stdout = execFileSync(process.execPath, [scope, "--root", root, ...(base ? ["--base", base] : [])], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 }); + } catch (err) { + stdout = err.stdout; + } + let json; + try { + json = JSON.parse(stdout); + } catch { + fail(EXIT.CRASH, "review-scope-failed", "review-scope.mjs printed no JSON.", "Run review-scope.mjs on its own to see why."); + } + if (!json.ok) fail(EXIT.NOT_FOUND, json.error, json.message, json.next); + list = json.files.map((f) => f.path); + } else { + const pick = base ? [base, `origin/${base}`] : ["main", "origin/main", "master", "origin/master"]; + const ref = pick.find((r) => git(root, ["rev-parse", "--verify", "--quiet", `${r}^{commit}`]) !== null); + if (base && !ref) fail(EXIT.NOT_FOUND, "no-base", `No branch named ${base} (or origin/${base}).`, "Pass an existing --base, or omit it to use main / master."); + const lines = (args) => (git(top.trim(), args) || "").split("\n").filter(Boolean); + list = [ + ...(ref ? lines(["diff", "--name-only", `${ref}...HEAD`]) : []), + ...lines(["diff", "--name-only", "--cached"]), + ...lines(["diff", "--name-only"]), + ...lines(["ls-files", "--others", "--exclude-standard"]), + ]; + } + return [...new Set(list.map(toPosix))] + .filter((f) => f.startsWith(prefix)) + .map((f) => f.slice(prefix.length)) + .filter((f) => fs.existsSync(path.join(root, f))); +} + +function isSource(file) { + const f = toPosix(file); + if (!CODE_EXT.has(extOf(f)) || /\.d\.ts$/i.test(f) || isTestFile(f)) return false; + return !segs(dirOf(f)).some((s) => SOURCE_SKIP.has(s)); +} + +// Commits in the last 90 days per file, and the newest commit time, from one +// git log read. Paths relative to root. +function churn(root) { + const prefix = (git(root, ["rev-parse", "--show-prefix"]) || "").trim(); + const since = new Date(now().getTime() - 90 * 24 * 3600 * 1000).toISOString(); + const text = git(root, ["log", `--since=${since}`, "--name-only", "--format=%x00%ct"]) || ""; + const stats = new Map(); + for (const chunk of text.split("\0")) { + const lines = chunk.split("\n"); + const ts = Number(lines[0]); + if (!ts) continue; + for (const raw of new Set(lines.slice(1).filter(Boolean))) { + if (!raw.startsWith(prefix)) continue; + const f = raw.slice(prefix.length); + const s = stats.get(f) || { commits: 0, newest: 0 }; + s.commits++; + s.newest = Math.max(s.newest, ts); + stats.set(f, s); + } + } + return stats; +} + +function gaps(root, { scope, sub, base }) { + const repo = inGit(root); + let files; + if (scope === "branch") files = branchFiles(root, base); + else { + files = allFiles(root); + if (scope === "path") { + const p = toPosix(sub).replace(/\/+$/, ""); + files = files.filter((f) => fold(f) === fold(p) || fold(f).startsWith(`${fold(p)}/`)); + } + } + let sources = [...new Set(files)].filter(isSource).sort(); + const capped = sources.length > CAP; + if (capped) sources = sources.slice(0, CAP); + const map = readTestMap(root); + const rows = map.found ? map.rows : []; + const testFiles = listTestFiles(root); + const stats = repo ? churn(root) : null; + const list = []; + let covered = 0; + for (const file of sources) { + // Any matching row with a run command covers the file, as in covers, so + // a gap's area is set only by a row that names it without one. + const row = rows.find((r) => rowMatches(r, file)); + if (rows.some((r) => r.run && rowMatches(r, file)) || findTests(root, file, testFiles).tests.length) { + covered++; + continue; + } + const s = stats && stats.get(file); + list.push({ + file, + area: row ? row.area : null, + runner: row && row.run ? row.run : null, + commits90d: stats ? (s ? s.commits : 0) : null, + lastTouched: s ? new Date(s.newest * 1000).toISOString().slice(0, 10) : null, + }); + } + list.sort((a, b) => { + if (a.lastTouched !== b.lastTouched) { + if (a.lastTouched === null) return 1; + if (b.lastTouched === null) return -1; + return a.lastTouched < b.lastTouched ? 1 : -1; + } + if ((b.commits90d || 0) !== (a.commits90d || 0)) return (b.commits90d || 0) - (a.commits90d || 0); + return a.file < b.file ? -1 : a.file > b.file ? 1 : 0; + }); + return { ok: true, scope, gaps: list, scanned: sources.length, covered, capped }; +} + +/* --------------------------------------------------------------- nearest */ + +// Path tokens in a Run command that name a file or folder in the project. +function runPaths(root, cmd) { + return (cmd || "") + .split(/\s+/) + .map((t) => toPosix(t.replace(/^["']|["']$/g, "")).replace(/\/+$/, "")) + .filter((t) => t && !t.startsWith("-") && inside(t) && fs.existsSync(path.join(root, t))); +} + +function nearest(root, file) { + const f = toPosix(file); + const testFiles = listTestFiles(root).filter((t) => fold(t) !== fold(f)); + const picked = []; + const take = (list) => { + for (const t of list) { + if (picked.length >= 3) return; + if (!picked.includes(t)) picked.push(t); + } + }; + take(findTests(root, f, testFiles).tests); + take(testFiles.filter((t) => fold(dirOf(t)) === fold(dirOf(f)))); + take(testFiles.filter((t) => mirrors(f, t))); + if (picked.length < 3) { + const map = readTestMap(root); + const row = map.found ? map.rows.find((r) => rowMatches(r, f)) : null; + if (row) { + for (const p of runPaths(root, row.run)) { + take(isDir(path.join(root, p)) ? testFiles.filter((t) => t.startsWith(`${p}/`)) : testFiles.filter((t) => t === p)); + } + } + } + if (picked.length < 3) { + const mine = segs(dirOf(f)); + const shared = (t) => { + const ts = segs(dirOf(t)); + let n = 0; + while (n < mine.length && n < ts.length && fold(mine[n]) === fold(ts[n])) n++; + return n; + }; + // Same language first: a Python test teaches nothing about a JS file's style. + const lang = (p) => (JS_EXT.has(extOf(p)) ? "js" : extOf(p)); + const other = (t) => (lang(t) === lang(f) ? 0 : 1); + take([...testFiles].sort((a, b) => other(a) - other(b) || shared(b) - shared(a) || (a < b ? -1 : a > b ? 1 : 0))); + } + return { ok: true, file: f, tests: picked }; +} + +/* ------------------------------------------------------------------ main */ + +const listArg = (s) => String(s).split(",").map((x) => toPosix(x.trim())).filter(Boolean); + +async function main(argv) { + const args = parseArgs(argv, { values: ["root", "files", "scope", "path", "base", "file"], booleans: ["stdin"] }); + const root = path.resolve(args.root || "."); + const cmd = args._[0]; + if (cmd === "covers") { + let files; + if (args.files) files = listArg(args.files); + else if (args.stdin) { + let json; + try { + json = JSON.parse(readStdin()); + } catch { + fail(EXIT.USAGE, "bad-stdin", "--stdin needs review-scope.mjs JSON.", "Pipe review-scope.mjs output in, or pass --files."); + } + if (!json || !Array.isArray(json.files)) fail(EXIT.USAGE, "bad-stdin", "The JSON on stdin has no files list.", "Pipe review-scope.mjs output in, or pass --files."); + files = json.files.map((f) => toPosix(f.path)).filter(Boolean); + } else fail(EXIT.USAGE, "missing-files", "covers needs --files or --stdin.", "Run with --help for usage."); + out(covers(root, [...new Set(files)])); + return; + } + if (cmd === "gaps") { + if (!["branch", "all", "path"].includes(args.scope)) fail(EXIT.USAGE, "bad-scope", "gaps needs --scope branch, all or path.", "Run with --help for usage."); + if (args.scope === "path" && !args.path) fail(EXIT.USAGE, "missing-path", "--scope path needs --path

.", "Run with --help for usage."); + out(gaps(root, { scope: args.scope, sub: args.path, base: args.base })); + return; + } + if (cmd === "nearest") { + if (!args.file) fail(EXIT.USAGE, "missing-file", "nearest needs --file .", "Run with --help for usage."); + out(nearest(root, args.file)); + return; + } + fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", "Commands: covers, gaps, nearest. Run with --help."); +} + +const isMain = (() => { + try { + return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url)); + } catch { + return false; + } +})(); +if (isMain) run(USAGE, main); diff --git a/src/web-console/public/activities/ghoul-rush/rides/wagon/ghoul-wagon-draw.js b/src/web-console/public/activities/ghoul-rush/rides/wagon/ghoul-wagon-draw.js index aa11657..d6e01b4 100644 --- a/src/web-console/public/activities/ghoul-rush/rides/wagon/ghoul-wagon-draw.js +++ b/src/web-console/public/activities/ghoul-rush/rides/wagon/ghoul-wagon-draw.js @@ -1066,9 +1066,10 @@ export function wagonArt(d) { ctx.restore(); } - // The mob's meter along the top left: how far back they are, red as they close, with a word when it matters. - function meter(ctx, v, c) { - const x = 4; + // The mob's meter along the top left of the screen (`cam` is the view's left edge: `front` draws in + // room units, so it follows the camera): how far back they are, red as they close, with a word when it matters. + function meter(ctx, v, c, cam) { + const x = cam + 4; const y = 9.2; const w = 34; const near = clamp(1 - c.gap / GAP_MAX, 0, 1); @@ -1147,7 +1148,7 @@ export function wagonArt(d) { ctx.fillRect(cam, 0, 40, FH); ctx.globalAlpha = 1; } - meter(ctx, v, c); + meter(ctx, v, c, cam); } } diff --git a/src/web-console/public/tones.js b/src/web-console/public/tones.js index 93d7d8b..01bc22a 100644 --- a/src/web-console/public/tones.js +++ b/src/web-console/public/tones.js @@ -508,6 +508,9 @@ function blip(c, type, from, to, t0, seconds, peak) { osc.type = type; osc.frequency.setValueAtTime(from, t0); osc.frequency.exponentialRampToValueAtTime(to, end); + // Silent from the start: a gain node is 1 until its first scheduled value, + // which made a part that starts later click. + gain.gain.value = FLOOR; gain.gain.setValueAtTime(FLOOR, t0); gain.gain.exponentialRampToValueAtTime(peak, t0 + ATTACK); gain.gain.exponentialRampToValueAtTime(FLOOR, end); @@ -524,6 +527,8 @@ function voice(c, p, t0, peak, k) { const end = t0 + p.seconds; const gain = c.createGain(); const top = Math.max(FLOOR * 10, peak * (p.gain ?? 1)); + // Silent from the start (see blip): no click before a delayed part begins. + gain.gain.value = FLOOR; gain.gain.setValueAtTime(FLOOR, t0); gain.gain.exponentialRampToValueAtTime(top, t0 + Math.min(p.attack ?? ATTACK, p.seconds * 0.8)); gain.gain.exponentialRampToValueAtTime(FLOOR, end);