SLOPSHOPPER

Modster Hunter

Catch Modsters while you wait for Claude.

panebandspinnercommandtoaststatus
★ 1v0.1.2MITupdated 2026-10-23danielpg95/modster-hunter/plugin
A shopper browsing a rack in a slop shop
README

Modster Hunter

Catch Modsters while you wait for Claude.

<table align="center"> <tr> <td align="center" width="50%"> <img src="docs/previews/readme-musketail.gif" alt="Musketail, a mouse in a feathered hat and leaf cloak, raising a pine-needle sword" height="160"><br> <b>Musketail</b><br> <sub>It picks a fresh leaf cloak each season. Autumn ones are its favorite, because red looks heroic.</sub> </td> <td align="center" width="50%"> <img src="docs/previews/readme-lamparito.gif" alt="Lamparito, a grinning purple smoke spirit rising from a brass lamp" height="160"><br> <b>Lamparito</b><br> <sub>A spirit of hot smoke that sleeps in a brass lamp half-buried in the sand. It offers every traveler three wishes and twists every one of them. Its grin is the only part of it that is never smoke.</sub> </td> </tr> </table>

Modster Hunter is a Claude Code mod: a tiny collecting game that lives in your terminal, right above the prompt.

You ask Claude for something. While it works, a wild Modster wanders into view. Press 1 to throw. You get a few tries before it gets bored and leaves. When Claude is done, the game steps aside and you get back to work.

Biomes

Each session drops you into one biome at random, each with its own Modsters:

🌲 Whispering Forest: tall pines, soft moss, something rustling.

<img src="docs/previews/readme-whispering-forest.gif" alt="The Whispering Forest: dusk pines with leaves drifting by" width="600">

💎 Crystal Grotto: whisper here and the crystals whisper back, a little out of tune.

<img src="docs/previews/readme-crystal-grotto.gif" alt="The Crystal Grotto: pink and cyan crystals glinting in a dark cave" width="600">

Two more are out there for you to find.

Catchers

Every throw plays a catcher. Pick yours in /modsters, on the Catchers tab:

<table align="center"> <tr> <td align="center"><img src="docs/previews/readme-catch-hootlet.gif" alt="Hootlet, a mossy owl, shrinks into a seed pod, which rocks three times and sparkles" height="128"><br><b>Seed pod</b></td> <td align="center"><img src="docs/previews/readme-catch-echobat.gif" alt="Echobat, a purple bat with crystal ears, is drawn into a brass lantern, which rocks three times and sparkles" height="128"><br><b>Lantern</b></td> <td align="center"><img src="docs/previews/readme-catch-glowcap.gif" alt="Glowcap, a blue mushroom, goes into a scrambled puzzle cube, which comes out solved" height="128"><br><b>Puzzle Cube</b></td> </tr> </table>

Install

You need Claude Code v2.1.292 or later (claude --version), in a terminal.

claude plugin install modster-hunter --marketplace danielpg95/modster-hunter

Or, inside a session: /plugin marketplace add danielpg95/modster-hunter, then /plugin install modster-hunter@modster-hunter. Start a new session and ask Claude for anything. /modsters stop turns the game off.

How to play

Key or commandWhat it does
/modsters huntStart hunting: Modsters show up while Claude works
/modsters stopStop hunting
1 / 2Throw / run while a Modster is up
/modstersYour collection, the biomes, stats, catchers and settings
/modsters paneA bigger encounter pane, for a better view
/modsters settingsEvery option: Auto start, where the game shows, and more
/modsters reloadLoad your own Modsters after you add or change them
/modsters helpEvery command

Contributing

New hands are welcome, especially pixel artists. Pitch a Modster or biome in an issue, playtest, report bugs, or pick up a task from the roadmap. CONTRIBUTING.md explains the routine. If you use Claude Code, open the repo and start with the start-session skill.

To run from source:

git clone https://github.com/danielpg95/modster-hunter.git
cd modster-hunter
claude --plugin-dir ./plugin

License

Code is under the MIT License. Built-in art and sounds are under CC BY 4.0, credited per asset in plugin/content/CREDITS.md (decision 0011).

Source 75 files
hooks/register.tsx 2121 lines
1import type { EngineInterface, Register, Timer } from 'claude-code'
2import { BAND, CATCH, COLLECTION, CONTENT, USER_CONTENT, WELCOME_TOAST_MS } from './constants'
3import {
4  cachedSheetLoader,
5  formatIssue,
6  leavesNoBiome,
7  loadAllContent,
8  noBiomesMessage,
9  toggleDisabled,
10  type ContentReader,
11  type ContentRegistry,
12  type LoadedBiome,
13  type LoadedCatcher,
14  type LoadedModster,
15  type Sprite,
16  type MergedContent,
17  type SheetFiles,
18  type ToggleChange,
19} from './content'
20import {
21  pickBiome,
22  startEncounters,
23  stepEncounter,
24  throwingMs,
25  type CatchOutcome,
26  type EncounterContext,
27  type EncounterInput,
28  type EncounterState,
29} from './game'
30import {
31  BAND_BUTTONS,
32  COLLECTION_TABS,
33  bandView,
34  biomeEntries,
35  biomeRow,
36  biomesBody,
37  catchDots,
38  catchFrame,
39  catcherEntries,
40  catcherRow,
41  previewModsterId,
42  pixelsToCells,
43  prepareCatch,
44  oddsRow,
45  tierRow,
46  tierSections,
47  collectionBody,
48  collectionEntries,
49  collectionLayout,
50  detailLines,
51  listRow,
52  listWindow,
53  moreText,
54  silhouettePalette,
55  displayPlan,
56  idleScene,
57  isAnimated,
58  makeParticles,
59  paneHint,
60  readDisplaySettings,
61  sceneCells,
62  settingsLines,
63  spriteCells,
64  statsLines,
65  TOGGLE_HOTKEY,
66  itemNotes,
67  toggleLabel,
68  type BandEncounter,
69  type BandLine,
70  type BiomeEntry,
71  type CatchArt,
72  type CatcherEntry,
73  type CollectionEntry,
74  type CollectionTab,
75  type DisplayPlan,
76  type IdleScene,
77  type Particle,
78  MODSTERS_ARGUMENT_HINT,
79  PANE_OFF_REPLY,
80  SETTING_SPECS,
81  STOP_REPLY,
82  nextSettingValue,
83  readSettingValues,
84  settingDeniedText,
85  settingRow,
86  type SettingField,
87  type SettingValue,
88  type SettingValues,
89  autoStartDeniedReply,
90  helpText,
91  huntReply,
92  unknownSubcommandText,
93  welcomeText,
94} from './render'
95import {
96  CATCHER_KEY,
97  HUNT_PANE_KEY,
98  WELCOMED_KEY,
99  readWelcomed,
100  welcomedPref,
101  catcherInUse,
102  catcherPref,
103  caughtKey,
104  compactStats,
105  huntPanePref,
106  isCaught,
107  prefAfterClose,
108  readCaughtRecord,
109  readCatcherId,
110  readHuntPaneOpen,
111  recordEncounterEvents,
112  recordStat,
113  type CaughtRecord,
114  type SessionStats,
115  type StatsStorePort,
116} from './store'
117
118// Rebuilt at every session start; cheap, so it isn't kept in $.state (ARCHITECTURE.md)
119let content: MergedContent | undefined
120// The session's biome (decision 0006). /clear, /resume and /branch don't start a
121// new process or reload the module, so it survives them as a module variable.
122let biomeId: string | undefined
123// After a reload that dropped the session's biome, its old copy plays on until the
124// encounter in progress ends; then a new biome is picked (P4-02)
125let retiredBiome: LoadedBiome | undefined
126// A reload in progress, so a second /modsters reload waits on it instead of racing it
127let reloading: Promise<Reloaded> | undefined
128// Turning items off and on (decision 0032), one at a time: each reads settings.json after the last wrote it
129let toggling: Promise<void> = Promise.resolve()
130
131// The encounter loop (decisions 0005, 0014). Not persisted: a reload or a new
132// session drops an encounter in progress without counting it (0005).
133let machine: EncounterState | undefined
134let machineContext: EncounterContext | undefined
135let tickTimer: Timer | undefined
136// The Modster as it loaded when it appeared, so a reload leaves the encounter as it was (P4-02)
137let encounterModster: LoadedModster | undefined
138
139// Collection and stats (decision 0009). Writes run one after another so this
140// session never races itself; each one re-reads its key first.
141let sessionId = 'unknown'
142let pendingWrites: Promise<void> = Promise.resolve()
143
144// How issues and messages name the user's content folder (decision 0007)
145const USER_FOLDER_LABEL = `~/${USER_CONTENT.contentFolder}/`
146
147// Sprite animation: each mounted Raster is repainted in place with $.ui.blit (0012).
148// The band and the encounter pane (0015) are "sites"; each frame is blitted to every
149// site drawing the sprite right now.
150const SPRITE_KEY = 'sprite'
151// Keyed by id, checked against the sprite it was made from: a reload may change a sprite
152const cellsByModster = new Map<string, { sprite: LoadedModster['sprite']; cells: string[] }>()
153const spriteSites = new Set<string>() // requestIds
154let frameTimer: Timer | undefined
155let frameModster: LoadedModster | undefined
156let frameIndex = 0
157let isBlitting = false
158
159// The catch animation (decision 0035): while a throw plays, its frames are blitted to
160// the same sprite sites at CATCH.fps, and the Modster's idle loop waits. The throw
161// keeps the catcher it started with. With no catcher drawn (none loaded, or one too
162// big for the sprite area) the Modster holds still and the text tells the throw (0035 point 8).
163// The picked catcher's id from `prefs:catcher`, read at session start (point 9)
164let pickedCatcherId: string | undefined
165// Keyed by catcher and Modster id, checked against what they were made from: a reload may change either
166const catchArts = new Map<string, { catcher: LoadedCatcher; modster: LoadedModster; art: CatchArt }>()
167// The throw as a dot count for the text (point 7), kept current by the tick
168let shownDots: string | undefined
169let catchPlay: { art: CatchArt; outcome: CatchOutcome; rocks: number; throwAt: number; endsAt: number } | undefined
170let catchCells: string | undefined
171let catchTimer: Timer | undefined
172let isBlittingCatch = false
173
174// The biome's idle scene between encounters (decision 0026). The band is its only
175// site; it moves only while Claude works and holds still otherwise (point 5).
176const SCENE_KEY = 'scene'
177let scene: IdleScene | undefined
178const particlesByColumns = new Map<number, Particle[]>()
179const sceneSites = new Map<string, number>() // requestId → columns
180let sceneTimer: Timer | undefined
181let sceneTick = 0
182let isBlittingScene = false
183// Why the band last skipped the scene, so the debug log notes each change once
184let loggedSceneSkip: string | undefined
185
186// The opt-in encounter pane (decision 0015), opened with `/modsters pane` (0038); it
187// reopens at session start for people who opened it (0019), or every session (0023)
188const PANE_ID = 'modster-hunt'
189
190// Where the game shows (0023). A change in /config reloads the module, so this is
191// read once per load
192let display = readDisplaySettings({})
193// Whether the game runs (decision 0038): the `autoStart` option at load, then what
194// /modsters hunt and stop wrote. While false, nothing draws outside /modsters
195let hunting = false
196// The options as the Settings tab shows them (decision 0040): read at load, then
197// what the tab, /modsters hunt and stop wrote
198let settingValues: SettingValues = readSettingValues({})
199// The Settings tab's selected row
200let settingsSelected: SettingField = 'autoStart'
201// An idle timeout changed during an encounter waits for the next one (0040 point 5)
202let pendingIdleTimeoutMs: number | undefined
203// Options the Settings tab changes in place (0040 point 5); read from the load's options in register
204let idleTimeoutSec = 90
205let showIdleLine = true
206let showIdleScene = true
207let includeBuiltins = true
208// The `includeBuiltins` option, for messages outside register's closure
209let builtinsIncluded = true
210// What the status line shows now, so a tick that changes nothing doesn't re-pin it
211let shownStatus: string | undefined
212/** The collection had the current Modster when it appeared (P5-10); read once per encounter */
213let alreadyCaught = false
214/** Bumped on every appearance, so a slow read never marks a later encounter */
215let caughtCheck = 0
216
217// The collection pane (decision 0002, P3-01), opened with `/modsters`. Separate from
218// the encounter pane (0015); Esc closes it
219const COLLECTION_PANE_ID = 'modster-collection'
220// The tab it shows; kept while the module lives, so a reopened pane shows the last one
221let collectionTab: CollectionTab = 'collection'
222// The Collection tab (P3-02). Render hooks can't wait on $.store, so the records are
223// read into memory at session start, when /modsters opens the pane, and after a catch
224const collectionRecords = new Map<string, CaughtRecord>()
225// The selected Modster's id; kept across tab switches like the tab
226let collectionSelected: string | undefined
227// The Biomes tab's selection (P3-03); none yet means the session's biome
228let biomesSelected: string | undefined
229// The Stats tab (P3-04): every session's counts summed, read when the tab shows.
230// Undefined until the first read finishes
231let statsShown: { stats: SessionStats | undefined } | undefined
232// Its sprite animates on a loop of its own: the encounter's loop follows the encounter's Modster
233const COLLECTION_SPRITE_KEY = 'collection-sprite'
234// The Catchers tab (P5-30): its selection, none yet meaning the catcher in use, and
235// a preview that loops a catch on its own timer while the tab shows it
236let catchersSelected: string | undefined
237const CATCHER_PREVIEW_KEY = 'catcher-preview'
238let catcherPreview: { requestId: string; key: string; catcher: LoadedCatcher; sprite: Sprite; art: CatchArt; tick: number; cells: string } | undefined
239let catcherPreviewTimer: Timer | undefined
240let isBlittingPreview = false
241const silhouettes = new Map<string, string>()
242let collectionSite: string | undefined
243let collectionSpriteModster: LoadedModster | undefined
244let collectionFrame = 0
245let collectionTimer: Timer | undefined
246let isBlittingCollection = false
247// The Biomes tab's scene (0028): the selected biome's, on a timer of its own that
248// runs whenever the tab draws it, apart from the band's (0026 point 5)
249const BIOMES_SCENE_KEY = 'biomes-scene'
250const biomeScenes = new Map<string, IdleScene | undefined>()
251let biomesSceneSite: { requestId: string; biomeId: string; scene: IdleScene; columns: number; particles: Particle[] } | undefined
252let biomesSceneTimer: Timer | undefined
253let biomesSceneTick = 0
254let isBlittingBiomesScene = false
255
256export const register: Register = (on, options) => {
257  idleTimeoutSec = typeof options.encounterIdleTimeoutSec === 'number' ? options.encounterIdleTimeoutSec : 90
258  showIdleLine = options.showIdleLine !== false
259  showIdleScene = options.showIdleScene !== false
260  includeBuiltins = options.includeBuiltins !== false
261  settingValues = readSettingValues(options)
262  builtinsIncluded = includeBuiltins
263  display = readDisplaySettings(options)
264  // On unless the player turned it off (decision 0041)
265  hunting = options.autoStart !== false
266
267  on('session.start', async ($, e, next) => {
268    content = await loadGameContent($, includeBuiltins)
269    biomeScenes.clear()
270    if (content.biomes.size === 0) $.ui.toast(`Modster Hunter: ${noBiomesMessage(includeBuiltins, USER_FOLDER_LABEL)}`)
271    sessionId = await $.session.id().catch(() => 'unknown')
272    // A reload (a /config change, 0040) drops module variables; $.state keeps the session's view
273    await restoreSessionState($)
274    // Keep the biome if session.start ever repeats in this process; pick only when there's none yet
275    if (biomeId === undefined || !content.biomes.has(biomeId)) biomeId = pickBiome(content.biomes.keys(), Math.random)
276    if (biomeId !== undefined) await keepState($, 'biomeId', biomeId)
277    pickedCatcherId = readCatcherId(await $.store.get(CATCHER_KEY).catch(() => undefined))
278    await welcome($)
279    if (hunting) startMachine($, idleTimeoutSec)
280    loadCollectionRecords($)
281    // Clears a line left by a load that had the status line on (0023 point 6)
282    shownStatus = undefined
283    $.ui.status(undefined)
284    // The encounter pane waits for hunting too; one left open is closed (0038 point 1)
285    if (hunting) await openHuntPaneAtStart($)
286    else await closeHuntPane($)
287    // Register last: a taken name throws and would skip the rest of this hook. Immediate, so it
288    // runs while Claude works, when people play; the command.run hook never reads the turn (0039)
289    await $.command.register({ name: 'modsters', description: 'Open your Modster collection', argumentHint: MODSTERS_ARGUMENT_HINT, immediate: true })
290    return next(e)
291  })
292
293  // /clear, /resume and /branch don't fire session.start; keep the pane for them too (0019)
294  on('classic.SessionStart', async ($, e, next) => {
295    if (e.source !== 'startup' && hunting) {
296      // They do fire session.end, which stopped the timers: start the game again
297      // on the same biome, under the new session id (P5-15)
298      if (!tickTimer && content) {
299        sessionId = await $.session.id().catch(() => 'unknown')
300        startMachine($, idleTimeoutSec)
301        shownStatus = undefined
302        $.ui.status(undefined)
303        $.ui.invalidate('ui.render')
304      }
305      await openHuntPaneAtStart($)
306    }
307    return next(e)
308  })
309
310  on('turn.start', async ($, e, next) => {
311    // No turn stats while the game is off (0038 point 1)
312    if (!hunting) return next(e)
313    await advanceMachine($, { type: 'turnStart' })
314    const at = await $.clock.now()
315    queueWrite($, (store) => recordStat(store, sessionId, { kind: 'turn', at }))
316    return next(e)
317  })
318
319  on('turn.complete', async ($, e, next) => {
320    await advanceMachine($, { type: 'turnEnd' })
321    return next(e)
322  })
323
324  // Background subagents count as work time, so Modsters can appear while you wait on them (0018)
325  on('classic.SubagentStart', async ($, e, next) => {
326    await advanceMachine($, { type: 'agentStart', agentId: e.agent_id })
327    return next(e)
328  })
329
330  on('classic.SubagentStop', async ($, e, next) => {
331    await advanceMachine($, { type: 'agentStop', agentId: e.agent_id })
332    return next(e)
333  })
334
335  on('session.end', async ($, e, next) => {
336    await advanceMachine($, { type: 'sessionEnd' })
337    stopTimers()
338    shownStatus = undefined
339    $.ui.status(undefined)
340    // Let queued writes land, within the 1.5 s session.end budget (ARCHITECTURE.md)
341    await Promise.race([pendingWrites, $.clock.sleep(1000)])
342    return next(e)
343  })
344
345  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
346    // A survey owns the band while it's up
347    if (e.props.hasSurvey) return next(e)
348    // The game is off: the band is the prompt's alone (0038 point 1)
349    if (!hunting) {
350      removeSite(e.requestId)
351      removeSceneSite(e.requestId)
352      return next(e)
353    }
354    // While the encounter pane is on screen the band steps aside, so the same
355    // encounter isn't drawn twice (0015)
356    if (await isPaneShown($)) {
357      removeSite(e.requestId)
358      removeSceneSite(e.requestId)
359      return next(e)
360    }
361    const modster = currentModster()
362    const biome = sessionBiome()?.biome
363    const band = markedEncounter()
364    const view = bandView({
365      maxRows: e.props.maxRows,
366      columns: e.props.bodyColumns,
367      // Raster is terminal only (0012; Svg for the desktop app is P5-06)
368      canDrawSprite: e.surface === 'terminal',
369      showIdleLine,
370      // The band turned off still keeps Throw on screen during an encounter (0023 point 3)
371      ...(currentPlan().band === 'one-row' ? { oneRow: true } : {}),
372      ...(band ? { encounter: band } : {}),
373      ...(biome ? { biome: biome.accentColor ? { name: biome.name, accentColor: biome.accentColor } : { name: biome.name } } : {}),
374      ...(scene && showIdleScene ? { sceneRows: scene.rows } : {}),
375    })
376
377    if (view.kind !== 'full') removeSite(e.requestId)
378    if (view.kind !== 'scene') removeSceneSite(e.requestId)
379    if (scene && showIdleScene && view.kind === 'idle') {
380      const skip = `idle scene: not drawn (surface ${e.surface}, band ${e.props.maxRows} rows, scene needs ${scene.rows + 1})`
381      if (skip !== loggedSceneSkip) {
382        loggedSceneSkip = skip
383        $.ui.log(skip, { to: 'debug' })
384      }
385    }
386    if (view.kind === 'none') return next(e)
387
388    const { Box, Text, Button } = $.ui.resolve(e)
389    const line = (segments: BandLine, index: number) => (
390      <Box key={`line-${index}`} flexDirection="row">
391        {segments.map((segment, at) =>
392          'button' in segment ? (
393            <Button
394              key={segment.button}
395              label={BAND_BUTTONS[segment.button].label}
396              hotkey={BAND_BUTTONS[segment.button].hotkey}
397              plain
398              onPress={() => {
399                void advanceMachine($, { type: segment.button })
400              }}
401            />
402          ) : (
403            <Text
404              key={`text-${at}`}
405              wrap="truncate"
406              {...(segment.bold ? { bold: true } : {})}
407              {...(segment.dim ? { dimColor: true } : {})}
408              {...(segment.color ? { color: segment.color } : {})}
409            >
410              {segment.text}
411            </Text>
412          ),
413        )}
414      </Box>
415    )
416
417    if (view.kind === 'idle') return line(view.line, 0)
418    if (view.kind === 'scene') {
419      // Chosen only on the terminal (canDrawSprite); the check narrows the surface so Raster resolves
420      if (e.surface !== 'terminal') return line(view.line, 0)
421      const { Raster } = $.ui.resolve(e)
422      const columns = e.props.bodyColumns
423      addSceneSite($, e.requestId, columns)
424      return (
425        <Box flexDirection="column">
426          <Raster key={SCENE_KEY} columns={columns} rows={view.sceneRows} cells={sceneCellsFor(columns)} />
427          {line(view.line, 0)}
428        </Box>
429      )
430    }
431    if (view.kind === 'compact') return <Box flexDirection="column">{view.lines.map(line)}</Box>
432
433    // Full layout: the sprite, then the text block beside it. Only chosen on the
434    // terminal (canDrawSprite); the check narrows the surface so Raster resolves
435    if (e.surface !== 'terminal') return next(e)
436    const { Raster } = $.ui.resolve(e)
437    const cells = modster ? cellsFor(modster) : []
438    if (modster) addSite($, e.requestId, modster)
439    return (
440      <Box flexDirection="row" columnGap={BAND.gapColumns}>
441        <Raster key={SPRITE_KEY} columns={view.spriteColumns} rows={view.spriteRows} cells={catchCells ?? cells[frameIndex] ?? cells[0] ?? ''} />
442        <Box flexDirection="column">{view.lines.map(line)}</Box>
443      </Box>
444    )
445  })
446
447  // The same encounter in a pane the person opens (0015). It docks beside the
448  // transcript in fullscreen from 110 columns, else sits inline above the prompt.
449  on('ui.render', { component: 'Pane' }, ($, e, next) => {
450    if (e.requestId !== PANE_ID) return next(e)
451    const { Box, Text, Button } = $.ui.resolve(e)
452    const modster = currentModster()
453    const encounter = markedEncounter()
454    const biome = sessionBiome()?.biome
455    const rows = Math.max(0, e.props.scroll.bodyRows - 2) // header and a blank line
456    const columns = e.props.bodyColumns
457
458    const biomeName = biome ? biome.name : 'No biome'
459    const working = workingLabel(machine)
460    // How to move the keys between the prompt and the pane (0024 point 4)
461    const hint = paneHint({ isFocused: e.props.isFocused, placement: e.props.placement, columns: columns - biomeName.length - working.length })
462    const header = (
463      <Box key="header" flexDirection="row">
464        <Text bold {...(biome?.accentColor ? { color: biome.accentColor } : {})}>
465          {biomeName}
466        </Text>
467        <Text dimColor>{working}</Text>
468        {hint ? (
469          <Text key="hint" dimColor>
470            {hint}
471          </Text>
472        ) : null}
473      </Box>
474    )
475    if (!encounter || !modster) {
476      removeSite(e.requestId)
477      const idleText = (
478        <Text key="idle" dimColor>
479          Listening for Modsters… they appear while Claude works.
480        </Text>
481      )
482      // The scene above the idle text, by the band's rule on the pane's rows (0027)
483      const idleView = bandView({
484        maxRows: rows,
485        columns,
486        canDrawSprite: e.surface === 'terminal',
487        showIdleLine: true,
488        biome: { name: biomeName },
489        ...(scene && showIdleScene ? { sceneRows: scene.rows } : {}),
490      })
491      if (idleView.kind === 'scene' && e.surface === 'terminal') {
492        const { Raster } = $.ui.resolve(e)
493        addSceneSite($, e.requestId, columns)
494        return (
495          <Box flexDirection="column">
496            {header}
497            <Text key="gap"> </Text>
498            <Raster key={SCENE_KEY} columns={columns} rows={idleView.sceneRows} cells={sceneCellsFor(columns)} />
499            {idleText}
500          </Box>
501        )
502      }
503      removeSceneSite(e.requestId)
504      if (scene && showIdleScene) {
505        const skip = `idle scene: not drawn in the pane (surface ${e.surface}, ${rows} rows, scene needs ${scene.rows + 1})`
506        if (skip !== loggedSceneSkip) {
507          loggedSceneSkip = skip
508          $.ui.log(skip, { to: 'debug' })
509        }
510      }
511      return (
512        <Box flexDirection="column">
513          {header}
514          <Text key="gap"> </Text>
515          {idleText}
516        </Box>
517      )
518    }
519
520    removeSceneSite(e.requestId)
521    // The sprite's normal size, as in the band: 2x looked far too big in a real terminal (0015)
522    const fits = () => Math.ceil(modster.sprite.height / 2) <= rows && modster.sprite.width + BAND.gapColumns + BAND.textColumns <= columns
523    const view = bandView({
524      maxRows: rows,
525      columns,
526      canDrawSprite: e.surface === 'terminal' && fits(),
527      showIdleLine: false,
528      encounter,
529    })
530    const line = (segments: BandLine, index: number) => (
531      <Box key={`line-${index}`} flexDirection="row">
532        {segments.map((segment, at) =>
533          'button' in segment ? (
534            <Button
535              key={segment.button}
536              label={BAND_BUTTONS[segment.button].label}
537              hotkey={BAND_BUTTONS[segment.button].hotkey}
538              plain
539              onPress={() => {
540                void advanceMachine($, { type: segment.button })
541              }}
542            />
543          ) : (
544            <Text
545              key={`text-${at}`}
546              wrap="truncate"
547              {...(segment.bold ? { bold: true } : {})}
548              {...(segment.dim ? { dimColor: true } : {})}
549              {...(segment.color ? { color: segment.color } : {})}
550            >
551              {segment.text}
552            </Text>
553          ),
554        )}
555      </Box>
556    )
557    if (view.kind !== 'full' || e.surface !== 'terminal') {
558      removeSite(e.requestId)
559      const lines = view.kind === 'compact' ? view.lines : []
560      return (
561        <Box flexDirection="column">
562          {header}
563          {lines.map(line)}
564        </Box>
565      )
566    }
567    const { Raster } = $.ui.resolve(e)
568    const cells = cellsFor(modster)
569    addSite($, e.requestId, modster)
570    return (
571      <Box flexDirection="column">
572        {header}
573        <Text key="gap"> </Text>
574        <Box key="encounter" flexDirection="row" columnGap={BAND.gapColumns}>
575          <Raster key={SPRITE_KEY} columns={view.spriteColumns} rows={view.spriteRows} cells={catchCells ?? cells[frameIndex] ?? cells[0] ?? ''} />
576          <Box flexDirection="column">{view.lines.map(line)}</Box>
577        </Box>
578      </Box>
579    )
580  })
581
582  // The collection pane (P3-01): tabs on hotkeys 1–5, which fire while the pane
583  // holds the keys. Inline the tabs share the header row when they fit; docked
584  // they get a row, or a row each when the dock is narrow
585  on('ui.render', { component: 'Pane' }, ($, e, next) => {
586    if (e.requestId !== COLLECTION_PANE_ID) return next(e)
587    const { Box, Text, Button } = $.ui.resolve(e)
588    const biome = sessionBiome()?.biome
589    const title = biome ? biome.name : 'No biome'
590    const layout = collectionLayout({
591      placement: e.props.placement,
592      isFocused: e.props.isFocused,
593      columns: e.props.bodyColumns,
594      titleColumns: title.length,
595    })
596    const tabButtons = COLLECTION_TABS.map((tab) => (
597      <Button
598        key={tab.id}
599        label={tab.label}
600        hotkey={tab.hotkey}
601        plain
602        {...(tab.id === collectionTab ? {} : { dimColor: true })}
603        onPress={() => {
604          if (tab.id === 'stats' && collectionTab !== 'stats') loadStats($)
605          collectionTab = tab.id
606          void keepState($, 'paneTab', tab.id)
607          $.ui.invalidate('ui.render')
608        }}
609      />
610    ))
611    const tabs =
612      layout.tabs === 'column' ? (
613        <Box key="tabs" flexDirection="column">
614          {tabButtons}
615        </Box>
616      ) : (
617        <Box key="tabs" flexDirection="row" columnGap={COLLECTION.tabGapColumns}>
618          {tabButtons}
619        </Box>
620      )
621    const header = (
622      <Box key="header" flexDirection="row">
623        <Text key="title" bold {...(biome?.accentColor ? { color: biome.accentColor } : {})}>
624          {title}
625        </Text>
626        {layout.tabs === 'beside' ? <Text key="tabs-gap">{' '.repeat(COLLECTION.tabGapColumns)}</Text> : null}
627        {layout.tabs === 'beside' ? tabs : null}
628        {layout.hint ? (
629          <Text key="hint" dimColor>
630            {layout.hint}
631          </Text>
632        ) : null}
633      </Box>
634    )
635    const texts = (line: BandLine, wrap: 'wrap' | 'truncate') =>
636      line.map((segment, at) =>
637        'text' in segment ? (
638          <Text
639            key={`text-${at}`}
640            wrap={wrap}
641            {...(segment.bold ? { bold: true } : {})}
642            {...(segment.dim ? { dimColor: true } : {})}
643            {...(segment.color ? { color: segment.color } : {})}
644          >
645            {segment.text}
646          </Text>
647        ) : null,
648      )
649    const tabRows = layout.tabs === 'beside' ? 0 : layout.tabs === 'row' ? 1 : COLLECTION_TABS.length
650    // Header, tabs, the blank line, and the no-biome note when there's no biome
651    const usedRows = 1 + tabRows + 1 + (biome ? 0 : 1)
652    if (collectionTab !== 'collection') dropCollectionSite(e.requestId)
653    if (collectionTab !== 'biomes') dropBiomesSceneSite(e.requestId)
654    if (collectionTab !== 'catchers') dropCatcherPreview(e.requestId)
655    return (
656      <Box flexDirection="column">
657        {header}
658        {layout.tabs === 'beside' ? null : tabs}
659        <Text key="gap"> </Text>
660        {biome ? null : (
661          <Text key="no-biome" dimColor>
662            {noBiomesMessage(includeBuiltins, USER_FOLDER_LABEL)}
663          </Text>
664        )}
665        {collectionTab === 'collection'
666          ? collectionView(e.props.scroll.bodyRows - usedRows)
667          : collectionTab === 'biomes'
668            ? biomesView(e.props.scroll.bodyRows - usedRows)
669            : collectionTab === 'stats'
670              ? statsView()
671              : collectionTab === 'catchers'
672                ? catchersView(e.props.scroll.bodyRows - usedRows)
673                : settingsView()}
674      </Box>
675    )
676
677    /** The Catchers tab: a summary line with k/j/u, the list, and the selected catcher's preview (decision 0035 point 9). */
678    function catchersView(rows: number) {
679      const inUse = content ? catcherInUse(content.catchers, pickedCatcherId, CATCH.defaultCatcher)?.catcher.id : undefined
680      const entries = content ? catcherEntries([...content.catchers.values()].map((loaded) => loaded.catcher), inUse, content.userIds.catchers) : []
681      // A selected catcher that no longer loads falls back to the one in use
682      const at = (id: string | undefined) => entries.findIndex((entry) => entry.id === id)
683      const index = Math.max(0, at(catchersSelected) >= 0 ? at(catchersSelected) : at(inUse))
684      const selected = entries[index]
685      const select = (entry: CatcherEntry | undefined) => {
686        if (!entry || entry.id === selected?.id) return
687        catchersSelected = entry.id
688        $.ui.invalidate('ui.render')
689      }
690      const summary = (
691        <Box key="summary" flexDirection="row" columnGap={COLLECTION.gapColumns}>
692          <Text bold>{`Catchers ${entries.length}`}</Text>
693          <Button key="catcher-up" label="Up" hotkey="k" plain dimColor onPress={() => select(entries[index - 1])} />
694          <Button key="catcher-down" label="Down" hotkey="j" plain dimColor onPress={() => select(entries[index + 1])} />
695          {selected && !selected.isInUse ? (
696            // `u`, not Enter: a hotkey is one digit or letter (asked by @danielpg95 in P5-30)
697            <Button key="catcher-use" label="Use" hotkey="u" plain dimColor onPress={() => useCatcher($, selected)} />
698          ) : null}
699        </Box>
700      )
701      const loadedCatcher = selected ? content?.catchers.get(selected.id) : undefined
702      if (!selected || !loadedCatcher) {
703        dropCatcherPreview(e.requestId)
704        return (
705          <Box key="catchers" flexDirection="column">
706            {summary}
707            <Text dimColor>No catchers loaded.</Text>
708          </Box>
709        )
710      }
711      // The preview plays on the Modster caught last, or a silhouette when none is caught yet
712      const all = content ? [...content.modsters.values(), ...content.off.modsters.values()] : []
713      const caughtId = previewModsterId(collectionRecords, new Set(all.map((loaded) => loaded.modster.id)))
714      const modster = all.find((loaded) => loaded.modster.id === caughtId) ?? all[0]
715      const lines: BandLine[] = [
716        [{ text: selected.name, bold: true }],
717        ...(selected.description ? [[{ text: selected.description, dim: true }] as BandLine] : []),
718        ...itemNotes('catcher', selected.id, selected),
719      ]
720      const plan = collectionBody({
721        columns: e.props.bodyColumns,
722        // Less the summary line
723        rows: Math.max(1, rows - 1),
724        spriteColumns: modster && e.surface === 'terminal' ? modster.sprite.width : Number.MAX_SAFE_INTEGER,
725        spriteRows: modster && e.surface === 'terminal' ? Math.ceil(modster.sprite.height / 2) : Number.MAX_SAFE_INTEGER,
726        detailRows: COLLECTION.catcherDetailRows,
727      })
728      const window = listWindow(entries.length, index, plan.listRows)
729      const more = moreText(window)
730      const list = (
731        <Box key="catcher-list" flexDirection="column" {...(plan.split === 'side' ? { width: COLLECTION.listColumns } : {})}>
732          {entries.slice(window.start, window.end).map((entry) => (
733            <Button key={entry.id} plain onPress={() => select(entry)}>
734              {texts(catcherRow(entry, entry.id === selected.id), 'truncate')}
735            </Button>
736          ))}
737          {more ? <Text dimColor>{more}</Text> : null}
738        </Box>
739      )
740      const text = (
741        <Box key="catcher-text" flexDirection="column" width={plan.textColumns}>
742          {lines.map((line, row) => (
743            <Box key={`catcher-line-${row}`} flexDirection="row">
744              {texts(line, 'wrap')}
745            </Box>
746          ))}
747        </Box>
748      )
749      let detail = text
750      if (plan.sprite !== 'none' && modster && e.surface === 'terminal') {
751        const { Raster } = $.ui.resolve(e)
752        const sprite = caughtId === undefined ? silhouetteSprite(modster.sprite) : modster.sprite
753        const cells = catcherPreviewCells($, e.requestId, loadedCatcher, modster, sprite)
754        const beside = plan.sprite === 'beside'
755        detail = (
756          <Box key="detail" flexDirection={beside ? 'row' : 'column'} {...(beside ? { columnGap: COLLECTION.gapColumns } : {})}>
757            <Raster key={CATCHER_PREVIEW_KEY} columns={sprite.width} rows={Math.ceil(sprite.height / 2)} cells={cells} />
758            {text}
759          </Box>
760        )
761      } else {
762        dropCatcherPreview(e.requestId)
763      }
764      return (
765        <Box key="catchers" flexDirection="column">
766          {summary}
767          {plan.split === 'side' ? (
768            <Box key="split" flexDirection="row" columnGap={COLLECTION.gapColumns}>
769              {list}
770              {detail}
771            </Box>
772          ) : (
773            <Box key="split" flexDirection="column">
774              {list}
775              <Text> </Text>
776              {detail}
777            </Box>
778          )}
779        </Box>
780      )
781    }
782
783    /** The Settings tab: every option with k/j/o (decision 0040), then the content issues and how to reload (P4-02). */
784    function settingsView() {
785      const fields = SETTING_SPECS.map((spec) => spec.field)
786      const index = Math.max(0, fields.indexOf(settingsSelected))
787      const select = (field: SettingField | undefined) => {
788        if (!field || field === settingsSelected) return
789        settingsSelected = field
790        void keepState($, 'settingsSelected', field)
791        $.ui.invalidate('ui.render')
792      }
793      return (
794        <Box key="settings" flexDirection="column">
795          <Box key="settings-summary" flexDirection="row" columnGap={COLLECTION.gapColumns}>
796            <Text bold>Settings</Text>
797            <Button key="setting-up" label="Up" hotkey="k" plain dimColor onPress={() => select(fields[index - 1])} />
798            <Button key="setting-down" label="Down" hotkey="j" plain dimColor onPress={() => select(fields[index + 1])} />
799            <Button key="setting-change" label="Change" hotkey={TOGGLE_HOTKEY} plain dimColor onPress={() => void changeSetting($, fields[index] ?? 'autoStart')} />
800          </Box>
801          {fields.map((field) => (
802            <Button key={`setting-${field}`} plain onPress={() => select(field)}>
803              {texts(settingRow(field, settingValues, field === fields[index]), 'truncate')}
804            </Button>
805          ))}
806          <Text key="settings-gap"> </Text>
807          {settingsLines(content?.issues ?? []).map((line, at) => (
808            <Box key={`settings-${at}`} flexDirection="row">
809              {texts(line, 'wrap')}
810            </Box>
811          ))}
812        </Box>
813      )
814    }
815
816    /** The Stats tab: the totals and a row per biome (P3-04). */
817    function statsView() {
818      if (!statsShown) {
819        return (
820          <Text key="stats" dimColor>
821            Counting…
822          </Text>
823        )
824      }
825      const biomes = new Map([...(content?.biomes.values() ?? []), ...(content?.off.biomes.values() ?? [])].map(({ biome: loaded }) => [loaded.id, { name: loaded.name, ...(loaded.accentColor ? { accentColor: loaded.accentColor } : {}) }]))
826      return (
827        <Box key="stats" flexDirection="column">
828          {statsLines(statsShown.stats, biomes).map((line, at) => (
829            <Box key={`stats-${at}`} flexDirection="row">
830              {texts(line, 'truncate')}
831            </Box>
832          ))}
833        </Box>
834      )
835    }
836
837    /** The Biomes tab: a summary line with k/j, the biome list, and the selected biome's odds (P3-03). */
838    function biomesView(rows: number) {
839      // Off biomes stay listed, dimmed, so `o` can turn them back on (0032 point 5)
840      const entries = content
841        ? biomeEntries([...content.biomes.values(), ...content.off.biomes.values()], content.modsters, collectionRecords, biomeId, {
842            off: new Set(content.off.biomes.keys()),
843            yours: content.userIds.biomes,
844          })
845        : []
846      // A selected biome that no longer loads falls back to the session's
847      const at = (id: string | undefined) => entries.findIndex((entry) => entry.id === id)
848      const index = Math.max(0, at(biomesSelected) >= 0 ? at(biomesSelected) : at(biomeId))
849      const selected = entries[index]
850      const select = (entry: BiomeEntry | undefined) => {
851        if (!entry || entry.id === selected?.id) return
852        biomesSelected = entry.id
853        $.ui.invalidate('ui.render')
854      }
855      const summary = (
856        <Box key="summary" flexDirection="row" columnGap={COLLECTION.gapColumns}>
857          <Text bold>{`Biomes ${entries.length}`}</Text>
858          <Button key="biome-up" label="Up" hotkey="k" plain dimColor onPress={() => select(entries[index - 1])} />
859          <Button key="biome-down" label="Down" hotkey="j" plain dimColor onPress={() => select(entries[index + 1])} />
860          {selected ? (
861            <Button
862              key="biome-toggle"
863              label={toggleLabel(selected)}
864              hotkey={TOGGLE_HOTKEY}
865              plain
866              dimColor
867              onPress={() => toggle($, { kind: 'biome', id: selected.id, off: !selected.isOff }, selected.name, includeBuiltins, idleTimeoutSec)}
868            />
869          ) : null}
870        </Box>
871      )
872      if (!selected) {
873        dropBiomesSceneSite(e.requestId)
874        return <Box key="biomes" flexDirection="column">{summary}</Box>
875      }
876      // Raster is terminal only (0012); 0028 point 3
877      const loadedBiome = content?.biomes.get(selected.id) ?? content?.off.biomes.get(selected.id)
878      const scene = showIdleScene && e.surface === 'terminal' && loadedBiome ? biomeScene(loadedBiome) : undefined
879      // Less the summary line
880      const plan = biomesBody({ columns: e.props.bodyColumns, rows: rows - 1, ...(scene ? { sceneRows: scene.rows } : {}) })
881      let sceneView = null
882      if (scene && plan.showScene && e.surface === 'terminal') {
883        const { Raster } = $.ui.resolve(e)
884        const site = setBiomesSceneSite($, e.requestId, selected.id, scene, e.props.bodyColumns)
885        sceneView = <Raster key={BIOMES_SCENE_KEY} columns={site.columns} rows={scene.rows} cells={sceneCells(scene, site.columns, site.particles, biomesSceneTick)} />
886      } else {
887        dropBiomesSceneSite(e.requestId)
888      }
889      const window = listWindow(entries.length, index, plan.listRows)
890      const more = moreText(window)
891      const list = (
892        <Box key="biome-list" flexDirection="column" {...(plan.split === 'side' ? { width: COLLECTION.biomeListColumns } : {})}>
893          {entries.slice(window.start, window.end).map((entry) => (
894            <Button key={entry.id} plain onPress={() => select(entry)}>
895              {texts(biomeRow(entry, entry.id === selected.id), 'truncate')}
896            </Button>
897          ))}
898          {more ? <Text dimColor>{more}</Text> : null}
899        </Box>
900      )
901      const odds = (
902        <Box key="odds" flexDirection="column">
903          {itemNotes('biome', selected.id, selected).map((line, at) => (
904            <Box key={`note-${at}`} flexDirection="row">
905              {texts(line, 'wrap')}
906            </Box>
907          ))}
908          {selected.odds.length === 0 ? <Text dimColor>No Modsters loaded.</Text> : null}
909          {tierSections(selected.odds).map((section, index) => (
910            <Box key={`tier-${section.tier}`} flexDirection="column">
911              {index > 0 ? <Text key="gap"> </Text> : null}
912              <Box key="tier-header" flexDirection="row">
913                {texts(tierRow(section), 'truncate')}
914              </Box>
915              {section.odds.map((row) => (
916                <Box key={`odds-${row.id}`} flexDirection="row">
917                  {texts(oddsRow(row, selected.id), 'truncate')}
918                </Box>
919              ))}
920            </Box>
921          ))}
922        </Box>
923      )
924      return (
925        <Box key="biomes" flexDirection="column">
926          {summary}
927          {sceneView}
928          {plan.split === 'side' ? (
929            <Box key="split" flexDirection="row" columnGap={COLLECTION.gapColumns}>
930              {list}
931              {odds}
932            </Box>
933          ) : (
934            <Box key="split" flexDirection="column">
935              {list}
936              <Text> </Text>
937              {odds}
938            </Box>
939          )}
940        </Box>
941      )
942    }
943
944    /** The Collection tab: a summary line with k/j, the list, and the selected Modster (P3-02). */
945    function collectionView(rows: number) {
946      // Off Modsters stay listed, dimmed, so `o` can turn them back on (0032 point 5)
947      const entries = content
948        ? collectionEntries([...content.modsters.values(), ...content.off.modsters.values()], collectionRecords, {
949            off: new Set(content.off.modsters.keys()),
950            yours: content.userIds.modsters,
951          })
952        : []
953      const caught = entries.filter((entry) => entry.record).length
954      const index = Math.max(0, entries.findIndex((entry) => entry.id === collectionSelected))
955      const selected = entries[index]
956      const select = (entry: CollectionEntry | undefined) => {
957        if (!entry || entry.id === selected?.id) return
958        collectionSelected = entry.id
959        $.ui.invalidate('ui.render')
960      }
961      const summary = (
962        <Box key="summary" flexDirection="row" columnGap={COLLECTION.gapColumns}>
963          <Text bold>{`Caught ${caught}/${entries.length}`}</Text>
964          <Button key="up" label="Up" hotkey="k" plain dimColor onPress={() => select(entries[index - 1])} />
965          <Button key="down" label="Down" hotkey="j" plain dimColor onPress={() => select(entries[index + 1])} />
966          {selected ? (
967            <Button
968              key="toggle"
969              label={toggleLabel(selected)}
970              hotkey={TOGGLE_HOTKEY}
971              plain
972              dimColor
973              // An uncaught Modster's name stays a secret (0032 point 4)
974              onPress={() =>
975                toggle($, { kind: 'modster', id: selected.id, off: !selected.isOff }, selected.record ? selected.name : 'That Modster', includeBuiltins, idleTimeoutSec)
976              }
977            />
978          ) : null}
979        </Box>
980      )
981      if (!selected) {
982        dropCollectionSite(e.requestId)
983        return (
984          <Box key="collection" flexDirection="column">
985            {summary}
986            <Text dimColor>No Modsters loaded.</Text>
987          </Box>
988        )
989      }
990      const loaded = content?.modsters.get(selected.id) ?? content?.off.modsters.get(selected.id)
991      const habitat = content
992        ? [...content.biomes.values()].filter(({ biome }) => biome.modsters.some((entry) => entry.id === selected.id)).map(({ biome }) => biome.name)
993        : []
994      const lines = detailLines({ entry: selected, ...(loaded?.modster.dex ? { dex: loaded.modster.dex } : {}), habitat })
995      // Sized from the pane and the largest sprite, never the selection, so scrolling
996      // keeps one layout. Raster is terminal only (0012); elsewhere no sprite fits
997      const box = e.surface === 'terminal' ? spriteBox() : undefined
998      const plan = collectionBody({
999        columns: e.props.bodyColumns,
1000        // Less the summary line
1001        rows: Math.max(1, rows - 1),
1002        spriteColumns: box ? box.columns : Number.MAX_SAFE_INTEGER,
1003        spriteRows: box ? box.rows : Number.MAX_SAFE_INTEGER,
1004        detailRows: COLLECTION.detailRows,
1005      })
1006      const window = listWindow(entries.length, index, plan.listRows)
1007      const more = moreText(window)
1008      const list = (
1009        <Box key="list" flexDirection="column" {...(plan.split === 'side' ? { width: COLLECTION.listColumns } : {})}>
1010          {entries.slice(window.start, window.end).map((entry) => (
1011            <Button key={entry.id} plain onPress={() => select(entry)}>
1012              {texts(listRow(entry, entry.id === selected.id), 'truncate')}
1013            </Button>
1014          ))}
1015          {more ? <Text dimColor>{more}</Text> : null}
1016        </Box>
1017      )
1018      // Always the same height: a short detail leaves room, a long entry is cut
1019      const text = (
1020        <Box key="detail-text" flexDirection="column" width={plan.textColumns} height={COLLECTION.detailRows} overflow="hidden">
1021          {lines.map((line, at) => (
1022            <Box key={`detail-${at}`} flexDirection="row">
1023              {texts(line, 'wrap')}
1024            </Box>
1025          ))}
1026        </Box>
1027      )
1028      let detail = text
1029      if (plan.sprite !== 'none' && box && loaded && e.surface === 'terminal') {
1030        const { Raster } = $.ui.resolve(e)
1031        // Only a caught Modster animates; the silhouette holds still
1032        setCollectionSite($, e.requestId, selected.record ? loaded : undefined)
1033        const beside = plan.sprite === 'beside'
1034        detail = (
1035          <Box key="detail" flexDirection={beside ? 'row' : 'column'} {...(beside ? { columnGap: COLLECTION.gapColumns } : {})}>
1036            <Box key="sprite-box" width={box.columns} height={box.rows} alignItems="center" justifyContent="center">
1037              <Raster key={COLLECTION_SPRITE_KEY} columns={loaded.sprite.width} rows={Math.ceil(loaded.sprite.height / 2)} cells={collectionCells(loaded, selected)} />
1038            </Box>
1039            {text}
1040          </Box>
1041        )
1042      } else {
1043        dropCollectionSite(e.requestId)
1044      }
1045      return (
1046        <Box key="collection" flexDirection="column">
1047          {summary}
1048          {plan.split === 'side' ? (
1049            <Box key="split" flexDirection="row" columnGap={COLLECTION.gapColumns}>
1050              {list}
1051              {detail}
1052            </Box>
1053          ) : (
1054            <Box key="split" flexDirection="column">
1055              {list}
1056              <Text> </Text>
1057              {detail}
1058            </Box>
1059          )}
1060        </Box>
1061      )
1062    }
1063  })
1064
1065  // The spinner names the Modster while Claude works (0023 point 5). Subagents'
1066  // rows keep their own words; their requestId is the agent id
1067  on('ui.render', { component: 'Spinner' }, ($, e, next) => {
1068    const message = currentPlan().spinner
1069    if (message === undefined || (machine && e.requestId in machine.agents)) return next(e)
1070    // An empty suffix: the engine's ellipsis would follow "Caught Sproutling!"
1071    return next({ ...e, props: { ...e.props, message, suffix: '' } })
1072  })
1073
1074  // When the pane closes, the band takes the encounter back (0015). Only a close
1075  // by hand stops the reopening; ours and an unload change nothing (0019)
1076  on('ui.close', async ($, e, next) => {
1077    const result = await next(e)
1078    if (e.id === COLLECTION_PANE_ID) dropCollectionSite(COLLECTION_PANE_ID)
1079    if (e.id === COLLECTION_PANE_ID) dropBiomesSceneSite(COLLECTION_PANE_ID)
1080    if (e.id === COLLECTION_PANE_ID) dropCatcherPreview(COLLECTION_PANE_ID)
1081    const pref = e.id === PANE_ID ? prefAfterClose(e.origin.kind) : undefined
1082    if (pref) queueWrite($, (store) => store.set(HUNT_PANE_KEY, pref))
1083    $.ui.invalidate('ui.render')
1084    return result
1085  })
1086
1087  on('command.run', { command: 'modsters' }, async ($, e) => {
1088    const verb = typeof e.args === 'string' ? e.args.trim() : ''
1089    // `/modsters hunt` and `stop` turn the game on and off through autoStart (0038 points 3–4)
1090    if (verb === 'hunt') {
1091      const denied = await startHunting($, idleTimeoutSec, { reopenPane: true })
1092      return { text: denied === undefined ? huntReply(sessionBiome()?.biome.name) : autoStartDeniedReply(true, denied) }
1093    }
1094    if (verb === 'stop') {
1095      const denied = await stopHunting($)
1096      return { text: denied === undefined ? STOP_REPLY : autoStartDeniedReply(false, denied) }
1097    }
1098    // `/modsters pane` opens the encounter pane, starting the game when it's off (0015, 0019, 0024; 0038 point 5)
1099    if (verb === 'pane') {
1100      if (display.encounterPane === 'off') return { text: PANE_OFF_REPLY }
1101      const denied = await startHunting($, idleTimeoutSec, { reopenPane: false })
1102      if (denied !== undefined) return { text: autoStartDeniedReply(true, denied) }
1103      queueWrite($, (store) => store.set(HUNT_PANE_KEY, huntPanePref(true)))
1104      // The person asked for it, so the pane takes the keys; granted only over an empty composer (0024)
1105      const opened = await $.ui.open({ id: PANE_ID, title: 'Modster Hunter', focus: true })
1106      // The band redraws without the encounter now that the pane shows it
1107      $.ui.invalidate('ui.render')
1108      return opened.isPlaced ? {} : { text: 'Modster Hunter: the pane is waiting for more room (widen the terminal)' }
1109    }
1110    if (verb === 'help') return { text: helpText(hunting) }
1111    // `/modsters settings` opens the collection on its Settings tab (0040 point 1)
1112    if (verb === 'settings') {
1113      collectionTab = 'settings'
1114      await keepState($, 'paneTab', 'settings')
1115    }
1116    if (verb === 'reload') {
1117      reloading ??= reloadContent($, includeBuiltins, idleTimeoutSec).finally(() => {
1118        reloading = undefined
1119      })
1120      return { text: (await reloading).reply }
1121    }
1122    // A word it doesn't know gets the help, not the collection (0038 point 7)
1123    if (verb !== '' && verb !== 'settings') return { text: unknownSubcommandText(verb, hunting) }
1124    // Catches from other sessions show up when the pane opens
1125    loadCollectionRecords($)
1126    if (collectionTab === 'stats') loadStats($)
1127    await pendingWrites
1128    // The person asked for it, so the pane takes the keys over an empty composer (0024)
1129    const opened = await $.ui.open({ id: COLLECTION_PANE_ID, title: 'Modster collection', focus: true, closeOnEscape: true })
1130    return opened.isPlaced ? {} : { text: 'Modster Hunter: the collection is waiting for more room (widen the terminal)' }
1131  })
1132
1133}
1134
1135/**
1136 * The Settings tab's `o` (decision 0040 points 3–5): writes the next value through
1137 * /config and applies it at once. A refused write keeps the value and says why.
1138 */
1139async function changeSetting($: EngineInterface, field: SettingField): Promise<void> {
1140  const next = nextSettingValue(field, settingValues[field])
1141  // The write below reloads the mod (0023): the pane must come back here, on this row (0040 point 5)
1142  await keepState($, 'paneTab', 'settings')
1143  await keepState($, 'settingsSelected', field)
1144  const label = SETTING_SPECS.find((spec) => spec.field === field)?.label ?? field
1145  if (field === 'autoStart') {
1146    // Exactly what /modsters hunt and stop do (0038 points 3–4)
1147    const denied = next === true ? await startHunting($, idleTimeoutSec, { reopenPane: true }) : await stopHunting($)
1148    if (denied !== undefined) $.ui.toast(settingDeniedText(label, denied))
1149    $.ui.invalidate('ui.render')
1150    return
1151  }
1152  const denied = await setOption($, field, next)
1153  if (denied !== undefined) {
1154    $.ui.toast(settingDeniedText(label, denied))
1155    return
1156  }
1157  settingValues = { ...settingValues, [field]: next }
1158  switch (field) {
1159    case 'showInBand':
1160    case 'encounterPane':
1161    case 'showInSpinner':
1162    case 'showInStatusLine':
1163      // Where the game shows, by 0023's rules
1164      display = readDisplaySettings(settingValues)
1165      if (field === 'encounterPane' && next === 'off') await closeHuntPane($)
1166      if (field === 'encounterPane' && next === 'always' && hunting) await openHuntPaneAtStart($)
1167      updateStatus($)
1168      break
1169    case 'showIdleLine':
1170      showIdleLine = next === true
1171      break
1172    case 'showIdleScene':
1173      showIdleScene = next === true
1174      updateSceneTimer($)
1175      break
1176    case 'includeBuiltins': {
1177      includeBuiltins = next === true
1178      builtinsIncluded = includeBuiltins
1179      // As /modsters reload does (0031)
1180      await reloading?.catch(() => undefined)
1181      reloading = reloadContent($, includeBuiltins, idleTimeoutSec).finally(() => {
1182        reloading = undefined
1183      })
1184      $.ui.toast((await reloading).reply)
1185      break
1186    }
1187    case 'encounterIdleTimeoutSec':
1188      idleTimeoutSec = Number(next)
1189      setIdleTimeout(idleTimeoutSec * 1000)
1190      break
1191  }
1192  $.ui.invalidate('ui.render')
1193}
1194
1195function cellsFor(loaded: LoadedModster): string[] {
1196  const cached = cellsByModster.get(loaded.modster.id)
1197  if (cached?.sprite === loaded.sprite) return cached.cells
1198  const cells = spriteCells(loaded.sprite)
1199  cellsByModster.set(loaded.modster.id, { sprite: loaded.sprite, cells })
1200  return cells
hooks/constants.ts 269 lines
1// Tunable numbers, in one place. Each group names the decision or doc it comes from.
2
3/**
4 * Rarity tiers, most common first. An encounter draws a tier by `weight`, the
5 * same in every biome (decision 0030 point 2); the catch defaults apply unless
6 * the biome entry or the Modster overrides them (decision 0004).
7 */
8export const TIERS = [
9  { tier: 'common', weight: 76, maxAttempts: 3, catchRate: 0.5 },
10  { tier: 'uncommon', weight: 19, maxAttempts: 3, catchRate: 0.35 },
11  { tier: 'rare', weight: 4.5, maxAttempts: 4, catchRate: 0.2 },
12  { tier: 'legendary', weight: 0.5, maxAttempts: 5, catchRate: 0.08 },
13] as const
14
15/**
16 * Encounter phase lengths, decision 0014. A throw lasts as long as its catch
17 * animation (decision 0035, `CATCH`). The idle timeout is the
18 * `encounterIdleTimeoutSec` user option.
19 */
20export const ENCOUNTER = {
21  appearingMs: 1000,
22  resultMs: 4000,
23  /** A subagent counts as work time for at most this long after its start, in case its stop event is lost (0018 point 3, `AGENT_WORK_MAX_MIN` = 30) */
24  agentWorkMaxMs: 30 * 60 * 1000,
25} as const
26
27/**
28 * The catch animation, decision 0035 point 5: beat lengths are the same for
29 * every catcher. `caught` plays at the start of the result card. The rest
30 * tune how frames made from a catcher's frame 0 move (CONTENT_FORMAT "Styles").
31 */
32export const CATCH = {
33  fps: 12,
34  beatMs: { throw: 350, take: 400, settle: 150, rock: 500, caught: 700, broken: 450 },
35  /** A catch rocks this many times; a miss 1 to one fewer (0035 point 6) */
36  rocksToCatch: 3,
37  /** How far frame 0 tilts at the top of a rock */
38  tiltRadians: 0.26,
39  /** How far the lid rises while the Modster goes in */
40  lidLiftPx: 4,
41  /** A `shrink` (a cover catcher cinching) ends at this scale */
42  shrinkScale: 0.65,
43  /** How high a `hop-out` jumps */
44  hopPx: 3,
45  /** A `dim` Modster's colors are mixed this far toward black */
46  dimAmount: 0.5,
47  /** A `stretch` shape reaches this far past the Modster's outline, within its area */
48  stretchMarginPx: 2,
49  /** Past this share of a `stretch` shape's radius, `rimIndex` draws the edge */
50  rimFrom: 0.82,
51  /** A catch's sparkles: a white center that glints on dark terminals, deep gold arms that show on light ones */
52  sparkleCore: '#ffffff',
53  sparkleArms: '#e0a800',
54  /** The Catchers tab's preview loops a catch, then holds still this long before the next */
55  previewPauseMs: 800,
56  /** Played when `prefs:catcher` is missing or names a catcher that didn't load (0035 point 10) */
57  defaultCatcher: 'jar',
58  /** `glowIndex` takes the Modster's most common color with summed RGB over this (half of full brightness) */
59  glowMinBrightness: 384,
60} as const
61
62/**
63 * The welcome toast (decision 0038 point 9) stays this long: it shows at session
64 * start, when the person may be looking elsewhere, and the 4 s default went by
65 * unread in the hand check. The pointer over it holds it; a click takes it off.
66 */
67export const WELCOME_TOAST_MS = 15_000
68
69/** The Settings tab's option rows (decision 0040). */
70export const SETTINGS = {
71  /** What `o` steps the idle timeout through, wrapping (0040 point 2) */
72  idleTimeoutChoicesSec: [30, 60, 90, 180, 300],
73  /** Columns a row's label is padded to, so the values line up */
74  labelColumns: 24,
75} as const
76
77/** Band layout, decision 0012: the full layout needs sprite + gap + text block in the band's width. */
78export const BAND = {
79  gapColumns: 2,
80  textColumns: 24,
81  /** How often the encounter machine is stepped (timers resolve to within this) */
82  tickMs: 250,
83  /** After the name of a Modster already in the collection (P5-10) */
84  caughtMark: '●',
85} as const
86
87/**
88 * The biome idle scene, decision 0026. Particle speeds are pixels per tick at
89 * `particleFps`; `sway` is how far a particle rocks sideways, in pixels.
90 */
91export const SCENE = {
92  defaultFps: 2,
93  defaultDensity: 2,
94  defaultParticleColor: '#ffffff',
95  particleFps: 8,
96  /** The strip a biome with particles and no background gets (0026 point 4) */
97  particleOnlyRows: 3,
98  /** One particle per this many pixels at density 1 */
99  pixelsPerParticle: 240,
100  /** A sparkle shows for `on` ticks out of every `period` */
101  sparkleTicks: { on: 3, period: 12 },
102  motion: {
103    sparkle: { dx: 0, dy: 0, sway: 0 },
104    leaf: { dx: 0.4, dy: 0.2, sway: 1 },
105    sand: { dx: 1.2, dy: 0.05, sway: 0 },
106    bubble: { dx: 0, dy: -0.3, sway: 0.5 },
107    snow: { dx: 0, dy: 0.25, sway: 1 },
108  },
109} as const
110
111/** Where the game shows, decision 0023 point 1: the `userConfig` defaults and the pane picker's values. */
112export const DISPLAY = {
113  encounterPaneModes: ['off', 'when-opened', 'always'],
114  defaults: {
115    showInBand: true,
116    encounterPane: 'when-opened',
117    showInSpinner: true,
118    showInStatusLine: true,
119  },
120} as const
121
122/** The collection pane, decision 0002 and P3-01: its tab row is plain Buttons `1`–`4`, this far apart. */
123export const COLLECTION = {
124  tabGapColumns: 2,
125  /** P3-02's list: `▸ #001 Sproutling      ×3 legendary`; names past `nameColumns` are cut */
126  listColumns: 36,
127  nameColumns: 14,
128  /** Between the list and the detail, and between the sprite and the text beside it */
129  gapColumns: 2,
130  /** The detail's text needs this much room beside the list, else it goes under the list */
131  detailMinColumns: 24,
132  /** The detail's text always takes this many rows, so the layout holds still while scrolling; a long dex entry is cut */
133  detailRows: 9,
134  /** An uncaught Modster's still silhouette: one gray that reads on dark and light terminals */
135  silhouetteColor: '#5a5a5a',
136  /** P3-03's biome list: `▸ Whispering Forest 2/5 here`; names past `biomeNameColumns` are cut */
137  biomeListColumns: 30,
138  biomeNameColumns: 17,
139  /** P5-30's catcher list, as wide as the Collection tab's: `▸ Glass jar          ✓ in use`; names past this are cut */
140  catcherNameColumns: 18,
141  /** Rows the Catchers tab's text under or beside the preview takes: the description and the delete hint */
142  catcherDetailRows: 4,
143  /** P3-03's odds rows: `#001 Sproutling     40.0%  legendary ×3` */
144  oddsColumns: 44,
145  /** A biome list under nothing but the odds (a narrow dock) shows at most this many rows */
146  biomeStackRows: 3,
147  /** The selected biome's scene shows only when the list still gets this many rows (0028 point 3) */
148  biomeSceneListRows: 3,
149  /** P3-04's per-biome table: each count right-aligned in this many columns */
150  statColumns: 7,
151} as const
152
153/** Stats compaction, decision 0029: a session's `stats:` key idle this long folds into `stats:total`. */
154export const STATS = {
155  compactAfterMs: 24 * 60 * 60 * 1000,
156} as const
157
158/** Content file bounds: docs/CONTENT_FORMAT.md (schema version 1), decisions 0004, 0007 and 0012. */
159export const CONTENT = {
160  schemaVersion: 1,
161  idPattern: /^[a-z][a-z0-9-]{1,31}$/,
162  /** A file name with no folder part, ending in `.sprite.json` (CONTENT_FORMAT "in this folder"). */
163  spriteFilePattern: /^[^/\\]+\.sprite\.json$/,
164  /** A PNG sheet in the Modster's folder; user content only (decision 0016). */
165  pngFilePattern: /^[^/\\]+\.png$/,
166  rgbColorPattern: /^#[0-9a-fA-F]{6}$/,
167  rgbaColorPattern: /^#[0-9a-fA-F]{8}$/,
168  descriptionMaxChars: 120,
169  biome: {
170    nameMaxChars: 32,
171    encounterEverySecMin: 3,
172    encounterEverySecMax: 600,
173    defaultEncounterEverySec: [10, 30] as const,
174    modstersMin: 1,
175    modstersMax: 50,
176    // Decision 0026 points 1 and 3: the idle scene and its particles
177    backgroundFramesMax: 4,
178    backgroundFpsMin: 1,
179    backgroundFpsMax: 12,
180    particleStyles: ['sparkle', 'leaf', 'sand', 'bubble', 'snow'],
181    particleDensityMin: 1,
182    particleDensityMax: 5,
183  },
184  modster: {
185    // Has to fit in the band
186    nameMaxChars: 24,
187    fpsMin: 1,
188    fpsMax: 12,
189    defaultFps: 6,
190  },
191  // Decision 0017 point 1
192  dex: {
193    numberMin: 1,
194    numberMax: 999,
195    categoryMaxChars: 24,
196    heightMMin: 0.01,
197    heightMMax: 100,
198    weightKgMin: 0.01,
199    weightKgMax: 10_000,
200    entryMaxChars: 240,
201    // Decision 0022: one or two types, the first one primary
202    typesMin: 1,
203    typesMax: 2,
204  },
205  // Decision 0004 point 5
206  maxAttemptsMin: 1,
207  maxAttemptsMax: 10,
208  catchRateMin: 0.01,
209  catchRateMax: 1,
210  sprite: {
211    // Decision 0021 (amends 0012 point 5). Where a sprite doesn't fit, the band and
212    // the pane show the compact layout (0012 points 6–8)
213    widthMin: 8,
214    widthMax: 48,
215    heightMin: 8,
216    heightMax: 48,
217    paletteMin: 1,
218    paletteMax: 64,
219    framesMin: 1,
220    framesMax: 8,
221  },
222  // Decision 0035 points 2–4: a catcher's file and its beats
223  catcher: {
224    nameMaxChars: 32,
225    styles: ['contain', 'cover', 'custom'],
226    beats: ['throw', 'take', 'settle', 'rock', 'caught', 'broken'],
227    places: ['over', 'behind', 'stretch'],
228    modsterActions: ['visible', 'hidden', 'dim', 'shake', 'shrink-in', 'shrink', 'hop-out', 'pop-out'],
229    paths: ['arc', 'drop', 'none'],
230    widthMax: 32,
231    heightMax: 32,
232    framesMax: 16,
233    beatFramesMax: 16,
234    paletteIndexMin: 1,
235    paletteIndexMax: 63,
236    lidRowsMin: 1,
237    lidRowsMax: 31,
238  },
239} as const
240
241/** Modster types and their badge colors, decision 0017 point 2. Flavor only: no effect on odds. */
242export const MODSTER_TYPES = {
243  normal: '#9e9e8e',
244  fire: '#f4511e',
245  water: '#2196f3',
246  grass: '#4caf50',
247  electric: '#fdd835',
248  steel: '#90a4ae',
249  fighting: '#c62828',
250  poison: '#9c27b0',
251  ground: '#c49a5a',
252  flying: '#90a4ff',
253  ice: '#80deea',
254  dark: '#6d5d4b',
255  psychic: '#ec407a',
256  bug: '#9ccc65',
257  rock: '#a1887f',
258  ghost: '#6a5acd',
259  dragon: '#5c6bc0',
260  fairy: '#f8a5c2',
261} as const
262
263/** Where user content and the decoded-PNG cache live, under the home folder (decisions 0007, 0016). */
264export const USER_CONTENT = {
265  contentFolder: '.claude/modster-hunter/content',
266  spriteCacheFolder: '.claude/modster-hunter/cache/sprites',
267  spriteCacheVersion: 1,
268} as const
269
hooks/content/index.ts 31 lines
1export { cachedSheetLoader, type SheetFiles } from './cached-sheet-loader'
2export { checkBiomeReferences } from './check-biome-references'
3export { checkTierBalance } from './check-tier-balance'
4export { formatIssue } from './issue-list'
5export { leavesNoBiome } from './leaves-no-biome'
6export { loadAllContent, type ContentFolders } from './load-all-content'
7export {
8  loadContent,
9  loadFolder,
10  resolveReferences,
11  type ContentReader,
12  type ContentRegistry,
13  type LoadedBiome,
14  type LoadedCatcher,
15  type LoadedModster,
16  type LoadOptions,
17  type SheetLoader,
18} from './load-content'
19export { mergeContent, type ContentSources, type MergedContent } from './merge-content'
20export { noBiomesMessage } from './no-biomes-message'
21export { spriteFromGif } from './sprite-from-gif'
22export { spriteFromPng } from './sprite-from-png'
23export { spriteFromSheet, type RgbaImage } from './sprite-from-sheet'
24export { toggleDisabled, type ToggleChange, type TogglePlan } from './toggle-disabled'
25export type { Biome, BiomeModsterEntry, BiomeParticles, Catcher, CatcherBeat, CatcherBeatName, CatcherModsterAction, CatcherPath, CatcherPlace, CatcherStyle, ContentIssue, Modster, ModsterDex, ModsterType, ParticleStyle, Rarity, Sprite, UserSettings, Validation } from './types'
26export { validateBiome } from './validate-biome'
27export { checkCatcherSprite, validateCatcher } from './validate-catcher'
28export { validateModster } from './validate-modster'
29export { validateSettings } from './validate-settings'
30export { validateSprite } from './validate-sprite'
31
hooks/game/index.ts 22 lines
1export {
2  startEncounters,
3  stepEncounter,
4  isWorking,
5  workTime,
6  type Encounter,
7  type EncounterContext,
8  type EncounterEvent,
9  type EncounterInput,
10  type EncounterPhase,
11  type EncounterState,
12  type EncounterStep,
13} from './encounter-machine'
14export { catchBeatAt, throwingMs, type CatchBeatAt, type CatchOutcome } from './catch-timeline'
15export { formatOddsTable, oddsTable, type OddsRow } from './odds-table'
16export { pickBiome } from './pick-biome'
17export { encounterPool, pickEncounter, tierChances, type PoolMember } from './pick-encounter'
18export { pickWeighted } from './pick-weighted'
19export type { RandomSource } from './random-source'
20export { rarityTier } from './rarity-tier'
21export { resolveCatchOdds, type CatchOdds } from './resolve-catch-odds'
22
hooks/render/index.ts 27 lines
1export { BAND_BUTTONS, bandRows, bandView, lineWidth, resultText, type BandButton, type BandEncounter, type BandInput, type BandLine, type BandSegment, type BandView } from './band-view'
2export { displayPlan, type DisplayPlan, type DisplayState } from './display-plan'
3export { readDisplaySettings, type DisplaySettings, type EncounterPaneMode } from './display-settings'
4export { catchDots } from './catch-dots'
5export { resolveBeats, type ResolvedBeat, type ResolvedBeats } from './catch-beats'
6export { catchFrame, prepareCatch, type CatchArt } from './catch-frame'
7export { DEFAULT_COLOR, pixelsToCells, type Frame } from './pixels-to-cells'
8export { paneHint, type PaneHintInput } from './pane-hint'
9export { rgbaOf, spriteCells, spriteRgba } from './sprite-cells'
10export { artFrame, idleScene, isAnimated, makeParticles, particlePixel, sceneCells, type IdleScene, type Particle } from './idle-scene'
11export { COLLECTION_TABS, tabRowWidth, tabWidth, type CollectionTab, type CollectionTabInfo } from './collection-tabs'
12export { collectionLayout, type CollectionLayout, type CollectionLayoutInput } from './collection-layout'
13export { collectionEntries, dexNumber, entryMarks, type CollectionEntry, type EntryMarks } from './collection-entries'
14export { catcherEntries, catcherRow, previewModsterId, type CatcherEntry } from './catcher-entries'
15export { TOGGLE_HOTKEY, itemNotes, offRow, toggleLabel, type ItemMarks } from './item-notes'
16export { listRow, listWindow, moreText, type ListWindow } from './collection-list'
17export { detailLines, type DetailInput } from './collection-detail'
18export { collectionBody, type CollectionBody, type CollectionBodyInput } from './collection-body'
19export { silhouettePalette } from './silhouette'
20export { biomeEntries, tierSections, type BiomeEntry, type BiomeOdds, type TierSection } from './biome-entries'
21export { biomeRow, oddsRow, tierRow } from './biome-rows'
22export { biomesBody, type BiomesBody, type BiomesBodyInput } from './biomes-body'
23export { NO_STATS_TEXT, ratio, statsLines, type StatsBiome } from './stats-lines'
24export { NO_ISSUES_TEXT, RELOAD_TEXT, TOGGLE_TEXT, settingsLines } from './settings-lines'
25export { MODSTERS_ARGUMENT_HINT, PANE_OFF_REPLY, STOP_REPLY, settingDeniedText, autoStartDeniedReply, helpText, huntReply, unknownSubcommandText, welcomeText } from './command-text'
26export { SETTING_DEFAULTS, SETTING_SPECS, nextSettingValue, readSettingValues, settingRow, settingText, type SettingField, type SettingValue, type SettingValues } from './setting-rows'
27
hooks/store/index.ts 10 lines
1export { addCatch, caughtKey, isCaught, readCaughtRecord, type Catch, type CaughtRecord } from './caught-record'
2export { CATCHER_KEY, catcherInUse, catcherPref, readCatcherId, type CatcherPref } from './catcher-pref'
3export { WELCOMED_KEY, readWelcomed, welcomedPref, type WelcomedPref } from './welcome-pref'
4export { HUNT_PANE_KEY, huntPanePref, prefAfterClose, readHuntPaneOpen, type HuntPanePref } from './hunt-pane-pref'
5export { recordEncounterEvents, recordStat } from './record-encounter-events'
6export { addToStats, readSessionStats, statsKey, type BiomeStats, type SessionStats, type StatsEvent } from './session-stats'
7export type { StorePort } from './store-port'
8export { compactStats, type StatsStorePort } from './compact-stats'
9export { readStatsTotal, STATS_TOTAL_KEY, sumStats, type StatsTotal } from './stats-total'
10
hooks/content/cached-sheet-loader.ts 70 lines
1import { USER_CONTENT } from '../constants'
2import { isObject } from './fields'
3import type { SheetLoader } from './load-content'
4import { spriteFromPng } from './sprite-from-png'
5import type { Sprite, Validation } from './types'
6import { validateSprite } from './validate-sprite'
7
8/** The file access the PNG cache needs; the adapter backs it with `$.fs`. */
9export interface SheetFiles {
10  /** Size and modification time, or undefined when the file doesn't exist */
11  stat(path: string): Promise<{ size: number; mtimeMs: number } | undefined>
12  readBytes(path: string): Promise<Uint8Array>
13  readText(path: string): Promise<string | undefined>
14  writeText(path: string, text: string): Promise<void>
15}
16
17/** What a cache file records about the PNG it was made from. */
18interface Source {
19  size: number
20  mtimeMs: number
21  frames: number
22}
23
24/**
25 * Loads PNG sheets through a cache in `cacheFolder`, one `<cacheKey>.sprite.json`
26 * each (decision 0016 point 7). The cache is used only when the PNG's size,
27 * mtime and frame count match and its sprite still validates. A cache that
28 * can't be read or written is ignored: the PNG is decoded instead.
29 */
30export function cachedSheetLoader(files: SheetFiles, cacheFolder: string): SheetLoader {
31  return async ({ path, file, cacheKey, frames, maxFrames }) => {
32    const stat = await files.stat(path)
33    if (!stat) return undefined
34    const source: Source = { size: stat.size, mtimeMs: stat.mtimeMs, frames }
35    const cachePath = `${cacheFolder}/${cacheKey}.sprite.json`
36
37    const cached = await readCache(files, cachePath, source, file, maxFrames)
38    if (cached) return { ok: true, value: cached, issues: [] }
39
40    const result = spriteFromPng(await files.readBytes(path), frames, file, maxFrames)
41    if (result.ok) await writeCache(files, cachePath, source, result.value)
42    return result
43  }
44}
45
46async function readCache(files: SheetFiles, cachePath: string, source: Source, file: string, maxFrames: number | undefined): Promise<Sprite | undefined> {
47  try {
48    const text = await files.readText(cachePath)
49    if (text === undefined) return undefined
50    const entry: unknown = JSON.parse(text)
51    if (!isObject(entry) || entry.v !== USER_CONTENT.spriteCacheVersion || !sameSource(entry.source, source)) return undefined
52    const sprite: Validation<Sprite> = validateSprite(entry.sprite, { file, ...(maxFrames === undefined ? {} : { maxFrames }) })
53    return sprite.ok ? sprite.value : undefined
54  } catch {
55    return undefined
56  }
57}
58
59async function writeCache(files: SheetFiles, cachePath: string, source: Source, sprite: Sprite): Promise<void> {
60  try {
61    await files.writeText(cachePath, JSON.stringify({ v: USER_CONTENT.spriteCacheVersion, source, sprite }))
62  } catch {
63    // The sprite still loads; the next session decodes the PNG again
64  }
65}
66
67function sameSource(value: unknown, source: Source): boolean {
68  return isObject(value) && value.size === source.size && value.mtimeMs === source.mtimeMs && value.frames === source.frames
69}
70
hooks/content/check-biome-references.ts 20 lines
1import { fieldPath } from './fields'
2import { IssueList } from './issue-list'
3import type { Biome, Validation } from './types'
4
5/**
6 * Runs after merging (decision 0007): drops biome entries whose Modster
7 * doesn't exist, an error for that entry only (CONTENT_FORMAT.md). The biome
8 * itself is dropped only when no entries are left.
9 */
10export function checkBiomeReferences(biome: Biome, modsterIds: ReadonlySet<string>, file: string): Validation<Biome> {
11  const issues = new IssueList(file)
12  const modsters = biome.modsters.filter((entry, index) => {
13    if (modsterIds.has(entry.id)) return true
14    issues.error(fieldPath(fieldPath('modsters', index), 'id'), `names a Modster that doesn't exist: "${entry.id}"`)
15    return false
16  })
17  if (modsters.length === 0) return issues.fail('modsters', 'has no Modsters left that exist')
18  return { ok: true, value: { ...biome, modsters }, issues: issues.items }
19}
20
hooks/content/check-tier-balance.ts 38 lines
1import { TIERS } from '../constants'
2import { IssueList } from './issue-list'
3import type { Biome, ContentIssue, Modster, Rarity } from './types'
4
5const percent = (value: number): string => `${(value * 100).toFixed(1)}%`
6
7/**
8 * Decision 0030 point 6: a warning for each tier whose Modsters each appear
9 * less often than the Modsters of a rarer tier in the same biome, e.g. 100
10 * commons sharing 76% next to a lone uncommon. Entries whose Modster is
11 * missing are skipped; `checkBiomeReferences` reports those.
12 */
13export function checkTierBalance(biome: Biome, modsters: ReadonlyMap<string, Modster>, file: string): ContentIssue[] {
14  const counts = new Map<Rarity, number>()
15  for (const entry of biome.modsters) {
16    const modster = modsters.get(entry.id)
17    if (!modster) continue
18    const tier = entry.rarity ?? modster.rarity
19    counts.set(tier, (counts.get(tier) ?? 0) + 1)
20  }
21  const present = TIERS.filter((row) => counts.has(row.tier))
22  const total = present.reduce((sum, row) => sum + row.weight, 0)
23  // Each Modster's chance to appear, by tier, most common tier first
24  const each = present.map((row) => ({ tier: row.tier, chance: row.weight / total / (counts.get(row.tier) ?? 1) }))
25
26  const issues = new IssueList(file)
27  each.forEach((tier, index) => {
28    const rarer = each.slice(index + 1).filter((other) => other.chance > tier.chance)
29    if (rarer.length === 0) return
30    const most = rarer.reduce((best, other) => (other.chance > best.chance ? other : best))
31    issues.warning(
32      'modsters',
33      `each ${tier.tier} Modster appears ${percent(tier.chance)} of the time, less than each ${most.tier} one (${percent(most.chance)}); move some to a rarer tier or out of this biome`,
34    )
35  })
36  return issues.items
37}
38
hooks/content/issue-list.ts 43 lines
1import type { ContentIssue, Validation } from './types'
2
3/** Collects the issues for one file while a validator walks it. */
4export class IssueList {
5  readonly items: ContentIssue[] = []
6  readonly file: string
7
8  // A plain field, not a parameter property: tools/ load this file with Node's type stripping, which has no parameter properties
9  constructor(file: string) {
10    this.file = file
11  }
12
13  error(field: string, problem: string): void {
14    this.items.push({ severity: 'error', file: this.file, field, problem })
15  }
16
17  warning(field: string, problem: string): void {
18    this.items.push({ severity: 'warning', file: this.file, field, problem })
19  }
20
21  get hasErrors(): boolean {
22    return this.items.some((issue) => issue.severity === 'error')
23  }
24
25  /** Not `ok`, for input too broken to walk any further. */
26  fail(field: string, problem: string): Validation<never> {
27    this.error(field, problem)
28    return { ok: false, issues: this.items }
29  }
30
31  /** `ok` with `value` when nothing is an error; the issues come along either way. */
32  result<T>(value: T): Validation<T> {
33    return this.hasErrors ? { ok: false, issues: this.items } : { ok: true, value, issues: this.items }
34  }
35}
36
37/** One line for logs and the Settings tab: `biomes/forest/biome.json: modsters[1].rarity must be …` */
38export function formatIssue(issue: ContentIssue): string {
39  const where = issue.field ? `${issue.file}: ${issue.field}` : issue.file
40  const tag = issue.severity === 'warning' ? ' (warning)' : ''
41  return `${where} ${issue.problem}${tag}`
42}
43
hooks/content/leaves-no-biome.ts 17 lines
1import type { ContentRegistry } from './load-content'
2import type { ToggleChange } from './toggle-disabled'
3
4/**
5 * Whether turning an item off would leave no biome to play (decision 0032
6 * point 8): the last biome, or a Modster every biome left depends on alone.
7 * Turning on never does, and with no biome already there's nothing to keep.
8 */
9export function leavesNoBiome(content: Pick<ContentRegistry, 'biomes'>, change: ToggleChange): boolean {
10  if (!change.off || content.biomes.size === 0) return false
11  for (const { biome } of content.biomes.values()) {
12    const survives = change.kind === 'biome' ? biome.id !== change.id : biome.modsters.some((entry) => entry.id !== change.id)
13    if (survives) return false
14  }
15  return true
16}
17
hooks/content/load-all-content.ts 65 lines
1import { loadFolder, type ContentReader, type ContentRegistry, type SheetLoader } from './load-content'
2import { mergeContent, type MergedContent } from './merge-content'
3import type { ContentIssue, UserSettings } from './types'
4import { validateSettings } from './validate-settings'
5
6export interface ContentFolders {
7  reader: ContentReader
8  builtInRoot: string
9  /** The `includeBuiltins` option (decision 0007 point 5); built-in catchers load either way (decision 0035 point 1) */
10  includeBuiltins: boolean
11  /** The user's content folder; absent when the home folder is unknown */
12  user?: { root: string; label: string; sheets: SheetLoader }
13}
14
15/**
16 * Loads built-in and user content and merges them by id (decision 0007).
17 * The user folder and its `settings.json` are optional; never rejects.
18 */
19export async function loadAllContent(folders: ContentFolders): Promise<MergedContent> {
20  const { reader, builtInRoot, includeBuiltins, user } = folders
21  const [builtIn, userContent] = await Promise.all([
22    loadFolder(reader, builtInRoot, includeBuiltins ? {} : { catchersOnly: true }),
23    user ? loadFolder(reader, user.root, { label: user.label, sheets: user.sheets }) : emptyRegistry(),
24  ])
25  const settingsFile = `${user?.label ?? ''}settings.json`
26  const settingsIssues: ContentIssue[] = []
27  const settings = user ? await readSettings(reader, `${user.root}/settings.json`, settingsFile, settingsIssues) : undefined
28
29  return mergeContent({
30    builtIn,
31    user: { ...userContent, issues: [...userContent.issues, ...settingsIssues] },
32    ...(settings ? { settings } : {}),
33    settingsFile,
34  })
35}
36
37/** The settings, or undefined when there's no file or it's invalid (then nothing is disabled). */
38async function readSettings(reader: ContentReader, path: string, file: string, issues: ContentIssue[]): Promise<UserSettings | undefined> {
39  const fail = (problem: string): undefined => {
40    issues.push({ severity: 'error', file, field: '', problem })
41    return undefined
42  }
43  let text: string | undefined
44  try {
45    text = await reader.readText(path)
46  } catch (error) {
47    return fail(`could not be read: ${error instanceof Error ? error.message : String(error)}`)
48  }
49  // The file is optional
50  if (text === undefined) return undefined
51  let value: unknown
52  try {
53    value = JSON.parse(text)
54  } catch (error) {
55    return fail(`is not valid JSON: ${error instanceof Error ? error.message : String(error)}`)
56  }
57  const result = validateSettings(value, { file })
58  issues.push(...result.issues)
59  return result.ok ? result.value : undefined
60}
61
62function emptyRegistry(): ContentRegistry {
63  return { biomes: new Map(), modsters: new Map(), catchers: new Map(), issues: [] }
64}
65