mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 04:45:33 -08:00
feat: run each loop phase on its own strength (Thrifty, Balanced, Best)
AI Assisted
This commit is contained in:
1 parent
e963513a8a
commit
81d14c8e78
41 files changed
+3290
-81
No files matched your search
@@ -256,6 +256,8 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `public/activities/bumper-draw.js` | Bumper Ring's drawing: `drawScene(ctx, view)` from a plain view `bumper.js` builds (the round, the board geometry, the effects, the pill numbers), each arena's ring in its fixed palette (`themeFor`), the floor (ice, oil, holes, bumpers, the magnet, the warning bands), the cars (Planny upright at the wheel of a car in `--accent`, star eye and stick arms; rivals with a face each), the pills (laid out by `hudLayout`, which starts a row below rather than run into the ring's countdown or off the board), banners and the start and end strip, and `readColors(canvas)`; decides nothing |
|
||||
| `public/activities/rapids.js` | Rapids Run: its rules as plain exported functions over a round on a river scrolling down a 64 unit wide field, 84 units of it on the board (`newRound(seed)`, `newRiver(seed)`, `buildStretch(river, n, random)` (a stretch's rows from its own seed, each row a center, width and island width: a calm opening, then drifts, narrows and islands, every bank slanting at most `SLOPE` a unit, every channel at least `MIN_CHANNEL` wide, then a `BASIN_W` basin on a boss stretch and the narrowing to the `DAM_W` dam; and its plan of foes, buoys and crates, none in the first `SAFE_START` (where you start again) or by the dam), `ensureRiver`, `riverAt` (a row's banks and island eased from the row before's, so they slant as drawn), `channelsAt`, `channelAt`, `isWater`, `onLand` (the hull sampled at seven points), `placeAt` (the start of a stretch, its dam whole and its plan loaded afresh), `advance` in 4 ms slices over `round.input`, which `key()` and `release()` set: steering eased in, the whirlpools' tug, the speed held (up, down or neither, times the stretch's `pace`), the battery drained (`DRAIN` a second cruising, more at speed), distance points, the guns (`FIRE_MS`, Spread's fan), shots against foes, the boss, the dam and buoys, the foes (skiffs and darters drift and turn at the banks, a darter swerves into your lane, gulls take off as you near and swoop across, sentries fire at you), the boss (`spawnBoss` holds the river and the battery; its volleys by kind), bolts, pickups (a buoy `BUOY_CHARGE`, the magnet's pull, crates), crashes (`lose`: a shield takes any crash but a flat battery and slides you off a bank; blinking for `GRACE_MS` after a restart), skims (`SKIM_POINTS` each `SKIM_MS` closer than `SKIM_GAP` at speed), the dam (`hitDam`, then past it the next stretch, with `FLAWLESS_POINTS` times it for no life lost), `hurtFoe` (the combo, up to `MAX_COMBO`), `hurtBoss` (a life back and a crate), `applyPower`, `stretchFor` (built once a stretch; past the eighth, Night Water 2, 3 and on), `underBanner`, `screenY`, `seeded`), the `FOES`, `BOSSES`, `POWERS` and `STRETCHES`, and the game contract with `release()` (held arrows steer, speed and slow, held space fires; a pause lets go of every key); memo is the furthest dam blasted, which can pass 8; a read-only `round` getter for the tests only. Tuned by a scratch sim: a careful bot clears a stretch in 20 to 35 seconds, and the battery runs flat for one that grabs too few buoys |
|
||||
| `public/activities/rapids-draw.js` | Rapids Run's drawing: `drawScene(ctx, view)` from one view object `rapids.js` refills each frame, in field units: the strip above the field in the page's colors with the pills (laid out by `hudLayout`, which starts a second row rather than run off the board and centers its rows in the strip), the river a look at a time (`LOOKS`: meadow, autumn, canyon, marsh, dusk and night, each in fixed colors, the look changing at each dam): banded banks, the water between them with shore lines and flow streaks carried downstream by the view's clock, pointed islands, trees or rocks; the dam ahead (hazard stripes, a crack for every share knocked out, a trickle once it is close to going) and the broken one behind; charge buoys, crates with their glyphs, whirlpools, skiffs, darters, mines, bank sentries aiming at you and gull drones with their shadows; the mini-boss and its health bar; Planny's jet-skimmer in your highlight with a white trim (so a blue highlight still shows on blue water), his wake, jets, arms to the bars (up when a dam or a boss goes), his box and his star eye in your highlight, bobbing with the star spinning after a crash; shots, bolts, sparks, rings, floating words (kept on the field by `labelSpot`), the combo's big number, the battery gauge beside the field (green, amber, then red and blinking under the low mark), banners, and the start and end strip with the big final score and a dot per named stretch whose dam you have blasted; `readColors(canvas)`, `lookColor`, `inkOn`, `contrast`; decides nothing |
|
||||
| `public/activities/flock.js` | Flock Dash: its rules as plain exported functions over a round (`newRound(seed)`, `steer`, `recordPath`, `placeFlock`, `screenX`, `collect`, `spawnStrays`, `advance`) and the game contract. The flock is a recorded path with running arc length: follower k sits `k * SPACING` behind the leader along it. |
|
||||
| `public/activities/flock-draw.js` | Flock Dash's drawing: `drawScene(ctx, view)` and `hudLayout` from one view object `flock.js` refills each frame, in field units: the sunset sky, the strays, the flock, Planny as the lead bird with a star for an eye, and the pills. |
|
||||
| `public/activities/fuse.js` | Hot Potato: its rules as plain exported functions over a round on a 104 by 70 arena (`newRound`, `newMatch(round, venue)`, which lights each bomb on a rival, never you, in a match's first fuse, `advance` in 8 ms slices over `round.input`, which `key()` and `release()` set, `move` (speed eased toward the held direction at `GRIP`, a dash holding its line, belts and ice from the floor), `dash` (a holder's dash is a numbered lunge), `tag` (a holder touching a runner with no bomb passes it, never inside `NO_TAGBACK_MS` of the bomb changing hands, nor back to the one who just passed it within `TAGBACK_MS` while three or more are left, `tagBack`, with `tagSafe` saying who is safe that way for the drawing; a fuse under `PASS_FLOOR_MS`, `NO_TAGBACK_MS` plus `PASS_REACT_MS`, is raised to it on any pass, once a fuse for each runner (`bomb.lifted`); your pass scores, a hot one under `HOT_MS` as passed steps the streak), `burn` (Freeze takes its share first), `blast` (the holder out, everyone near knocked back, the match over when that was you or one is left), `nextFuse` (a survivor with no bomb, the next shorter fuse from `fuseFor`, never more bombs than one for every two left), `think` (a holder chases by its own flood-fill path, weighted toward a boxed-in or dashless target; a runner without a bomb scores candidate spots by the holders' path distance against its own and flees to the best; personalities bend both), `applyPower`, `spawnPickup`, `speedOf`, `clearLine`, `rivalPower` and `venueFor` (each built once per venue), `rivalColors(you)`), the `VENUES`, `LAYOUTS`, `RIVALS` and `POWERS`, and the game contract with `release()` (`key(name, repeat)` never dashes on a repeat); a rival holder winds up (`WINDUP_MS`, shorter when sharp) or, a Trickster, feints (`FAKE_MS`) before a lunge, and a runner a lunge comes at dodges once a lunge at its venue's odds after its reaction time; the fuse ticks quicker and higher as it burns down, on one clock however many bombs burn (yours, else the shortest); a bomb whose fuse has run out passes to nobody; memo is the furthest venue reached, which can pass 9; a read-only `round` getter for the tests only. Tuned by a scratch sim (see "As built" in `game-ideas/hot-potato.md`) |
|
||||
| `public/activities/fuse-draw.js` | Hot Potato's drawing: `drawScene(ctx, view)` from one view object `fuse.js` refills each frame, in arena units: the strip above the arena in the page's colors with the pills (laid out by `hudLayout`, which starts a second row rather than run into the fuse and centers its rows in the strip), each venue's floor in its fixed palette (`themeFor`, `venueColor`), ice, running belts, the Rooftop's open edge, the things to run round, pickups, the runners (Planny on his feet with his star eye and stick arms, flailing while he holds a bomb, and still Planny when charred; arms and feet on the floor in `limbInk(level)`, the ink that stands out from that venue's tiles; rivals with a mark per personality; a white ring with a dark edge at the feet of a runner safe from a tag-back; the charred waddle to the nearest wall and the fall from the roof), the bomb over its holder (a red ball with a `<<<` band, growing and glowing as it burns, flashing white while it cannot be passed, its fuse a shortening curl with a spark, the last seconds in big numbers (under the holder's feet when there is no room above, `countY`), a hop across on a pass), blast clouds, the Blackout's dark worked out once a frame in cells, the red edge pulse in a fuse's last second, banners and the start and end strip with the big final score, and `readColors(canvas)`; decides nothing |
|
||||
| `public/activities/hop.js` | Crossing Rush: its rules as plain exported functions over a round on a strip `COLS` (11) cells wide of 30 to 40 lanes, `VIEW_ROWS` (14) on the board at once (`newRound`, `newHeat(round, zone)`, which builds the heat's lanes from the round's seed, kept when a heat runs again, `buildLanes(zone, seed)` (groups of road, highway, ice, river, turtle, rapids or rail lanes with a grass row between each two, the zone's new thing first; the same seed builds the same lanes), `advance` in 8 ms slices (lanes flow, riders drift with their log, rivals choose, everyone is checked where they stand before any hop moves on, then hops and flights; hoppers home in the same slice finish by the moment each landed, a dead heat to you), `hop(round, hopper, dir)` (one cell, two with a Spring; a hopper counts in the cell it leaves for the first half and the one it lands on for the second; an icy lane slides it a cell more), `laneAt`, `occupied(round, row, col, atMs)` (a car or a train on it, or in a river no float or the edge, `atMs` ahead through `shiftAt`, which follows a lane's flips, surges and a Horn exactly), `sendBack` (to the last grass row, `safeBelow`, crediting a shove within `SHOVE_CREDIT_MS`), `shove(round, from, to)` (a cell the way `from` faces, only on a hopper `inReach` and never on one past the half of its hop home, once every `SHOVE_MS`), `plan(round, hopper, random, power)` (a look ahead of `LOOKAHEAD` to `LOOKAHEAD_SHARP` hops over the lanes as they will move, each hop followed by the hopper's wait where it lands; never a hop where it would be hit or fall in at full sharpness; a sloppy rival now and then hops on regardless), `applyPower`, `zoneFor` and `rivalPower` (each built once per zone), `rivalColors(you)`, `standings`), the `ZONES`, `RIVALS` and `POWERS`, and the game contract with `release()` (`key(name, repeat)` hops once a press: never on a repeat, never again until the arrow is let go, never with the press that plays on, and with one hop queued behind the one in the air; a pause drops what is held and the queue); rivals wait `REACT_MS` down to a sharp rival's after each landing, a Bruiser shoves anyone beside it into a lane, a Tagalong follows a row behind you and shoves near the top, and a rival that lets a shove go weighs the next one only after `SHOVE_LOOK_MS`; memo is the furthest zone reached, which can pass 9; a read-only `round` getter for the tests only. Tuned by a scratch sim (see "As built" in `game-ideas/crossing-rush.md`) |
|
||||
@@ -448,7 +450,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `public/state.js` | the page's shared state (`page.S` the server's truth, `page.local` what is staged) and the `redraw()` / save hooks every screen calls; defines only |
|
||||
| `public/tones.js` | the activities' sound engine, all synthesized in the browser. Three parts: a shared kit of rich one-shot sounds (`RICH`: `layers` of parts played together, each a wave or a noise (`noise`, `pink`, `brown`) with its own `delay`, `gain`, `attack`, a sweeping `filter` and `vibrato`: `explode`, `smash`, `skid`, `whoosh`, `splashBig`, `fanfare`, `gameOver` and some fifty more, up to 1.2 s, at most `MAX_VOICES` parts sounding at once), held **hums** (`hum(id, name, level, pitch)`, called every frame a game wants it: oscillators and noise through one filter that follows the pitch, pulsed for an engine's strokes; a hum not asked for within `HUM_HOLD_MS` fades by itself, so a paused or closed game goes quiet without saying so, `hushTones()` quiets every one and the Activities window calls it whenever it stops ticking; at most `MAX_HUMS`; shared ones `car`, `toycar`, `electric`, `outboard`, `river`, `wind`, `cycle`, `fuse`, `haunt`, `squeal`, `meter`, `swarm`, `train`, `crowd`), and each game's own extras in `public/activities/<id>-sfx.js` (`{ tones, hums }`, plain objects, names prefixed with the game id, merged and frozen here; a name may be defined once across all of them, which `scripts/test-web-console-tones.mjs` checks along with every spec's shape and every name a game's source asks for). Everything plays through one compressor. The older single blips (`BLIPS`): `tone(name, level, pitch)` with an optional loudness from 0 to 1 and an optional pitch that scales every frequency, kept between 0.25 and 4, and an optional fourth `louder` (a game lifting its sounds as a whole, up to `LOUDER_MAX`, also the fifth argument of `hum()`), `unlockTones()`; Snake's blips plus golf's `putt`, `wall`, `bump`, `cup`, `ace` (a three-note rise), `splash`, `power` (a power-up, three notes), `tunnel`, `boom` (a cannon putt), `sizzle` (lava) and `fall` (the pit), the countdown's `count` and `go`, Stack Deploy's `thunk`, `slice` and `perfect`, which it pitches up a scale step for each perfect in a row, and Bumper Ring's `ram`, pitched and leveled by how hard the hit, and `rev`, a rival winding up a dash, and Hot Potato's `tick`, the fuse, which it ticks quicker and pitches higher as the fuse burns down, and `pop`, a pass, and Crossing Rush's `hop`, which it pitches up a step for each quick hop forward in a row, `boing`, a send-back, `bell`, a train coming, and `horn`, and Bounce Road's `engine`, a soft low triangle hum it plays every few frames while you pick up speed (quiet once you cruise or coast), pitched up with your speed, `spring`, a jump, pitched with your speed, and `squash`, a rival flattened, pitched up a step for each in a chain, and `beat`, a low thump while your wheels run on the verge (it borrows the other games' blips for its hazards and rivals), and Rapids Run's `pew` (a shot, a short soft triangle played quietly about seven times a second while fire is held), `charge` (a buoy taken), `lowcell` (the low battery's two-note beep, quicker the lower it runs), `dambreak` (a dam bursting) and `skim` (a bank skimmed at speed, pitched up the more you have skimmed), and Ghoul Rush's `ghoulBlast` (the blaster's bolt, a short soft triangle repeated while fire is held), `zombiePop` (a kill, pitched up a step for each in the chain), `ghoulStomp`, `ghoulBoo`, `ghoulRoar` and `zombieGroan` (now kept for the other games and the tests: Ghoul Rush's monsters speak with their own voices from `ghoul-sfx.js`), `ghoulCandy` (pitched up for candy in quick succession), `batSwoop` (a bat's kill), `doorUnlock` (the key), `doorThrough` (the door to the next room) and `creakBoard` (a crawler coming up, a chandelier or a crumbling board about to go), all soft triangles and sines), silent while Play sounds is off; separate from `sound.js`'s cue queue |
|
||||
| `public/music.js` | the games' chiptune music: a small sequencer over `tones.js`'s context and compressor (`audioOut()`). A game calls `music(name, intensity)` from its `tick`; the track fades out within `MUSIC_HOLD_MS` once it stops being asked for, picks up again on the bar it left, asking for a different track crossfades the two over `CROSSFADE_S` (the old one keeps playing as it fades, so a new level is not a cut), and `hushMusic()` stops it at once. Tracks are note data under `music` in each game's `activities/<id>-sfx.js` (`{ bpm, rush, bar, voices, patterns, order }`, `bar` the steps in a bar when it is not 16, so the track resumes on a bar start and each pattern is whole bars: pulse, triangle and noise-drum voices, each joining once the intensity reaches its `from`; a step a token, `A4`, `-` to hold, `.` a rest, `A3^037` an arpeggio, drums `k s h o`), read by `compileTrack()` and booked `LOOKAHEAD_S` ahead on the audio clock. It also plays recorded **songs**: mp3s a game names under `songs` in its sfx file (a name to a served path, merged by `tones.js` as `SONG_TABLES`, listed by `songNames()`), asked for the same way, one `<audio>` element each made on first use, at `SONG_PEAK` times the volume, faded over `SONG_FADE_MS`; a song plays once, never looped, `music()` returning `"playing"` or `"ended"` (which the window's wrapper passes back to the game), `{ restart: true }` taking it back to the top with `load()` (no seeking, since the server sends no byte ranges), and a song no longer asked for fades and pauses where it was. The window plays it only while Play sounds, Play game sounds and Play game music (`looks.gameMusic`, off by default) are all on |
|
||||
| `public/activities/snake-sfx.js` · `public/activities/golf-sfx.js` · `public/activities/trails-sfx.js` · `public/activities/bugs-sfx.js` · `public/activities/drive-sfx.js` · `public/activities/stack-sfx.js` · `public/activities/bumper-sfx.js` · `public/activities/rapids-sfx.js` · `public/activities/fuse-sfx.js` · `public/activities/hop-sfx.js` · `public/activities/bounce-sfx.js` · `public/activities/ghoul-rush/sfx/ghoul-sfx.js` | each game's own sound effects as data, `{ tones, hums }` in the shapes `tones.js` documents, every name prefixed with the game id (`driveEngine`, `ghoulMoan`), merged and frozen by `tones.js`; no imports, but for `ghoul-sfx.js`, which merges each Ghoul Rush stage's own `ghoul-sfx-<stage>.js` into its `tones`, `hums` and `music`, and `snake-sfx.js`, which merges `snake-music.js` as its `music`; `trails-sfx.js` has `songs` instead of `music` |
|
||||
| `public/activities/snake-sfx.js` · `public/activities/flock-sfx.js` · `public/activities/golf-sfx.js` · `public/activities/trails-sfx.js` · `public/activities/bugs-sfx.js` · `public/activities/drive-sfx.js` · `public/activities/stack-sfx.js` · `public/activities/bumper-sfx.js` · `public/activities/rapids-sfx.js` · `public/activities/fuse-sfx.js` · `public/activities/hop-sfx.js` · `public/activities/bounce-sfx.js` · `public/activities/ghoul-rush/sfx/ghoul-sfx.js` | each game's own sound effects as data, `{ tones, hums }` in the shapes `tones.js` documents, every name prefixed with the game id (`driveEngine`, `ghoulMoan`), merged and frozen by `tones.js`; no imports, but for `ghoul-sfx.js`, which merges each Ghoul Rush stage's own `ghoul-sfx-<stage>.js` into its `tones`, `hums` and `music`, and `snake-sfx.js`, which merges `snake-music.js` as its `music`; `trails-sfx.js` has `songs` instead of `music` |
|
||||
| `public/activities/snake-music.js` | Snake's ten music tracks as data (no imports): `SNAKE_MUSIC`, `{ bpm, rush, voices, patterns, order }` each, named `snake<Place>` and listed in `MUSIC_TRACKS` in `snake.js`. A round deals them in a fresh order, one to each level, so a run hears a different track at every level and none twice. They were picked on the pages in `prototypes/music/snake` (rhythm-first folk and world tunes led by something plucked or reedy, mostly dark or modal), and their bars are not all sixteen steps: 6/8 is 12, 7/8 is 14, ten beats is 20, twelve beats is 24, each pattern a whole number of its bars; merged by `snake-sfx.js` |
|
||||
| `public/activities/light-trails/1.mp3` to `5.mp3` | Light Trails' five background songs, named `trailsSong1` to `trailsSong5` under `songs` in `trails-sfx.js` and listed in `SERVABLE`; re-encoded for size with ffmpeg (80 kbps stereo MP3 at 44.1 kHz, loudness-normalized to -16 LUFS with `loudnorm`, metadata stripped), about 7.6 MB together, and copied into every skill with the rest of the console. The server leaves them out of its start-up cache warm |
|
||||
| `public/activities/ghoul-rush/stages/graveyard/ghoul-sfx-graveyard.js` | The Graveyard's own sounds as data (no imports): `GRAVEYARD_SFX`, its `tones` (the picked `ghoul<Kind><Act>` sounds of the grasping hands, mourners, grave robbers, rotters and their legs, carrion crows and Mother Mourning) and `music` (`ghoulLychgate`, `ghoulGraves`, `ghoulMausoleums`, `ghoulAngel`, named in `ROOM_MUSIC`), merged by `ghoul-sfx.js` after the house's own. Every new stage gets its own `ghoul-sfx-<stage>.js`, listed in `STAGE_SFX` there |
|
||||
@@ -470,6 +472,11 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `public/screens/agents/agents-list-editor.js` | the one row-list editor behind the three argument lists and the models list: `listEditor({list, kind, field, placeholder, addLabel, optionalName, aria, onChange})` draws `div.agent-rows` (a Remove per row, an Add that appends and focuses the new row, edits written into the live list) |
|
||||
| `public/screens/agents/agents-summary.js` | the agents view's collection side: `renderSummary(ctx)` draws the left column for both modes (prefs rows with found badges, the shipped templates under "Or start from a template" and the orchestrator placeholder; setup pick rows, badges and templates), `drawSummaryPane(ctx)` draws the right pane while nothing is open (empty text, a picked template's note and Use this template, or the picked setup entry's state area: Start, Use it from here, install lines), plus `BADGES`/`drawBadge` |
|
||||
| `public/screens/agents/agents-form.js` | the agents view's per-agent form: `drawForm(ctx)` draws the detail pane (the built-in's Models fold, or an added agent's identity fields plus folded Models and Command-line arguments sections), `renderDirty(ctx)` toggles the Unsaved badge and Save/Discard; the foot (Save, Discard, Save anyway on 409, Delete with inline confirm), `input.invalid[data-field]` marking and the `FORM_FOCUSABLE` focus save/restore |
|
||||
| `public/screens/agents/agents-strengths.js` | the "Strengths in the loop" fold under Models in an agent's form: `strengthsFold(ctx, agentId, draft, { models, hasEffort })` maps Thrifty, Balanced and Best to one of the agent's own models (and an effort for Claude and Codex), shows untouched rows as shipped with a "default" tag and changed rows with Reset, and keeps only changed rows in `ctx.strengthDrafts` for the form's Save |
|
||||
| `public/strengths.js` | the loop's strength rule, shared by the page and the server: `resolveStrengths` and `nextStrength`, held to `scripts/fixtures/strength-cases.json` (the Rust twin is in `models.rs`) |
|
||||
| `strengths.mjs` | the server-side name for `public/strengths.js` (a re-export) |
|
||||
| `strengths` key (`src/launcher/models.json`, `~/.plan2code/models.json`) | per agent, `thrifty`/`balanced`/`best` rows of `{model, effort?}`; a user row beats the shipped one, and a row whose model is not in the agent's Models list is ignored. `models.rs` `strengths_for` and the JS resolver are held to `scripts/fixtures/strength-cases.json` (change the fixture first, then both) |
|
||||
| loop setup `phaseStrength` / `strengths` | `loop-setup.mjs` keeps the per-project toggle and, per spec folder, a list of `{n, name, strength}` picks, pruned as specs finish and phases move (twin: `LoopSetup` in `loop_driver.rs`). `loop_driver.rs` starts a phase with `AgentManager::start_phase_on(prompt, model, effort, env)` and sets `PLAN2CODE_LOOP_STRENGTH` (thrifty, balanced or best) in its environment, which `cmd-open.mjs` reads to give the phase's helpers the same Helper strength line; a retry goes one step up with `models::next_strength` (Rust twin of `nextStrength`; a Match my session phase stays) |
|
||||
| `public/screens/setup.js` | the agent-less setup screen (`workflow === "setup"`, opened by `plan2code` or the app when no agent can run): the "No agent yet" headline, Planny's setup pose, the agent list from `mountAgentsView` in setup mode, Check again, and the "Starting <Label>..." pane after a Start send (`{i:"__start"}` via `/submit`). `setupMoved(url)` disarms the 2-minute no-page notice once the `move` event lands |
|
||||
| `public/screens/prefs-dialog.js` | User Preferences as a dialog: its four tabs (wired by `tabs.js` from `PREFS_TABS`), `openPrefs(tab)` (the one way in, loading Agents & models each time), the fading Saved mark beside a fieldset (`markSaved`), Back to default for the tab on screen, and `confirmUnsaved()`, the in-dialog Save / Discard / Keep editing prompt before Close, Esc, a backdrop click, a tab switch or picking another agent leaves an unsaved agent edit. Other screens reach it through `hooks` |
|
||||
| `public/screens/starting.js` | the launching, starting and waiting screens, with Planny's poses |
|
||||
|
||||
@@ -21,7 +21,7 @@ Run from the repo root (the folder holding `install.js` and `src/launcher/`). Ru
|
||||
|
||||
### Step 2 — Read the current files
|
||||
|
||||
Read `src/launcher/models.json`. It has four keys: `_note` (a string), `claude`, `devin` and `codex` (each an array of `{ "id", "label" }`; `codex` is empty today, because Codex's docs name no models to verify and the launcher skips the model question for it). Keep the `_note` text exactly as read — Step 9 writes it back verbatim and the Validation rules check it.
|
||||
Read `src/launcher/models.json`. It has five keys: `_note` (a string), `claude`, `devin` and `codex` (each an array of `{ "id", "label" }`) and `strengths` (an object, see Step 4c). Keep the `_note` text exactly as read — Step 9 writes it back verbatim and the Validation rules check it.
|
||||
|
||||
Read `src/launcher/agents.json`. It has `schema` (currently `1`) and `agents`, a list of entries. Each entry carries `id`, `name`, `kind` (`builtin` or `template`), `command`, `prompt`, `args`, `bypassArgs`, `modelArgs`, and optional `note`. A `builtin` entry also carries `installUrl`, `install` (lists under `win`, `mac` and `linux`, each `{ label, run, note? }`) and `installDirs` (the same OS keys). Keep the file's shape and order exactly as read.
|
||||
|
||||
@@ -49,6 +49,10 @@ If the lookup fails or the page does not list aliases, say so, and switch to **g
|
||||
|
||||
Look up Codex's current model documentation (locate it on each run). Propose `codex` entries only for model ids the docs name explicitly. If they name none, say so and leave `codex` empty. If entries are added, the `_note` sentence about Codex goes stale; keep `_note` verbatim as everywhere else, but tell the maintainer so they can reword it by hand. If the lookup fails, use guided manual edits as in Step 3.
|
||||
|
||||
### Step 4c: Check the strengths mapping
|
||||
|
||||
`models.json` also has a top-level `strengths` object: for an agent id, the loop's `thrifty`, `balanced` and `best` words, each `{ "model", "effort"? }`. After Steps 3 to 4b settled the refreshed lists, check that every `strengths` row still names a `model` that is in that agent's refreshed list (an `effort` is kept only for an agent that takes one, and is `low`, `medium` or `high`). For a row whose model is **gone**, propose a replacement from the same family, one step lighter or stronger as the word implies (Thrifty lighter, Best stronger), and show it in Step 7's table as a `strengths.<agent>.<word>` change. Never add a mapping for an agent that has none: only agents already under `strengths` are checked.
|
||||
|
||||
### Step 5: Re-check the agent list against vendor docs
|
||||
|
||||
For each entry in `agents.json`, locate the vendor's current install documentation on each run (search for it; do not use a remembered URL, since docs move and `installUrl` itself may be stale). Compare the file against what the docs say today:
|
||||
@@ -136,6 +140,7 @@ Check every rule before `npm test` (Step 10). They mirror the shipped-file tests
|
||||
- Every entry in `claude`, `devin` and `codex` has a non-empty string `id` and a non-empty string `label`.
|
||||
- Ids are unique within each list, and labels are unique within each list.
|
||||
- No Devin id ends in `xhigh`, `max`, `fast` or `priority`.
|
||||
- Every `strengths` row names a `model` that is in that agent's list in the same file, uses only the words `thrifty`, `balanced` and `best`, and no agent other than the ones already under `strengths` gains a mapping.
|
||||
|
||||
**`agents.json`:**
|
||||
|
||||
|
||||
@@ -647,7 +647,7 @@ Ghoul Rush at 65).
|
||||
star eye, and one to three rivals each leave a glowing wall behind; a wall, a
|
||||
trail (yours too), a crystal or another rider's head is out, and a rival's
|
||||
trail goes once it has faded. You get a split second of grace: about to
|
||||
ride into something, you hold in place for 150 ms first, and a turn pressed
|
||||
ride into something, you hold in place for 190 ms first, and a turn pressed
|
||||
then rides out of it (the rivals get none). Arrows steer and space spends a **boost**
|
||||
charge for 1.4 seconds of speed (two charges a heat, up to three). A round
|
||||
is a run of heats through nine arenas, each with its own scenery: Neon Grid,
|
||||
@@ -665,7 +665,8 @@ Ghoul Rush at 65).
|
||||
trails but not crystals, three shots, each a rival out with the cut bonus)
|
||||
and **Score x2** (8 seconds of double points), a third rival and a pair of
|
||||
**portals** at 4 with a **Wide Trail** (4 seconds of a wall three cells
|
||||
across) and **Coin Rain** (seven coins over the board), **closing walls**
|
||||
across; you can turn onto the side cells you have just laid, so a corner
|
||||
never crashes you) and **Coin Rain** (seven coins over the board), **closing walls**
|
||||
at 5 (from 10 seconds in, the outer ring turns to stone every 3.5 seconds,
|
||||
flashing red first) with a **Hyperjump** (straight out to the most open
|
||||
space on the board), and at 6 a second pair of portals and a rainbow
|
||||
@@ -1738,6 +1739,8 @@ Most people never need this tab: Plan2Code finds the agents installed on the mac
|
||||
|
||||
**Models.** The `plan2code` launcher's model menu comes from `models.json`, which every install overwrites with the authors' curated list. Each built-in agent's form (Claude, Devin, Codex) shows that list under *Comes with Plan2Code*, and below it **Models you added**, each a model id and the name shown in the menu, for a model that came out before Plan2Code was updated. Additions are kept in `~/.plan2code/models.json` and survive updates, unless the curated list now includes them; **Remove** takes one out. Restart `plan2code` to see a change. You can always run `plan2code --model <id>`, or switch model inside your agent before running a skill. Devin ids ending `-xhigh` or `-max` are refused. Maintainers refresh the curated list, and the shipped agent list's install data, with the repo-local `/plan2code-launcher-update` skill, which shows a diff and changes only what they approve.
|
||||
|
||||
**Strengths in the loop.** Under *Models*, a fold of the same name maps **Thrifty**, **Balanced** and **Best** to one of that agent's own models (and an effort, for agents that take one). Rows you have not changed show as shipped, tagged *default*; a changed row has **Reset**. The Implementation Loop's **Strength per phase** setting reads these three words to start each phase, its retry and its helpers on the model you chose (see the Implementation Loop in the desktop app's guide). Saved with the agent's form in `~/.plan2code/models.json`.
|
||||
|
||||
**Agents.** An agent you add is an agent CLI Plan2Code did not find on its own, which the `plan2code` command and the desktop app can then start. Each one has a name, the command to run (a bare name looked up on `PATH`, or a full path), and optional fields:
|
||||
|
||||
- **Start prompt**: `/plan2code` by default. Leave it blank to start the agent with nothing typed.
|
||||
|
||||
+2
-1
@@ -16,7 +16,7 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
- **web console**: start Pathfinder, Plan or Quick Task (on **Start fresh**) or Revise plan (on a picked spec with no plan change waiting) from a Notebook tab. A lit card's confirm pane offers **Start with a note from your Notebook**, with the tab list, a preview of the whole tab and up to five ticked pictures (the first five start ticked; a tab over 50 KB says so). The skill's first box arrives filled with the tab's text and pictures, editable, and the agent reads it only once you send it; nothing about the tab rides the launch itself. The tab then shows a **sent** badge and a "Sent to <Skill> · <Date>" line in the Notebook, and the Notebook's privacy line now reads: the agent never reads your Notebook, and a tab reaches it only when you start a workflow with it.
|
||||
- **web console**: **Ask for suggestions**, a chip in the **Notes on this** panel of an open choice, multi or confirm card, asks Plan2Code what it would pick and why, on its own: it sends one request for that card (with anything typed in the note box), and every pick already staged, on that card or another, stays staged. The request shows in the thread tagged **Asked for suggestions** until the agent replies there, with the chip held off meanwhile; `console.md` tells the agent to answer a `Suggestions wanted on <title>:` line in the item's thread with each suggestion and why, re-posting the question only when that helps. A re-post that drops an option clears only the pick staged on it, and a banner names the question.
|
||||
- **web console**: **Activities**, a die in the top bar right of the megaphone, opens a window of small games to play while you wait, say through a long build. The first is **Snake**, built in-house from local files (arrows or WASD, space or Enter to start, P or Enter to pause and play on, Esc to close). It speeds up as it grows and gets wilder each level: every new level opens in Slow-mo (which eases back to full speed as it runs out, never with a jolt), and every 5 foods brings something new (rocks that flash before they land, mystery boxes, portals, tail-cutting comets, chaos, then ice, where a turn slides two steps before it takes), five power-ups turn up on their own (Shield, Slow-mo, Magnet, Ghost, Scissors), a mystery box holds one of nine surprises (Jackpot, Gold rush, Lights out, Disco fever and more), each level serves its own fruit (an apple, then cherries, an orange, grapes, a banana, a strawberry, watermelon, a peach and a golden apple) on its own scenery (meadow, desert, lagoon, starry night, carnival, ice, volcano, gold), the last food of every odd level from 3 on is a crowned four-cell boss fruit that takes three bites, a runaway fruit on little feet hops away until you corner it or tire it out, quick eating builds a combo up to x5, and passing your best plays a fanfare. A level, power-up or surprise banner opens on the half of the board away from the snake and fades almost clear while the snake is under it or heading into it, so it never hides a crash. The start and end screens count the surprises you have found so far and hint at what waits next. The second is **Mini golf**: goofy holes seen from above on themed courses (see the course dashboard further down), among them Pirate Cove (a shark sea, cannonballs, a kraken, a ghost ship, a skull to putt through) and the Caves of Doom (dark but for the ball's light, with lava, a bottomless pit, mine carts, stone crushers and a sleeping dragon), played arcade style: the aim follows the mouse (or held arrows, turning faster the longer they are held) and points back at the cup after every stop, holding there until the mouse really moves so a click never swings it, one click or space starts a power meter beside the ball and a second sets the power (slow near the bottom for soft putts, fast near the top, with a gold MAX band for a 1.15x putt and a red overswing band past it that shanks the ball), a 6 second shot clock starts the meter for you, a meter left running dribbles the ball, and holding space or the mouse fast-forwards the roll, with par per hole, at most 8 strokes a hole, and its best kept as the lowest full round. Glowing power-up pads help the next putt: a free putt, a cannon shot, a ghost ball that floats over water, a cup magnet, a rubber duck that keeps its speed off walls, a huge cup, and a spyglass that shows where the putt will roll. With two games, a picker chooses between them. A new question, a sign-off or a finish pauses the game at once and shows a banner with **Go to it**, so a game never hides your turn; hiding the page or clicking away pauses it too. While that banner is up, nothing resumes until you click its **Unpause game** button, so a key or click already on its way cannot wave the banner away unread; after **Go to it**, or once you close and reopen the window, a game key or a click on the board plays on. Resuming puts the your-turn banner away until the next question. Every round start and every play-on after a pause counts down 3, 2, 1 first, so a game never moves before you are ready. The window's header shows the current game's best. Best scores (shown beside the score and after each round, cleared by **Reset best scores**; the score line is a pair of colored chips with a meter filling toward the best, which glows when you reach it, turns into a rainbow with a burst of sparks when you pass it, and ends the round with **New best!**) and the last pick are saved privately in `~/.plan2code/console/looks.json` and never reach the agent. **User Preferences → Sounds & activities → Show Activities** hides the die everywhere, and Help has a new Activities topic.
|
||||
- **web console**: Activities has a third game, **Light Trails**: every rider leaves a glowing wall behind it, and the last one still moving wins the heat. Arrows steer and space spends a boost charge (two a heat, up to three). Riding into something holds you in place for a split second first, so a turn pressed then still gets you out (rivals get no such grace). A round runs through nine arenas, from Neon Grid to the Golden Arena, each on its own scenery: a win moves you on, and a crash costs one of five lives and runs the heat again, and every 750 points gives a life back (up to nine). Each arena brings a rival more (Zip, Bolt, then Echo, who ride sharper the further you go) or something new: power-up pads at 2 (Boost, Phase through trails, an Eraser that wipes the trails around you, Slow-mo for the rivals, coins, a beating Heart for a life, and a Shield, held from heat to heat until it takes a crash for you), crystals at 3 with a Laser that zaps rival heads in your line through their trails and Score x2, portals at 4 with a Wide Trail three cells across and Coin Rain, walls that close in a ring at a time, flashing first, at 5 with a Hyperjump out to open space, and at 6 a rainbow Mystery pad that could be any of them; the first pad of each kind in a run says it is new. A rival out while you still ride scores points, and more when your trail or your laser got it. You ride with Planny's star eye, and the start and end screens show the furthest arena you have reached and what waits next.
|
||||
- **web console**: Activities has a third game, **Light Trails**: every rider leaves a glowing wall behind it, and the last one still moving wins the heat. Arrows steer and space spends a boost charge (two a heat, up to three). Riding into something holds you in place for a split second first, so a turn pressed then still gets you out (rivals get no such grace). A round runs through nine arenas, from Neon Grid to the Golden Arena, each on its own scenery: a win moves you on, and a crash costs one of five lives and runs the heat again, and every 750 points gives a life back (up to nine). Each arena brings a rival more (Zip, Bolt, then Echo, who ride sharper the further you go) or something new: power-up pads at 2 (Boost, Phase through trails, an Eraser that wipes the trails around you, Slow-mo for the rivals, coins, a beating Heart for a life, and a Shield, held from heat to heat until it takes a crash for you), crystals at 3 with a Laser that zaps rival heads in your line through their trails and Score x2, portals at 4 with a Wide Trail three cells across (you can turn onto the side cells just laid, so a corner never crashes you) and Coin Rain, walls that close in a ring at a time, flashing first, at 5 with a Hyperjump out to open space, and at 6 a rainbow Mystery pad that could be any of them; the first pad of each kind in a run says it is new. A rival out while you still ride scores points, and more when your trail or your laser got it. You ride with Planny's star eye, and the start and end screens show the furthest arena you have reached and what waits next.
|
||||
- **web console**: Activities has a fourth game, **Bug Hunt**, an arcade shooter. Planny's ship slides along the bottom (the arrows move it, held space fires) and squashes waves of bugs that swoop in from the sides into a swaying formation, then break off and dive at you. The first waves each bring a new bug: the everyday **Bug**, a **Beetle** that splits in two, a zigzagging **Race condition**, an **Exception** that throws things, a **Null pointer** that shots pass through while it fades, and a **Firewall** that soaks up shots. Every fifth wave is a boss: the **Memory Leak**, which grows while you wait, the **Spaghetti Monster**, whose tentacles have to go first, and the **Heisenbug**, which is only there when you look, then round again, tougher. Squashed bugs drop coins and now and then a power-up (Spread shot, Rapid fire, Shield, Slow-mo, Magnet, Refactor, which cleans up the screen, and a 1UP), quick kills build a combo up to x5, and a wave cleared without a hit scores extra. The board is Snake's checkerboard scrolling past with bits of code drifting by, with new scenery every five waves (the Codebase, Legacy Code, Production, the Cloud), and the start and end screens count the 16 bugs, bosses and power-ups found so far.
|
||||
- **web console**: Activities has a fifth game, **Sunset Drive**, a road racer against the clock. Planny drives a convertible down an endless road seen from behind, with bends, hills, traffic and scenery scrolling past: hold up to drive, down to brake, the arrows to steer, and space burns a nitro can for a burst of speed. The clock sits big in the top middle, blinking red and swelling on every tick in its last ten seconds. Each stage ends at a checkpoint that adds time, and just before it the road splits around a median: the side you keep to picks the next of six roads (Sunset Coast, Canyon Road, Maple Valley, Snowcap Pass, Neon City and Starlight Highway), each with its own sky, props, traffic and points bonus, the harder ones worth more. Coins, clocks and nitro cans line the road, a car passed close at speed scores a close call, and catching up with a car or hitting a palm, cactus or rock on the shoulder costs you speed. As the fork is called, a postcard of each road (its sky, hills, road and scenery, with its name and points bonus) shows in the top corner on its side, the side you are on lit. Spinning **?** boxes on the road hold power-ups, queued up to three: while one is held, space fires the oldest instead of a nitro can, and timed ones run side by side (one fired again while it runs adds its time). **Rocket Hop** leaps over the traffic and the shoulder, **Ghost Car** drives right through cars and props, **Coin Magnet** pulls in every coin across the road, **Monster Truck** flings the cars it hits into the sky for points and flattens props, and **Coin Storm** turns the traffic ahead into coins. The round ends when the clock runs out, and the start and end screens count the roads found so far.
|
||||
- **web console**: Activities has a sixth game, **Stack Deploy**, a one-button tower stacker. A block slides back and forth above the tower and space, up or a click drops it: the overhang is sliced off and tumbles away, so the next block is narrower, and a block that misses the tower ends the round with the camera pulling back over the whole tower. A drop dead on is a **Perfect**: nothing is sliced, the thunk climbs a scale with each one in a row, the bonus multiplies up to x5, and every third in a row grows the block back. Gold blocks from floor 15 are worth more and grow it twice as much. The slide speeds up from floor 10, and the floors bring twists: blocks from either side that may turn back (20), lag spikes that freeze a block for a beat (30) and wind (40), then a rush through the middle (70) and everything faster (90). The tower goes from server racks to office floors, glass towers and rockets under a sky that turns from day to space, Planny rides the top block (and wobbles after a sloppy drop), and a dashed line marks the highest floor ever reached, which the start screen names with the next style to reach.
|
||||
@@ -62,6 +62,7 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
|
||||
- **contributors**: `npm run play` opens the web console straight from `src/` with the server reading each page file fresh, so a change to an Activities game shows on the next page reload, without `npm run build:skills` or a reinstall.
|
||||
- **first run**: when no agent CLI can be used (a fresh install, an agent installed but off PATH, the only agent gone after an uninstall, or `--cli` naming a missing agent), the `plan2code` command and the desktop app show one **setup page**: the web console running an agent-less `setup` workflow. It lists each built-in agent (Claude Code, Devin, Codex) as **found**, **found outside PATH** or **not found**, with install commands for your OS, an install page link and **Check again**, plus four starter templates (Pi, Gemini CLI, OpenCode, GitHub Copilot CLI). **Use it from here** makes an off-PATH agent usable without a restart; once an agent is found the run carries straight on, the same browser tab (or the app's launch card) picking up where it left off. With no window or no person, the command prints the install steps and exits 127. One shared agent list (`src/launcher/agents.json`, installed to `~/.plan2code/bin/`) and one lookup rule (`agent-lookup.mjs`, with a Rust twin in the app held to the same fixture cases) serve the launcher, the console and the app; the maintainer skill `plan2code-model-update` is now `plan2code-launcher-update` and re-checks the list's install data too.
|
||||
- **desktop app**: the Implementation Loop setup has **Set strength per phase**: pick Thrifty, Balanced, Best or Match my session for each phase of the spec, and each phase's agent starts on the model and effort that strength maps to for the loop's agent. A phase left alone runs on the launch choice, so a loop with the toggle off behaves as before. The phase's helpers follow its strength, the one retry steps up a strength, and the loop strip and the loop report show what each phase ran on. Claude Code and Devin ship with a mapping; for any other agent **Strengths in the loop** in User Preferences, Agents & models, maps each strength to one of its models.
|
||||
|
||||
### 💥 Breaking
|
||||
|
||||
|
||||
@@ -146,6 +146,7 @@ not), so your own edits never end up inside a phase's commit.
|
||||
- **Fix findings**: **Smart pick** (the default) has a fresh agent read the findings and fix only the
|
||||
ones worth fixing, recording every skip. A skipped Critical stops the phase. **By level** fixes the
|
||||
Critical, Warning and Suggestion findings you tick (all three start ticked).
|
||||
- **Strength per phase** (off): turn on **Set strength per phase** to pick **Thrifty**, **Balanced**, **Best** or **Match my session** for each phase still to build (or **Set all to** one pick). A phase you leave untouched runs on the model the app was launched with, as before. A phase whose agent crashes or goes quiet gets its one retry (when the retry tick is on) one step up (Thrifty to Balanced, Balanced to Best; Best stays Best; **Match my session** runs on the launch model and its retry stays there), and the phase's helpers follow the same strength. Which model each word means for your agent is set in User Preferences, **Agents & models**, under **Strengths in the loop**; an agent with nothing mapped shows the toggle off with a link there. The picks are remembered per project and spec, and a pick for a phase that is done or gone is dropped.
|
||||
- **When a phase asks something**: **Take the agent's best guess** (the default), which records the
|
||||
assumption as a `[?]` task, **Pause and wait for me**, or **Stop the loop**.
|
||||
- **After the last phase**: **Stop and offer Finalize** (the default) or **Run Finalize automatically**.
|
||||
|
||||
+1
-1
@@ -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-test-map.mjs scripts/test-script-test-match.mjs scripts/test-script-test-commands.mjs scripts/test-script-run-check.mjs scripts/test-script-pr-prep.mjs scripts/test-script-coverage.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-pointers.mjs scripts/test-console-wire-budgets.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-lantern.mjs scripts/test-web-console-activities-ghoul-marrow.mjs scripts/test-web-console-activities-ghoul-mat.mjs scripts/test-web-console-activities-ghoul-eye.mjs scripts/test-web-console-activities-ghoul-bonestair.mjs scripts/test-web-console-activities-ghoul-heart.mjs scripts/test-web-console-activities-ghoul-ending.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-banister.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-tray.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-intro.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-story.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-send-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-skill-test-runs.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-agent-lookup.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-activities.mjs scripts/test-web-console-page-setup.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs"
|
||||
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-test-map.mjs scripts/test-script-test-match.mjs scripts/test-script-test-commands.mjs scripts/test-script-run-check.mjs scripts/test-script-pr-prep.mjs scripts/test-script-coverage.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-pointers.mjs scripts/test-console-wire-budgets.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities-flock.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-lantern.mjs scripts/test-web-console-activities-ghoul-marrow.mjs scripts/test-web-console-activities-ghoul-mat.mjs scripts/test-web-console-activities-ghoul-eye.mjs scripts/test-web-console-activities-ghoul-bonestair.mjs scripts/test-web-console-activities-ghoul-heart.mjs scripts/test-web-console-activities-ghoul-ending.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-banister.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-tray.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-intro.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-story.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-send-state.mjs scripts/test-web-console-strengths.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-skill-test-runs.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-agent-lookup.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-activities.mjs scripts/test-web-console-page-setup.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"gpt-tokenizer": "2.9.0",
|
||||
|
||||
@@ -207,6 +207,8 @@ impl AgentManager {
|
||||
},
|
||||
brief,
|
||||
prompt,
|
||||
None,
|
||||
Vec::new(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -231,6 +233,42 @@ impl AgentManager {
|
||||
},
|
||||
None,
|
||||
prompt,
|
||||
None,
|
||||
Vec::new(),
|
||||
)
|
||||
}
|
||||
|
||||
/// `start_transient` for a loop phase that runs on its own strength after
|
||||
/// the agent was stopped: the stored launch choice is `kind`, `model`,
|
||||
/// `effort` and `mode` (so a later New Session or phase runs on it), while
|
||||
/// this one launch runs on `phase_model` and `phase_effort` with
|
||||
/// `extra_env` added.
|
||||
pub fn start_transient_on(
|
||||
&self,
|
||||
launch: (Agent, Option<String>, Option<String>, PermissionMode),
|
||||
prompt: String,
|
||||
phase_model: String,
|
||||
phase_effort: Option<String>,
|
||||
extra_env: Vec<(String, String)>,
|
||||
) -> Result<(), String> {
|
||||
let (kind, model, effort, mode) = launch;
|
||||
let on = StartChoice {
|
||||
kind: kind.clone(),
|
||||
model: Some(phase_model),
|
||||
effort: phase_effort,
|
||||
mode,
|
||||
};
|
||||
self.begin(
|
||||
StartChoice {
|
||||
kind,
|
||||
model,
|
||||
effort,
|
||||
mode,
|
||||
},
|
||||
None,
|
||||
prompt,
|
||||
Some(on),
|
||||
extra_env,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -242,6 +280,8 @@ impl AgentManager {
|
||||
choice: StartChoice,
|
||||
restart_brief: Option<String>,
|
||||
first_prompt: String,
|
||||
launch_choice: Option<StartChoice>,
|
||||
launch_env: Vec<(String, String)>,
|
||||
) -> Result<(), String> {
|
||||
let mut inner = lock(&self.shared.inner);
|
||||
if inner.state == AgentState::Running {
|
||||
@@ -249,7 +289,10 @@ impl AgentManager {
|
||||
}
|
||||
inner.brief_note = None;
|
||||
let previous = inner.last_start.replace((choice, restart_brief));
|
||||
match self.shared.spawn(&mut inner, first_prompt) {
|
||||
match self
|
||||
.shared
|
||||
.spawn(&mut inner, first_prompt, launch_choice, launch_env)
|
||||
{
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => {
|
||||
// A start that never ran must not take away what Restart would
|
||||
@@ -270,6 +313,42 @@ impl AgentManager {
|
||||
/// was, so a later New Session still opens the dashboard, not this
|
||||
/// prompt again.
|
||||
pub fn start_fresh(&self, prompt: String) -> Result<(), String> {
|
||||
self.fresh(prompt, None, Vec::new())
|
||||
}
|
||||
|
||||
/// Like `start_fresh`, but the agent runs on `model` and `effort` for this
|
||||
/// launch alone, with `extra_env` added to its environment: the loop's way
|
||||
/// to start a phase on its strength. The agent kind and permission mode
|
||||
/// stay the stored launch choice's, and the stored choice itself is never
|
||||
/// written, so a later `start_fresh`, New Session or Restart runs on the
|
||||
/// original model and effort without `extra_env`.
|
||||
pub fn start_phase_on(
|
||||
&self,
|
||||
prompt: String,
|
||||
model: String,
|
||||
effort: Option<String>,
|
||||
extra_env: Vec<(String, String)>,
|
||||
) -> Result<(), String> {
|
||||
let stored = lock(&self.shared.inner)
|
||||
.last_start
|
||||
.as_ref()
|
||||
.map(|(choice, _)| choice.clone())
|
||||
.ok_or("no agent has been started")?;
|
||||
let choice = StartChoice {
|
||||
model: Some(model),
|
||||
effort,
|
||||
..stored
|
||||
};
|
||||
self.fresh(prompt, Some(choice), extra_env)
|
||||
}
|
||||
|
||||
/// The kill-then-spawn body `start_fresh` and `start_phase_on` share.
|
||||
fn fresh(
|
||||
&self,
|
||||
prompt: String,
|
||||
choice: Option<StartChoice>,
|
||||
extra_env: Vec<(String, String)>,
|
||||
) -> Result<(), String> {
|
||||
let mut inner = lock(&self.shared.inner);
|
||||
if inner.last_start.is_none() {
|
||||
return Err("no agent has been started".to_string());
|
||||
@@ -282,7 +361,7 @@ impl AgentManager {
|
||||
let _ = old.host.kill();
|
||||
}
|
||||
}
|
||||
match self.shared.spawn(&mut inner, prompt) {
|
||||
match self.shared.spawn(&mut inner, prompt, choice, extra_env) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => {
|
||||
inner.state = AgentState::Ended {
|
||||
@@ -427,11 +506,28 @@ impl Shared {
|
||||
/// end. `prompt` is this launch's first prompt: the stored brief for a
|
||||
/// start or a Restart, or a transient one (`start_fresh`,
|
||||
/// `start_transient`) that a Restart must not repeat.
|
||||
fn spawn(self: &Arc<Self>, inner: &mut Inner, prompt: String) -> Result<(), String> {
|
||||
let (choice, _) = inner
|
||||
.last_start
|
||||
.clone()
|
||||
.ok_or("no agent has been started")?;
|
||||
///
|
||||
/// `choice_override` runs this launch on another choice than the stored
|
||||
/// one (which it never replaces), and `launch_env` is added to the
|
||||
/// process env after the manager's own; both are empty for every caller
|
||||
/// but the loop's phase start.
|
||||
fn spawn(
|
||||
self: &Arc<Self>,
|
||||
inner: &mut Inner,
|
||||
prompt: String,
|
||||
choice_override: Option<StartChoice>,
|
||||
launch_env: Vec<(String, String)>,
|
||||
) -> Result<(), String> {
|
||||
let choice = match choice_override {
|
||||
Some(choice) => choice,
|
||||
None => {
|
||||
inner
|
||||
.last_start
|
||||
.clone()
|
||||
.ok_or("no agent has been started")?
|
||||
.0
|
||||
}
|
||||
};
|
||||
let mut spec = agent_launch_spec(
|
||||
&choice.kind,
|
||||
&self.folder,
|
||||
@@ -443,6 +539,7 @@ impl Shared {
|
||||
if let Ok(extra) = self.extra_env.lock() {
|
||||
spec.env.extend(extra.iter().cloned());
|
||||
}
|
||||
spec.env.extend(launch_env);
|
||||
let generation = self.generation.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
|
||||
let on_output = {
|
||||
@@ -520,7 +617,7 @@ impl Shared {
|
||||
.unwrap_or_else(|| choice.kind.default_prompt().to_string())
|
||||
})
|
||||
.ok_or("no agent has been started")?;
|
||||
match self.spawn(inner, prompt) {
|
||||
match self.spawn(inner, prompt, None, Vec::new()) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => {
|
||||
inner.state = AgentState::Ended {
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
//! retry; every other failure stops at once through `stop_loop`, the one place
|
||||
//! a stop goes, with its evidence on the page.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
@@ -27,6 +28,7 @@ use crate::loop_commit;
|
||||
use crate::loop_notify::{self, NotifyKind};
|
||||
use crate::loop_report::{self, EntryResult, LoopReport, ReportEntry};
|
||||
use crate::loop_tools;
|
||||
use crate::models::{self, StrengthRow};
|
||||
use crate::session_reader::{self, ReadError};
|
||||
|
||||
// ---------------------------------------------------------------- the setup
|
||||
@@ -74,6 +76,57 @@ pub enum AfterLast {
|
||||
RunFinalize,
|
||||
}
|
||||
|
||||
/// A phase's strength word: what the person picked for one phase.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Strength {
|
||||
Thrifty,
|
||||
Balanced,
|
||||
Best,
|
||||
}
|
||||
|
||||
impl Strength {
|
||||
/// The word the setup, the env var and the console use.
|
||||
pub fn word(self) -> &'static str {
|
||||
match self {
|
||||
Strength::Thrifty => "thrifty",
|
||||
Strength::Balanced => "balanced",
|
||||
Strength::Best => "best",
|
||||
}
|
||||
}
|
||||
|
||||
/// The word for the report and the page.
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Strength::Thrifty => "Thrifty",
|
||||
Strength::Balanced => "Balanced",
|
||||
Strength::Best => "Best",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_word(word: &str) -> Option<Strength> {
|
||||
match word {
|
||||
"thrifty" => Some(Strength::Thrifty),
|
||||
"balanced" => Some(Strength::Balanced),
|
||||
"best" => Some(Strength::Best),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The env var a strength phase's agent gets; the console reads it so the
|
||||
/// phase's helpers follow the phase.
|
||||
pub const STRENGTH_ENV: &str = "PLAN2CODE_LOOP_STRENGTH";
|
||||
|
||||
/// One saved pick: the phase's number and name (a renamed phase drops the pick)
|
||||
/// and the strength word chosen for it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PhasePick {
|
||||
pub n: u32,
|
||||
pub name: String,
|
||||
pub strength: Strength,
|
||||
}
|
||||
|
||||
/// One project's entry in `loop-setup.json`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
@@ -97,6 +150,10 @@ pub struct LoopSetup {
|
||||
/// The query parameter or JSON field that carries the message, for the
|
||||
/// kinds that let the person name it.
|
||||
pub notify_param: String,
|
||||
/// Whether each phase runs on its own strength (off: every phase runs as today).
|
||||
pub phase_strength: bool,
|
||||
/// The picks per spec folder (`specs/<name>`), only for phases not yet done.
|
||||
pub strengths: BTreeMap<String, Vec<PhasePick>>,
|
||||
}
|
||||
|
||||
impl Default for LoopSetup {
|
||||
@@ -114,6 +171,8 @@ impl Default for LoopSetup {
|
||||
notify_kind: NotifyKind::Query,
|
||||
notify_url: String::new(),
|
||||
notify_param: loop_notify::DEFAULT_PARAM.to_string(),
|
||||
phase_strength: false,
|
||||
strengths: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -260,6 +319,9 @@ pub struct PhaseRecord {
|
||||
pub commit: Option<String>,
|
||||
pub subject: Option<String>,
|
||||
pub retries: u32,
|
||||
/// The strength this phase runs on now: its pick, stepped up by a retry.
|
||||
/// `None` for Match my session and for a run with the toggle off.
|
||||
pub strength: Option<Strength>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -321,6 +383,37 @@ pub struct RunningRecord {
|
||||
/// How many looks in a row could not read the phase's session; reset by
|
||||
/// the next good read. While it is above zero a silence stop says why.
|
||||
pub read_failures: u32,
|
||||
/// What each strength word maps to for the loop's agent, resolved once at
|
||||
/// the start (empty with the toggle off), so no phase start rereads files.
|
||||
pub strength_rows: BTreeMap<String, StrengthRow>,
|
||||
/// The launch choice's model and effort, which a Match my session phase runs on.
|
||||
pub launch_model: Option<String>,
|
||||
pub launch_effort: Option<String>,
|
||||
}
|
||||
|
||||
/// What one phase runs on, for its start, the strip and the report.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PhaseRun {
|
||||
/// `None`: the phase runs on the launch choice.
|
||||
pub strength: Option<Strength>,
|
||||
pub model: Option<String>,
|
||||
pub effort: Option<String>,
|
||||
}
|
||||
|
||||
impl PhaseRun {
|
||||
/// "sonnet, low", "opus", or "" when no model is known.
|
||||
pub fn model_text(&self) -> String {
|
||||
match (&self.model, &self.effort) {
|
||||
(Some(m), Some(e)) => format!("{m}, {e}"),
|
||||
(Some(m), None) => m.clone(),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The report's word: "Thrifty", or "Match my session".
|
||||
pub fn word_text(&self) -> &'static str {
|
||||
self.strength.map_or("Match my session", Strength::label)
|
||||
}
|
||||
}
|
||||
|
||||
fn report_time() -> String {
|
||||
@@ -375,6 +468,48 @@ impl RunningRecord {
|
||||
start_head: None,
|
||||
own_dirty: Vec::new(),
|
||||
read_failures: 0,
|
||||
strength_rows: BTreeMap::new(),
|
||||
launch_model: None,
|
||||
launch_effort: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// What phase `index` runs on, or `None` with Set strength per phase off.
|
||||
/// A phase whose word the agent does not map runs on the launch choice
|
||||
/// (Start is held for such a pick, so this is only a guard).
|
||||
pub fn phase_run(&self, index: usize) -> Option<PhaseRun> {
|
||||
if !self.setup.phase_strength {
|
||||
return None;
|
||||
}
|
||||
let word = self.phases.get(index)?.strength;
|
||||
if let Some(word) = word {
|
||||
if let Some(row) = self.strength_rows.get(word.word()) {
|
||||
return Some(PhaseRun {
|
||||
strength: Some(word),
|
||||
model: Some(row.model.clone()),
|
||||
effort: row.effort.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Some(PhaseRun {
|
||||
strength: None,
|
||||
model: self.launch_model.clone(),
|
||||
effort: self.launch_effort.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Step phase `index` one strength up for its retry: Thrifty to Balanced,
|
||||
/// Balanced to Best, Best stays; a partly mapped agent goes to the next
|
||||
/// word it maps, or stays. A Match my session phase stays.
|
||||
pub fn step_strength_up(&mut self, index: usize) {
|
||||
let Some(phase) = self.phases.get_mut(index) else {
|
||||
return;
|
||||
};
|
||||
let Some(word) = phase.strength else { return };
|
||||
if let Some(next) = models::next_strength(&self.strength_rows, word.word())
|
||||
.and_then(|w| Strength::from_word(&w))
|
||||
{
|
||||
phase.strength = Some(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -402,6 +537,11 @@ pub struct LoopStateEvent {
|
||||
pub stopping: bool,
|
||||
/// Stop after this phase can be turned on (false on the run's last phase).
|
||||
pub can_stop_after: bool,
|
||||
/// The running phase's strength word, when it has one (not Match my session).
|
||||
pub strength: Option<String>,
|
||||
/// The model and effort the phase runs on, when known.
|
||||
pub model: Option<String>,
|
||||
pub effort: Option<String>,
|
||||
}
|
||||
|
||||
impl LoopStateEvent {
|
||||
@@ -422,6 +562,9 @@ impl LoopStateEvent {
|
||||
stop_after_phase: false,
|
||||
stopping: false,
|
||||
can_stop_after: false,
|
||||
strength: None,
|
||||
model: None,
|
||||
effort: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -433,6 +576,7 @@ pub fn state_event(rec: &RunningRecord) -> LoopStateEvent {
|
||||
.checked_sub(1)
|
||||
.and_then(|at| rec.phases.get(at))
|
||||
.filter(|p| p.status == PhaseStatus::Done);
|
||||
let run = rec.phase_run(rec.current);
|
||||
LoopStateEvent {
|
||||
running: true,
|
||||
spec_name: rec
|
||||
@@ -452,6 +596,12 @@ pub fn state_event(rec: &RunningRecord) -> LoopStateEvent {
|
||||
stop_after_phase: rec.stop_after_phase,
|
||||
stopping: rec.stop_now,
|
||||
can_stop_after: rec.current + 1 < rec.phases.len(),
|
||||
strength: run
|
||||
.as_ref()
|
||||
.and_then(|r| r.strength)
|
||||
.map(|w| w.word().to_string()),
|
||||
model: run.as_ref().and_then(|r| r.model.clone()),
|
||||
effort: run.as_ref().and_then(|r| r.effort.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -964,6 +1114,7 @@ pub fn prepare_with(
|
||||
commit: None,
|
||||
subject: None,
|
||||
retries: 0,
|
||||
strength: phase_pick(&setup, spec, n, p["name"].as_str().unwrap_or("")),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
@@ -1020,6 +1171,33 @@ pub fn prepare_with(
|
||||
Ok(rec)
|
||||
}
|
||||
|
||||
/// The strength the person picked for phase `n` called `name` of `spec`, only
|
||||
/// with the toggle on. A renamed phase drops its pick.
|
||||
fn phase_pick(setup: &LoopSetup, spec: &str, n: u32, name: &str) -> Option<Strength> {
|
||||
if !setup.phase_strength {
|
||||
return None;
|
||||
}
|
||||
setup
|
||||
.strengths
|
||||
.get(spec)?
|
||||
.iter()
|
||||
.find(|p| p.n == n && p.name == name)
|
||||
.map(|p| p.strength)
|
||||
}
|
||||
|
||||
/// What each strength word maps to for `agent`, from the shipped and user
|
||||
/// model files: read once, when the loop begins.
|
||||
fn strength_rows_for(agent: &Agent) -> BTreeMap<String, StrengthRow> {
|
||||
let models: Vec<String> = match agent {
|
||||
Agent::Builtin(entry) => models::models_for_builtin(&entry.id),
|
||||
Agent::Custom(custom) => custom.models.clone(),
|
||||
}
|
||||
.into_iter()
|
||||
.map(|m| m.id)
|
||||
.collect();
|
||||
models::strengths_for(agent.id(), &models, agent.has_effort())
|
||||
}
|
||||
|
||||
/// Open again the phases `prepare` found marked done with no commit behind
|
||||
/// them. Writes to the spec, so Start calls it only after the confirm.
|
||||
pub fn reopen_rebuilt(rec: &RunningRecord) -> Result<(), String> {
|
||||
@@ -1281,6 +1459,11 @@ pub fn begin_with_limits(
|
||||
let home = session_reader::console_home().ok_or("no home folder found")?;
|
||||
// A build that stopped earlier carries on in the same report.
|
||||
let mut rec = rec;
|
||||
if rec.setup.phase_strength {
|
||||
rec.strength_rows = strength_rows_for(&launch.0);
|
||||
}
|
||||
rec.launch_model.clone_from(&launch.1);
|
||||
rec.launch_effort.clone_from(&launch.2);
|
||||
if let Some(report) = loop_report::load(&home, &rec.project, &rec.spec) {
|
||||
rec.report = report;
|
||||
}
|
||||
@@ -1340,6 +1523,32 @@ pub fn start_with(agent: &AgentManager, launch: &Launch, prompt: String) -> Resu
|
||||
}
|
||||
}
|
||||
|
||||
/// Start a fresh agent on `prompt` for a phase that runs on `word`'s `row`: the
|
||||
/// agent starts on that model and effort with `PLAN2CODE_LOOP_STRENGTH` set,
|
||||
/// and the stored launch choice stays what it was (an agent the loop stopped
|
||||
/// gets the launch choice stored, then the phase's own run on top).
|
||||
pub fn start_phase_with(
|
||||
agent: &AgentManager,
|
||||
launch: &Launch,
|
||||
prompt: String,
|
||||
row: &StrengthRow,
|
||||
word: Strength,
|
||||
) -> Result<(), String> {
|
||||
let env = vec![(STRENGTH_ENV.to_string(), word.word().to_string())];
|
||||
if agent.launch_choice().is_some() {
|
||||
agent.start_phase_on(prompt, row.model.clone(), row.effort.clone(), env)
|
||||
} else {
|
||||
agent.forget_session();
|
||||
agent.start_transient_on(
|
||||
launch.clone(),
|
||||
prompt,
|
||||
row.model.clone(),
|
||||
row.effort.clone(),
|
||||
env,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The prompt behind Fix it by hand: an ordinary Implement session.
|
||||
pub fn fix_prompt(spec: &str) -> String {
|
||||
format!("/plan2code-3-implement {spec}/overview.md --web")
|
||||
@@ -1376,12 +1585,21 @@ fn start_phase(ctx: &Ctx, index: usize) -> Result<(), String> {
|
||||
rec.phase_started_at = Instant::now();
|
||||
rec.activity_checked = Instant::now();
|
||||
rec.last_activity = SystemTime::now();
|
||||
phase_prompt(&rec.spec, rec.phases[index].n, &rec.setup)
|
||||
let prompt = phase_prompt(&rec.spec, rec.phases[index].n, &rec.setup);
|
||||
let on = rec.phase_run(index).and_then(|run| {
|
||||
let word = run.strength?;
|
||||
Some((word, rec.strength_rows.get(word.word())?.clone()))
|
||||
});
|
||||
(prompt, on)
|
||||
};
|
||||
let (prompt, on) = prompt;
|
||||
// Said before the agent starts: the banner is up from the moment of Start,
|
||||
// and says what is happening between phases.
|
||||
emit(ctx);
|
||||
start_with(&ctx.agent, &ctx.launch, prompt)?;
|
||||
match on {
|
||||
Some((word, row)) => start_phase_with(&ctx.agent, &ctx.launch, prompt, &row, word)?,
|
||||
None => start_with(&ctx.agent, &ctx.launch, prompt)?,
|
||||
}
|
||||
let generation = ctx.agent.snapshot().generation;
|
||||
if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) {
|
||||
rec.generation = generation;
|
||||
@@ -1719,6 +1937,10 @@ fn fail(ctx: &Ctx, snap: &Snapshot, cause: StopCause, detail: String) -> bool {
|
||||
return false;
|
||||
}
|
||||
if should_retry(&cause, &snap.setup, snap.phase_retries) {
|
||||
// The retry runs one strength up, and its entry says so.
|
||||
if let Some(rec) = lock(&ctx.slot).as_mut().filter(|r| r.run_id == ctx.run_id) {
|
||||
rec.step_strength_up(snap.current);
|
||||
}
|
||||
let why = stop_line(&cause, snap.phase_n, &detail, false);
|
||||
let name = phase_name(ctx);
|
||||
add_entry(
|
||||
@@ -2098,11 +2320,19 @@ fn phase_assumptions(
|
||||
/// Add to the report and save it straight away, so a crash loses nothing. A save
|
||||
/// that fails never stops the loop; the report stays in memory and the end says so.
|
||||
fn add_entry(ctx: &Ctx, entry: ReportEntry) {
|
||||
let mut entry = entry;
|
||||
let saved = {
|
||||
let mut guard = lock(&ctx.slot);
|
||||
let Some(rec) = guard.as_mut().filter(|r| r.run_id == ctx.run_id) else {
|
||||
return;
|
||||
};
|
||||
// What the phase ran on, with Set strength per phase on.
|
||||
if entry.strength.is_empty() {
|
||||
if let Some(run) = rec.phase_run(rec.current) {
|
||||
entry.strength = run.word_text().to_string();
|
||||
entry.model = run.model_text();
|
||||
}
|
||||
}
|
||||
rec.report.entries.push(entry);
|
||||
(rec.project.clone(), rec.report.clone())
|
||||
};
|
||||
@@ -2575,6 +2805,11 @@ fn stop_loop(ctx: &Ctx, cause: StopCause, line: String, can: &[&str]) {
|
||||
entry = entry.with_outcome(outcome);
|
||||
}
|
||||
}
|
||||
// What the phase ran on, as `add_entry` does for every other entry.
|
||||
if let Some(run) = rec.phase_run(at) {
|
||||
entry.strength = run.word_text().to_string();
|
||||
entry.model = run.model_text();
|
||||
}
|
||||
rec.report.entries.push(entry);
|
||||
rec.report_failure = loop_report::save(&ctx.home, &rec.project, &rec.report).err();
|
||||
let mut evidence = evidence_with_report(&evidence_markdown(&cause, &line, &rec), &rec);
|
||||
@@ -3048,6 +3283,7 @@ mod tests {
|
||||
commit: None,
|
||||
subject: None,
|
||||
retries: 0,
|
||||
strength: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3545,6 +3781,43 @@ second line"
|
||||
assert_eq!(s.silence_minutes, 30);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_older_entry_reads_without_phase_strengths() {
|
||||
let s: LoopSetup =
|
||||
serde_json::from_value(json!({ "review": true, "commit": false })).unwrap();
|
||||
assert!(!s.phase_strength);
|
||||
assert!(s.strengths.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_entry_with_phase_strengths_round_trips() {
|
||||
let entry = json!({
|
||||
"phaseStrength": true,
|
||||
"strengths": { "specs/lunch": [
|
||||
{ "n": 2, "name": "The API", "strength": "thrifty" },
|
||||
{ "n": 3, "name": "The page", "strength": "best" }
|
||||
] }
|
||||
});
|
||||
let s: LoopSetup = serde_json::from_value(entry.clone()).unwrap();
|
||||
assert!(s.phase_strength);
|
||||
let picks = &s.strengths["specs/lunch"];
|
||||
assert_eq!(picks.len(), 2);
|
||||
assert_eq!(picks[0].strength, Strength::Thrifty);
|
||||
assert_eq!(
|
||||
picks[1],
|
||||
PhasePick {
|
||||
n: 3,
|
||||
name: "The page".to_string(),
|
||||
strength: Strength::Best
|
||||
}
|
||||
);
|
||||
let back = serde_json::to_value(&s).unwrap();
|
||||
assert_eq!(back["phaseStrength"], true);
|
||||
assert_eq!(back["strengths"], entry["strengths"]);
|
||||
let again: LoopSetup = serde_json::from_value(back).unwrap();
|
||||
assert_eq!(again, s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_setup_is_found_under_the_consoles_folded_key() {
|
||||
let dir = std::env::temp_dir().join(format!("plan2code-loop-setup-{}", std::process::id()));
|
||||
@@ -4428,6 +4701,223 @@ second line"
|
||||
assert!(entry.line.ends_with("after one retry"), "{}", entry.line);
|
||||
}
|
||||
|
||||
fn strength_rows() -> BTreeMap<String, StrengthRow> {
|
||||
let row = |model: &str, effort: Option<&str>| StrengthRow {
|
||||
model: model.into(),
|
||||
effort: effort.map(str::to_string),
|
||||
};
|
||||
BTreeMap::from([
|
||||
("thrifty".to_string(), row("sonnet", Some("low"))),
|
||||
("balanced".to_string(), row("opus", Some("medium"))),
|
||||
("best".to_string(), row("opus", Some("high"))),
|
||||
])
|
||||
}
|
||||
|
||||
/// Turn Set strength per phase on for the harness loop: the phases'
|
||||
/// words, the rows an agent maps and a launch model for Match my session.
|
||||
fn with_strengths(ctx: &Ctx, words: &[Option<Strength>]) {
|
||||
let mut guard = lock(&ctx.slot);
|
||||
let rec = guard.as_mut().unwrap();
|
||||
rec.setup.phase_strength = true;
|
||||
rec.strength_rows = strength_rows();
|
||||
rec.launch_model = Some("haiku".into());
|
||||
for (phase, word) in rec.phases.iter_mut().zip(words) {
|
||||
phase.strength = *word;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thrifty_phase_starts_on_its_strength_and_a_retry_steps_it_up() {
|
||||
if !git_ready("strength retry") {
|
||||
return;
|
||||
}
|
||||
let repo = throwaway_repo("strength-retry");
|
||||
let (ctx, home, seen) = running_loop_seen(&repo, Limits::default());
|
||||
with_strengths(&ctx, &[Some(Strength::Thrifty), Some(Strength::Best)]);
|
||||
let ready = |count: usize| {
|
||||
wait_until("the fake agent ready", || {
|
||||
lock(&seen).matches("FAKE-AGENT ready").count() >= count
|
||||
})
|
||||
};
|
||||
start_phase(&ctx, 0).expect("start the fake agent");
|
||||
ready(1);
|
||||
ctx.agent.input(b"ENV PLAN2CODE_LOOP_STRENGTH\r").unwrap();
|
||||
wait_until("the strength env", || {
|
||||
lock(&seen).contains("ENV PLAN2CODE_LOOP_STRENGTH=thrifty")
|
||||
});
|
||||
// The strip says what the phase runs on.
|
||||
let event = state_event(lock(&ctx.slot).as_ref().unwrap());
|
||||
assert_eq!(event.strength.as_deref(), Some("thrifty"));
|
||||
assert_eq!(event.model.as_deref(), Some("sonnet"));
|
||||
assert_eq!(event.effort.as_deref(), Some("low"));
|
||||
// The stored launch choice is the loop's own, not the phase's.
|
||||
let (_, model, _, _) = ctx.agent.launch_choice().unwrap();
|
||||
assert_eq!(model, None);
|
||||
|
||||
ctx.agent.input(b"EXIT 3\r").unwrap();
|
||||
wait_until("the agent ended", || {
|
||||
matches!(ctx.agent.snapshot().state, AgentState::Ended { .. })
|
||||
});
|
||||
assert!(tick(&ctx), "the crash is retried");
|
||||
{
|
||||
let guard = lock(&ctx.slot);
|
||||
let rec = guard.as_ref().unwrap();
|
||||
assert_eq!(rec.phases[0].strength, Some(Strength::Balanced));
|
||||
let entry = rec.report.entries.last().unwrap();
|
||||
assert_eq!(entry.result, EntryResult::Retried);
|
||||
assert_eq!(entry.strength, "Balanced");
|
||||
assert_eq!(entry.model, "opus, medium");
|
||||
}
|
||||
ready(2);
|
||||
ctx.agent.input(b"ENV PLAN2CODE_LOOP_STRENGTH\r").unwrap();
|
||||
wait_until("the stepped-up env", || {
|
||||
lock(&seen).contains("ENV PLAN2CODE_LOOP_STRENGTH=balanced")
|
||||
});
|
||||
let saved = loop_report::load(&home, &repo, "specs/lunch").expect("a saved report");
|
||||
assert_eq!(saved.entries.last().unwrap().strength, "Balanced");
|
||||
end_the_test(&ctx);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_loop_with_the_toggle_off_starts_every_phase_without_the_strength_env() {
|
||||
if !git_ready("strength off") {
|
||||
return;
|
||||
}
|
||||
let repo = throwaway_repo("strength-off");
|
||||
let (ctx, _home, seen) = running_loop_seen(&repo, Limits::default());
|
||||
{
|
||||
// The words are there, but the toggle is off: they are ignored.
|
||||
let mut guard = lock(&ctx.slot);
|
||||
let rec = guard.as_mut().unwrap();
|
||||
rec.strength_rows = strength_rows();
|
||||
rec.phases[0].strength = Some(Strength::Best);
|
||||
assert!(rec.phase_run(0).is_none());
|
||||
}
|
||||
start_phase(&ctx, 0).expect("start the fake agent");
|
||||
wait_until("the fake agent ready", || {
|
||||
lock(&seen).contains("FAKE-AGENT ready")
|
||||
});
|
||||
ctx.agent.input(b"ENV PLAN2CODE_LOOP_STRENGTH\r").unwrap();
|
||||
wait_until("the env line", || {
|
||||
lock(&seen).contains("ENV PLAN2CODE_LOOP_STRENGTH=\r")
|
||||
});
|
||||
let event = state_event(lock(&ctx.slot).as_ref().unwrap());
|
||||
assert_eq!(
|
||||
(event.strength, event.model, event.effort),
|
||||
(None, None, None)
|
||||
);
|
||||
end_the_test(&ctx);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fix_it_by_hand_and_finalize_never_pass_the_strength_env() {
|
||||
if !git_ready("strength fix") {
|
||||
return;
|
||||
}
|
||||
let repo = throwaway_repo("strength-fix");
|
||||
let (ctx, _home, seen) = running_loop_seen(&repo, Limits::default());
|
||||
with_strengths(&ctx, &[Some(Strength::Thrifty), None]);
|
||||
start_phase(&ctx, 0).expect("start the fake agent");
|
||||
wait_until("the phase agent ready", || {
|
||||
lock(&seen).matches("FAKE-AGENT ready").count() >= 1
|
||||
});
|
||||
for (round, prompt) in [fix_prompt("specs/lunch"), finalize_prompt("specs/lunch")]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
start_with(&ctx.agent, &ctx.launch, prompt).unwrap();
|
||||
wait_until("the next agent ready", || {
|
||||
lock(&seen).matches("FAKE-AGENT ready").count() >= round + 2
|
||||
});
|
||||
ctx.agent.input(b"ENV PLAN2CODE_LOOP_STRENGTH\r").unwrap();
|
||||
wait_until("the env line", || {
|
||||
lock(&seen).matches("PLAN2CODE_LOOP_STRENGTH=\r").count() > round
|
||||
});
|
||||
}
|
||||
assert!(!lock(&seen).contains("PLAN2CODE_LOOP_STRENGTH=thrifty"));
|
||||
end_the_test(&ctx);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_retry_steps_best_stays_and_a_partly_mapped_agent_skips_to_its_next_word() {
|
||||
let mut rec = record("specs/x", vec![phase(1), phase(2), phase(3), phase(4)]);
|
||||
rec.strength_rows = strength_rows();
|
||||
rec.phases[0].strength = Some(Strength::Thrifty);
|
||||
rec.phases[1].strength = Some(Strength::Balanced);
|
||||
rec.phases[2].strength = Some(Strength::Best);
|
||||
for i in 0..4 {
|
||||
rec.step_strength_up(i);
|
||||
}
|
||||
assert_eq!(rec.phases[0].strength, Some(Strength::Balanced));
|
||||
assert_eq!(rec.phases[1].strength, Some(Strength::Best));
|
||||
assert_eq!(rec.phases[2].strength, Some(Strength::Best), "Best stays");
|
||||
assert_eq!(rec.phases[3].strength, None, "Match my session stays");
|
||||
|
||||
// An agent that maps only Thrifty and Best skips the gap, and stays
|
||||
// when nothing above is mapped.
|
||||
rec.strength_rows.remove("balanced");
|
||||
rec.phases[0].strength = Some(Strength::Thrifty);
|
||||
rec.step_strength_up(0);
|
||||
assert_eq!(rec.phases[0].strength, Some(Strength::Best));
|
||||
rec.strength_rows.remove("best");
|
||||
rec.phases[1].strength = Some(Strength::Thrifty);
|
||||
rec.step_strength_up(1);
|
||||
assert_eq!(rec.phases[1].strength, Some(Strength::Thrifty));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_strip_says_a_match_my_session_phase_runs_on_the_launch_model() {
|
||||
let mut rec = record("specs/x", vec![phase(1)]);
|
||||
rec.setup.phase_strength = true;
|
||||
rec.strength_rows = strength_rows();
|
||||
rec.launch_model = Some("opus".into());
|
||||
rec.launch_effort = Some("high".into());
|
||||
let event = state_event(&rec);
|
||||
assert_eq!(event.strength, None);
|
||||
assert_eq!(event.model.as_deref(), Some("opus"));
|
||||
assert_eq!(event.effort.as_deref(), Some("high"));
|
||||
let json = serde_json::to_value(&event).unwrap();
|
||||
assert_eq!(json["model"], "opus");
|
||||
assert!(json["strength"].is_null());
|
||||
// A pick the agent does not map runs on the launch choice too.
|
||||
rec.strength_rows.clear();
|
||||
rec.phases[0].strength = Some(Strength::Thrifty);
|
||||
assert_eq!(rec.phase_run(0).unwrap().strength, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stopped_phase_entry_says_what_it_ran_on() {
|
||||
if !git_ready("stopped ran on") {
|
||||
return;
|
||||
}
|
||||
let repo = throwaway_repo("stopped-ran-on");
|
||||
let limits = Limits {
|
||||
notice_wait: Duration::ZERO,
|
||||
..Limits::default()
|
||||
};
|
||||
let (ctx, home) = running_loop(&repo, limits);
|
||||
{
|
||||
let mut guard = lock(&ctx.slot);
|
||||
let rec = guard.as_mut().unwrap();
|
||||
rec.sid = None;
|
||||
rec.setup.retry_once = false;
|
||||
rec.setup.phase_strength = true;
|
||||
rec.phases[rec.current].strength = Some(Strength::Thrifty);
|
||||
rec.strength_rows.insert(
|
||||
"thrifty".to_string(),
|
||||
StrengthRow {
|
||||
model: "sonnet".to_string(),
|
||||
effort: Some("low".to_string()),
|
||||
},
|
||||
);
|
||||
}
|
||||
assert!(!tick(&ctx), "the loop is over");
|
||||
let entry = last_entry_saved(&home, &repo);
|
||||
assert_eq!(entry.result, EntryResult::Stopped);
|
||||
assert_eq!(entry.strength, "Thrifty");
|
||||
assert_eq!(entry.model, "sonnet, low");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_commit_stops_the_loop() {
|
||||
if !harness_ready("refused commit") {
|
||||
|
||||
@@ -59,6 +59,12 @@ pub struct ReportEntry {
|
||||
/// Things the app noticed that did not stop the phase (leftover Suggestions).
|
||||
pub warnings: Vec<String>,
|
||||
pub retries: u32,
|
||||
/// What the phase ran on, with Set strength per phase on: "Thrifty",
|
||||
/// "Balanced", "Best" or "Match my session" (the word a retry stepped up
|
||||
/// to, for a retry); empty with the toggle off.
|
||||
pub strength: String,
|
||||
/// The model it ran on, with the effort folded in ("sonnet, low").
|
||||
pub model: String,
|
||||
}
|
||||
|
||||
impl ReportEntry {
|
||||
@@ -281,6 +287,14 @@ fn entry_markdown(md: &mut String, e: &ReportEntry) {
|
||||
} else if e.result == EntryResult::Passed {
|
||||
md.push_str("- Commit: not committed\n");
|
||||
}
|
||||
if !e.strength.is_empty() {
|
||||
let on = if e.model.is_empty() {
|
||||
e.strength.clone()
|
||||
} else {
|
||||
format!("{} ({})", e.strength, e.model)
|
||||
};
|
||||
md.push_str(&format!("- Ran on: {}\n", cell(&on)));
|
||||
}
|
||||
if e.retries > 0 {
|
||||
md.push_str(&format!("- Retries: {}\n", e.retries));
|
||||
}
|
||||
@@ -565,4 +579,31 @@ mod tests {
|
||||
let old: ReportEntry = serde_json::from_str(r#"{"phase":4,"name":"P4"}"#).unwrap();
|
||||
assert!(old.warnings.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_phase_line_says_what_it_ran_on_and_an_old_store_says_nothing() {
|
||||
let mut thrifty = entry(2, EntryResult::Passed);
|
||||
thrifty.strength = "Thrifty".into();
|
||||
thrifty.model = "sonnet, low".into();
|
||||
let mut matched = entry(3, EntryResult::Passed);
|
||||
matched.strength = "Match my session".into();
|
||||
matched.model = "opus".into();
|
||||
let mut bare = entry(4, EntryResult::Passed);
|
||||
bare.strength = "Best".into();
|
||||
let mut report = LoopReport::new("specs/x", "2026-11-01 10:00");
|
||||
report.entries = vec![thrifty, matched, bare, entry(5, EntryResult::Passed)];
|
||||
let md = body_markdown(&report);
|
||||
assert!(md.contains("- Ran on: Thrifty (sonnet, low)"), "{md}");
|
||||
assert!(md.contains("- Ran on: Match my session (opus)"), "{md}");
|
||||
assert!(
|
||||
md.contains(
|
||||
"- Ran on: Best
|
||||
"
|
||||
),
|
||||
"{md}"
|
||||
);
|
||||
assert_eq!(md.matches("Ran on").count(), 3, "toggle off adds nothing");
|
||||
let old: ReportEntry = serde_json::from_str(r#"{"phase":4,"name":"P4"}"#).unwrap();
|
||||
assert!(old.strength.is_empty() && old.model.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,9 @@
|
||||
//! agents never come through here: their menu is their own `models` in
|
||||
//! agents.json.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::agents::CustomModel;
|
||||
@@ -108,6 +109,126 @@ pub fn models_for_builtin(cli_id: &str) -> Vec<CustomModel> {
|
||||
)
|
||||
}
|
||||
|
||||
/// The loop's strength words, lightest first (`STRENGTH_ORDER` in
|
||||
/// src/web-console/strengths.mjs).
|
||||
pub const STRENGTH_ORDER: [&str; 3] = ["thrifty", "balanced", "best"];
|
||||
|
||||
/// One strength's model, and the effort when the agent takes one.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct StrengthRow {
|
||||
pub model: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub effort: Option<String>,
|
||||
}
|
||||
|
||||
/// A row as the resolver keeps it, or None when it is not usable: the model
|
||||
/// must be a string in `models`; an effort survives only when the agent takes
|
||||
/// one and it is low, medium or high (`validRow` in strengths.mjs).
|
||||
fn valid_strength_row(
|
||||
row: Option<&Value>,
|
||||
models: &[String],
|
||||
has_effort: bool,
|
||||
) -> Option<StrengthRow> {
|
||||
let row = row?.as_object()?;
|
||||
let model = row.get("model")?.as_str()?;
|
||||
if !models.iter().any(|m| m == model) {
|
||||
return None;
|
||||
}
|
||||
let effort = row
|
||||
.get("effort")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|e| has_effort && matches!(*e, "low" | "medium" | "high"))
|
||||
.map(str::to_string);
|
||||
Some(StrengthRow {
|
||||
model: model.to_string(),
|
||||
effort,
|
||||
})
|
||||
}
|
||||
|
||||
/// `{ thrifty?, balanced?, best? }` for one agent from the shipped and the
|
||||
/// user's `strengths` objects (each keyed by agent id): per word the user's row
|
||||
/// if it is valid, else the shipped row if it is valid; a word with neither is
|
||||
/// left out. The twin of `resolveStrengths` in strengths.mjs, held to
|
||||
/// scripts/fixtures/strength-cases.json.
|
||||
pub fn resolve_strengths(
|
||||
shipped: &Value,
|
||||
user: &Value,
|
||||
agent: &str,
|
||||
models: &[String],
|
||||
has_effort: bool,
|
||||
) -> BTreeMap<String, StrengthRow> {
|
||||
let mut resolved = BTreeMap::new();
|
||||
for word in STRENGTH_ORDER {
|
||||
let row = valid_strength_row(
|
||||
user.get(agent).and_then(|a| a.get(word)),
|
||||
models,
|
||||
has_effort,
|
||||
)
|
||||
.or_else(|| {
|
||||
valid_strength_row(
|
||||
shipped.get(agent).and_then(|a| a.get(word)),
|
||||
models,
|
||||
has_effort,
|
||||
)
|
||||
});
|
||||
if let Some(row) = row {
|
||||
resolved.insert(word.to_string(), row);
|
||||
}
|
||||
}
|
||||
resolved
|
||||
}
|
||||
|
||||
/// The first mapped word after `word` in `STRENGTH_ORDER`, else None
|
||||
/// (`nextStrength` in strengths.mjs).
|
||||
pub fn next_strength(resolved: &BTreeMap<String, StrengthRow>, word: &str) -> Option<String> {
|
||||
let at = STRENGTH_ORDER.iter().position(|w| *w == word)?;
|
||||
STRENGTH_ORDER[at + 1..]
|
||||
.iter()
|
||||
.find(|w| resolved.contains_key(**w))
|
||||
.map(|w| w.to_string())
|
||||
}
|
||||
|
||||
/// `strengths_for` from explicit file paths, so tests never touch the real
|
||||
/// home. The shipped file falls back to the baked list, like `models_for`.
|
||||
fn strengths_from(
|
||||
agent: &str,
|
||||
models: &[String],
|
||||
has_effort: bool,
|
||||
shipped_file: Option<&Path>,
|
||||
user_file: Option<&Path>,
|
||||
) -> BTreeMap<String, StrengthRow> {
|
||||
let shipped = shipped_file
|
||||
.and_then(read_json)
|
||||
.or_else(|| serde_json::from_str(BAKED_MODELS).ok())
|
||||
.unwrap_or(Value::Null);
|
||||
let user = user_file.and_then(read_json).unwrap_or(Value::Null);
|
||||
resolve_strengths(
|
||||
shipped.get("strengths").unwrap_or(&Value::Null),
|
||||
user.get("strengths").unwrap_or(&Value::Null),
|
||||
agent,
|
||||
models,
|
||||
has_effort,
|
||||
)
|
||||
}
|
||||
|
||||
/// What each strength word maps to for the built-in `agent`, from the same
|
||||
/// shipped and user files as `models_for_builtin`. `models` is the ids of the
|
||||
/// agent's menu; a row naming a model outside it reads unmapped.
|
||||
pub fn strengths_for(
|
||||
agent: &str,
|
||||
models: &[String],
|
||||
has_effort: bool,
|
||||
) -> BTreeMap<String, StrengthRow> {
|
||||
strengths_from(
|
||||
agent,
|
||||
models,
|
||||
has_effort,
|
||||
shipped_models_file().as_deref(),
|
||||
user_models_file().as_deref(),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -211,7 +332,7 @@ mod tests {
|
||||
assert!(baked.len() > 1);
|
||||
std::fs::write(&missing, "{ nope").unwrap();
|
||||
assert!(models_for("claude", Some(&missing), Some(&missing)).len() > 1);
|
||||
assert!(models_for("codex", Some(&missing), Some(&missing)).is_empty());
|
||||
assert!(models_for("nonesuch", Some(&missing), Some(&missing)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -234,4 +355,157 @@ mod tests {
|
||||
vec![model("sonnet", Some("S"))]
|
||||
);
|
||||
}
|
||||
|
||||
/// Every case in the shared strength fixture: the same file drives
|
||||
/// scripts/test-web-console-strengths.mjs, so the console's resolver and
|
||||
/// this one stay the one rule.
|
||||
#[test]
|
||||
fn the_shared_strength_cases_all_resolve_the_same() {
|
||||
let cases: Value = serde_json::from_str(include_str!(
|
||||
"../../../scripts/fixtures/strength-cases.json"
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(cases["schema"], 1);
|
||||
let list = cases["cases"].as_array().unwrap();
|
||||
assert!(list.len() >= 10);
|
||||
for case in list {
|
||||
let name = case["name"].as_str().unwrap();
|
||||
let agent = case["agent"].as_str().unwrap();
|
||||
let models: Vec<String> = case["models"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|m| m.as_str().unwrap().to_string())
|
||||
.collect();
|
||||
// The fixture holds one agent's rows; the resolver reads them by agent id.
|
||||
let wrap = |rows: &Value| json!({ agent: rows.clone() });
|
||||
let resolved = resolve_strengths(
|
||||
&wrap(&case["shipped"]),
|
||||
&wrap(&case["user"]),
|
||||
agent,
|
||||
&models,
|
||||
case["hasEffort"].as_bool().unwrap(),
|
||||
);
|
||||
let got = serde_json::to_value(&resolved).unwrap();
|
||||
assert_eq!(got, case["expect"]["resolved"], "{name}: resolved");
|
||||
for word in STRENGTH_ORDER {
|
||||
let want = case["expect"]["next"][word].as_str().map(str::to_string);
|
||||
assert_eq!(
|
||||
next_strength(&resolved, word),
|
||||
want,
|
||||
"{name}: next after {word}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_strength_of_an_unknown_word_is_none() {
|
||||
let mut resolved = BTreeMap::new();
|
||||
resolved.insert(
|
||||
"best".to_string(),
|
||||
StrengthRow {
|
||||
model: "x".to_string(),
|
||||
effort: None,
|
||||
},
|
||||
);
|
||||
assert_eq!(next_strength(&resolved, "cheap"), None);
|
||||
assert_eq!(
|
||||
next_strength(&resolved, "thrifty"),
|
||||
Some("best".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strengths_for_reads_the_shipped_and_user_files() {
|
||||
let dir = temp_dir("strengths");
|
||||
let shipped = dir.join("bin").join("models.json");
|
||||
let user = dir.join("models.json");
|
||||
std::fs::write(
|
||||
&shipped,
|
||||
r#"{ "claude": [{ "id": "sonnet", "label": "S" }, { "id": "opus", "label": "O" }],
|
||||
"strengths": { "claude": {
|
||||
"thrifty": { "model": "sonnet", "effort": "low" },
|
||||
"best": { "model": "opus", "effort": "medium" } } } }"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
&user,
|
||||
r#"{ "strengths": { "claude": { "best": { "model": "sonnet", "effort": "high" } } } }"#,
|
||||
)
|
||||
.unwrap();
|
||||
let models = vec!["sonnet".to_string(), "opus".to_string()];
|
||||
let got = strengths_from("claude", &models, true, Some(&shipped), Some(&user));
|
||||
assert_eq!(got["thrifty"].model, "sonnet");
|
||||
assert_eq!(got["best"].model, "sonnet");
|
||||
assert_eq!(got["best"].effort.as_deref(), Some("high"));
|
||||
assert!(!got.contains_key("balanced"));
|
||||
// No user file: the shipped rows alone.
|
||||
let got = strengths_from("claude", &models, true, Some(&shipped), None);
|
||||
assert_eq!(got["best"].model, "opus");
|
||||
// An agent with no rows anywhere has none.
|
||||
assert!(strengths_from("codex", &models, false, Some(&shipped), Some(&user)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_baked_copy_ships_the_claude_and_devin_strengths() {
|
||||
let dir = temp_dir("baked-strengths");
|
||||
let missing = dir.join("bin").join("models.json");
|
||||
let ids = |agent: &str| -> Vec<String> {
|
||||
models_for(agent, Some(&missing), Some(&missing))
|
||||
.into_iter()
|
||||
.map(|m| m.id)
|
||||
.collect()
|
||||
};
|
||||
let claude = strengths_from(
|
||||
"claude",
|
||||
&ids("claude"),
|
||||
true,
|
||||
Some(&missing),
|
||||
Some(&missing),
|
||||
);
|
||||
assert_eq!(claude.len(), 3);
|
||||
let devin = strengths_from(
|
||||
"devin",
|
||||
&ids("devin"),
|
||||
false,
|
||||
Some(&missing),
|
||||
Some(&missing),
|
||||
);
|
||||
assert_eq!(devin.len(), 3);
|
||||
assert!(strengths_from(
|
||||
"codex",
|
||||
&ids("codex"),
|
||||
false,
|
||||
Some(&missing),
|
||||
Some(&missing)
|
||||
)
|
||||
.is_empty());
|
||||
}
|
||||
|
||||
/// A `strengths` key beside the agents' lists is never read as a model
|
||||
/// list: the menus come out as they did without it.
|
||||
#[test]
|
||||
fn a_strengths_key_leaves_the_model_menus_unchanged() {
|
||||
let dir = temp_dir("strengths-menu");
|
||||
let shipped = dir.join("bin").join("models.json");
|
||||
let user = dir.join("models.json");
|
||||
std::fs::write(
|
||||
&shipped,
|
||||
r#"{ "claude": [{ "id": "sonnet", "label": "S" }],
|
||||
"strengths": { "claude": { "best": { "model": "sonnet" } } } }"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
&user,
|
||||
r#"{ "claude": [{ "id": "mine", "label": "M" }],
|
||||
"strengths": { "claude": { "best": { "model": "mine" } } } }"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
models_for("claude", Some(&shipped), Some(&user)),
|
||||
vec![model("sonnet", Some("S")), model("mine", Some("M"))]
|
||||
);
|
||||
assert!(models_for("strengths", Some(&shipped), Some(&user)).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -432,3 +432,57 @@ fn a_custom_agent_runs_the_override_too_and_restart_keeps_its_id() {
|
||||
);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_phase_start_runs_on_its_model_and_env_and_leaves_the_launch_choice_alone() {
|
||||
let mut h = Harness::new();
|
||||
h.manager
|
||||
.start(
|
||||
Agent::Builtin(builtin_entry("claude").unwrap()),
|
||||
Some("opus".to_string()),
|
||||
Some("high".to_string()),
|
||||
PermissionMode::Checked,
|
||||
None,
|
||||
)
|
||||
.expect("start the fake agent");
|
||||
h.wait_for_output(READY, 1);
|
||||
|
||||
h.manager
|
||||
.start_phase_on(
|
||||
"/plan2code phase".to_string(),
|
||||
"sonnet".to_string(),
|
||||
Some("low".to_string()),
|
||||
vec![("PLAN2CODE_LOOP_STRENGTH".to_string(), "thrifty".to_string())],
|
||||
)
|
||||
.expect("start the phase on its strength");
|
||||
h.wait_for_output(READY, 2);
|
||||
// The agent-bin override drops every argument, so the fake agent sees the
|
||||
// env only; the model is checked through the stored choice below.
|
||||
h.type_line("ENV PLAN2CODE_LOOP_STRENGTH");
|
||||
h.wait_for_output("ENV PLAN2CODE_LOOP_STRENGTH=thrifty", 1);
|
||||
|
||||
// The stored choice, kind and mode are what they were.
|
||||
let (kind, model, effort, mode) = h.manager.launch_choice().unwrap();
|
||||
assert_eq!(kind.id(), "claude");
|
||||
assert_eq!(model.as_deref(), Some("opus"));
|
||||
assert_eq!(effort.as_deref(), Some("high"));
|
||||
assert_eq!(mode, PermissionMode::Checked);
|
||||
|
||||
// The next plain start runs on the original choice, with no strength.
|
||||
h.manager
|
||||
.start_fresh("/plan2code next".to_string())
|
||||
.unwrap();
|
||||
h.wait_for_output(READY, 3);
|
||||
h.type_line("ENV PLAN2CODE_LOOP_STRENGTH");
|
||||
h.wait_for_output("ENV PLAN2CODE_LOOP_STRENGTH=\r", 1);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_phase_start_with_no_launch_choice_is_refused() {
|
||||
let h = Harness::new();
|
||||
let refused = h
|
||||
.manager
|
||||
.start_phase_on("p".to_string(), "sonnet".to_string(), None, Vec::new());
|
||||
assert!(refused.is_err());
|
||||
}
|
||||
@@ -181,7 +181,22 @@ export function loopBanner(state) {
|
||||
}
|
||||
return { ...base, title: "Starting the loop", detail: `Opening a fresh agent for ${named}.` };
|
||||
}
|
||||
return { ...base, title: "Implementation loop running", detail: step ? `${named} \u00b7 ${step}` : named };
|
||||
const ran = loopRunText(state);
|
||||
const where = step ? `${named} \u00b7 ${step}` : named;
|
||||
return { ...base, title: "Implementation loop running", detail: ran ? `${where} \u00b7 ${ran}` : where };
|
||||
}
|
||||
|
||||
/**
|
||||
* What the running phase runs on, from the app's `loop-state`: "Thrifty (sonnet,
|
||||
* low)" for a phase on a strength, "(opus, high)" for a Match my session phase
|
||||
* with a known model, and "" when the loop runs as it always did.
|
||||
*/
|
||||
export function loopRunText(state) {
|
||||
const model = state && typeof state.model === "string" ? state.model : "";
|
||||
const effort = model && state.effort ? `, ${state.effort}` : "";
|
||||
const word = state && typeof state.strength === "string" && state.strength ? state.strength[0].toUpperCase() + state.strength.slice(1) : "";
|
||||
if (word) return model ? `${word} (${model}${effort})` : word;
|
||||
return model ? `(${model}${effort})` : "";
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1891,6 +1891,169 @@
|
||||
"args": [
|
||||
"a $HOME & \"b\""
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "OpenCode's shape: a chosen model goes ahead of the prompt",
|
||||
"entry": {
|
||||
"id": "opencode",
|
||||
"name": "OpenCode",
|
||||
"command": "opencode",
|
||||
"args": [
|
||||
"{model}",
|
||||
"--prompt",
|
||||
"{prompt}"
|
||||
],
|
||||
"prompt": "Use the plan2code skill",
|
||||
"bypassArgs": [
|
||||
"--auto"
|
||||
],
|
||||
"modelArgs": [
|
||||
"--model",
|
||||
"{model}"
|
||||
]
|
||||
},
|
||||
"options": {
|
||||
"model": "anthropic/sonnet",
|
||||
"bypass": false
|
||||
},
|
||||
"args": [
|
||||
"--model",
|
||||
"anthropic/sonnet",
|
||||
"--prompt",
|
||||
"Use the plan2code skill"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "OpenCode's shape: no model, no model argument",
|
||||
"entry": {
|
||||
"id": "opencode",
|
||||
"name": "OpenCode",
|
||||
"command": "opencode",
|
||||
"args": [
|
||||
"{model}",
|
||||
"--prompt",
|
||||
"{prompt}"
|
||||
],
|
||||
"prompt": "Use the plan2code skill",
|
||||
"bypassArgs": [
|
||||
"--auto"
|
||||
],
|
||||
"modelArgs": [
|
||||
"--model",
|
||||
"{model}"
|
||||
]
|
||||
},
|
||||
"options": {
|
||||
"bypass": false
|
||||
},
|
||||
"args": [
|
||||
"--prompt",
|
||||
"Use the plan2code skill"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Gemini CLI's shape: a chosen model goes ahead of the prompt",
|
||||
"entry": {
|
||||
"id": "gemini",
|
||||
"name": "Gemini CLI",
|
||||
"command": "gemini",
|
||||
"args": [
|
||||
"{model}",
|
||||
"{prompt}"
|
||||
],
|
||||
"prompt": "Use the plan2code skill",
|
||||
"bypassArgs": [
|
||||
"--approval-mode=yolo"
|
||||
],
|
||||
"modelArgs": [
|
||||
"--model",
|
||||
"{model}"
|
||||
]
|
||||
},
|
||||
"options": {
|
||||
"model": "flash",
|
||||
"bypass": false
|
||||
},
|
||||
"args": [
|
||||
"--model",
|
||||
"flash",
|
||||
"Use the plan2code skill"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Gemini CLI's shape: no model, no model argument",
|
||||
"entry": {
|
||||
"id": "gemini",
|
||||
"name": "Gemini CLI",
|
||||
"command": "gemini",
|
||||
"args": [
|
||||
"{model}",
|
||||
"{prompt}"
|
||||
],
|
||||
"prompt": "Use the plan2code skill",
|
||||
"bypassArgs": [
|
||||
"--approval-mode=yolo"
|
||||
],
|
||||
"modelArgs": [
|
||||
"--model",
|
||||
"{model}"
|
||||
]
|
||||
},
|
||||
"options": {
|
||||
"bypass": false
|
||||
},
|
||||
"args": [
|
||||
"Use the plan2code skill"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Pi's shape: a chosen model goes ahead of the prompt",
|
||||
"entry": {
|
||||
"id": "pi",
|
||||
"name": "Pi",
|
||||
"command": "pi",
|
||||
"args": [
|
||||
"{model}",
|
||||
"{prompt}"
|
||||
],
|
||||
"prompt": "/skill:plan2code",
|
||||
"modelArgs": [
|
||||
"--model",
|
||||
"{model}"
|
||||
]
|
||||
},
|
||||
"options": {
|
||||
"model": "sonnet:high",
|
||||
"bypass": false
|
||||
},
|
||||
"args": [
|
||||
"--model",
|
||||
"sonnet:high",
|
||||
"/skill:plan2code"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Pi's shape: no model, no model argument",
|
||||
"entry": {
|
||||
"id": "pi",
|
||||
"name": "Pi",
|
||||
"command": "pi",
|
||||
"args": [
|
||||
"{model}",
|
||||
"{prompt}"
|
||||
],
|
||||
"prompt": "/skill:plan2code",
|
||||
"modelArgs": [
|
||||
"--model",
|
||||
"{model}"
|
||||
]
|
||||
},
|
||||
"options": {
|
||||
"bypass": false
|
||||
},
|
||||
"args": [
|
||||
"/skill:plan2code"
|
||||
]
|
||||
}
|
||||
],
|
||||
"ids": [
|
||||
|
||||
@@ -0,0 +1,478 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"cases": [
|
||||
{
|
||||
"name": "claude shipped only",
|
||||
"agent": "claude",
|
||||
"shipped": {
|
||||
"thrifty": {
|
||||
"model": "sonnet",
|
||||
"effort": "low"
|
||||
},
|
||||
"balanced": {
|
||||
"model": "sonnet",
|
||||
"effort": "medium"
|
||||
},
|
||||
"best": {
|
||||
"model": "opus",
|
||||
"effort": "medium"
|
||||
}
|
||||
},
|
||||
"user": null,
|
||||
"models": [
|
||||
"default",
|
||||
"sonnet",
|
||||
"opus",
|
||||
"haiku"
|
||||
],
|
||||
"hasEffort": true,
|
||||
"expect": {
|
||||
"resolved": {
|
||||
"thrifty": {
|
||||
"model": "sonnet",
|
||||
"effort": "low"
|
||||
},
|
||||
"balanced": {
|
||||
"model": "sonnet",
|
||||
"effort": "medium"
|
||||
},
|
||||
"best": {
|
||||
"model": "opus",
|
||||
"effort": "medium"
|
||||
}
|
||||
},
|
||||
"next": {
|
||||
"thrifty": "balanced",
|
||||
"balanced": "best",
|
||||
"best": null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "devin shipped only",
|
||||
"agent": "devin",
|
||||
"shipped": {
|
||||
"thrifty": {
|
||||
"model": "swe-2-medium"
|
||||
},
|
||||
"balanced": {
|
||||
"model": "swe-2-high"
|
||||
},
|
||||
"best": {
|
||||
"model": "claude-opus-5-5-medium"
|
||||
}
|
||||
},
|
||||
"user": null,
|
||||
"models": [
|
||||
"adaptive",
|
||||
"swe-2-medium",
|
||||
"swe-2-high",
|
||||
"claude-opus-5-5-medium"
|
||||
],
|
||||
"hasEffort": false,
|
||||
"expect": {
|
||||
"resolved": {
|
||||
"thrifty": {
|
||||
"model": "swe-2-medium"
|
||||
},
|
||||
"balanced": {
|
||||
"model": "swe-2-high"
|
||||
},
|
||||
"best": {
|
||||
"model": "claude-opus-5-5-medium"
|
||||
}
|
||||
},
|
||||
"next": {
|
||||
"thrifty": "balanced",
|
||||
"balanced": "best",
|
||||
"best": null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "a user row overrides one shipped row, the others follow shipped",
|
||||
"agent": "claude",
|
||||
"shipped": {
|
||||
"thrifty": {
|
||||
"model": "sonnet",
|
||||
"effort": "low"
|
||||
},
|
||||
"balanced": {
|
||||
"model": "sonnet",
|
||||
"effort": "medium"
|
||||
},
|
||||
"best": {
|
||||
"model": "opus",
|
||||
"effort": "medium"
|
||||
}
|
||||
},
|
||||
"user": {
|
||||
"balanced": {
|
||||
"model": "opus",
|
||||
"effort": "low"
|
||||
}
|
||||
},
|
||||
"models": [
|
||||
"default",
|
||||
"sonnet",
|
||||
"opus",
|
||||
"haiku"
|
||||
],
|
||||
"hasEffort": true,
|
||||
"expect": {
|
||||
"resolved": {
|
||||
"thrifty": {
|
||||
"model": "sonnet",
|
||||
"effort": "low"
|
||||
},
|
||||
"balanced": {
|
||||
"model": "opus",
|
||||
"effort": "low"
|
||||
},
|
||||
"best": {
|
||||
"model": "opus",
|
||||
"effort": "medium"
|
||||
}
|
||||
},
|
||||
"next": {
|
||||
"thrifty": "balanced",
|
||||
"balanced": "best",
|
||||
"best": null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "user-only mapping for an agent with nothing shipped",
|
||||
"agent": "codex",
|
||||
"shipped": null,
|
||||
"user": {
|
||||
"thrifty": {
|
||||
"model": "gpt-a"
|
||||
},
|
||||
"balanced": {
|
||||
"model": "gpt-b"
|
||||
},
|
||||
"best": {
|
||||
"model": "gpt-c"
|
||||
}
|
||||
},
|
||||
"models": [
|
||||
"gpt-a",
|
||||
"gpt-b",
|
||||
"gpt-c"
|
||||
],
|
||||
"hasEffort": false,
|
||||
"expect": {
|
||||
"resolved": {
|
||||
"thrifty": {
|
||||
"model": "gpt-a"
|
||||
},
|
||||
"balanced": {
|
||||
"model": "gpt-b"
|
||||
},
|
||||
"best": {
|
||||
"model": "gpt-c"
|
||||
}
|
||||
},
|
||||
"next": {
|
||||
"thrifty": "balanced",
|
||||
"balanced": "best",
|
||||
"best": null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "partly mapped: Balanced only",
|
||||
"agent": "opencode",
|
||||
"shipped": null,
|
||||
"user": {
|
||||
"balanced": {
|
||||
"model": "m1"
|
||||
}
|
||||
},
|
||||
"models": [
|
||||
"m1",
|
||||
"m2"
|
||||
],
|
||||
"hasEffort": false,
|
||||
"expect": {
|
||||
"resolved": {
|
||||
"balanced": {
|
||||
"model": "m1"
|
||||
}
|
||||
},
|
||||
"next": {
|
||||
"thrifty": "balanced",
|
||||
"balanced": null,
|
||||
"best": null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "partly mapped: Thrifty and Best only",
|
||||
"agent": "opencode",
|
||||
"shipped": null,
|
||||
"user": {
|
||||
"thrifty": {
|
||||
"model": "m1"
|
||||
},
|
||||
"best": {
|
||||
"model": "m2"
|
||||
}
|
||||
},
|
||||
"models": [
|
||||
"m1",
|
||||
"m2"
|
||||
],
|
||||
"hasEffort": false,
|
||||
"expect": {
|
||||
"resolved": {
|
||||
"thrifty": {
|
||||
"model": "m1"
|
||||
},
|
||||
"best": {
|
||||
"model": "m2"
|
||||
}
|
||||
},
|
||||
"next": {
|
||||
"thrifty": "best",
|
||||
"balanced": "best",
|
||||
"best": null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "a user row whose model left the list falls back to the shipped row",
|
||||
"agent": "claude",
|
||||
"shipped": {
|
||||
"thrifty": {
|
||||
"model": "sonnet",
|
||||
"effort": "low"
|
||||
},
|
||||
"balanced": {
|
||||
"model": "sonnet",
|
||||
"effort": "medium"
|
||||
},
|
||||
"best": {
|
||||
"model": "opus",
|
||||
"effort": "medium"
|
||||
}
|
||||
},
|
||||
"user": {
|
||||
"best": {
|
||||
"model": "gone",
|
||||
"effort": "high"
|
||||
}
|
||||
},
|
||||
"models": [
|
||||
"default",
|
||||
"sonnet",
|
||||
"opus",
|
||||
"haiku"
|
||||
],
|
||||
"hasEffort": true,
|
||||
"expect": {
|
||||
"resolved": {
|
||||
"thrifty": {
|
||||
"model": "sonnet",
|
||||
"effort": "low"
|
||||
},
|
||||
"balanced": {
|
||||
"model": "sonnet",
|
||||
"effort": "medium"
|
||||
},
|
||||
"best": {
|
||||
"model": "opus",
|
||||
"effort": "medium"
|
||||
}
|
||||
},
|
||||
"next": {
|
||||
"thrifty": "balanced",
|
||||
"balanced": "best",
|
||||
"best": null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "a shipped row whose model left the list reads unmapped",
|
||||
"agent": "claude",
|
||||
"shipped": {
|
||||
"thrifty": {
|
||||
"model": "sonnet",
|
||||
"effort": "low"
|
||||
},
|
||||
"balanced": {
|
||||
"model": "sonnet",
|
||||
"effort": "medium"
|
||||
},
|
||||
"best": {
|
||||
"model": "opus",
|
||||
"effort": "medium"
|
||||
}
|
||||
},
|
||||
"user": null,
|
||||
"models": [
|
||||
"default",
|
||||
"opus"
|
||||
],
|
||||
"hasEffort": true,
|
||||
"expect": {
|
||||
"resolved": {
|
||||
"best": {
|
||||
"model": "opus",
|
||||
"effort": "medium"
|
||||
}
|
||||
},
|
||||
"next": {
|
||||
"thrifty": "best",
|
||||
"balanced": "best",
|
||||
"best": null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "an effort on an agent without one is dropped",
|
||||
"agent": "devin",
|
||||
"shipped": null,
|
||||
"user": {
|
||||
"thrifty": {
|
||||
"model": "swe-2-medium",
|
||||
"effort": "low"
|
||||
},
|
||||
"best": {
|
||||
"model": "swe-2-high",
|
||||
"effort": "high"
|
||||
}
|
||||
},
|
||||
"models": [
|
||||
"adaptive",
|
||||
"swe-2-medium",
|
||||
"swe-2-high",
|
||||
"claude-opus-5-5-medium"
|
||||
],
|
||||
"hasEffort": false,
|
||||
"expect": {
|
||||
"resolved": {
|
||||
"thrifty": {
|
||||
"model": "swe-2-medium"
|
||||
},
|
||||
"best": {
|
||||
"model": "swe-2-high"
|
||||
}
|
||||
},
|
||||
"next": {
|
||||
"thrifty": "best",
|
||||
"balanced": "best",
|
||||
"best": null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "an effort outside low, medium and high is dropped, the row stays",
|
||||
"agent": "claude",
|
||||
"shipped": null,
|
||||
"user": {
|
||||
"thrifty": {
|
||||
"model": "haiku",
|
||||
"effort": "max"
|
||||
},
|
||||
"balanced": {
|
||||
"model": "sonnet",
|
||||
"effort": "medium"
|
||||
}
|
||||
},
|
||||
"models": [
|
||||
"default",
|
||||
"sonnet",
|
||||
"opus",
|
||||
"haiku"
|
||||
],
|
||||
"hasEffort": true,
|
||||
"expect": {
|
||||
"resolved": {
|
||||
"thrifty": {
|
||||
"model": "haiku"
|
||||
},
|
||||
"balanced": {
|
||||
"model": "sonnet",
|
||||
"effort": "medium"
|
||||
}
|
||||
},
|
||||
"next": {
|
||||
"thrifty": "balanced",
|
||||
"balanced": null,
|
||||
"best": null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "a bad word or a row that is not an object is ignored",
|
||||
"agent": "claude",
|
||||
"shipped": null,
|
||||
"user": {
|
||||
"cheap": {
|
||||
"model": "haiku"
|
||||
},
|
||||
"thrifty": "haiku",
|
||||
"balanced": [
|
||||
"sonnet"
|
||||
],
|
||||
"best": {
|
||||
"model": 7
|
||||
},
|
||||
"extra": null
|
||||
},
|
||||
"models": [
|
||||
"default",
|
||||
"sonnet",
|
||||
"opus",
|
||||
"haiku"
|
||||
],
|
||||
"hasEffort": true,
|
||||
"expect": {
|
||||
"resolved": {},
|
||||
"next": {
|
||||
"thrifty": null,
|
||||
"balanced": null,
|
||||
"best": null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "nothing anywhere",
|
||||
"agent": "pi",
|
||||
"shipped": null,
|
||||
"user": null,
|
||||
"models": [],
|
||||
"hasEffort": false,
|
||||
"expect": {
|
||||
"resolved": {},
|
||||
"next": {
|
||||
"thrifty": null,
|
||||
"balanced": null,
|
||||
"best": null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "mappings that are not objects",
|
||||
"agent": "pi",
|
||||
"shipped": [
|
||||
"x"
|
||||
],
|
||||
"user": "y",
|
||||
"models": [
|
||||
"x"
|
||||
],
|
||||
"hasEffort": false,
|
||||
"expect": {
|
||||
"resolved": {},
|
||||
"next": {
|
||||
"thrifty": null,
|
||||
"balanced": null,
|
||||
"best": null
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopLocks, loopStopLabels, loopWindowTitle, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS } from "../plan2code-app/ui/meter.js";
|
||||
import { attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopRunText, loopLocks, loopStopLabels, loopWindowTitle, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS } from "../plan2code-app/ui/meter.js";
|
||||
import { findBrowser, launchBrowser } from "./browser.mjs";
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
@@ -339,6 +339,18 @@ test("the loop banner says what the loop is doing at every moment", () => {
|
||||
assert.deepEqual(said({ phase: 0, phases: 0 }).pips, []);
|
||||
});
|
||||
|
||||
test("the loop banner names the strength and model a phase runs on, and nothing when the toggle is off", () => {
|
||||
const base = { phase: 3, phases: 5, phaseName: "API", step: "Build" };
|
||||
const said = (extra) => loopBanner({ ...base, ...extra }).detail;
|
||||
assert.equal(said({ strength: "thrifty", model: "sonnet", effort: "low" }), "Phase 3 of 5: API \u00b7 Build \u00b7 Thrifty (sonnet, low)");
|
||||
assert.equal(said({ strength: "best", model: "opus" }), "Phase 3 of 5: API \u00b7 Build \u00b7 Best (opus)");
|
||||
assert.equal(said({ strength: "balanced" }), "Phase 3 of 5: API \u00b7 Build \u00b7 Balanced");
|
||||
assert.equal(said({ strength: null, model: "opus", effort: "high" }), "Phase 3 of 5: API \u00b7 Build \u00b7 (opus, high)", "Match my session shows the launch model");
|
||||
assert.equal(said({ strength: null, model: null, effort: null }), "Phase 3 of 5: API \u00b7 Build", "toggle off or no model known: unchanged");
|
||||
assert.equal(said({}), "Phase 3 of 5: API \u00b7 Build");
|
||||
assert.equal(loopRunText({}), "");
|
||||
});
|
||||
|
||||
test("Stop now turns the banner to Stopping, ahead of a question or a stop on its way", () => {
|
||||
const base = { phase: 2, phases: 4, phaseName: "API", step: "Build", stopAfterPhase: false, stopping: true };
|
||||
for (const extra of [{}, { step: "Waiting on you" }, { stopAfterPhase: true }, { step: "Starting" }]) {
|
||||
|
||||
@@ -334,6 +334,26 @@ test("launcher: mergeModels keeps the shipped list first and drops user duplicat
|
||||
assert.deepEqual(modelEntries({ devin: [{ id: 1 }, null, { id: "ok", label: "Ok" }] }, "devin"), [{ id: "ok", label: "Ok" }]);
|
||||
});
|
||||
|
||||
test("launcher: a strengths key in the models files is never read as a model list, and every shipped strength names a listed model", () => {
|
||||
const { modelEntries, mergeModels } = require(LAUNCHER);
|
||||
const shipped = JSON.parse(fs.readFileSync(path.join(path.dirname(LAUNCHER), "models.json"), "utf8"));
|
||||
assert.ok(shipped.strengths && typeof shipped.strengths === "object");
|
||||
assert.deepEqual(modelEntries(shipped, "strengths"), []);
|
||||
const claude = modelEntries(shipped, "claude");
|
||||
assert.ok(claude.length > 0);
|
||||
const user = { claude: [{ id: "mine", label: "Mine" }], strengths: { claude: { best: { model: "mine" } } } };
|
||||
assert.deepEqual(modelEntries(user, "strengths"), []);
|
||||
assert.deepEqual(mergeModels(claude, modelEntries(user, "claude")), [...claude, { id: "mine", label: "Mine" }]);
|
||||
assert.deepEqual(mergeModels(claude, modelEntries({ claude: user.claude }, "claude")), mergeModels(claude, modelEntries(user, "claude")));
|
||||
// Only Claude Code and Devin ship a mapping, and every row names a model in that agent's list.
|
||||
assert.deepEqual(Object.keys(shipped.strengths).sort(), ["claude", "devin"]);
|
||||
for (const [agent, rows] of Object.entries(shipped.strengths)) {
|
||||
assert.deepEqual(Object.keys(rows), ["thrifty", "balanced", "best"], agent);
|
||||
const ids = new Set(shipped[agent].map((m) => m.id));
|
||||
for (const row of Object.values(rows)) assert.ok(ids.has(row.model), `${agent}: ${row.model}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("launcher: the shipped models.json is curated Devin at low/medium/high only", () => {
|
||||
const shipped = JSON.parse(fs.readFileSync(path.join(path.dirname(LAUNCHER), "models.json"), "utf8"));
|
||||
assert.ok(shipped.claude.length > 0);
|
||||
|
||||
@@ -536,7 +536,7 @@ test("models: the user's additions round-trip, XHigh and Max are refused, and th
|
||||
assert.equal((await post("/models", { nope: true })).status, 400);
|
||||
assert.equal((await get()).user.devin.length, 1, "a refused write must not touch what is saved");
|
||||
|
||||
// Codex has no curated list, but the launcher reads a user `codex` list all the same.
|
||||
// The launcher reads a user `codex` list too. The shipped file this test serves has no `codex` key, so that list is empty here.
|
||||
const codex = await post("/models", { models: { codex: [{ id: " gpt-5-codex ", label: "GPT-5 Codex" }, { id: "gpt-5-codex" }] } });
|
||||
assert.equal(codex.status, 200);
|
||||
assert.deepEqual((await get()).user, { claude: [], devin: [], codex: [{ id: "gpt-5-codex", label: "GPT-5 Codex" }] });
|
||||
@@ -547,6 +547,88 @@ test("models: the user's additions round-trip, XHigh and Max are refused, and th
|
||||
assert.deepEqual((await get()).user, { claude: [], devin: [], codex: [] });
|
||||
});
|
||||
|
||||
test("models: strengths come back shipped and user, round-trip, survive a models-only save, and bad rows name their field", async () => {
|
||||
fs.mkdirSync(path.join(MODELS_DIR, "bin"), { recursive: true });
|
||||
const shippedStrengths = { claude: { thrifty: { model: "sonnet", effort: "low" }, best: { model: "opus" } } };
|
||||
fs.writeFileSync(
|
||||
path.join(MODELS_DIR, "bin", "models.json"),
|
||||
JSON.stringify({ claude: [{ id: "opus", label: "Opus" }, { id: "sonnet", label: "Sonnet" }], strengths: shippedStrengths })
|
||||
);
|
||||
const get = async () => (await fetch(baseUrl + "/models", { headers: { cookie: cookieFor(baseUrl, token) } })).json();
|
||||
const userFile = () => JSON.parse(fs.readFileSync(path.join(MODELS_DIR, "models.json"), "utf8"));
|
||||
|
||||
const first = await get();
|
||||
assert.deepEqual(first.strengths, { shipped: shippedStrengths, user: {} }, "shipped rows come back, no user rows yet");
|
||||
assert.ok(!("strengths" in first.shipped) && !("strengths" in first.user), "strengths is never read as an agent's model list");
|
||||
|
||||
const mapping = { claude: { balanced: { model: " sonnet ", effort: "medium" }, best: { model: "opus" } }, codex: { thrifty: { model: "gpt-5-codex" } } };
|
||||
const saved = await post("/models", { models: { claude: [{ id: "mine" }] }, strengths: mapping });
|
||||
assert.equal(saved.status, 200);
|
||||
const want = { claude: { balanced: { model: "sonnet", effort: "medium" }, best: { model: "opus" } }, codex: { thrifty: { model: "gpt-5-codex" } } };
|
||||
assert.deepEqual((await get()).strengths.user, want);
|
||||
assert.deepEqual(userFile().strengths, want, "the launcher's file carries the mapping beside the lists");
|
||||
assert.equal(userFile().claude.length, 1);
|
||||
|
||||
// A save with only a Models list never wipes the mapping.
|
||||
assert.equal((await post("/models", { models: { claude: [{ id: "mine" }, { id: "other" }] } })).status, 200);
|
||||
assert.deepEqual((await get()).strengths.user, want);
|
||||
assert.equal((await get()).user.claude.length, 2);
|
||||
|
||||
// The agents' own lists and the reset keep it too; an explicit empty mapping clears it.
|
||||
assert.equal((await post("/models", { models: {} })).status, 200);
|
||||
assert.deepEqual((await get()).strengths.user, want);
|
||||
|
||||
const refused = [
|
||||
[{ claude: { thrifty: { model: "bad id!" } } }, /strengths\.claude\.thrifty\.model/],
|
||||
[{ claude: { cheap: { model: "sonnet" } } }, /strengths\.claude\.cheap/],
|
||||
[{ claude: { best: { model: "opus", effort: "max" } } }, /strengths\.claude\.best\.effort/],
|
||||
[{ nobody: { best: { model: "opus" } } }, /strengths\.nobody/],
|
||||
[{ claude: { best: "opus" } }, /strengths\.claude\.best/],
|
||||
[["claude"], /strengths/],
|
||||
];
|
||||
for (const [body, field] of refused) {
|
||||
const res = await post("/models", { models: {}, strengths: body });
|
||||
assert.equal(res.status, 400, JSON.stringify(body));
|
||||
assert.match((await res.json()).error, field);
|
||||
}
|
||||
assert.deepEqual((await get()).strengths.user, want, "a refused write must not touch what is saved");
|
||||
|
||||
assert.equal((await post("/models", { models: {}, strengths: {} })).status, 200);
|
||||
assert.deepEqual((await get()).strengths.user, {});
|
||||
assert.ok(!("strengths" in userFile()), "an empty mapping leaves no key behind");
|
||||
});
|
||||
|
||||
test("models: a saved mapping for an agent that is gone is skipped, and never hides or wipes the others", async (t) => {
|
||||
const userFile = path.join(MODELS_DIR, "models.json");
|
||||
t.after(() => fs.rmSync(userFile, { force: true }));
|
||||
fs.writeFileSync(
|
||||
userFile,
|
||||
JSON.stringify({ claude: [], strengths: { claude: { best: { model: "opus" } }, "deleted-agent": { best: { model: "x" } }, devin: { cheap: { model: "y" } } } })
|
||||
);
|
||||
const get = async () => (await fetch(baseUrl + "/models", { headers: { cookie: cookieFor(baseUrl, token) } })).json();
|
||||
assert.deepEqual((await get()).strengths.user, { claude: { best: { model: "opus" } } });
|
||||
assert.equal((await post("/models", { models: { claude: [{ id: "mine" }] } })).status, 200);
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(userFile, "utf8")).strengths, { claude: { best: { model: "opus" } } }, "the models-only save kept the good rows");
|
||||
});
|
||||
|
||||
test("models: one bad saved row never drops the other rows of its agent, like the app", async (t) => {
|
||||
const userFile = path.join(MODELS_DIR, "models.json");
|
||||
t.after(() => fs.rmSync(userFile, { force: true }));
|
||||
fs.writeFileSync(
|
||||
userFile,
|
||||
JSON.stringify({
|
||||
claude: [],
|
||||
strengths: { claude: { thrifty: { model: "haiku", effort: "max" }, balanced: { model: "bad id!" }, cheap: { model: "x" }, best: { model: "opus", effort: "high" } } },
|
||||
})
|
||||
);
|
||||
const get = async () => (await fetch(baseUrl + "/models", { headers: { cookie: cookieFor(baseUrl, token) } })).json();
|
||||
assert.deepEqual(
|
||||
(await get()).strengths.user,
|
||||
{ claude: { thrifty: { model: "haiku" }, best: { model: "opus", effort: "high" } } },
|
||||
"a bad effort is dropped and its row stays; a bad model or word drops only that row"
|
||||
);
|
||||
});
|
||||
|
||||
test("agents: no file is an empty list, a save is written whole and keeps unknown keys, and a bad save names its entry and field", async (t) => {
|
||||
const file = path.join(MODELS_DIR, "agents.json");
|
||||
t.after(() => fs.rmSync(file, { force: true }));
|
||||
|
||||
@@ -18,7 +18,7 @@ import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { applyPatch, blankState, validate, switchWorkflow } from "../src/web-console/patches.mjs";
|
||||
import { ROOT, CONSOLE_CLI, ENV, HOME, cli, readState, sessionUrl, payload } from "./web-console-test-helpers.mjs";
|
||||
import { ROOT, CONSOLE_CLI, ENV, HOME, MODELS_DIR, cli, readState, sessionUrl, payload } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const APP_VARS = ["PLAN2CODE_IN_APP", "PLAN2CODE_EMBED_ORIGIN", "PLAN2CODE_APP_ANNOUNCE", "PLAN2CODE_APP_TOKEN", "PLAN2CODE_CONSOLE_SID"];
|
||||
|
||||
@@ -472,10 +472,16 @@ test("loopEnd: a valid stopped with an evidence doc in the same patch is stored"
|
||||
assert.equal(replaced.next.loopEnd.line, "A later word replaces the earlier");
|
||||
});
|
||||
|
||||
test("loopEnd: ask is accepted in can, so a stopped loop can offer a question before anything runs", () => {
|
||||
const { problems, next } = tryPatch(loopState(), { loopEnd: goodEnd({ can: ["resume", "ask", "fix", "dashboard"] }) });
|
||||
assert.deepEqual(problems, []);
|
||||
assert.deepEqual(next.loopEnd.can, ["resume", "ask", "fix", "dashboard"]);
|
||||
});
|
||||
|
||||
test("loopEnd: an unknown evidence id, a push in can, and the other bad fields are refused, each named", () => {
|
||||
const cases = [
|
||||
["an unknown evidence id", goodEnd({ evidence: "nope" }), /loopEnd\.evidence must be the id of a doc on the page/],
|
||||
["a push in can", goodEnd({ can: ["resume", "push"] }), /loopEnd\.can must be an array with entries from resume, fix, finalize, dashboard/],
|
||||
["a push in can", goodEnd({ can: ["resume", "push"] }), /loopEnd\.can must be an array with entries from resume, ask, fix, finalize, dashboard/],
|
||||
["a bad kind", goodEnd({ kind: "paused" }), /loopEnd\.kind must be "stopped" or "finished"/],
|
||||
["a two-line line", goodEnd({ line: "one\ntwo" }), /loopEnd\.line must be one line/],
|
||||
["an absolute uncommitted path", goodEnd({ uncommitted: ["/etc/passwd"] }), /loopEnd\.uncommitted must be an array of relative paths/],
|
||||
@@ -772,7 +778,7 @@ test("loop-setup: GET /loop-setup lists the phases left for a spec and refuses a
|
||||
}
|
||||
|
||||
// Saving through the route, then reading it back in a new request.
|
||||
const save = await send({ review: true, fixMode: "smart", fix: ["critical"], commit: true, onQuestion: "stop", afterLast: "offer-finalize", quickCheck: "", notifyKind: "query", notifyUrl: "https://example.com/hook", notifyParam: "msg", retryOnce: true, silenceMinutes: 30 });
|
||||
const save = await send({ review: true, fixMode: "smart", fix: ["critical"], commit: true, onQuestion: "stop", afterLast: "offer-finalize", quickCheck: "", notifyKind: "query", notifyUrl: "https://example.com/hook", notifyParam: "msg", retryOnce: true, silenceMinutes: 30, phaseStrength: false, strengths: {} });
|
||||
assert.equal(save.status, 200, await save.clone().text());
|
||||
const after = await get("?spec=specs/demo");
|
||||
assert.equal(after.body.remembered, true);
|
||||
@@ -789,3 +795,170 @@ test("loop-setup: GET /loop-setup lists the phases left for a spec and refuses a
|
||||
cli(["stop", "--session", opened.json.sid, "--force"], { cwd, expectFail: true });
|
||||
}
|
||||
});
|
||||
|
||||
/* ------------------------------ phase strength: the setup's new fields */
|
||||
|
||||
const specWith = (project, name, phases) => {
|
||||
const dir = path.join(project, "specs", name);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const rows = phases.map(([mark, n, title]) => `- [${mark}] **Phase ${n}:** ${title} - [phase-${n}.md](phase-${n}.md)`);
|
||||
fs.writeFileSync(path.join(dir, "overview.md"), ["# Demo", "", "## Phase Checklist", "", ...rows, ""].join("\n"));
|
||||
};
|
||||
|
||||
test("loop-setup: the strength fields default off, and their bad values are named", () => {
|
||||
fs.rmSync(LOOP_SETUP_PATH, { force: true });
|
||||
const cases = [
|
||||
["phaseStrength as a string", { phaseStrength: "yes" }, /"phaseStrength" must be true or false/],
|
||||
["strengths as a list", { strengths: [] }, /"strengths" must be an object/],
|
||||
["a key outside specs/", { strengths: { "../x": [] } }, /must be a folder directly under specs\//],
|
||||
["a hidden spec folder", { strengths: { "specs/.hidden": [] } }, /must be a folder directly under specs\//],
|
||||
["a nested spec key", { strengths: { "specs/a/b": [] } }, /must be a folder directly under specs\//],
|
||||
["picks as an object", { strengths: { "specs/a": {} } }, /at most 100 phase picks/],
|
||||
["101 picks", { strengths: { "specs/a": Array.from({ length: 101 }, (_, i) => ({ n: i + 1, name: "p", strength: "best" })) } }, /at most 100 phase picks/],
|
||||
["n of 0", { strengths: { "specs/a": [{ n: 0, name: "p", strength: "best" }] } }, /positive whole number/],
|
||||
["n as text", { strengths: { "specs/a": [{ n: "2", name: "p", strength: "best" }] } }, /positive whole number/],
|
||||
["a repeated n", { strengths: { "specs/a": [{ n: 2, name: "p", strength: "best" }, { n: 2, name: "q", strength: "best" }] } }, /Phase 2 twice/],
|
||||
["a 201-character name", { strengths: { "specs/a": [{ n: 1, name: "x".repeat(201), strength: "best" }] } }, /at most 200 characters/],
|
||||
["an unknown word", { strengths: { "specs/a": [{ n: 1, name: "p", strength: "max" }] } }, /strength of thrifty, balanced, best/],
|
||||
];
|
||||
const got = inStore(
|
||||
(m, { project, list }) =>
|
||||
list.map(([what, change]) => {
|
||||
try {
|
||||
m.saveLoopSetup(project, { ...m.LOOP_DEFAULTS, fix: [...m.LOOP_DEFAULTS.fix], ...change });
|
||||
return { what, threw: false };
|
||||
} catch (e) {
|
||||
return { what, threw: true, message: e.message };
|
||||
}
|
||||
}),
|
||||
{ project: projectA, list: cases.map(([what, change]) => [what, change]) }
|
||||
);
|
||||
for (const [i, [what, , expected]] of cases.entries()) {
|
||||
assert.equal(got[i].threw, true, `${what} is refused`);
|
||||
assert.match(got[i].message, expected, what);
|
||||
}
|
||||
assert.equal(fs.existsSync(LOOP_SETUP_PATH), false, "a refused save writes nothing");
|
||||
const fresh = inStore((m, { project }) => m.readLoopSetup(project), { project: projectA });
|
||||
assert.equal(fresh.phaseStrength, false);
|
||||
assert.deepEqual(fresh.strengths, {});
|
||||
});
|
||||
|
||||
test("loop-setup: an entry saved before the strength fields reads as off with no picks", () => {
|
||||
fs.rmSync(LOOP_SETUP_PATH, { force: true });
|
||||
const project = path.join(HOME, "store-project-old");
|
||||
inStore((m, { p }) => (m.saveLoopSetup(p, { ...m.LOOP_DEFAULTS, fix: ["warning"] }), null), { p: project });
|
||||
const store = JSON.parse(fs.readFileSync(LOOP_SETUP_PATH, "utf8"));
|
||||
const [folded] = Object.keys(store.projects);
|
||||
delete store.projects[folded].phaseStrength;
|
||||
delete store.projects[folded].strengths;
|
||||
fs.writeFileSync(LOOP_SETUP_PATH, JSON.stringify(store));
|
||||
const got = inStore((m, { p }) => m.readLoopSetup(p), { p: project });
|
||||
assert.equal(got.remembered, true);
|
||||
assert.equal(got.phaseStrength, false);
|
||||
assert.deepEqual(got.strengths, {});
|
||||
assert.deepEqual(got.fix, ["warning"]);
|
||||
});
|
||||
|
||||
test("loop-setup: picks for a removed spec folder or a renamed phase are pruned on read and on save", () => {
|
||||
fs.rmSync(LOOP_SETUP_PATH, { force: true });
|
||||
const project = fs.mkdtempSync(path.join(HOME, "prune-"));
|
||||
specWith(project, "keep", [["x", 1, "Done"], [" ", 2, "Build it"], [" ", 3, "Ship it"]]);
|
||||
specWith(project, "gone", [[" ", 1, "Only"]]);
|
||||
const picks = {
|
||||
"specs/keep": [
|
||||
{ n: 2, name: "Build it", strength: "thrifty" },
|
||||
{ n: 3, name: "Ship it renamed", strength: "best" },
|
||||
{ n: 1, name: "Done", strength: "best" },
|
||||
],
|
||||
"specs/gone": [{ n: 1, name: "Only", strength: "best" }],
|
||||
"specs/never": [{ n: 1, name: "x", strength: "best" }],
|
||||
};
|
||||
const out = inStore(
|
||||
async (m, { project, picks }) => {
|
||||
const fs = await import("node:fs");
|
||||
const path = await import("node:path");
|
||||
const left = (spec) => {
|
||||
const text = fs.readFileSync(path.join(project, spec, "overview.md"), "utf8");
|
||||
return [...text.matchAll(/^- \[ \] \*\*Phase (\d+):\*\* (.+?) - /gm)].map((x) => ({ n: Number(x[1]), name: x[2] }));
|
||||
};
|
||||
fs.rmSync(path.join(project, "specs", "gone"), { recursive: true });
|
||||
const saved = m.saveLoopSetup(project, { ...m.LOOP_DEFAULTS, fix: [...m.LOOP_DEFAULTS.fix], phaseStrength: true, strengths: picks }, left);
|
||||
const onDisk = JSON.parse(fs.readFileSync(m.LOOP_SETUP_FILE, "utf8"));
|
||||
const raw = Object.values(onDisk.projects)[0].strengths;
|
||||
// A later read, with the overview changed again, drops the next pick too.
|
||||
fs.writeFileSync(path.join(project, "specs", "keep", "overview.md"), "# Demo\n\n## Phase Checklist\n\n- [ ] **Phase 3:** Ship it - [phase-3.md](phase-3.md)\n");
|
||||
const later = m.readLoopSetup(project, left);
|
||||
return { saved: saved.strengths, raw, later: later.strengths };
|
||||
},
|
||||
{ project, picks }
|
||||
);
|
||||
const kept = [{ n: 2, name: "Build it", strength: "thrifty" }];
|
||||
assert.deepEqual(out.saved, { "specs/keep": kept }, "the removed folder, the never-made one, the renamed phase and the finished phase are dropped");
|
||||
assert.deepEqual(out.raw, { "specs/keep": kept }, "the file holds the pruned copy");
|
||||
assert.deepEqual(out.later, {}, "a later read prunes what the overview no longer lists");
|
||||
});
|
||||
|
||||
test("loop-setup: the picks live only in loop-setup.json, never under specs/", () => {
|
||||
fs.rmSync(LOOP_SETUP_PATH, { force: true });
|
||||
const project = fs.mkdtempSync(path.join(HOME, "nowrite-"));
|
||||
specWith(project, "demo", [[" ", 1, "One"]]);
|
||||
const before = fs.readFileSync(path.join(project, "specs", "demo", "overview.md"), "utf8");
|
||||
inStore(
|
||||
(m, { project }) => (m.saveLoopSetup(project, { ...m.LOOP_DEFAULTS, fix: [...m.LOOP_DEFAULTS.fix], phaseStrength: true, strengths: { "specs/demo": [{ n: 1, name: "One", strength: "best" }] } }), null),
|
||||
{ project }
|
||||
);
|
||||
assert.ok(fs.existsSync(LOOP_SETUP_PATH));
|
||||
assert.deepEqual(fs.readdirSync(path.join(project, "specs", "demo")), ["overview.md"]);
|
||||
assert.equal(fs.readFileSync(path.join(project, "specs", "demo", "overview.md"), "utf8"), before);
|
||||
assert.deepEqual(fs.readdirSync(project), ["specs"], "nothing else appears in the project");
|
||||
});
|
||||
|
||||
test("GET /loop-setup?agent= answers the loop agent's resolved strengths and this spec's picks", async () => {
|
||||
fs.rmSync(LOOP_SETUP_PATH, { force: true });
|
||||
const cwd = tempProject("route-strength");
|
||||
specWith(cwd, "demo", [[" ", 1, "One"], [" ", 2, "Two"]]);
|
||||
// The installed copy of the shipped model menu, with its strengths, as install.js drops it.
|
||||
const shipped = path.join(MODELS_DIR, "bin", "models.json");
|
||||
const hadShipped = fs.existsSync(shipped) ? fs.readFileSync(shipped) : null;
|
||||
fs.mkdirSync(path.dirname(shipped), { recursive: true });
|
||||
fs.copyFileSync(path.join(ROOT, "src", "launcher", "models.json"), shipped);
|
||||
const opened = run(["open", "--workflow", "implement", "--no-open"], { cwd });
|
||||
assert.equal(opened.status, 0, opened.stderr);
|
||||
const { base, cookie } = sessionUrl(opened.json.url);
|
||||
const get = async (query) => {
|
||||
const res = await fetch(`${base}/loop-setup${query}`, { headers: { cookie, connection: "close" } });
|
||||
return { status: res.status, body: await res.json() };
|
||||
};
|
||||
try {
|
||||
const none = await get("?spec=specs/demo");
|
||||
assert.equal(none.body.resolved, null, "no agent asked, none answered");
|
||||
assert.deepEqual(none.body.picks, []);
|
||||
assert.equal(none.body.phaseStrength, false);
|
||||
|
||||
const claude = await get("?spec=specs/demo&agent=claude");
|
||||
assert.equal(claude.status, 200);
|
||||
assert.deepEqual(Object.keys(claude.body.resolved).sort(), ["balanced", "best", "thrifty"], "the shipped Claude Code rows");
|
||||
for (const word of ["thrifty", "balanced", "best"]) assert.equal(typeof claude.body.resolved[word].model, "string");
|
||||
|
||||
const codex = await get("?spec=specs/demo&agent=codex");
|
||||
assert.deepEqual(codex.body.resolved, {}, "codex has nothing mapped");
|
||||
|
||||
for (const agent of ["nobody", "..%2Fx", ""]) assert.equal((await get(`?spec=specs/demo&agent=${agent}`)).body.resolved, null, `agent=${agent}`);
|
||||
|
||||
// A save with picks reads back for its own spec; a pick for a phase that is not there is pruned.
|
||||
const entry = {
|
||||
review: true, fixMode: "smart", fix: ["critical"], commit: true, onQuestion: "guess", afterLast: "offer-finalize", quickCheck: "",
|
||||
notifyKind: "query", notifyUrl: "", notifyParam: "message", retryOnce: true, silenceMinutes: 20, phaseStrength: true,
|
||||
strengths: { "specs/demo": [{ n: 2, name: "Two", strength: "best" }, { n: 9, name: "Gone", strength: "best" }] },
|
||||
};
|
||||
const save = await fetch(`${base}/loop-setup`, { method: "POST", headers: { "content-type": "application/json", cookie, origin: base, connection: "close" }, body: JSON.stringify(entry) });
|
||||
assert.equal(save.status, 200, await save.clone().text());
|
||||
const back = await get("?spec=specs/demo&agent=claude");
|
||||
assert.equal(back.body.phaseStrength, true);
|
||||
assert.deepEqual(back.body.picks, [{ n: 2, name: "Two", strength: "best" }]);
|
||||
} finally {
|
||||
if (hadShipped) fs.writeFileSync(shipped, hadShipped);
|
||||
else fs.rmSync(shipped, { force: true });
|
||||
cli(["stop", "--session", opened.json.sid, "--force"], { cwd, expectFail: true });
|
||||
}
|
||||
});
|
||||
@@ -5,7 +5,11 @@
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { pageSuite, openSession, tempProject, textOf } from "./page-test-helpers.mjs";
|
||||
import { MODELS_DIR } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
@@ -46,6 +50,7 @@ test("the setup lists each phase on its own line, in the agreed order of fields
|
||||
|
||||
const labels = await s.page.locator(".loop-label").allInnerTexts();
|
||||
assert.deepEqual(labels, [
|
||||
"Strength per phase",
|
||||
"Review",
|
||||
"Fix findings",
|
||||
"When a phase asks something",
|
||||
@@ -256,6 +261,27 @@ test("the finish card counts each kind of decision per phase and opens on the fu
|
||||
assert.deepEqual(seen.actions, ["Finalize", "Back to the dashboard"], "the way home is offered next to Finalize");
|
||||
});
|
||||
|
||||
test("a stopped loop offers Ask a question, which tells the app and wakes no loop", async (t) => {
|
||||
const s = await openSetup(t);
|
||||
await frameInFakeApp(s);
|
||||
const seen = await s.page.evaluate(async () => {
|
||||
const m = await import(new URL("screens/ending.js", document.baseURI).href);
|
||||
const card = m.renderLoopEnd({
|
||||
kind: "stopped",
|
||||
line: "Phase 5 stopped",
|
||||
phases: [{ n: 5, name: "Docs", commit: null, unfixed: 0, retries: 0 }],
|
||||
uncommitted: [],
|
||||
can: ["ask", "resume", "fix", "dashboard"],
|
||||
});
|
||||
const buttons = [...card.querySelectorAll(".loop-end-actions button")];
|
||||
const ask = buttons.find((b) => b.textContent === "Ask a question");
|
||||
if (ask) ask.click();
|
||||
return { labels: buttons.map((b) => b.textContent), told: window.__told.map((x) => x.plan2code) };
|
||||
});
|
||||
assert.deepEqual(seen.labels, ["Ask a question", "Resume the loop", "Fix it by hand", "Back to the dashboard"]);
|
||||
assert.deepEqual(seen.told, ["loop-ask"]);
|
||||
});
|
||||
|
||||
// A real loop session: `open --loop` under the app's signal stamps the lock.
|
||||
async function openLoopPage(t) {
|
||||
return openSession(await suite.browser(), {
|
||||
@@ -329,3 +355,172 @@ test("a loop phase still starting says the loop is starting it, and promises no
|
||||
await s.page.getByRole("heading", { name: "The loop is starting this phase" }).waitFor();
|
||||
assert.doesNotMatch(await textOf(s.page.locator("#main")), /pause for approvals/);
|
||||
});
|
||||
|
||||
/* ------------------------------------------- Strength per phase (the section) */
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const LAUNCH = { agent: "claude", agentLabel: "Claude Code", model: "opus", effort: "medium", permissionMode: "bypass", promptSupport: true, running: false };
|
||||
|
||||
// The installed copy of the shipped model menu, with its strengths, as install.js drops it.
|
||||
function installShippedModels() {
|
||||
const shipped = path.join(MODELS_DIR, "bin", "models.json");
|
||||
fs.mkdirSync(path.dirname(shipped), { recursive: true });
|
||||
fs.copyFileSync(path.join(ROOT, "src", "launcher", "models.json"), shipped);
|
||||
}
|
||||
|
||||
// The setup screen with the app's answer in: this launch choice, then the strengths read for it.
|
||||
async function openStrengthSetup(t, launch = LAUNCH) {
|
||||
installShippedModels();
|
||||
const s = await openSetup(t);
|
||||
await s.page.evaluate(async (facts) => {
|
||||
const { page, redraw } = await import(new URL("state.js", document.baseURI).href);
|
||||
page.loopFacts = facts;
|
||||
redraw();
|
||||
}, launch);
|
||||
return s;
|
||||
}
|
||||
|
||||
const strengthRows = (s) =>
|
||||
s.page.locator(".loop-strength-row").evaluateAll((rows) =>
|
||||
rows.map((r) => ({ phase: r.querySelector(".loop-strength-phase").textContent, pick: r.querySelector("select").value, model: r.querySelector(".loop-strength-model").textContent }))
|
||||
);
|
||||
|
||||
test("the strength section is first in the form and off by default", async (t) => {
|
||||
const s = await openStrengthSetup(t);
|
||||
const toggle = s.page.locator("#loop-phase-strength");
|
||||
await toggle.waitFor();
|
||||
assert.equal(await toggle.isChecked(), false);
|
||||
assert.equal(await s.page.locator(".loop-label").first().innerText(), "Strength per phase");
|
||||
assert.equal(await s.page.locator(".loop-strength-row").count(), 0, "no rows until the toggle is on");
|
||||
assert.equal(await s.page.locator("#loop-strength-all").count(), 0);
|
||||
});
|
||||
|
||||
test("turning it on shows one row per phase left with the model each pick becomes, and Set all to fills them", async (t) => {
|
||||
const s = await openStrengthSetup(t);
|
||||
await s.page.locator("#loop-phase-strength").check();
|
||||
await s.page.locator(".loop-strength-row").first().waitFor();
|
||||
assert.deepEqual(await strengthRows(s), [
|
||||
{ phase: "Phase 1: One", pick: "", model: "opus, medium" },
|
||||
{ phase: "Phase 2: Two", pick: "", model: "opus, medium" },
|
||||
], "untouched rows match the session and show the launch choice");
|
||||
|
||||
await s.page.locator("#loop-strength-1").selectOption("thrifty");
|
||||
assert.equal(await textOf(s.page.locator('[data-phase="1"] .loop-strength-model')), "sonnet, low");
|
||||
|
||||
assert.equal(await s.page.locator("#loop-strength-all").inputValue(), "-", "Set all to starts blank");
|
||||
await s.page.locator("#loop-strength-all").selectOption("best");
|
||||
assert.deepEqual((await strengthRows(s)).map((r) => [r.pick, r.model]), [["best", "opus, medium"], ["best", "opus, medium"]]);
|
||||
assert.equal(await s.page.locator("#loop-strength-all").inputValue(), "-", "and goes blank again: it is not a saved value");
|
||||
|
||||
await s.page.locator("#loop-strength-2").selectOption("balanced");
|
||||
assert.deepEqual((await strengthRows(s)).map((r) => [r.pick, r.model]), [["best", "opus, medium"], ["balanced", "sonnet, medium"]], "a row can change after Set all");
|
||||
|
||||
await s.page.locator("#loop-strength-all").selectOption("match");
|
||||
assert.deepEqual((await strengthRows(s)).map((r) => r.pick), ["", ""], "Match my session fills every row too");
|
||||
});
|
||||
|
||||
test("an agent with nothing mapped grays the section and links to Agents & models", async (t) => {
|
||||
const s = await openStrengthSetup(t, { ...LAUNCH, agent: "codex", agentLabel: "Codex" });
|
||||
const note = s.page.locator(".loop-strength-none");
|
||||
await note.waitFor();
|
||||
assert.match(await textOf(note), /This agent has no strengths mapped yet\./);
|
||||
assert.equal(await s.page.locator("#loop-phase-strength").isDisabled(), true);
|
||||
assert.equal(await s.page.locator(".loop-strength-row").count(), 0);
|
||||
await note.getByRole("button").click();
|
||||
await s.page.locator("#prefs-tab-agents[aria-selected='true']").waitFor();
|
||||
});
|
||||
|
||||
test("a saved pick that is not mapped holds Start with a line naming the row, and a change releases it", async (t) => {
|
||||
const s = await openStrengthSetup(t);
|
||||
await s.page.locator("#loop-phase-strength").check();
|
||||
await s.page.locator(".loop-strength-row").first().waitFor();
|
||||
// Thrifty is no longer mapped for this agent (an override went away); Phase 2 still holds it.
|
||||
await s.page.evaluate(async () => {
|
||||
const { page, redraw } = await import(new URL("state.js", document.baseURI).href);
|
||||
page.loopSetup.facts.resolved = { best: { model: "opus", effort: "medium" } };
|
||||
page.loopSetup.form.strengths["specs/ready"] = [{ n: 2, name: "Two", strength: "thrifty" }];
|
||||
redraw();
|
||||
});
|
||||
const why = s.page.locator(".loop-why");
|
||||
assert.equal(await textOf(why), "Pick a new strength for Phase 2: not mapped for this agent.");
|
||||
assert.equal(await s.page.locator("#loop-start").isDisabled(), true);
|
||||
const pick = s.page.locator("#loop-strength-2");
|
||||
assert.equal(await pick.inputValue(), "thrifty", "the saved word stays in the row");
|
||||
assert.equal(await pick.locator("option:checked").innerText(), "Thrifty (not mapped)");
|
||||
assert.equal(await pick.locator("option:checked").evaluate((o) => o.disabled), true);
|
||||
|
||||
await pick.selectOption("best");
|
||||
assert.equal(await s.page.locator(".loop-why").count(), 0, "the hold is gone");
|
||||
assert.equal(await s.page.locator("#loop-start").isDisabled(), false);
|
||||
});
|
||||
|
||||
test("startBlock names every unmapped row, ignores the picks while the toggle is off, and waits for the strengths", async (t) => {
|
||||
const s = await openSetup(t);
|
||||
const lines = await s.page.evaluate(async () => {
|
||||
const { startBlock } = await import(new URL("screens/loop-setup.js", document.baseURI).href);
|
||||
const phasesLeft = [{ n: 2, name: "A" }, { n: 3, name: "B" }, { n: 4, name: "C" }];
|
||||
const strengths = { "specs/x": [{ n: 2, name: "A", strength: "thrifty" }, { n: 3, name: "B", strength: "best" }, { n: 4, name: "C", strength: "thrifty" }] };
|
||||
const facts = (resolved) => ({ spec: "specs/x", phasesLeft, pending: 0, resolved });
|
||||
const form = (phaseStrength) => ({ commit: false, phaseStrength, strengths });
|
||||
const app = { permissionMode: "bypass", promptSupport: true };
|
||||
return {
|
||||
two: startBlock(form(true), facts({ best: { model: "m" } }), app),
|
||||
off: startBlock(form(false), facts({ best: { model: "m" } }), app),
|
||||
allMapped: startBlock(form(true), facts({ thrifty: { model: "s" }, best: { model: "m" } }), app),
|
||||
nothingMapped: startBlock(form(true), facts({}), app),
|
||||
loading: startBlock(form(true), facts(undefined), app),
|
||||
last: startBlock(form(true), { ...facts({ best: { model: "m" } }), phasesLeft: [] }, app),
|
||||
};
|
||||
});
|
||||
assert.equal(lines.two, "Pick a new strength for Phase 2, Phase 4: not mapped for this agent.");
|
||||
assert.equal(lines.off, "");
|
||||
assert.equal(lines.allMapped, "");
|
||||
assert.equal(lines.nothingMapped, "", "an agent with nothing mapped grays the section instead");
|
||||
assert.equal(lines.loading, "Asking the app...");
|
||||
assert.equal(lines.last, "Nothing left to build in this spec.", "the older checks keep their order");
|
||||
});
|
||||
|
||||
test("the toggle and the picks survive reopening the screen, and the toggle off sends nothing for the loop", async (t) => {
|
||||
const s = await openStrengthSetup(t);
|
||||
await s.page.locator("#loop-phase-strength").check();
|
||||
await s.page.locator("#loop-strength-1").selectOption("thrifty");
|
||||
await s.page.locator("#loop-strength-2").selectOption("best");
|
||||
|
||||
const save = () =>
|
||||
s.page.evaluate(async () => {
|
||||
const { page } = await import(new URL("state.js", document.baseURI).href);
|
||||
const { setupBody } = await import(new URL("screens/loop-setup.js", document.baseURI).href);
|
||||
const res = await fetch("/loop-setup", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(setupBody(page.loopSetup.form, page.loopSetup)) });
|
||||
return { status: res.status, body: await res.json() };
|
||||
});
|
||||
const saved = await save();
|
||||
assert.equal(saved.status, 200, JSON.stringify(saved.body));
|
||||
assert.equal(saved.body.setup.phaseStrength, true);
|
||||
assert.deepEqual(saved.body.setup.strengths, { "specs/ready": [{ n: 1, name: "One", strength: "thrifty" }, { n: 2, name: "Two", strength: "best" }] });
|
||||
|
||||
const reopen = async () => {
|
||||
await s.page.evaluate(async () => {
|
||||
const m = await import(new URL("screens/loop-setup.js", document.baseURI).href);
|
||||
const { page, redraw } = await import(new URL("state.js", document.baseURI).href);
|
||||
await m.openLoopSetup({ dir: "specs/ready" });
|
||||
redraw();
|
||||
});
|
||||
await s.page.locator("#loop-start").waitFor();
|
||||
};
|
||||
await reopen();
|
||||
await s.page.locator("#loop-strength-1").waitFor();
|
||||
assert.equal(await s.page.locator("#loop-phase-strength").isChecked(), true);
|
||||
assert.deepEqual((await strengthRows(s)).map((r) => [r.pick, r.model]), [["thrifty", "sonnet, low"], ["best", "opus, medium"]]);
|
||||
|
||||
// Off: the picks stay saved, the loop is told nothing.
|
||||
await s.page.locator("#loop-phase-strength").uncheck();
|
||||
const off = await save();
|
||||
assert.equal(off.body.setup.phaseStrength, false);
|
||||
assert.equal(off.body.setup.strengths["specs/ready"].length, 2, "the toggle hides the picks, it does not erase them");
|
||||
|
||||
// Back to Match my session for every row removes the key.
|
||||
await s.page.locator("#loop-phase-strength").check();
|
||||
await s.page.locator("#loop-strength-all").selectOption("match");
|
||||
const cleared = await save();
|
||||
assert.deepEqual(cleared.body.setup.strengths, {});
|
||||
});
|
||||
@@ -162,6 +162,199 @@ test("Agents & models: the table lists Claude, Devin and Codex, and a model id t
|
||||
assert.equal(await formField(s, "Model id").inputValue(), "gpt-test-codex-2");
|
||||
});
|
||||
|
||||
// The "Strengths in the loop" fold: Thrifty, Balanced and Best mapped to the
|
||||
// agent's own models. models.json under PLAN2CODE_MODELS_DIR is what Save writes.
|
||||
const MODELS_FILE = path.join(MODELS_DIR, "models.json");
|
||||
const strengthsFold = (s) => agentForm(s).locator("details.prefs-agents-strengths");
|
||||
const strengthRow = (s, word) => strengthsFold(s).locator(`.strength-row[data-word="${word}"]`);
|
||||
const savedStrengths = () => {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(MODELS_FILE, "utf8")).strengths ?? null;
|
||||
} catch {
|
||||
return null; // not written yet
|
||||
}
|
||||
};
|
||||
|
||||
// The shipped list the tests start with has no models at all; the fold needs some
|
||||
// (and Claude and Devin's shipped strengths), so a test writes them and puts the file back.
|
||||
const SHIPPED_FILE = path.join(MODELS_DIR, "bin", "models.json");
|
||||
function seedShippedModels(t) {
|
||||
fs.mkdirSync(path.dirname(SHIPPED_FILE), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
SHIPPED_FILE,
|
||||
JSON.stringify({
|
||||
claude: [{ id: "sonnet", label: "Sonnet" }, { id: "opus", label: "Opus" }],
|
||||
devin: [{ id: "swe-2-medium", label: "SWE 2 Medium" }, { id: "swe-2-high", label: "SWE 2 High" }, { id: "claude-opus-5-5-medium", label: "Opus 5.5 Medium" }],
|
||||
codex: [],
|
||||
strengths: {
|
||||
claude: { thrifty: { model: "sonnet", effort: "low" }, balanced: { model: "sonnet", effort: "medium" }, best: { model: "opus", effort: "medium" } },
|
||||
devin: { thrifty: { model: "swe-2-medium" }, balanced: { model: "swe-2-high" }, best: { model: "claude-opus-5-5-medium" } },
|
||||
},
|
||||
})
|
||||
);
|
||||
t.after(() => fs.rmSync(SHIPPED_FILE, { force: true }));
|
||||
}
|
||||
|
||||
// Save lands asynchronously and an earlier Saved mark may still be on screen, so wait on the file.
|
||||
async function savedStrengthsAre(expected) {
|
||||
for (let i = 0; i < 100; i++) {
|
||||
if (JSON.stringify(savedStrengths()) === JSON.stringify(expected)) return;
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
}
|
||||
assert.deepEqual(savedStrengths(), expected);
|
||||
}
|
||||
|
||||
async function openStrengths(s, name) {
|
||||
await s.page.getByRole("button", { name: `Edit ${name}` }).click();
|
||||
await formPane(s).waitFor();
|
||||
await strengthsFold(s).locator("summary").click();
|
||||
}
|
||||
|
||||
test("Agents & models: Claude's fold shows the shipped rows as default, and only a changed row is saved, until Reset", async (t) => {
|
||||
noSavedLooks(t);
|
||||
seedAgents(t);
|
||||
t.after(() => fs.rmSync(MODELS_FILE, { force: true }));
|
||||
seedShippedModels(t);
|
||||
fs.rmSync(MODELS_FILE, { force: true });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openAgentsTab(s);
|
||||
await openStrengths(s, "Claude");
|
||||
assert.equal(await strengthRow(s, "thrifty").locator('select[data-field="model"]').inputValue(), "sonnet");
|
||||
assert.equal(await strengthRow(s, "thrifty").locator('select[data-field="effort"]').inputValue(), "low");
|
||||
assert.equal(await strengthRow(s, "best").locator('select[data-field="model"]').inputValue(), "opus");
|
||||
assert.equal(await strengthsFold(s).locator(".strength-default").count(), 3, "all three rows are untouched defaults");
|
||||
assert.equal(await textOf(strengthRow(s, "balanced").locator(".strength-default")), "default");
|
||||
assert.equal(await strengthsFold(s).locator(".strength-reset").count(), 0, "nothing to reset yet");
|
||||
assert.equal(await textOf(strengthsFold(s).locator(".strength-offer")), "The loop will offer: Thrifty, Balanced, Best");
|
||||
|
||||
await strengthRow(s, "thrifty").locator('select[data-field="model"]').selectOption("opus");
|
||||
await agentForm(s).locator(".prefs-unsaved-badge").waitFor();
|
||||
assert.equal(await strengthRow(s, "thrifty").locator(".strength-reset").count(), 1, "a changed row has Reset");
|
||||
assert.equal(await strengthRow(s, "thrifty").locator(".strength-default").count(), 0);
|
||||
assert.equal(await strengthRow(s, "balanced").locator(".strength-reset").count(), 0, "the other rows stay default");
|
||||
assert.equal(fs.existsSync(MODELS_FILE), false, "nothing is saved before Save");
|
||||
|
||||
await formButton(s, "Save").click();
|
||||
await agentForm(s).locator(".prefs-saved").filter({ hasText: /^Saved. Restart plan2code/ }).waitFor();
|
||||
assert.deepEqual(savedStrengths(), { claude: { thrifty: { model: "opus", effort: "low" } } }, "only the changed row is written");
|
||||
|
||||
await strengthRow(s, "thrifty").locator(".strength-reset").click();
|
||||
assert.equal(await strengthRow(s, "thrifty").locator('select[data-field="model"]').inputValue(), "sonnet", "Reset restores the shipped row");
|
||||
assert.equal(await textOf(strengthRow(s, "thrifty").locator(".strength-default")), "default");
|
||||
await agentForm(s).locator(".prefs-unsaved-badge").waitFor();
|
||||
await formButton(s, "Save").click();
|
||||
await savedStrengthsAre(null); // with every row back at its default, no strengths are stored
|
||||
});
|
||||
|
||||
test("Agents & models: Codex has an effort select on each row and Devin does not", async (t) => {
|
||||
noSavedLooks(t);
|
||||
seedAgents(t);
|
||||
t.after(() => fs.rmSync(MODELS_FILE, { force: true }));
|
||||
seedShippedModels(t);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openAgentsTab(s);
|
||||
await openStrengths(s, "Codex");
|
||||
assert.equal(await textOf(strengthsFold(s).locator(".strength-empty")), "Add a model under Models first", "no models ship for Codex");
|
||||
await formButton(s, "Add a model").click();
|
||||
await formField(s, "Model id").fill("gpt-test-codex-1");
|
||||
assert.equal(await strengthsFold(s).locator('select[data-field="effort"]').count(), 3);
|
||||
assert.equal(await strengthRow(s, "thrifty").locator('select[data-field="model"]').inputValue(), "", "nothing ships for Codex, so the row is not mapped");
|
||||
assert.equal(await textOf(strengthsFold(s).locator(".strength-offer")), "The loop will not offer a strength for this agent until one is mapped.");
|
||||
await formButton(s, "Discard").click(); // the added model is unsaved: leaving would ask first
|
||||
await s.page.getByRole("button", { name: "Edit Devin" }).click();
|
||||
await strengthsFold(s).locator("summary").click();
|
||||
assert.equal(await strengthsFold(s).locator('select[data-field="model"]').count(), 3);
|
||||
assert.equal(await strengthsFold(s).locator('select[data-field="effort"]').count(), 0, "Devin takes no separate effort");
|
||||
});
|
||||
|
||||
test("Agents & models: a strength-only edit is unsaved until Save, Discard puts the shipped rows back, and Reset keeps focus on its row", async (t) => {
|
||||
noSavedLooks(t);
|
||||
seedAgents(t);
|
||||
t.after(() => fs.rmSync(MODELS_FILE, { force: true }));
|
||||
seedShippedModels(t);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openAgentsTab(s);
|
||||
await openStrengths(s, "Claude");
|
||||
assert.equal(await agentForm(s).locator(".prefs-unsaved-badge").isVisible(), false);
|
||||
await strengthRow(s, "best").locator('select[data-field="model"]').selectOption("sonnet");
|
||||
await agentForm(s).locator(".prefs-unsaved-badge").waitFor();
|
||||
await formButton(s, "Discard").click();
|
||||
assert.equal(await agentForm(s).locator(".prefs-unsaved-badge").isVisible(), false, "Discard clears the strength-only change");
|
||||
assert.equal(await strengthRow(s, "best").locator('select[data-field="model"]').inputValue(), "opus", "the shipped row is back");
|
||||
assert.equal(fs.existsSync(MODELS_FILE), false, "nothing was written");
|
||||
|
||||
await strengthRow(s, "best").locator('select[data-field="model"]').selectOption("sonnet");
|
||||
await strengthRow(s, "best").locator(".strength-reset").focus();
|
||||
await strengthRow(s, "best").locator(".strength-reset").click();
|
||||
assert.equal(
|
||||
await s.page.evaluate(() => document.activeElement?.closest("[data-word]")?.dataset.word),
|
||||
"best",
|
||||
"focus stays in the row the Reset was in"
|
||||
);
|
||||
});
|
||||
|
||||
test("Agents & models: a saved row whose model was removed reads not mapped while other models remain, and Save drops it", async (t) => {
|
||||
noSavedLooks(t);
|
||||
seedAgents(t);
|
||||
t.after(() => fs.rmSync(MODELS_FILE, { force: true }));
|
||||
seedShippedModels(t);
|
||||
fs.rmSync(MODELS_FILE, { force: true });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openAgentsTab(s);
|
||||
await s.page.click("#agents-add");
|
||||
await formPane(s).waitFor();
|
||||
await formField(s, "Name").fill("Gemini");
|
||||
await formField(s, "Command").fill("node");
|
||||
await agentForm(s).locator("details.agent-fold > summary", { hasText: /^Models$/ }).click();
|
||||
await formButton(s, "Add a model").click();
|
||||
await formField(s, "Model id").fill("model-a");
|
||||
await formButton(s, "Add a model").click();
|
||||
await formField(s, "Model id").nth(1).fill("model-b");
|
||||
await strengthsFold(s).locator("summary").click();
|
||||
await strengthRow(s, "thrifty").locator('select[data-field="model"]').selectOption("model-a");
|
||||
await strengthRow(s, "best").locator('select[data-field="model"]').selectOption("model-b");
|
||||
await formButton(s, "Save").click();
|
||||
await savedStrengthsAre({ gemini: { thrifty: { model: "model-a" }, best: { model: "model-b" } } });
|
||||
|
||||
await agentForm(s).locator(".agent-row.model").first().getByRole("button", { name: "Remove" }).click();
|
||||
assert.equal(await strengthRow(s, "thrifty").locator('select[data-field="model"]').inputValue(), "", "the removed model reads not mapped");
|
||||
assert.equal(await textOf(strengthsFold(s).locator(".strength-offer")), "The loop will offer: Best");
|
||||
await formButton(s, "Save").click();
|
||||
await savedStrengthsAre({ gemini: { best: { model: "model-b" } } });
|
||||
});
|
||||
|
||||
test("Agents & models: an added agent maps strengths only from its own Models, and a removed model reads not mapped", async (t) => {
|
||||
noSavedLooks(t);
|
||||
seedAgents(t);
|
||||
t.after(() => fs.rmSync(MODELS_FILE, { force: true }));
|
||||
seedShippedModels(t);
|
||||
fs.rmSync(MODELS_FILE, { force: true });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openAgentsTab(s);
|
||||
await s.page.click("#agents-add");
|
||||
await formPane(s).waitFor();
|
||||
await formField(s, "Name").fill("Copilot");
|
||||
await formField(s, "Command").fill("node");
|
||||
await strengthsFold(s).locator("summary").click();
|
||||
assert.equal(await textOf(strengthsFold(s).locator(".strength-empty")), "Add a model under Models first");
|
||||
assert.equal(await strengthsFold(s).locator("select").count(), 0, "no selects without a model");
|
||||
|
||||
await agentForm(s).locator("details.agent-fold > summary", { hasText: /^Models$/ }).click();
|
||||
await formButton(s, "Add a model").click();
|
||||
await formField(s, "Model id").fill("gpt-test-1");
|
||||
assert.equal(await strengthsFold(s).locator(".strength-empty").count(), 0, "the fold follows the Models list as it changes");
|
||||
await strengthRow(s, "thrifty").locator('select[data-field="model"]').selectOption("gpt-test-1");
|
||||
assert.equal(await strengthRow(s, "thrifty").locator('select[data-field="effort"]').count(), 0, "an added agent has no effort select");
|
||||
await formButton(s, "Save").click();
|
||||
await agentForm(s).locator(".prefs-saved").waitFor();
|
||||
assert.deepEqual(savedStrengths(), { copilot: { thrifty: { model: "gpt-test-1" } } }, "saved under the new agent's id");
|
||||
|
||||
await agentForm(s).locator(".agent-row.model").first().getByRole("button", { name: "Remove" }).click();
|
||||
assert.equal(await textOf(strengthsFold(s).locator(".strength-empty")), "Add a model under Models first");
|
||||
await formButton(s, "Save").click();
|
||||
await savedStrengthsAre(null);
|
||||
});
|
||||
|
||||
test("Agents & models: a person adds an agent, tests its command, sees it after a reload, and deletes it", async (t) => {
|
||||
noSavedLooks(t);
|
||||
seedAgents(t);
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
// Tests for src/web-console/strengths.mjs against the shared cases in
|
||||
// scripts/fixtures/strength-cases.json (the Rust twin in models.rs loads the
|
||||
// same file). Run with: node --test scripts/test-web-console-strengths.mjs
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { STRENGTH_ORDER, nextStrength, resolveStrengths } from "../src/web-console/strengths.mjs";
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const FIXTURE = JSON.parse(fs.readFileSync(path.join(ROOT, "scripts", "fixtures", "strength-cases.json"), "utf8"));
|
||||
|
||||
test("the fixture is schema 1 and covers every kind of case", () => {
|
||||
assert.equal(FIXTURE.schema, 1);
|
||||
assert.ok(FIXTURE.cases.length >= 10);
|
||||
const names = FIXTURE.cases.map((c) => c.name);
|
||||
assert.equal(new Set(names).size, names.length, "case names are unique");
|
||||
});
|
||||
|
||||
for (const c of FIXTURE.cases) {
|
||||
test(`resolveStrengths: ${c.name}`, () => {
|
||||
const resolved = resolveStrengths({ shipped: c.shipped, user: c.user, models: c.models, hasEffort: c.hasEffort });
|
||||
assert.deepEqual(resolved, c.expect.resolved);
|
||||
});
|
||||
|
||||
test(`nextStrength: ${c.name}`, () => {
|
||||
for (const word of STRENGTH_ORDER) {
|
||||
assert.equal(nextStrength(c.expect.resolved, word), c.expect.next[word], `next after ${word}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test("nextStrength: an unknown word or a missing mapping has no next", () => {
|
||||
assert.equal(nextStrength({ best: { model: "x" } }, "cheap"), null);
|
||||
assert.equal(nextStrength(null, "thrifty"), null);
|
||||
assert.equal(nextStrength(undefined, "balanced"), null);
|
||||
});
|
||||
|
||||
test("resolveStrengths: called with nothing at all resolves nothing", () => {
|
||||
assert.deepEqual(resolveStrengths(), {});
|
||||
assert.deepEqual(resolveStrengths({}), {});
|
||||
});
|
||||
@@ -9,10 +9,15 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { defaultInstruction, offered, onLines, STRENGTH_LINES, STRENGTHS } from "../src/web-console/public/subagents.js";
|
||||
import { readSubagentCursor } from "../src/web-console/settings.mjs";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { readSubagentCursor, readSubagentSetting } from "../src/web-console/settings.mjs";
|
||||
import { foldKey } from "../src/web-console/workspace.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
HOME,
|
||||
ENV,
|
||||
CONSOLE_CLI,
|
||||
safeJson,
|
||||
cli,
|
||||
sessionUrl,
|
||||
readState,
|
||||
@@ -510,3 +515,63 @@ test("subagents: a change arrives as reply lines only, carrying state, strength
|
||||
cli(["stop", "--session", s.sid, "--force"]);
|
||||
}
|
||||
});
|
||||
|
||||
/* ------------------------------------- a loop phase's helpers follow its strength */
|
||||
|
||||
const loopOpen = (cwd, env, workflow = "implement", extraArgs = ["--loop"]) => {
|
||||
const clean = { ...process.env, ...ENV };
|
||||
for (const key of ["PLAN2CODE_IN_APP", "PLAN2CODE_EMBED_ORIGIN", "PLAN2CODE_APP_ANNOUNCE", "PLAN2CODE_APP_TOKEN", "PLAN2CODE_CONSOLE_SID", "PLAN2CODE_LOOP_STRENGTH"]) delete clean[key];
|
||||
const res = spawnSync(process.execPath, [CONSOLE_CLI, "open", "--workflow", workflow, ...extraArgs, "--no-open"], { env: { ...clean, ...env }, encoding: "utf8", cwd });
|
||||
assert.equal(res.status, 0, res.stderr);
|
||||
return safeJson(res.stdout);
|
||||
};
|
||||
|
||||
test("subagents: open --loop on a phase strength tells the agent that strength, leaves the stored setting alone and off stays off", () => {
|
||||
const cwd = fs.mkdtempSync(path.join(HOME, "sub-loop-"));
|
||||
const stored = (entry) => fs.writeFileSync(SUBAGENTS_STORE, JSON.stringify({ [foldKey(cwd)]: { implement: entry } }));
|
||||
const sessions = [];
|
||||
try {
|
||||
stored({ on: true, instruction: null, max: 3, strength: "balanced" });
|
||||
const before = fs.readFileSync(SUBAGENTS_STORE, "utf8");
|
||||
const thrifty = loopOpen(cwd, { PLAN2CODE_IN_APP: "1", PLAN2CODE_LOOP_STRENGTH: "thrifty" });
|
||||
sessions.push(thrifty.sid);
|
||||
assert.deepEqual(subagentLines(thrifty.reply), ["Subagents: on, thrifty strength, at most 3 helpers at once (a console setting, not typed by the person)."]);
|
||||
assert.deepEqual(readState(thrifty.session).loop, { driving: true, strength: "thrifty" });
|
||||
assert.equal(fs.readFileSync(SUBAGENTS_STORE, "utf8"), before, "the stored setting is not rewritten");
|
||||
|
||||
// The next phase in the same session runs on another strength, then none.
|
||||
const best = loopOpen(cwd, { PLAN2CODE_IN_APP: "1", PLAN2CODE_LOOP_STRENGTH: "best" }, "implement", ["--resume", thrifty.sid, "--loop"]);
|
||||
assert.deepEqual(subagentLines(best.reply).map((l) => l.replace(/ \(a console.*/, "")), ["Subagents: on, best strength, at most 3 helpers at once"]);
|
||||
assert.equal(fs.readFileSync(SUBAGENTS_STORE, "utf8"), before);
|
||||
|
||||
// A phase with no strength after a strength phase hears the stored one.
|
||||
const none = loopOpen(cwd, { PLAN2CODE_IN_APP: "1" }, "implement", ["--resume", thrifty.sid, "--loop"]);
|
||||
assert.deepEqual(subagentLines(none.reply).map((l) => l.replace(/ \(a console.*/, "")), ["Subagents: on, balanced strength, at most 3 helpers at once"]);
|
||||
assert.deepEqual(readState(thrifty.session).loop, { driving: true });
|
||||
|
||||
// Off stays off, whatever the phase's strength.
|
||||
stored({ on: false, instruction: null, max: 3, strength: "balanced" });
|
||||
const off = loopOpen(cwd, { PLAN2CODE_IN_APP: "1", PLAN2CODE_LOOP_STRENGTH: "thrifty" }, "implement", ["--resume", thrifty.sid, "--loop"]);
|
||||
assert.ok(!subagentLines(off.reply).some((l) => /on,/.test(l)), JSON.stringify(off.reply));
|
||||
assert.equal(readSubagentSetting(thrifty.session).on, false);
|
||||
} finally {
|
||||
for (const sid of sessions) cli(["stop", "--session", sid, "--force"], { expectFail: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("subagents: open without --loop ignores PLAN2CODE_LOOP_STRENGTH, and a word that is not a strength is dropped", () => {
|
||||
const cwd = fs.mkdtempSync(path.join(HOME, "sub-noloop-"));
|
||||
fs.writeFileSync(SUBAGENTS_STORE, JSON.stringify({ [foldKey(cwd)]: { implement: { on: true, instruction: null, max: 3, strength: "balanced" } } }));
|
||||
const sessions = [];
|
||||
try {
|
||||
const plain = loopOpen(cwd, { PLAN2CODE_LOOP_STRENGTH: "thrifty" }, "implement", []);
|
||||
sessions.push(plain.sid);
|
||||
assert.deepEqual(subagentLines(plain.reply).map((l) => l.replace(/ \(a console.*/, "")), ["Subagents: on, balanced strength, at most 3 helpers at once"]);
|
||||
assert.equal("loop" in readState(plain.session), false);
|
||||
const odd = loopOpen(cwd, { PLAN2CODE_IN_APP: "1", PLAN2CODE_LOOP_STRENGTH: "session" });
|
||||
sessions.push(odd.sid);
|
||||
assert.deepEqual(readState(odd.session).loop, { driving: true });
|
||||
} finally {
|
||||
for (const sid of sessions) cli(["stop", "--session", sid, "--force"], { expectFail: true });
|
||||
}
|
||||
});
|
||||
@@ -104,8 +104,9 @@
|
||||
"kind": "template",
|
||||
"command": "opencode",
|
||||
"prompt": "Use the plan2code skill",
|
||||
"args": ["--prompt", "{prompt}"],
|
||||
"bypassArgs": ["--auto"]
|
||||
"args": ["{model}", "--prompt", "{prompt}"],
|
||||
"bypassArgs": ["--auto"],
|
||||
"modelArgs": ["--model", "{model}"]
|
||||
},
|
||||
{
|
||||
"id": "gemini",
|
||||
@@ -113,8 +114,9 @@
|
||||
"kind": "template",
|
||||
"command": "gemini",
|
||||
"prompt": "Use the plan2code skill",
|
||||
"args": ["{prompt}"],
|
||||
"args": ["{model}", "{prompt}"],
|
||||
"bypassArgs": ["--approval-mode=yolo"],
|
||||
"modelArgs": ["--model", "{model}"],
|
||||
"note": "For unpaid tier and Google One accounts Gemini CLI was replaced by Antigravity CLI on June 18, 2026; whether gemini still runs depends on the account."
|
||||
},
|
||||
{
|
||||
@@ -123,7 +125,8 @@
|
||||
"kind": "template",
|
||||
"command": "pi",
|
||||
"prompt": "/skill:plan2code",
|
||||
"args": ["{prompt}"]
|
||||
"args": ["{model}", "{prompt}"],
|
||||
"modelArgs": ["--model", "{model}"]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"_note": "Curated model menu for the plan2code launcher. Maintained by the Plan2Code authors; every install overwrites this file. Users add models in User Preferences (kept in ~/.plan2code/models.json). Devin entries are explicit ids at Low, Medium and High effort only, verified against `devin models list`. Codex has no curated entries yet (its docs name none to verify): the launcher skips the model question for it. Pass --model <name> to choose one.",
|
||||
"_note": "Curated model menu for the plan2code launcher. Maintained by the Plan2Code authors; every install overwrites this file. Users add models in User Preferences (kept in ~/.plan2code/models.json). Devin entries are explicit ids at Low, Medium and High effort only, verified against `devin models list`. Codex entries are the models its docs name as current. The strengths key maps the loop's Thrifty, Balanced and Best to a model (and effort) per agent; users override it in User Preferences. Pass --model <name> to choose any other.",
|
||||
"claude": [
|
||||
{
|
||||
"id": "default",
|
||||
@@ -138,7 +138,63 @@
|
||||
{
|
||||
"id": "gpt-6-astra-high",
|
||||
"label": "GPT-6 Astra High Thinking"
|
||||
},
|
||||
{
|
||||
"id": "gpt-5-6-sol-low",
|
||||
"label": "GPT-5.6 Sol Low Thinking"
|
||||
},
|
||||
{
|
||||
"id": "gpt-5-6-sol-medium",
|
||||
"label": "GPT-5.6 Sol Medium Thinking"
|
||||
},
|
||||
{
|
||||
"id": "gpt-5-6-sol-high",
|
||||
"label": "GPT-5.6 Sol High Thinking"
|
||||
}
|
||||
],
|
||||
"codex": []
|
||||
"codex": [
|
||||
{
|
||||
"id": "gpt-6-astra",
|
||||
"label": "GPT-6 Astra"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6.1-sol",
|
||||
"label": "GPT-6.1 Sol"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6.1-terra",
|
||||
"label": "GPT-6.1 Terra"
|
||||
},
|
||||
{
|
||||
"id": "gpt-6-luna",
|
||||
"label": "GPT-6 Luna"
|
||||
}
|
||||
],
|
||||
"strengths": {
|
||||
"claude": {
|
||||
"thrifty": {
|
||||
"model": "sonnet",
|
||||
"effort": "low"
|
||||
},
|
||||
"balanced": {
|
||||
"model": "sonnet",
|
||||
"effort": "medium"
|
||||
},
|
||||
"best": {
|
||||
"model": "opus",
|
||||
"effort": "medium"
|
||||
}
|
||||
},
|
||||
"devin": {
|
||||
"thrifty": {
|
||||
"model": "swe-2-medium"
|
||||
},
|
||||
"balanced": {
|
||||
"model": "swe-2-high"
|
||||
},
|
||||
"best": {
|
||||
"model": "claude-opus-5-5-medium"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,10 +48,11 @@ import {
|
||||
workspaceForAgent,
|
||||
writeWorkspaceCursor,
|
||||
} from "./workspace.mjs";
|
||||
import { readPrHosts, resetSubagentCursor } from "./settings.mjs";
|
||||
import { readPrHosts, resetSubagentCursor, subagentStoreEntry } from "./settings.mjs";
|
||||
import { resetPointers } from "./pointers.mjs";
|
||||
import { WORKFLOWS, isWorkflow } from "./public/skills.js";
|
||||
import { startsClean } from "./public/hops.js";
|
||||
import { STRENGTH_ORDER } from "./strengths.mjs";
|
||||
import { snapshot } from "./git-repo.mjs";
|
||||
import { announcePage, currentSession, inAppSignal } from "./in-app.mjs";
|
||||
import { findAgent } from "./agent-lookup.mjs";
|
||||
@@ -107,6 +108,14 @@ const EMBED_API = 1;
|
||||
// The only workflows a loop drives (open --loop).
|
||||
const LOOP_WORKFLOWS = ["implement", "implement-review"];
|
||||
|
||||
// What the loop locks a session with: `driving`, and, when the app started this
|
||||
// phase on a strength, its word (PLAN2CODE_LOOP_STRENGTH), which the server's
|
||||
// Subagents sync reads so the phase's helpers follow it.
|
||||
function loopLock() {
|
||||
const strength = process.env.PLAN2CODE_LOOP_STRENGTH;
|
||||
return STRENGTH_ORDER.includes(strength) ? { driving: true, strength } : { driving: true };
|
||||
}
|
||||
|
||||
export async function cmdOpen() {
|
||||
trace("open: start");
|
||||
// A workflow the console does not know is refused first, before the pointer,
|
||||
@@ -256,7 +265,7 @@ export async function cmdOpen() {
|
||||
// without it (Fix it by hand, from a stop screen) is an ordinary,
|
||||
// unlocked session. `loopExpect` goes with the lock: the app restamps it
|
||||
// on its next look, so a stale setup never judges a new run.
|
||||
if (loopMode) s.loop = { driving: true };
|
||||
if (loopMode) s.loop = loopLock();
|
||||
else {
|
||||
delete s.loop;
|
||||
delete s.loopExpect;
|
||||
@@ -288,7 +297,7 @@ export async function cmdOpen() {
|
||||
// Only a freshly opened dashboard plays Planny's wake-up.
|
||||
if (args.workflow === "dashboard") state.wake = true;
|
||||
// Locked from the first frame, before the state is first written.
|
||||
if (loopMode) state.loop = { driving: true };
|
||||
if (loopMode) state.loop = loopLock();
|
||||
// The setup session's hand-over data (forCli + the token /handover
|
||||
// checks), created with the state so the first write already has it.
|
||||
if (args.workflow === "setup") {
|
||||
@@ -450,7 +459,11 @@ export async function cmdOpen() {
|
||||
// A standing instruction the new agent is owed, as a `reply` holding only
|
||||
// its lines; no key when nothing is owed.
|
||||
const subagentsOwed = () => {
|
||||
awaitSubagentSync(dir, state.workflow);
|
||||
// In a loop the setting must carry this phase's strength, or the stored one
|
||||
// when the phase has none, before the first block is built: a resume leaves
|
||||
// the earlier phase's strength in the setting until the server syncs.
|
||||
const expected = loopMode ? (state.loop && state.loop.strength) || subagentStoreEntry(worktree, state.workflow).strength : undefined;
|
||||
awaitSubagentSync(dir, state.workflow, expected);
|
||||
const [out, cursor] = withSubagents(dir, { reply: "" });
|
||||
return [cursor ? out : {}, cursor];
|
||||
};
|
||||
|
||||
@@ -553,12 +553,14 @@ export function advanceWorkspace(dir, changes) {
|
||||
// an older server, which never writes one: a short look, not the full wait.
|
||||
const SUBAGENT_SYNC_WAIT_MS = 1500;
|
||||
const SUBAGENT_SYNC_MISSING_MS = 250;
|
||||
export function awaitSubagentSync(dir, workflow) {
|
||||
export function awaitSubagentSync(dir, workflow, strength) {
|
||||
if (!offered(workflow)) return;
|
||||
const start = Date.now();
|
||||
for (;;) {
|
||||
const setting = readSubagentSetting(dir);
|
||||
if (setting && setting.workflow === workflow) return;
|
||||
// A loop phase's strength rides on the session's state: the setting must
|
||||
// carry it before the first block is built, or the agent hears the stored one.
|
||||
if (setting && setting.workflow === workflow && (!strength || setting.strength === strength)) return;
|
||||
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
|
||||
if (Date.now() - start >= budget) return;
|
||||
sleepSync(25);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// Plan2Code Web Console - the Implementation Loop's setup, remembered per project.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { ensureDir, HOME_DIR, readJson, withStateLock, writeJsonAtomic } from "./files.mjs";
|
||||
@@ -22,6 +23,9 @@ const AFTER_LAST = ["offer-finalize", "run-finalize"];
|
||||
const NOTIFY_KINDS = ["query", "discord", "slack", "teams", "google-chat", "json"];
|
||||
// The kinds where the person names the parameter or field that holds the message.
|
||||
const NAMED_KINDS = ["query", "json"];
|
||||
const STRENGTH_WORDS = ["thrifty", "balanced", "best"];
|
||||
// A spec folder directly under specs/, no leading dot (the route's own rule).
|
||||
const SPEC_KEY = /^specs\/[^/\\.][^/\\]*$/;
|
||||
|
||||
export const LOOP_DEFAULTS = Object.freeze({
|
||||
review: true,
|
||||
@@ -36,6 +40,8 @@ export const LOOP_DEFAULTS = Object.freeze({
|
||||
notifyKind: "query",
|
||||
notifyUrl: "",
|
||||
notifyParam: "message",
|
||||
phaseStrength: false,
|
||||
strengths: Object.freeze({}),
|
||||
});
|
||||
|
||||
/** An http or https address in printable ASCII, with a host and no user name or password (the app's `valid_url`). */
|
||||
@@ -78,9 +84,72 @@ export function loopSetupProblems(entry) {
|
||||
if (typeof entry.notifyParam !== "string" || (entry.notifyUrl && NAMED_KINDS.includes(entry.notifyKind) && !/^[A-Za-z0-9._~-]{1,64}$/.test(entry.notifyParam))) {
|
||||
problems.push('"notifyParam" must be 1 to 64 letters, digits, or - _ . ~');
|
||||
}
|
||||
if (typeof entry.phaseStrength !== "boolean") problems.push('"phaseStrength" must be true or false');
|
||||
problems.push(...strengthsProblems(entry.strengths));
|
||||
return problems;
|
||||
}
|
||||
|
||||
/** Problems with the per-spec phase picks; empty when they are good. */
|
||||
function strengthsProblems(strengths) {
|
||||
if (strengths === null || typeof strengths !== "object" || Array.isArray(strengths)) return ['"strengths" must be an object'];
|
||||
const problems = [];
|
||||
for (const [key, picks] of Object.entries(strengths)) {
|
||||
if (!SPEC_KEY.test(key)) {
|
||||
problems.push(`"strengths" key "${key}" must be a folder directly under specs/`);
|
||||
continue;
|
||||
}
|
||||
if (!Array.isArray(picks) || picks.length > 100) {
|
||||
problems.push(`"strengths.${key}" must list at most 100 phase picks`);
|
||||
continue;
|
||||
}
|
||||
const seen = new Set();
|
||||
for (const pick of picks) {
|
||||
const ok = pick && typeof pick === "object" && !Array.isArray(pick);
|
||||
if (!ok || !Number.isInteger(pick.n) || pick.n < 1) {
|
||||
problems.push(`"strengths.${key}" picks need a phase number "n" (a positive whole number)`);
|
||||
} else if (seen.has(pick.n)) {
|
||||
problems.push(`"strengths.${key}" has Phase ${pick.n} twice`);
|
||||
} else {
|
||||
seen.add(pick.n);
|
||||
}
|
||||
if (!ok) continue;
|
||||
if (typeof pick.name !== "string" || pick.name.length > 200) problems.push(`"strengths.${key}" pick names must be text of at most 200 characters`);
|
||||
if (!STRENGTH_WORDS.includes(pick.strength)) problems.push(`"strengths.${key}" picks need a strength of ${STRENGTH_WORDS.join(", ")}`);
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop picks that no longer mean anything (FR-12, FR-13): a spec key whose folder
|
||||
* is gone from the project, and, for a spec whose phases can be read, picks whose
|
||||
* number and name match no phase left. `phasesFor(spec)` returns the phases left
|
||||
* as [{ n, name }], or null when the overview cannot be read (its picks stay).
|
||||
* Returns a fresh object; the input is never changed.
|
||||
*/
|
||||
export function pruneStrengths(project, strengths, phasesFor) {
|
||||
const out = {};
|
||||
for (const [spec, picks] of Object.entries(strengths && typeof strengths === "object" ? strengths : {})) {
|
||||
if (!SPEC_KEY.test(spec) || !Array.isArray(picks)) continue;
|
||||
let isDir = false;
|
||||
try {
|
||||
isDir = fs.statSync(path.join(project, spec)).isDirectory();
|
||||
} catch {
|
||||
/* gone */
|
||||
}
|
||||
if (!isDir) continue;
|
||||
let left = null;
|
||||
try {
|
||||
left = typeof phasesFor === "function" ? phasesFor(spec) : null;
|
||||
} catch {
|
||||
left = null;
|
||||
}
|
||||
const kept = Array.isArray(left) ? picks.filter((p) => left.some((l) => l.n === p.n && l.name === p.name)) : picks;
|
||||
if (kept.length) out[spec] = kept.map((p) => ({ ...p }));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function readStore() {
|
||||
const saved = readJson(LOOP_SETUP_FILE, null);
|
||||
const ok = saved && saved.schema === 1 && saved.projects && typeof saved.projects === "object" && !Array.isArray(saved.projects);
|
||||
@@ -94,14 +163,22 @@ function readStore() {
|
||||
* file reads as empty. An entry saved before `fixMode` existed fixed by level,
|
||||
* so it keeps doing that rather than taking the newer default.
|
||||
*/
|
||||
export function readLoopSetup(project) {
|
||||
export function readLoopSetup(project, phasesFor) {
|
||||
const saved = readStore().projects[foldKey(project)];
|
||||
if (saved && typeof saved === "object") return { ...LOOP_DEFAULTS, fix: [...LOOP_DEFAULTS.fix], fixMode: "levels", ...saved, remembered: true };
|
||||
return { ...LOOP_DEFAULTS, fix: [...LOOP_DEFAULTS.fix], remembered: false };
|
||||
const base = { ...LOOP_DEFAULTS, fix: [...LOOP_DEFAULTS.fix], strengths: {} };
|
||||
if (saved && typeof saved === "object") {
|
||||
const setup = { ...base, fixMode: "levels", ...saved, remembered: true };
|
||||
// Deep-copied and pruned like `fix`: the caller may change it freely.
|
||||
const strengths = saved.strengths && typeof saved.strengths === "object" && !Array.isArray(saved.strengths) ? saved.strengths : {};
|
||||
setup.strengths = pruneStrengths(project, strengths, phasesFor);
|
||||
if (typeof setup.phaseStrength !== "boolean") setup.phaseStrength = false;
|
||||
return setup;
|
||||
}
|
||||
return { ...base, remembered: false };
|
||||
}
|
||||
|
||||
/** Validate and save this project's setup; throws an Error listing the problems. */
|
||||
export function saveLoopSetup(project, entry) {
|
||||
export function saveLoopSetup(project, entry, phasesFor) {
|
||||
const problems = loopSetupProblems(entry);
|
||||
if (problems.length) {
|
||||
const err = new Error(`the loop setup is not valid: ${problems.join("; ")}`);
|
||||
@@ -115,9 +192,10 @@ export function saveLoopSetup(project, entry) {
|
||||
const store = readStore();
|
||||
// Only the known fields are kept, in the defaults' order.
|
||||
const known = Object.fromEntries(Object.keys(LOOP_DEFAULTS).map((key) => [key, entry[key]]));
|
||||
known.strengths = pruneStrengths(project, known.strengths, phasesFor);
|
||||
store.projects[foldKey(project)] = { ...known, saved: new Date().toISOString() };
|
||||
writeJsonAtomic(LOOP_SETUP_FILE, { schema: 1, projects: store.projects });
|
||||
return readLoopSetup(project);
|
||||
return readLoopSetup(project, phasesFor);
|
||||
},
|
||||
LOOP_SETUP_LOCK,
|
||||
);
|
||||
|
||||
@@ -1075,7 +1075,7 @@ export function isOpen(item) {
|
||||
|
||||
const LOOP_LEVELS = ["critical", "warning", "suggestion"];
|
||||
const LOOP_REASONS = ["tests", "findings", "blocked", "conflict", "other"];
|
||||
const LOOP_CAN = ["resume", "fix", "finalize", "dashboard"];
|
||||
const LOOP_CAN = ["resume", "ask", "fix", "finalize", "dashboard"];
|
||||
const TASK_ID = /^\d+\.\d+$/;
|
||||
|
||||
// A one-line path that stays inside the project: not absolute, no `..` step.
|
||||
@@ -1298,7 +1298,7 @@ export function loopEndProblems(e, state) {
|
||||
}
|
||||
|
||||
// Loop mode adds four optional keys that a blank state does not hold (absent,
|
||||
// not null): `loop: { driving: true }` (set by `open --loop`), `loopExpect`
|
||||
// not null): `loop: { driving: true, strength? }` (set by `open --loop`), `loopExpect`
|
||||
// (the app's judging criteria), `loopOutcome` (the skill's report) and
|
||||
// `loopEnd` (the app's ending).
|
||||
export function blankState({ sid, workflow, title, project, specDir }) {
|
||||
|
||||
@@ -36,6 +36,8 @@
|
||||
<link rel="modulepreload" href="/screens/agents/agents-list-editor.js" />
|
||||
<link rel="modulepreload" href="/screens/agents/agents-summary.js" />
|
||||
<link rel="modulepreload" href="/screens/agents/agents-form.js" />
|
||||
<link rel="modulepreload" href="/screens/agents/agents-strengths.js" />
|
||||
<link rel="modulepreload" href="/strengths.js" />
|
||||
<link rel="modulepreload" href="/screens/cleanup.js" />
|
||||
<link rel="modulepreload" href="/screens/help-dialog.js" />
|
||||
<link rel="modulepreload" href="/screens/workspace.js" />
|
||||
@@ -2251,6 +2253,15 @@
|
||||
wait on a prompt nobody sees, so Start stays grayed out.
|
||||
</li>
|
||||
</ul>
|
||||
<h4>Strength per phase</h4>
|
||||
<p>
|
||||
Turn on <strong>Set strength per phase</strong> in the setup to run each
|
||||
phase on <strong>Thrifty</strong>, <strong>Balanced</strong>, <strong>Best</strong>
|
||||
or <strong>Match my session</strong>. A phase you leave untouched runs on
|
||||
the launch model. The one retry after a crash or a quiet agent (when retry
|
||||
is on) goes one step up (Match my session stays on the launch model),
|
||||
and the phase's helpers follow.
|
||||
</p>
|
||||
<h4>What is locked while it runs</h4>
|
||||
<p>
|
||||
Answers, sign-offs, launches, Workspace, Helpers and
|
||||
@@ -3305,6 +3316,11 @@
|
||||
opens one agent's form, and <strong>Add agent</strong> a blank one.
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
<strong>Strengths in the loop</strong>: under Models, map Thrifty,
|
||||
Balanced and Best to one of the agent's own models. The Implementation
|
||||
Loop's per-phase strength reads them. Untouched rows stay as shipped.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Models</strong>: each built-in agent (Claude, Devin, Codex)
|
||||
shows the models that come with Plan2Code, which every update
|
||||
|
||||
@@ -15,6 +15,7 @@ import { hooks } from "../state.js";
|
||||
import {
|
||||
MODEL_CLIS,
|
||||
emptyLists,
|
||||
emptyStrengths,
|
||||
newAgent,
|
||||
normalizeAgent,
|
||||
cliOf,
|
||||
@@ -91,7 +92,16 @@ export function mountAgentsView(container, opts = {}) {
|
||||
$,
|
||||
// The last server reply for each list. Unknown keys on an agent ride along
|
||||
// untouched; builtins and templates only feed the setup pick list.
|
||||
saved: { agents: [], user: emptyLists(), shipped: emptyLists(), builtins: [], templates: [] },
|
||||
saved: { agents: [], user: emptyLists(), shipped: emptyLists(), builtins: [], templates: [], strengths: emptyStrengths() },
|
||||
// The person's own strength rows per form key, once the fold changed them
|
||||
// (agents-strengths.js); a form with no entry has not touched its fold.
|
||||
strengthDrafts: new Map(),
|
||||
strengthsOpen: false,
|
||||
// The open fold's redraw, set by the fold itself.
|
||||
strengthsRefresh: null,
|
||||
// Whether GET /models answered: without it the page holds none of the
|
||||
// person's models or strengths, so the fold stays away and no save sends them.
|
||||
modelsLoaded: false,
|
||||
// At most one per form being edited: "cli:<cli>" for a built-in's own models,
|
||||
// "agent:<id>" for an added agent, "agent:new" for one being added.
|
||||
drafts: new Map(),
|
||||
@@ -148,15 +158,20 @@ export function mountAgentsView(container, opts = {}) {
|
||||
}
|
||||
|
||||
function edited() {
|
||||
if (ctx.openKey) renderDirty(ctx, ctx.openKey);
|
||||
if (ctx.openKey) {
|
||||
// A model added or removed changes what the strengths fold may pick.
|
||||
if (ctx.strengthsRefresh) ctx.strengthsRefresh();
|
||||
renderDirty(ctx, ctx.openKey);
|
||||
}
|
||||
}
|
||||
|
||||
// Leaving a form for another row drops its draft, as closing it always did:
|
||||
// a dirty one asks first (the dialog's Save / Discard / Keep editing).
|
||||
async function leaveForm() {
|
||||
if (!ctx.openKey) return true;
|
||||
if (isDirty(ctx.saved, ctx.drafts, ctx.openKey) && !(await confirmUnsaved())) return false;
|
||||
if (isDirty(ctx.saved, ctx.drafts, ctx.openKey, ctx.strengthDrafts) && !(await confirmUnsaved())) return false;
|
||||
ctx.drafts.delete(ctx.openKey);
|
||||
ctx.strengthDrafts.delete(ctx.openKey);
|
||||
ctx.openKey = null;
|
||||
return true;
|
||||
}
|
||||
@@ -183,6 +198,7 @@ export function mountAgentsView(container, opts = {}) {
|
||||
ctx.formError = null;
|
||||
ctx.formReplace = null;
|
||||
ctx.confirming = false;
|
||||
ctx.strengthsOpen = false;
|
||||
ctx.argsOpen = key === "agent:new";
|
||||
// A built-in's only section is its models: folded it would show nothing.
|
||||
ctx.modelsOpen = key.startsWith("cli:");
|
||||
@@ -198,7 +214,10 @@ export function mountAgentsView(container, opts = {}) {
|
||||
// one just deleted).
|
||||
function closeForm() {
|
||||
const left = ctx.openKey;
|
||||
if (ctx.openKey) ctx.drafts.delete(ctx.openKey);
|
||||
if (ctx.openKey) {
|
||||
ctx.drafts.delete(ctx.openKey);
|
||||
ctx.strengthDrafts.delete(ctx.openKey);
|
||||
}
|
||||
ctx.openKey = null;
|
||||
ctx.formError = null;
|
||||
ctx.formReplace = null;
|
||||
@@ -286,6 +305,7 @@ export function mountAgentsView(container, opts = {}) {
|
||||
// Fresh from what was just saved: the form redraws on a clean draft.
|
||||
function savedAs(key) {
|
||||
ctx.drafts.delete(ctx.openKey);
|
||||
ctx.strengthDrafts.delete(ctx.openKey);
|
||||
ctx.openKey = key;
|
||||
ctx.drafts.set(key, structuredClone(savedEntry(ctx.saved, key)));
|
||||
ctx.formError = null;
|
||||
@@ -294,15 +314,35 @@ export function mountAgentsView(container, opts = {}) {
|
||||
drawForm(ctx);
|
||||
}
|
||||
|
||||
// The strengths mapping to send for `owner` (a built-in's cli or an added
|
||||
// agent's id): every other agent's saved rows that still name a known agent
|
||||
// (a deleted agent's rows drop out here), plus the owner's own rows. Those are
|
||||
// the form's draft when its fold changed, else what is saved, keeping only
|
||||
// rows whose model is still in `modelIds`.
|
||||
function strengthsToSend(owner, key, modelIds) {
|
||||
const known = new Set([...MODEL_CLIS, ...ctx.saved.agents.map((a) => a.id)]);
|
||||
const out = {};
|
||||
for (const [id, rows] of Object.entries(ctx.saved.strengths.user)) if (id !== owner && known.has(id)) out[id] = rows;
|
||||
const mine = ctx.strengthDrafts.has(key) ? ctx.strengthDrafts.get(key) : ctx.saved.strengths.user[owner] || {};
|
||||
const kept = Object.fromEntries(Object.entries(mine).filter(([, row]) => row && modelIds.includes(row.model)));
|
||||
if (Object.keys(kept).length) out[owner] = kept;
|
||||
return out;
|
||||
}
|
||||
|
||||
async function saveModelsFor(cli) {
|
||||
const sent = ctx.drafts.get("cli:" + cli).filter((m) => m.id);
|
||||
const key = "cli:" + cli;
|
||||
const sent = ctx.drafts.get(key).filter((m) => m.id);
|
||||
try {
|
||||
const { res, body } = await postJson("/models", { models: { ...ctx.saved.user, [cli]: sent } });
|
||||
const modelIds = [...ctx.saved.shipped[cli], ...sent].map((m) => m.id);
|
||||
const payload = { models: { ...ctx.saved.user, [cli]: sent } };
|
||||
if (ctx.modelsLoaded) payload.strengths = strengthsToSend(cli, key, modelIds);
|
||||
const { res, body } = await postJson("/models", payload);
|
||||
if (!res.ok) {
|
||||
formMark({ ok: false, error: body.error || "Could not save." });
|
||||
return false;
|
||||
}
|
||||
ctx.saved.user[cli] = (body.user && body.user[cli]) || sent;
|
||||
if (ctx.modelsLoaded) ctx.saved.strengths.user = body.strengths || {};
|
||||
} catch {
|
||||
formMark({ ok: false, error: "Could not save." });
|
||||
return false;
|
||||
@@ -343,6 +383,32 @@ export function mountAgentsView(container, opts = {}) {
|
||||
return false;
|
||||
}
|
||||
const id = ctx.saved.agents[at].id;
|
||||
// The fold's rows ride a second save into models.json, under the id the
|
||||
// agent has now (a new agent only gets one from the first).
|
||||
const modelIds = draft.models.map((m) => m.id).filter(Boolean);
|
||||
const savedRows = ctx.saved.strengths.user[id] || {};
|
||||
const stale = Object.values(savedRows).some((row) => row && !modelIds.includes(row.model));
|
||||
if (ctx.modelsLoaded && (ctx.strengthDrafts.has(key) || stale)) {
|
||||
// The agent itself is saved by now: on a failure the form moves to its
|
||||
// saved id, keeps the fold's unsaved rows and says what did not land.
|
||||
const strengthsFailed = (message) => {
|
||||
const mine = ctx.strengthDrafts.get(key);
|
||||
ctx.found.delete(key);
|
||||
ctx.found.delete("agent:" + id);
|
||||
savedAs("agent:" + id);
|
||||
if (mine !== undefined) ctx.strengthDrafts.set("agent:" + id, mine);
|
||||
drawForm(ctx);
|
||||
formMark({ ok: false, error: message });
|
||||
return false;
|
||||
};
|
||||
try {
|
||||
const { res, body } = await postJson("/models", { models: ctx.saved.user, strengths: strengthsToSend(id, key, modelIds) });
|
||||
if (!res.ok) return strengthsFailed(body.error || "Saved, but the strengths could not be.");
|
||||
ctx.saved.strengths.user = body.strengths || {};
|
||||
} catch {
|
||||
return strengthsFailed("Saved, but the strengths could not be.");
|
||||
}
|
||||
}
|
||||
ctx.found.delete(key);
|
||||
ctx.found.delete("agent:" + id);
|
||||
savedAs("agent:" + id);
|
||||
@@ -379,7 +445,7 @@ export function mountAgentsView(container, opts = {}) {
|
||||
|
||||
// An open form whose draft differs from what is saved.
|
||||
function hasUnsaved() {
|
||||
return ctx.openKey !== null && isDirty(ctx.saved, ctx.drafts, ctx.openKey);
|
||||
return ctx.openKey !== null && isDirty(ctx.saved, ctx.drafts, ctx.openKey, ctx.strengthDrafts);
|
||||
}
|
||||
|
||||
// What the unsaved prompt calls the open form.
|
||||
@@ -395,6 +461,7 @@ export function mountAgentsView(container, opts = {}) {
|
||||
if (!ctx.openKey) return;
|
||||
if (ctx.openKey === "agent:new") return closeForm();
|
||||
ctx.drafts.set(ctx.openKey, structuredClone(savedEntry(ctx.saved, ctx.openKey)));
|
||||
ctx.strengthDrafts.delete(ctx.openKey);
|
||||
ctx.formError = null;
|
||||
ctx.formReplace = null;
|
||||
ctx.confirming = false;
|
||||
@@ -414,6 +481,7 @@ export function mountAgentsView(container, opts = {}) {
|
||||
const seq = ++loadSeq;
|
||||
ctx.openKey = null;
|
||||
ctx.drafts.clear();
|
||||
ctx.strengthDrafts.clear();
|
||||
ctx.found.clear();
|
||||
ctx.formError = null;
|
||||
ctx.formReplace = null;
|
||||
@@ -437,7 +505,14 @@ export function mountAgentsView(container, opts = {}) {
|
||||
}
|
||||
ctx.saved.user = emptyLists();
|
||||
ctx.saved.shipped = emptyLists();
|
||||
ctx.saved.strengths = emptyStrengths();
|
||||
ctx.modelsLoaded = Boolean(models);
|
||||
if (models) {
|
||||
// A failed or missing strengths answer reads as nothing mapped.
|
||||
for (const part of ["shipped", "user"]) {
|
||||
const rows = models.strengths && models.strengths[part];
|
||||
if (rows && typeof rows === "object" && !Array.isArray(rows)) ctx.saved.strengths[part] = rows;
|
||||
}
|
||||
for (const cli of MODEL_CLIS) {
|
||||
if (Array.isArray(models.user?.[cli])) ctx.saved.user[cli] = models.user[cli];
|
||||
if (Array.isArray(models.shipped?.[cli])) ctx.saved.shipped[cli] = models.shipped[cli];
|
||||
|
||||
@@ -11,6 +11,22 @@ export const MODEL_CLIS = ["claude", "devin", "codex"];
|
||||
// What the table calls each built-in, and the command it runs (the launcher's CLIS ids).
|
||||
export const BUILT_IN = { claude: "Claude", devin: "Devin", codex: "Codex" };
|
||||
|
||||
// The built-ins that take an effort beside the model (agents.rs has_effort).
|
||||
export const HAS_EFFORT = ["claude", "codex"];
|
||||
|
||||
// The loop's strength mapping as the page keeps it: the shipped rows and the
|
||||
// person's own, each { <agent id>: { thrifty?, balanced?, best? } }.
|
||||
export function emptyStrengths() {
|
||||
return { shipped: {}, user: {} };
|
||||
}
|
||||
|
||||
// The agent a form's strengths belong to: a built-in's cli, an added agent's id.
|
||||
// An agent not yet saved has no id, so nothing of anyone else's can be its rows.
|
||||
export function strengthOwner(key) {
|
||||
if (key === "agent:new") return null;
|
||||
return key.startsWith("cli:") ? cliOf(key) : agentId(key);
|
||||
}
|
||||
|
||||
export function emptyLists() {
|
||||
return Object.fromEntries(MODEL_CLIS.map((cli) => [cli, []]));
|
||||
}
|
||||
@@ -44,8 +60,15 @@ export function canonical(value) {
|
||||
);
|
||||
}
|
||||
|
||||
export function isDirty(saved, drafts, key) {
|
||||
return drafts.has(key) && canonical(drafts.get(key)) !== canonical(savedEntry(saved, key));
|
||||
// `strengthDrafts` holds, per form key, the person's own strength rows once the
|
||||
// fold changed them; absent means the fold was left alone.
|
||||
export function isDirty(saved, drafts, key, strengthDrafts) {
|
||||
if (!drafts.has(key)) return false;
|
||||
if (canonical(drafts.get(key)) !== canonical(savedEntry(saved, key))) return true;
|
||||
const rows = strengthDrafts && strengthDrafts.get(key);
|
||||
if (rows === undefined) return false;
|
||||
const was = (saved.strengths && saved.strengths.user[strengthOwner(key)]) || {};
|
||||
return canonical(rows) !== canonical(was);
|
||||
}
|
||||
|
||||
export function nameOf(saved, drafts, key) {
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
|
||||
import { el } from "../../render.js";
|
||||
import { listEditor } from "./agents-list-editor.js";
|
||||
import { BUILT_IN, cliOf, savedEntry, isDirty } from "./agents-data.js";
|
||||
import { BUILT_IN, HAS_EFFORT, cliOf, savedEntry, isDirty } from "./agents-data.js";
|
||||
import { strengthsFold } from "./agents-strengths.js";
|
||||
|
||||
function agentField(label, field, child) {
|
||||
const wrap = el("div", "agent-field");
|
||||
@@ -89,7 +90,11 @@ function builtInFields(ctx, cli, draft) {
|
||||
"models",
|
||||
listEditor({ list: draft, kind: "models", field: "models", optionalName: false, addLabel: "Add a model", onChange: ctx.edited })
|
||||
);
|
||||
return [fold(ctx, "modelsOpen", "Models", "agent-fold", [note, comes, yours])];
|
||||
const models = () => [...ctx.saved.shipped[cli], ...draft];
|
||||
return [
|
||||
fold(ctx, "modelsOpen", "Models", "agent-fold", [note, comes, yours]),
|
||||
...(ctx.modelsLoaded ? [strengthsFold(ctx, cli, draft, { models, hasEffort: HAS_EFFORT.includes(cli) })] : []),
|
||||
];
|
||||
}
|
||||
|
||||
function addedFields(ctx, draft) {
|
||||
@@ -112,6 +117,9 @@ function addedFields(ctx, draft) {
|
||||
command,
|
||||
agentField("Start prompt", "prompt", agentInput(ctx, draft, "prompt", "Start prompt", "/plan2code (blank starts with nothing typed)", false)),
|
||||
models,
|
||||
...(ctx.modelsLoaded
|
||||
? [strengthsFold(ctx, ctx.openKey === "agent:new" ? "" : savedEntry(ctx.saved, ctx.openKey).id, draft, { models: () => draft.models, hasEffort: false })]
|
||||
: []),
|
||||
args,
|
||||
];
|
||||
}
|
||||
@@ -165,7 +173,7 @@ function formFoot(ctx, key) {
|
||||
export function renderDirty(ctx, key) {
|
||||
const foot = ctx.$("form").querySelector(".prefs-agents-foot");
|
||||
if (!foot || key !== ctx.openKey) return;
|
||||
const dirty = isDirty(ctx.saved, ctx.drafts, key);
|
||||
const dirty = isDirty(ctx.saved, ctx.drafts, key, ctx.strengthDrafts);
|
||||
for (const sel of [".prefs-agents-save", ".prefs-agents-discard", ".prefs-unsaved-badge"]) foot.querySelector(sel).hidden = !dirty;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
// Plan2Code Web Console - the "Strengths in the loop" fold of an agent's form.
|
||||
//
|
||||
// Maps the loop's three words (Thrifty, Balanced, Best) to one of the agent's
|
||||
// own models, and to an effort where the agent takes one. Choices are
|
||||
// select-only from the agent's Models list. An untouched row follows what
|
||||
// ships; only a row the person changed is kept in the form's strength draft
|
||||
// (ctx.strengthDrafts, by form key), which the form's Save sends. The rule that
|
||||
// reads a row is resolveStrengths, the same module the server uses.
|
||||
|
||||
import { el } from "../../render.js";
|
||||
import { STRENGTH_ORDER, resolveStrengths } from "../../strengths.js";
|
||||
import { canonical, strengthOwner } from "./agents-data.js";
|
||||
|
||||
const WORDS = { thrifty: "Thrifty", balanced: "Balanced", best: "Best" };
|
||||
const EFFORTS = ["low", "medium", "high"];
|
||||
|
||||
function option(value, text) {
|
||||
const o = el("option", null, text);
|
||||
o.value = value;
|
||||
return o;
|
||||
}
|
||||
|
||||
/**
|
||||
* The fold for the open form. `models` is the agent's Models list ({ id, label }
|
||||
* rows) or a function returning it, read at every redraw so a model added in the
|
||||
* same form shows up. `hasEffort` adds the effort select.
|
||||
*/
|
||||
export function strengthsFold(ctx, agentId, draft, { models, hasEffort }) {
|
||||
const key = ctx.openKey;
|
||||
const owner = agentId || strengthOwner(key);
|
||||
const shipped = (ctx.saved.strengths.shipped && ctx.saved.strengths.shipped[owner]) || {};
|
||||
const modelList = () => {
|
||||
const rows = typeof models === "function" ? models() : models;
|
||||
const seen = new Set();
|
||||
return (rows || []).filter((m) => m && m.id && !seen.has(m.id) && seen.add(m.id));
|
||||
};
|
||||
// The person's own rows: the draft once changed, else what is saved.
|
||||
const userRows = () => {
|
||||
const rows = ctx.strengthDrafts.has(key) ? ctx.strengthDrafts.get(key) : ctx.saved.strengths.user && ctx.saved.strengths.user[owner];
|
||||
return rows && typeof rows === "object" ? rows : {};
|
||||
};
|
||||
|
||||
const details = el("details", "agent-fold prefs-agents-strengths");
|
||||
details.open = ctx.strengthsOpen;
|
||||
details.addEventListener("toggle", () => (ctx.strengthsOpen = details.open));
|
||||
details.appendChild(el("summary", null, "Strengths in the loop"));
|
||||
const body = el("div", "strength-body");
|
||||
details.appendChild(body);
|
||||
|
||||
function setRow(word, row) {
|
||||
const next = { ...userRows() };
|
||||
if (row) next[word] = row;
|
||||
else delete next[word];
|
||||
ctx.strengthDrafts.set(key, next);
|
||||
ctx.edited();
|
||||
}
|
||||
|
||||
function draw() {
|
||||
const active = document.activeElement;
|
||||
const back = active && body.contains(active) ? { word: active.closest("[data-word]")?.dataset.word, field: active.dataset.field } : null;
|
||||
body.replaceChildren();
|
||||
const list = modelList();
|
||||
if (!list.length) {
|
||||
body.appendChild(el("p", "help strength-empty", "Add a model under Models first"));
|
||||
return;
|
||||
}
|
||||
const base = { shipped, models: list.map((m) => m.id), hasEffort };
|
||||
const user = userRows();
|
||||
const resolved = resolveStrengths({ ...base, user });
|
||||
const dflt = resolveStrengths({ ...base, user: {} });
|
||||
|
||||
for (const word of STRENGTH_ORDER) {
|
||||
const row = el("div", "strength-row");
|
||||
row.dataset.word = word;
|
||||
row.appendChild(el("span", "strength-word", WORDS[word]));
|
||||
|
||||
const model = el("select");
|
||||
model.dataset.field = "model";
|
||||
model.setAttribute("aria-label", `${WORDS[word]} model`);
|
||||
// Nothing ships for this word: "not mapped" is a real choice. With a default,
|
||||
// clearing a row is Reset's job.
|
||||
if (!dflt[word]) model.appendChild(option("", "not mapped"));
|
||||
for (const m of list) model.appendChild(option(m.id, m.label && m.label !== m.id ? `${m.label} (${m.id})` : m.id));
|
||||
model.value = resolved[word] ? resolved[word].model : "";
|
||||
model.addEventListener("change", () => {
|
||||
if (!model.value) return setRow(word, null);
|
||||
const next = { model: model.value };
|
||||
if (hasEffort && resolved[word] && resolved[word].effort) next.effort = resolved[word].effort;
|
||||
setRow(word, canonical(next) === canonical(dflt[word]) ? null : next);
|
||||
});
|
||||
row.appendChild(model);
|
||||
|
||||
if (hasEffort) {
|
||||
const effort = el("select");
|
||||
effort.dataset.field = "effort";
|
||||
effort.setAttribute("aria-label", `${WORDS[word]} effort`);
|
||||
effort.disabled = !resolved[word];
|
||||
effort.appendChild(option("", "no effort"));
|
||||
for (const e of EFFORTS) effort.appendChild(option(e, e));
|
||||
effort.value = (resolved[word] && resolved[word].effort) || "";
|
||||
effort.addEventListener("change", () => {
|
||||
const next = { model: resolved[word].model };
|
||||
if (effort.value) next.effort = effort.value;
|
||||
setRow(word, canonical(next) === canonical(dflt[word]) ? null : next);
|
||||
});
|
||||
row.appendChild(effort);
|
||||
}
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(user, word)) {
|
||||
const reset = el("button", "btn small ghost strength-reset", "Reset");
|
||||
reset.type = "button";
|
||||
reset.dataset.field = "reset";
|
||||
reset.setAttribute("aria-label", `Reset ${WORDS[word]}`);
|
||||
reset.addEventListener("click", () => setRow(word, null));
|
||||
row.appendChild(reset);
|
||||
} else if (resolved[word]) {
|
||||
row.appendChild(el("span", "help strength-default", "default"));
|
||||
}
|
||||
body.appendChild(row);
|
||||
}
|
||||
|
||||
const offered = STRENGTH_ORDER.filter((w) => resolved[w]).map((w) => WORDS[w]);
|
||||
body.appendChild(
|
||||
el(
|
||||
"p",
|
||||
"help strength-offer",
|
||||
offered.length ? `The loop will offer: ${offered.join(", ")}` : "The loop will not offer a strength for this agent until one is mapped."
|
||||
)
|
||||
);
|
||||
if (back) {
|
||||
// A Reset that was pressed is gone with its row's change: the model select takes the focus.
|
||||
const row = body.querySelector(`[data-word="${back.word}"]`);
|
||||
(row?.querySelector(`[data-field="${back.field}"]`) || row?.querySelector('[data-field="model"]'))?.focus();
|
||||
}
|
||||
}
|
||||
|
||||
ctx.strengthsRefresh = draw;
|
||||
draw();
|
||||
return details;
|
||||
}
|
||||
@@ -29,6 +29,13 @@ const AFTER_LAST = [
|
||||
["run-finalize", "Run Finalize automatically", "Finalize starts by itself once every phase is built."],
|
||||
];
|
||||
|
||||
const STRENGTH_WORDS = [
|
||||
["thrifty", "Thrifty"],
|
||||
["balanced", "Balanced"],
|
||||
["best", "Best"],
|
||||
];
|
||||
const MATCH_SESSION = "Match my session";
|
||||
|
||||
const DEFAULT_NOTIFY_PARAM = "message";
|
||||
// What the setup can send a notification to. `name` is the label for the field
|
||||
// the person names, on the kinds that have one.
|
||||
@@ -57,7 +64,7 @@ export async function openLoopSetup(spec) {
|
||||
const dir = spec.dir;
|
||||
page.loopStart = null;
|
||||
page.loopNotifyTest = null;
|
||||
page.loopSetup = { spec: dir, loaded: false, failed: false, form: null, facts: null, problems: [], starting: false };
|
||||
page.loopSetup = { spec: dir, loaded: false, failed: false, form: null, facts: null, problems: [], starting: false, resolvedFor: undefined };
|
||||
tellApp("loop-facts");
|
||||
redraw();
|
||||
const mine = page.loopSetup;
|
||||
@@ -80,7 +87,7 @@ export async function openLoopSetup(spec) {
|
||||
redraw();
|
||||
return;
|
||||
}
|
||||
const { phasesLeft, branch, pending, suggestedQuickCheck, remembered, saved, ...setup } = answer;
|
||||
const { phasesLeft, branch, pending, suggestedQuickCheck, remembered, saved, picks, resolved, ...setup } = answer;
|
||||
mine.form = {
|
||||
review: setup.review !== false,
|
||||
fixMode: setup.fixMode === "levels" ? "levels" : "smart",
|
||||
@@ -94,18 +101,86 @@ export async function openLoopSetup(spec) {
|
||||
notifyKind: NOTIFY_KINDS.some((k) => k.id === setup.notifyKind) ? setup.notifyKind : "query",
|
||||
notifyUrl: typeof setup.notifyUrl === "string" ? setup.notifyUrl : "",
|
||||
notifyParam: setup.notifyParam || DEFAULT_NOTIFY_PARAM,
|
||||
phaseStrength: setup.phaseStrength === true,
|
||||
// Every spec's picks, as saved; only this spec's key is changed here.
|
||||
strengths: setup.strengths && typeof setup.strengths === "object" && !Array.isArray(setup.strengths) ? structuredClone(setup.strengths) : {},
|
||||
};
|
||||
if (Array.isArray(picks)) mine.form.strengths[dir] = structuredClone(picks);
|
||||
// A first visit with nothing typed starts from the project's own check.
|
||||
if (!remembered && !mine.form.quickCheck && suggestedQuickCheck) mine.form.quickCheck = suggestedQuickCheck;
|
||||
mine.facts = {
|
||||
spec: dir,
|
||||
phasesLeft: Array.isArray(phasesLeft) ? phasesLeft : [],
|
||||
branch: typeof branch === "string" ? branch : "",
|
||||
pending: Number.isInteger(pending) ? pending : null,
|
||||
// The loop agent's strengths: undefined until the app has named the agent
|
||||
// and the console has answered, then null (no such agent) or { word: { model, effort? } }.
|
||||
resolved: undefined,
|
||||
};
|
||||
mine.loaded = true;
|
||||
redraw();
|
||||
}
|
||||
|
||||
const loopAgent = () => (page.loopFacts && typeof page.loopFacts.agent === "string" ? page.loopFacts.agent : "");
|
||||
|
||||
/**
|
||||
* Read the loop agent's strengths once the app has said which agent it is. The
|
||||
* setup and the app answer in either order, so every draw asks (cheaply) whether
|
||||
* the agent changed since the last read.
|
||||
*/
|
||||
function ensureResolved(s) {
|
||||
if (!page.loopFacts || s.resolvedFor === loopAgent()) return;
|
||||
const agent = loopAgent();
|
||||
s.resolvedFor = agent;
|
||||
if (!agent) {
|
||||
s.facts.resolved = null;
|
||||
return;
|
||||
}
|
||||
fetch("/loop-setup?spec=" + encodeURIComponent(s.spec) + "&agent=" + encodeURIComponent(agent), { cache: "no-store" })
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.catch(() => null)
|
||||
.then((answer) => {
|
||||
if (page.loopSetup !== s || s.resolvedFor !== agent) return;
|
||||
s.facts.resolved = answer && answer.resolved && typeof answer.resolved === "object" ? answer.resolved : null;
|
||||
redraw();
|
||||
});
|
||||
}
|
||||
|
||||
const hasMapping = (resolved) => Boolean(resolved) && Object.keys(resolved).length > 0;
|
||||
|
||||
/** This spec's saved word for a phase, or "" for Match my session. */
|
||||
function pickOf(form, spec, phase) {
|
||||
const list = form.strengths && form.strengths[spec];
|
||||
const hit = Array.isArray(list) ? list.find((p) => p.n === phase.n && p.name === phase.name) : null;
|
||||
return hit ? hit.strength : "";
|
||||
}
|
||||
|
||||
function setPick(form, spec, phase, word) {
|
||||
const rest = (form.strengths[spec] || []).filter((p) => p.n !== phase.n);
|
||||
if (word) rest.push({ n: phase.n, name: phase.name, strength: word });
|
||||
rest.sort((a, b) => a.n - b.n);
|
||||
form.strengths[spec] = rest;
|
||||
}
|
||||
|
||||
/** The phases left whose saved pick is not mapped for the loop's agent. */
|
||||
function unmappedPicks(form, facts, spec) {
|
||||
const resolved = facts.resolved;
|
||||
return facts.phasesLeft.filter((p) => {
|
||||
const word = pickOf(form, spec, p);
|
||||
return word && !(resolved && resolved[word]);
|
||||
});
|
||||
}
|
||||
|
||||
/** "sonnet, low": what a pick becomes. Match my session shows the launch choice. */
|
||||
export function pickModelText(resolved, word, appFacts) {
|
||||
if (!word) {
|
||||
if (!appFacts) return "";
|
||||
return [appFacts.model || "default model", appFacts.effort].filter(Boolean).join(", ");
|
||||
}
|
||||
const row = resolved && resolved[word];
|
||||
return row ? [row.model, row.effort].filter(Boolean).join(", ") : "";
|
||||
}
|
||||
|
||||
function close() {
|
||||
page.loopSetup = null;
|
||||
page.loopStart = null;
|
||||
@@ -125,6 +200,13 @@ export function startBlock(form, facts, appFacts) {
|
||||
if (appFacts.permissionMode === "checked") return "The loop needs permission checks off. Start a New Session with checks off first.";
|
||||
if (appFacts.promptSupport === false) return "This agent cannot be started with a first prompt.";
|
||||
if (!facts.phasesLeft.length) return "Nothing left to build in this spec.";
|
||||
// A saved pick the agent no longer maps holds Start until it is changed (FR-14).
|
||||
// An agent with nothing mapped grays the section instead, and its picks do not count.
|
||||
if (form.phaseStrength && facts.resolved === undefined) return "Asking the app...";
|
||||
if (form.phaseStrength && hasMapping(facts.resolved)) {
|
||||
const bad = unmappedPicks(form, facts, facts.spec);
|
||||
if (bad.length) return `Pick a new strength for ${bad.map((p) => `Phase ${p.n}`).join(", ")}: not mapped for this agent.`;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
@@ -256,8 +338,91 @@ export function renderLoopSetup(main) {
|
||||
main.appendChild(pane);
|
||||
}
|
||||
|
||||
/** A plain select: [value, text, disabled?] options, the chosen value, a change handler. */
|
||||
function select(id, label, options, value, onChange) {
|
||||
const box = el("select", "loop-select");
|
||||
box.id = id;
|
||||
box.setAttribute("aria-label", label);
|
||||
for (const [v, text, disabled] of options) {
|
||||
const o = el("option", null, text);
|
||||
o.value = v;
|
||||
o.disabled = Boolean(disabled);
|
||||
box.appendChild(o);
|
||||
}
|
||||
box.value = value;
|
||||
box.addEventListener("change", () => onChange(box.value));
|
||||
return box;
|
||||
}
|
||||
|
||||
/** The "Strength per phase" field: the toggle, Set all to, and one row per phase left. */
|
||||
function strengthField(s, redo) {
|
||||
const f = s.form;
|
||||
const resolved = s.facts.resolved;
|
||||
const box = field("Strength per phase");
|
||||
const mapped = hasMapping(resolved);
|
||||
const loading = resolved === undefined;
|
||||
const off = !loading && !mapped;
|
||||
const sw = toggle("loop-phase-strength", "Set strength per phase", f.phaseStrength && !off, (v) => ((f.phaseStrength = v), redo()));
|
||||
if (off) {
|
||||
sw.classList.add("is-gray");
|
||||
sw.querySelector("input").disabled = true;
|
||||
}
|
||||
box.appendChild(sw);
|
||||
if (off) {
|
||||
const line = el("p", "loop-hint loop-strength-none");
|
||||
line.append("This agent has no strengths mapped yet. ");
|
||||
const link = el("button", "linky", "Map them in Agents & models");
|
||||
link.type = "button";
|
||||
link.addEventListener("click", () => hooks.openPrefs("agents"));
|
||||
line.appendChild(link);
|
||||
box.appendChild(line);
|
||||
return box;
|
||||
}
|
||||
if (loading) {
|
||||
box.appendChild(el("p", "loop-hint", "Asking the app which agent this loop uses..."));
|
||||
return box;
|
||||
}
|
||||
if (!f.phaseStrength) return box;
|
||||
|
||||
// An unmapped word stays in the list, grayed, so a saved one is seen and changed.
|
||||
const options = [
|
||||
["", MATCH_SESSION],
|
||||
...STRENGTH_WORDS.map(([word, label]) => [word, resolved[word] ? label : label + " (not mapped)", !resolved[word]]),
|
||||
];
|
||||
const all = el("div", "loop-strength-all");
|
||||
all.appendChild(el("label", "loop-strength-label", "Set all to"));
|
||||
all.firstChild.htmlFor = "loop-strength-all";
|
||||
const everyone = select("loop-strength-all", "Set all phases to", [["-", "Choose..."], ...options.map(([v, t, d]) => [v === "" ? "match" : v, t, d])], "-", (v) => {
|
||||
if (v === "-") return;
|
||||
for (const p of s.facts.phasesLeft) setPick(f, s.spec, p, v === "match" ? "" : v);
|
||||
redraw();
|
||||
});
|
||||
all.appendChild(everyone);
|
||||
box.appendChild(all);
|
||||
|
||||
const rows = el("div", "loop-strength-rows");
|
||||
for (const p of s.facts.phasesLeft) {
|
||||
const word = pickOf(f, s.spec, p);
|
||||
const row = el("div", "loop-strength-row");
|
||||
row.dataset.phase = String(p.n);
|
||||
row.appendChild(el("span", "loop-strength-phase", `Phase ${p.n}: ${p.name}`));
|
||||
row.appendChild(
|
||||
select(`loop-strength-${p.n}`, `Phase ${p.n} strength`, options, word, (v) => {
|
||||
setPick(f, s.spec, p, v);
|
||||
s.problems = [];
|
||||
redraw();
|
||||
})
|
||||
);
|
||||
row.appendChild(el("span", "loop-strength-model", pickModelText(resolved, word, page.loopFacts)));
|
||||
rows.appendChild(row);
|
||||
}
|
||||
box.appendChild(rows);
|
||||
return box;
|
||||
}
|
||||
|
||||
function drawBody(pane, s) {
|
||||
const f = s.form;
|
||||
ensureResolved(s);
|
||||
const redo = () => {
|
||||
s.problems = [];
|
||||
redraw();
|
||||
@@ -287,6 +452,8 @@ function drawBody(pane, s) {
|
||||
// The fields (FR-2, FR-4).
|
||||
const form = el("div", "loop-form");
|
||||
|
||||
form.appendChild(strengthField(s, redo));
|
||||
|
||||
const review = field("Review");
|
||||
review.appendChild(toggle("loop-review", "Review each phase with a fresh agent before it counts", f.review, (v) => ((f.review = v), redo())));
|
||||
form.appendChild(review);
|
||||
@@ -503,9 +670,19 @@ function gitButton() {
|
||||
return b;
|
||||
}
|
||||
|
||||
/** The form as the console saves it. */
|
||||
function setupBody(f) {
|
||||
return { ...f, quickCheck: f.quickCheck.trim(), notifyUrl: f.notifyUrl.trim(), notifyParam: f.notifyParam.trim() || DEFAULT_NOTIFY_PARAM };
|
||||
/** The form as the console saves it (exported for the page tests). */
|
||||
export function setupBody(f, s) {
|
||||
const body = { ...f, quickCheck: f.quickCheck.trim(), notifyUrl: f.notifyUrl.trim(), notifyParam: f.notifyParam.trim() || DEFAULT_NOTIFY_PARAM };
|
||||
// Only this spec's key changes: its rows that are not Match my session. With the
|
||||
// toggle off, or an agent with nothing mapped, the saved picks stay as they are
|
||||
// but the loop is told nothing about strengths (NFR-3).
|
||||
const strengths = structuredClone(f.strengths || {});
|
||||
const mine = (strengths[s.spec] || []).filter((p) => p.strength);
|
||||
if (mine.length) strengths[s.spec] = mine;
|
||||
else delete strengths[s.spec];
|
||||
body.strengths = strengths;
|
||||
body.phaseStrength = f.phaseStrength && hasMapping(s.facts.resolved);
|
||||
return body;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -519,7 +696,7 @@ async function sendTest(s) {
|
||||
s.problems = [];
|
||||
page.loopNotifyTest = { waiting: true };
|
||||
redraw();
|
||||
const { status, body: answer } = await postJson("/loop-setup", setupBody(f));
|
||||
const { status, body: answer } = await postJson("/loop-setup", setupBody(f, s));
|
||||
if (page.loopSetup !== s) return;
|
||||
if (status !== 200 || !answer || answer.ok !== true) {
|
||||
page.loopNotifyTest = null;
|
||||
@@ -537,7 +714,7 @@ async function startLoop(s) {
|
||||
page.loopStart = null;
|
||||
s.starting = true;
|
||||
redraw();
|
||||
const { status, body: answer } = await postJson("/loop-setup", setupBody(f));
|
||||
const { status, body: answer } = await postJson("/loop-setup", setupBody(f, s));
|
||||
if (page.loopSetup !== s) return;
|
||||
if (status !== 200 || !answer || answer.ok !== true) {
|
||||
s.starting = false;
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
// The loop's strength rule, shared by the page and the server (strengths.mjs re-exports it).
|
||||
// Turns Thrifty, Balanced and Best into a model (and effort) for one agent. Pure functions, no file reads: the caller passes the
|
||||
// shipped and user mappings (the `strengths` key of models.json) and the
|
||||
// agent's Models list. Held to scripts/fixtures/strength-cases.json; the Rust
|
||||
// twin is `resolve_strengths` / `next_strength` in
|
||||
// plan2code-app/src-tauri/src/models.rs, held to the same file.
|
||||
|
||||
export const STRENGTH_ORDER = ["thrifty", "balanced", "best"];
|
||||
const EFFORTS = ["low", "medium", "high"];
|
||||
|
||||
// One row as the resolver keeps it, or null when the row is not usable: the
|
||||
// model must be a string in `models`; an effort survives only when the agent
|
||||
// takes one and it is low, medium or high.
|
||||
function validRow(row, models, hasEffort) {
|
||||
if (!row || typeof row !== "object" || Array.isArray(row)) return null;
|
||||
if (typeof row.model !== "string" || !models.includes(row.model)) return null;
|
||||
const out = { model: row.model };
|
||||
if (hasEffort && EFFORTS.includes(row.effort)) out.effort = row.effort;
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* { thrifty?, balanced?, best? } for one agent: per word the user's row if it is
|
||||
* valid, else the shipped row if it is valid. A word with neither is left out
|
||||
* (unmapped).
|
||||
*/
|
||||
export function resolveStrengths({ shipped, user, models, hasEffort } = {}) {
|
||||
const list = Array.isArray(models) ? models : [];
|
||||
const obj = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {});
|
||||
const resolved = {};
|
||||
for (const word of STRENGTH_ORDER) {
|
||||
const row = validRow(obj(user)[word], list, !!hasEffort) || validRow(obj(shipped)[word], list, !!hasEffort);
|
||||
if (row) resolved[word] = row;
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
/** The first mapped word after `word` in STRENGTH_ORDER, else null. */
|
||||
export function nextStrength(resolved, word) {
|
||||
const at = STRENGTH_ORDER.indexOf(word);
|
||||
if (at < 0) return null;
|
||||
const have = resolved && typeof resolved === "object" ? resolved : {};
|
||||
for (const next of STRENGTH_ORDER.slice(at + 1)) if (have[next]) return next;
|
||||
return null;
|
||||
}
|
||||
@@ -155,3 +155,13 @@
|
||||
.split { grid-template-columns: 1fr; }
|
||||
.split-list { border-right: 0; border-bottom: 1px solid var(--rule); max-height: 260px; overflow: auto; }
|
||||
}
|
||||
|
||||
/* ------------------------------------------------- strengths in the loop */
|
||||
|
||||
.strength-body { display: grid; gap: 6px; }
|
||||
.strength-row { display: grid; grid-template-columns: 5.5em minmax(0, 1fr) auto; gap: 6px; align-items: center; }
|
||||
.strength-row:has(select + select) { grid-template-columns: 5.5em minmax(0, 1fr) minmax(0, 8em) auto; }
|
||||
.strength-row select { min-width: 0; }
|
||||
.strength-word { font-size: 0.9em; }
|
||||
.strength-default { margin: 0; font-size: 0.8em; color: var(--ink-3); }
|
||||
.strength-empty, .strength-offer { margin: 0; }
|
||||
@@ -629,6 +629,15 @@
|
||||
.loop-radios { display: grid; gap: 6px; }
|
||||
.loop-radio-body { display: grid; gap: 1px; }
|
||||
.loop-radio-detail { font-size: 12.5px; color: var(--ink-3); }
|
||||
.loop-switch.is-gray { opacity: 0.55; cursor: default; }
|
||||
.loop-strength-none .linky { font-size: inherit; }
|
||||
.loop-strength-all { display: flex; align-items: center; gap: 10px; margin-top: 4px; font-size: 13px; color: var(--ink-2); }
|
||||
.loop-strength-rows { display: grid; gap: 6px; }
|
||||
.loop-strength-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(150px, 190px) minmax(70px, 120px); align-items: center; gap: 10px; font-size: 13.5px; }
|
||||
.loop-strength-phase { overflow-wrap: anywhere; color: var(--ink); }
|
||||
.loop-strength-model { font-size: 12.5px; color: var(--ink-3); overflow-wrap: anywhere; }
|
||||
.loop-select { font: inherit; font-size: 13.5px; padding: 5px 8px; color: var(--ink); background: var(--panel-2); border: 1px solid var(--rule); border-radius: 6px; max-width: 100%; }
|
||||
@media (max-width: 560px) { .loop-strength-row { grid-template-columns: 1fr 1fr; } .loop-strength-phase { grid-column: 1 / -1; } }
|
||||
.loop-ticks { display: flex; flex-wrap: wrap; gap: 6px 18px; margin-left: 4px; }
|
||||
.loop-text { font: inherit; font-size: 14px; padding: 6px 10px; color: var(--ink); background: var(--panel-2); border: 1px solid var(--rule); border-radius: 6px; max-width: 520px; width: 100%; }
|
||||
.loop-text.loop-narrow { width: 90px; }
|
||||
|
||||
+144
-16
@@ -35,6 +35,7 @@ import { SHOTS_DIR_NAME, SHOT_NAME, shotType } from "./patches.mjs";
|
||||
import { appendChat, currentConversation, pendingChatCount, typedCount } from "./inbox.mjs";
|
||||
import { specKey } from "./workspace.mjs";
|
||||
import { readLoopSetup, saveLoopSetup } from "./loop-setup.mjs";
|
||||
import { resolveStrengths } from "./strengths.mjs";
|
||||
import { MARKERS, phaseChecklist } from "./spec-files.mjs";
|
||||
import {
|
||||
PR_HOST_KINDS,
|
||||
@@ -612,6 +613,79 @@ function cleanModels(input) {
|
||||
return { models };
|
||||
}
|
||||
|
||||
// The loop's strength words and the efforts a mapping may carry (strengths.mjs).
|
||||
const STRENGTH_WORDS = ["thrifty", "balanced", "best"];
|
||||
const STRENGTH_EFFORTS = ["low", "medium", "high"];
|
||||
|
||||
// Agent ids a strengths mapping may name: the shipped built-ins plus the ids of
|
||||
// the person's own added agents.
|
||||
function strengthAgentIds() {
|
||||
const ids = new Set(modelClis());
|
||||
try {
|
||||
const raw = fs.existsSync(USER_AGENTS_FILE) ? readText(USER_AGENTS_FILE) : undefined;
|
||||
for (const a of normalizeAgents(raw).agents) if (a && typeof a.id === "string" && a.id) ids.add(a.id);
|
||||
} catch {
|
||||
// A broken agents file adds no ids; the built-ins still map.
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* The user's strengths mapping: { <agent id>: { thrifty|balanced|best: { model, effort? } } }.
|
||||
* Returns { strengths } or { error } naming the field. Only known agent ids, the three
|
||||
* words, a model matching MODEL_ID and an effort of low, medium or high survive; an
|
||||
* agent left with no row is dropped.
|
||||
*/
|
||||
function cleanStrengths(input) {
|
||||
if (input == null) return { strengths: {} };
|
||||
if (typeof input !== "object" || Array.isArray(input)) return { error: "strengths must be an object" };
|
||||
const known = strengthAgentIds();
|
||||
const strengths = {};
|
||||
for (const [agent, rows] of Object.entries(input)) {
|
||||
if (!known.has(agent)) return { error: `strengths.${agent}: not a known agent` };
|
||||
if (!rows || typeof rows !== "object" || Array.isArray(rows)) return { error: `strengths.${agent} must be an object` };
|
||||
const out = {};
|
||||
for (const [word, row] of Object.entries(rows)) {
|
||||
if (!STRENGTH_WORDS.includes(word)) return { error: `strengths.${agent}.${word}: not a strength (thrifty, balanced or best)` };
|
||||
if (!row || typeof row !== "object" || Array.isArray(row)) return { error: `strengths.${agent}.${word} must be an object` };
|
||||
const model = typeof row.model === "string" ? row.model.trim() : "";
|
||||
if (!MODEL_ID.test(model)) return { error: `strengths.${agent}.${word}.model: "${model}" is not a valid model id` };
|
||||
const entry = { model };
|
||||
if (row.effort != null && row.effort !== "") {
|
||||
if (!STRENGTH_EFFORTS.includes(row.effort)) return { error: `strengths.${agent}.${word}.effort: must be low, medium or high` };
|
||||
entry.effort = row.effort;
|
||||
}
|
||||
out[word] = entry;
|
||||
}
|
||||
if (Object.keys(out).length) strengths[agent] = out;
|
||||
}
|
||||
return { strengths };
|
||||
}
|
||||
|
||||
// Strengths from a models file that was read from disk. Tolerant, unlike a POST body:
|
||||
// an agent that is no longer known (a deleted custom agent) or whose rows are bad is
|
||||
// skipped on its own, so it never hides or wipes the other agents' mapping.
|
||||
function savedStrengths(file) {
|
||||
const saved = file && file.strengths;
|
||||
if (!saved || typeof saved !== "object" || Array.isArray(saved)) return {};
|
||||
const out = {};
|
||||
for (const [agent, rows] of Object.entries(saved)) {
|
||||
if (!rows || typeof rows !== "object" || Array.isArray(rows)) continue;
|
||||
// Row by row, like the app: a bad row is dropped, a bad effort is dropped and
|
||||
// its row stays, and the agent keeps every other row.
|
||||
const kept = {};
|
||||
for (const [word, row] of Object.entries(rows)) {
|
||||
let one = cleanStrengths({ [agent]: { [word]: row } });
|
||||
if (!one.strengths && row && typeof row === "object" && !Array.isArray(row) && row.effort != null) {
|
||||
one = cleanStrengths({ [agent]: { [word]: { model: row.model } } });
|
||||
}
|
||||
if (one.strengths && one.strengths[agent]) Object.assign(kept, one.strengths[agent]);
|
||||
}
|
||||
if (Object.keys(kept).length) out[agent] = kept;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function shippedModels() {
|
||||
const file = readJson(SHIPPED_MODELS_FILE, null) || {};
|
||||
const out = {};
|
||||
@@ -625,7 +699,12 @@ function shippedModels() {
|
||||
function modelsGet(req, res) {
|
||||
const saved = readJson(USER_MODELS_FILE, null) || {};
|
||||
const { models } = cleanModels(saved);
|
||||
return json(res, 200, { shipped: shippedModels(), user: models || Object.fromEntries(modelClis().map((cli) => [cli, []])) });
|
||||
const shippedFile = readJson(SHIPPED_MODELS_FILE, null) || {};
|
||||
return json(res, 200, {
|
||||
shipped: shippedModels(),
|
||||
user: models || Object.fromEntries(modelClis().map((cli) => [cli, []])),
|
||||
strengths: { shipped: savedStrengths(shippedFile), user: savedStrengths(saved) },
|
||||
});
|
||||
}
|
||||
|
||||
function modelsPost(req, res) {
|
||||
@@ -633,13 +712,22 @@ function modelsPost(req, res) {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const { models, error } = cleanModels(body && body.models);
|
||||
if (error) return json(res, 400, { error });
|
||||
// A body without strengths keeps the mapping already saved, so saving a Models list never wipes it.
|
||||
let strengths;
|
||||
if (body && body.strengths !== undefined) {
|
||||
const cleaned = cleanStrengths(body.strengths);
|
||||
if (cleaned.error) return json(res, 400, { error: cleaned.error });
|
||||
strengths = cleaned.strengths;
|
||||
} else {
|
||||
strengths = savedStrengths(readJson(USER_MODELS_FILE, null));
|
||||
}
|
||||
try {
|
||||
ensureDir(path.dirname(USER_MODELS_FILE));
|
||||
writeJsonAtomic(USER_MODELS_FILE, models);
|
||||
writeJsonAtomic(USER_MODELS_FILE, Object.keys(strengths).length ? { ...models, strengths } : models);
|
||||
} catch (e) {
|
||||
return json(res, 500, { error: String(e.message) });
|
||||
}
|
||||
return json(res, 200, { ok: true, user: models });
|
||||
return json(res, 200, { ok: true, user: models, strengths });
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1492,22 +1580,60 @@ const loopProject = (ctx) => (ctx.readState() || {}).project || ctx.project || c
|
||||
// `?spec=specs/<name>` adds the setup screen's read-only facts (FR-3): the
|
||||
// phases not yet marked done, the branch and the count of uncommitted files.
|
||||
// The server reads the project here and never writes it.
|
||||
// The phases of `spec` not yet done, as [{ n, name }]; null when its overview.md
|
||||
// cannot be read (the store then keeps that spec's picks as they are).
|
||||
function phasesLeftOf(project, spec) {
|
||||
try {
|
||||
const overview = fs.readFileSync(path.join(project, spec, "overview.md"), "utf8");
|
||||
// Done as specs.mjs reads it ([x], [X], [?]), the same rule the app's Start uses.
|
||||
return phaseChecklist(overview)
|
||||
.filter((p) => !["complete", "assumed"].includes(MARKERS[p.marker]))
|
||||
.map((p) => ({ n: p.number, name: p.name }));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Agents that take an effort beside the model (the Preferences page's HAS_EFFORT).
|
||||
const EFFORT_AGENTS = ["claude", "codex"];
|
||||
|
||||
/**
|
||||
* The loop agent's resolved strengths ({ thrifty?, balanced?, best? }, each { model, effort? })
|
||||
* for `?agent=<id>`: a built-in's Models list is what ships plus what the person added; an
|
||||
* added agent's is its own. null when the id is neither.
|
||||
*/
|
||||
function resolvedStrengthsFor(agentId) {
|
||||
if (typeof agentId !== "string" || !agentId) return null;
|
||||
const shippedFile = readJson(SHIPPED_MODELS_FILE, null) || {};
|
||||
const savedFile = readJson(USER_MODELS_FILE, null) || {};
|
||||
let models;
|
||||
let hasEffort = false;
|
||||
if (modelClis().includes(agentId)) {
|
||||
const user = cleanModels(savedFile).models || {};
|
||||
models = [...(shippedModels()[agentId] || []), ...(user[agentId] || [])].map((m) => m.id);
|
||||
hasEffort = EFFORT_AGENTS.includes(agentId);
|
||||
} else {
|
||||
const raw = fs.existsSync(USER_AGENTS_FILE) ? readText(USER_AGENTS_FILE) : undefined;
|
||||
let found = null;
|
||||
try {
|
||||
found = normalizeAgents(raw).agents.find((a) => a && a.id === agentId) || null;
|
||||
} catch {
|
||||
found = null;
|
||||
}
|
||||
if (!found) return null;
|
||||
models = (Array.isArray(found.models) ? found.models : []).map((m) => m.id);
|
||||
}
|
||||
const owned = (file) => savedStrengths(file)[agentId] || {};
|
||||
return resolveStrengths({ shipped: owned(shippedFile), user: owned(savedFile), models, hasEffort });
|
||||
}
|
||||
|
||||
function loopSetupGet(req, res, ctx, url) {
|
||||
const answer = readLoopSetup(loopProject(ctx));
|
||||
const answer = readLoopSetup(loopProject(ctx), (s) => phasesLeftOf(loopProject(ctx), s));
|
||||
const spec = url && url.searchParams.get("spec");
|
||||
if (spec === null || spec === undefined) return json(res, 200, answer);
|
||||
if (!/^specs\/[^/\\]+$/.test(spec) || /^specs\/\./.test(spec)) return json(res, 400, { error: "spec must be a folder directly under specs/" });
|
||||
const state = ctx.readState() || {};
|
||||
let phasesLeft = [];
|
||||
try {
|
||||
const overview = fs.readFileSync(path.join(loopProject(ctx), spec, "overview.md"), "utf8");
|
||||
// Done as specs.mjs reads it ([x], [X], [?]), the same rule the app's Start uses.
|
||||
phasesLeft = phaseChecklist(overview)
|
||||
.filter((p) => !["complete", "assumed"].includes(MARKERS[p.marker]))
|
||||
.map((p) => ({ n: p.number, name: p.name }));
|
||||
} catch {
|
||||
/* no overview.md: nothing to build */
|
||||
}
|
||||
const phasesLeft = phasesLeftOf(loopProject(ctx), spec) || [];
|
||||
const pending = state.scan && Number.isInteger(state.scan.pending) ? state.scan.pending : null;
|
||||
// What to prefill an empty quick check with: the project's own build, then
|
||||
// lint, script. Text only; nothing here runs it.
|
||||
@@ -1519,7 +1645,9 @@ function loopSetupGet(req, res, ctx, url) {
|
||||
} catch {
|
||||
/* no package.json, or not JSON: no suggestion */
|
||||
}
|
||||
return json(res, 200, { ...answer, phasesLeft, branch: state.branch || "", pending, suggestedQuickCheck });
|
||||
const agent = url.searchParams.get("agent");
|
||||
const picks = Array.isArray(answer.strengths[spec]) ? answer.strengths[spec] : [];
|
||||
return json(res, 200, { ...answer, phasesLeft, branch: state.branch || "", pending, suggestedQuickCheck, picks, resolved: resolvedStrengthsFor(agent) });
|
||||
}
|
||||
|
||||
function loopSetupPost(req, res, ctx) {
|
||||
@@ -1527,7 +1655,7 @@ function loopSetupPost(req, res, ctx) {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { ok: false, problems: ["the setup must be a JSON object"] });
|
||||
try {
|
||||
return json(res, 200, { ok: true, setup: saveLoopSetup(loopProject(ctx), body) });
|
||||
return json(res, 200, { ok: true, setup: saveLoopSetup(loopProject(ctx), body, (s) => phasesLeftOf(loopProject(ctx), s)) });
|
||||
} catch (e) {
|
||||
if (Array.isArray(e.problems)) return json(res, 400, { ok: false, problems: e.problems });
|
||||
return json(res, 500, { error: String(e.message) });
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import path from "node:path";
|
||||
|
||||
import { cleanSetting, defaultSetting, DEFAULT_STRENGTH, offered } from "./public/subagents.js";
|
||||
import { cleanSetting, defaultSetting, DEFAULT_STRENGTH, offered, STRENGTHS } from "./public/subagents.js";
|
||||
import { ensureDir, fileStamp, HOME_DIR, readJson, readJsonLines, withStateLock, writeJsonAtomic } from "./files.mjs";
|
||||
import { foldKey } from "./workspace.mjs";
|
||||
|
||||
@@ -174,7 +174,12 @@ export function serverSubagents(ctx) {
|
||||
function sync(state) {
|
||||
if (!state || typeof state.workflow !== "string") return;
|
||||
const { workflow } = state;
|
||||
const { on, instruction, max, strength } = offered(workflow) ? subagentStoreEntry(ctx.worktree(), workflow) : defaultSetting(workflow);
|
||||
const stored = offered(workflow) ? subagentStoreEntry(ctx.worktree(), workflow) : defaultSetting(workflow);
|
||||
// A loop phase on a strength runs its helpers at that strength, for this
|
||||
// session only: the stored setting is read, never written (FR-16).
|
||||
const loopStrength = state.loop && state.loop.strength;
|
||||
const { on, instruction, max } = stored;
|
||||
const strength = STRENGTHS.includes(loopStrength) ? loopStrength : stored.strength;
|
||||
const target = { workflow, on, instruction, max, strength };
|
||||
const current = readSubagentSetting(dir);
|
||||
if (current && sameSetting(current, target)) return;
|
||||
|
||||
@@ -34,6 +34,7 @@ export const SERVABLE = new Set([
|
||||
"sound.js",
|
||||
"looks.js",
|
||||
"selectors.js",
|
||||
"strengths.js",
|
||||
"app.css",
|
||||
"render.js",
|
||||
"palette.js",
|
||||
@@ -75,6 +76,7 @@ export const SERVABLE = new Set([
|
||||
"screens/agents/agents-list-editor.js",
|
||||
"screens/agents/agents-summary.js",
|
||||
"screens/agents/agents-form.js",
|
||||
"screens/agents/agents-strengths.js",
|
||||
"screens/prefs-dialog.js",
|
||||
"screens/cleanup.js",
|
||||
"screens/help-dialog.js",
|
||||
@@ -110,6 +112,8 @@ export const SERVABLE = new Set([
|
||||
"activities/bumper-draw.js",
|
||||
"activities/rapids.js",
|
||||
"activities/rapids-draw.js",
|
||||
"activities/flock.js",
|
||||
"activities/flock-draw.js",
|
||||
"activities/fuse.js",
|
||||
"activities/fuse-draw.js",
|
||||
"activities/hop.js",
|
||||
@@ -232,6 +236,7 @@ export const SERVABLE = new Set([
|
||||
"activities/stack-sfx.js",
|
||||
"activities/bumper-sfx.js",
|
||||
"activities/rapids-sfx.js",
|
||||
"activities/flock-sfx.js",
|
||||
"activities/fuse-sfx.js",
|
||||
"activities/hop-sfx.js",
|
||||
"activities/bounce-sfx.js",
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
// The server-side name for the strength rule. The code lives in public/strengths.js
|
||||
// so the Preferences page imports the very same module; see that file's header.
|
||||
export { STRENGTH_ORDER, nextStrength, resolveStrengths } from "./public/strengths.js";
|
||||
Reference in new issue
Block a user