watchpot 1.0.0-rc.3 → 1.0.0-rc.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,21 @@
2
2
 
3
3
  Each release is a tag `vX.Y.Z`. A breaking change names its codemod in `codemods/` (policy in `codemods/README.md`).
4
4
 
5
+ ## 1.0.0-rc.6
6
+
7
+ - The auto-player keeps each feature's move list in a cell of the sim store and lists it again only when something it read changed, or a fit table did. A cell checked since the last write skips its walk, and a stats feature's unchanged flags keep their object. Exact: a heavy game's 40 h fit is 23% faster with an identical report.
8
+ - `tunables`, `sourceKey` and `simCache`: a snapshot cache that knows which knobs each snapshot read, so a fit resumes from the latest snapshot still valid after a change to code, plan or a knob.
9
+
10
+ ## 1.0.0-rc.5
11
+
12
+ rc.4 was tagged but never published: `runSeeds` imported `node:os`, which broke every browser bundle of `watchpot/sim` (the site's sim lab among them). It reads `navigator.hardwareConcurrency` now, and a rule test keeps `node:` imports out of `/core` and `/sim`. Everything below ships here.
13
+
14
+ ## 1.0.0-rc.4
15
+
16
+ - Fix: a stats feature kept every feed it ever made alive (each new feed's closures held the last one), so a long sim's memory grew without bound; a 20 h fit of a heavy game went from 195 MB live heap to 20 MB.
17
+ - `runFit` takes `stepping: { maxMs }`: steps grow while the pilot has nothing to buy and drop back on a buy, never past a planned gate minute or a snapshot. The proof replays the same steps.
18
+ - `runSeeds({ script, seeds, workers })` runs a sim script per seed across cores, results in seed order.
19
+
5
20
  ## 1.0.0-rc.3
6
21
 
7
22
  Found by scaffolding a game from npm: the published store types collapsed to `never` in a game (the declarations now load the zustand middleware types), npm dropped the template's `.gitignore` (it ships as `gitignore` and the scaffold renames it), and `create-watchpot` left a new game unformatted (it runs `lint:fix` after the install).
package/README.md CHANGED
@@ -1,28 +1,32 @@
1
1
  # watchpot
2
2
 
3
+ [![npm](https://img.shields.io/npm/v/watchpot)](https://www.npmjs.com/package/watchpot)
4
+ [![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
5
+
3
6
  A framework-light engine for idle and incremental games, in TypeScript on Bun and React. You describe a game as
4
7
  features (saved state, actions, tick steps, a reset rule); the engine runs the clock, the big numbers, saving, time
5
8
  away, the systems idle games share (currencies, generators, upgrade trees, prestige, gacha, events) and a sim lab
6
9
  that proves the pacing. It is for developers who want to build an idle game and keep the look, the words and the
7
10
  rules their own: the engine ships mechanism and behaviour, never a stylesheet.
8
11
 
9
- **How this was made.** This engine is more or less completely vibe-coded, prompted closely by somebody
10
- who has spent far too much time playing idle games.
12
+ The website — the guide, the reference pages and a game built with the engine — is at
13
+ <https://backshelf.github.io/watchpot>.
14
+
15
+ **How this was made.** The engine was written AI-assisted, under close direction from a developer who has spent
16
+ years playing idle games, and what it claims is held to by the sim lab and the test suite rather than by trust.
11
17
 
12
18
  ## Install
13
19
 
14
- Needs Bun 1.4.3 or later. watchpot 1.0 is meant to be public on npm as `watchpot` (MIT):
20
+ On npm under the MIT licence. Bun 1.4.3 or later is required (`engines.bun`):
15
21
 
16
22
  ```sh
17
23
  bun add watchpot
18
24
  ```
19
25
 
20
- On npm, the runtime entries (`core`, `sim`, `test`, `react`, `devtools`, `kit`, `sound`, `three`, `ui`, `shader`)
21
- work on Node bundlers (Vite) too: the package ships compiled JS and declarations in `dist/`. Bun-only, stated
22
- plainly: the template's dev server (`dev.ts`), `watchpot/sound/pack`, `watchpot/kit/theme`, and the sim's gate CLI.
23
-
24
- A release that is not on npm yet installs by git tag instead, with `"watchpot": "git+ssh://github.com/backshelf/watchpot.git#vX.Y.Z"`
25
- in `package.json`. [Installing](docs/installing.md) has the details and the peers each entry needs.
26
+ The runtime entries (`core`, `sim`, `test`, `react`, `devtools`, `kit`, `sound`, `three`, `ui`, `shader`) also work
27
+ on Node bundlers such as Vite: the package ships compiled JavaScript and type declarations in `dist/`. Bun-only,
28
+ stated plainly: the template's dev server (`dev.ts`), `watchpot/sound/pack`, `watchpot/kit/theme`, and the sim's
29
+ gate CLI. [Installing](docs/installing.md) has the details and the peers each entry needs.
26
30
 
27
31
  ## The watchpot command
28
32
 
@@ -53,6 +53,14 @@ export interface Cells {
53
53
  touchAll(): void;
54
54
  /** Works out every cell that is not current and writes it into its slice of `root`. */
55
55
  settle(root: object): void;
56
+ /**
57
+ * An ad-hoc cell, tied to no slice and never written into the state: `fn` is worked out from the state and its
58
+ * value kept, with the same tracking as a derived value (the fields and slices it read, the cells it read). The
59
+ * returned reader gives the cached value while none of those may have changed, and works it out again when one
60
+ * has. `root` is the plain state (not a view); `fn` is handed it under the same read-tracking a derived recipe
61
+ * gets. `fn` must be a pure read of the state.
62
+ */
63
+ memo<T>(fn: (state: never) => T): (root: object) => T;
56
64
  }
57
65
  /** The cells of a game's features: one set per store (or per sim run), since it remembers what it has seen. */
58
66
  export declare function createCells(features: readonly FeatureSpec[]): Cells;
@@ -30,6 +30,12 @@ export interface PlainStore<S extends object> {
30
30
  snapshot(): PlainData;
31
31
  /** Puts the state to what `snapshot` gave (this store's or another's over the same game); derived values follow. */
32
32
  restore(data: PlainData): void;
33
+ /**
34
+ * A value worked out from the state and kept: `fn` is read through the same tracking a derived value gets, and the
35
+ * reader returns the kept value until a field or cell it read may have changed (a write, a `trial`, a reset, a
36
+ * restore). `fn` must be a pure read of the state; what it returns is shared between reads, so do not change it.
37
+ */
38
+ memo<T>(fn: (state: S) => T): () => T;
33
39
  /** Present so the plain store stands in where a store is expected; it never calls back. */
34
40
  subscribe(listener: () => void): () => void;
35
41
  /** Settled already: there is no save to load. */
package/api/sim/auto.d.ts CHANGED
@@ -66,6 +66,13 @@ export interface LookResult {
66
66
  export interface AutoStore<S> {
67
67
  getState(): S;
68
68
  trial?<T>(run: () => T): T;
69
+ /**
70
+ * A value worked out from the state and kept until what it read changes (the plain store has one). The
71
+ * auto-player keeps each feature's move list this way, and drops them all when a fit table changes (prices live
72
+ * outside the state); without it, every look lists them afresh. A game whose moves read anything else outside its
73
+ * state (the wall clock, a module variable) must not hand the auto-player a store with `memo`.
74
+ */
75
+ memo?<T>(fn: (state: S) => T): () => T;
69
76
  }
70
77
  /** The auto-player `autoPlayer` makes. */
71
78
  export interface AutoPlayer<S> {
@@ -0,0 +1,70 @@
1
+ /**
2
+ * A snapshot cache that knows which knobs each snapshot depends on, so a fit can resume from the latest snapshot that
3
+ * is still exactly valid after a change, and play on as the fresh run would have.
4
+ *
5
+ * Three things can change between runs, and each invalidates what it must and no more. The game's code (anything not
6
+ * a tunable) is in the cache's key (`sourceKey`), so a change to it leaves nothing to resume. The plan is checked by
7
+ * `fitHolds`: a gate moved before a snapshot invalidates it. A tunable is read through `tunables`, which notes the
8
+ * play time of each key's first read; changing that key invalidates only the snapshots taken after it.
9
+ *
10
+ * Files only: `simCache` keeps one JSON file per snapshot under `<dir>/<key>/`, and every function that touches disk
11
+ * is async (Bun's file APIs, so the sim stays browser-safe).
12
+ */
13
+ import { type FitGate } from "./fit";
14
+ import { type SimSnapshot } from "./snapshot";
15
+ /** A tunable's value: the knobs a game lets a run turn. */
16
+ export type TunableValue = number | string | boolean;
17
+ /** Tunables as a fit reads them: a read-only view that notes when each key was first read. */
18
+ export interface Tunables<T extends Record<string, TunableValue>> {
19
+ /** Read-only: each key's first read records the play clock's time; a write throws. */
20
+ readonly values: Readonly<T>;
21
+ /** The play clock (a fit passes its `playedMs`). Reads before it is set record 0. */
22
+ setClock(clock: () => number): void;
23
+ /** Each key read so far, with the play time of its first read (a copy). */
24
+ firstRead(): Record<string, number>;
25
+ /** The values as they are (a copy). */
26
+ current(): T;
27
+ }
28
+ /**
29
+ * Tunables over `values`. `clock` (or `setClock` later) gives the play time a first read is noted at; `from.firstRead`
30
+ * starts the map where a resumed run left it, so the run does not under-record.
31
+ */
32
+ export declare function tunables<T extends Record<string, TunableValue>>(values: T, clock?: () => number, from?: {
33
+ firstRead?: Record<string, number>;
34
+ }): Tunables<T>;
35
+ /**
36
+ * The key of a game's code: a hex SHA-256 over every file the glob `patterns` match (under `cwd`, sorted by path; each
37
+ * path and its contents hashed), and `extra` (a version, a flag). Any change to a matched file gives another key.
38
+ */
39
+ export declare function sourceKey(patterns: string[], options?: {
40
+ cwd?: string;
41
+ extra?: string;
42
+ }): Promise<string>;
43
+ /** A snapshot to resume from, with the first-read map to start the run's `tunables` from. */
44
+ export interface Resumed<X = unknown> {
45
+ snapshot: SimSnapshot<X>;
46
+ firstRead: Record<string, number>;
47
+ }
48
+ /** A cache of one game's snapshots under one source key. */
49
+ export interface SimCache<X = unknown> {
50
+ /**
51
+ * Writes `snapshot` with the tunables' values and the first reads made by its moment, so it can be saved as it is
52
+ * taken or after the run.
53
+ */
54
+ save(snapshot: SimSnapshot<X>, t: Tunables<Record<string, TunableValue>>): Promise<void>;
55
+ /**
56
+ * The latest cached snapshot still exactly valid: the plan holds before it (`fitHolds`), and every tunable whose
57
+ * value differs from the one it was taken with (or was not there) was not yet read when it was taken. With the
58
+ * first-read map to start the resumed run's tunables from. Undefined when none is.
59
+ */
60
+ resume(gates: readonly FitGate[], t: Tunables<Record<string, TunableValue>>): Promise<Resumed<X> | undefined>;
61
+ /** Deletes the snapshots after `atMs` (a run that resumes there replaces them). */
62
+ dropAfter(atMs: number): Promise<void>;
63
+ /** Deletes every snapshot under this key. */
64
+ clear(): Promise<void>;
65
+ }
66
+ /** The cache for `key` (a `sourceKey`) under `dir` (default `.watchpot/sim-cache`): `<dir>/<key>/snap-<atMs>.json`. */
67
+ export declare function simCache<X = unknown>(options: {
68
+ key: string;
69
+ dir?: string;
70
+ }): SimCache<X>;
package/api/sim/fit.d.ts CHANGED
@@ -11,6 +11,7 @@
11
11
  * table between them.
12
12
  */
13
13
  import { Decimal } from "../core";
14
+ import type { LookResult } from "./auto";
14
15
  import { type SimSnapshot, type SnapshotParts } from "./snapshot";
15
16
  import type { FitTable, FitTableData } from "./table";
16
17
  import { type SimQuality } from "./world";
@@ -83,8 +84,11 @@ export interface FittedGate {
83
84
  export interface FitRun<X = unknown> {
84
85
  /** Advances the game `dtMs`. */
85
86
  step(dtMs: number): void;
86
- /** One look by the pilot: buys what it would buy. */
87
- look(): void;
87
+ /**
88
+ * One look by the pilot: buys what it would buy. It may return what it did (`LookResult`); with `stepping`, a look
89
+ * that did nothing lets the steps grow and one that bought or moved sends them back to the floor.
90
+ */
91
+ look(): void | LookResult;
88
92
  /** Ms of play so far. */
89
93
  playedMs(): number;
90
94
  /** After each step, before the gates are asked (sample the holdings here). */
@@ -110,6 +114,16 @@ export interface FitOptions<X = unknown> extends FitRun<X> {
110
114
  stepMs?: number;
111
115
  /** A look every this many steps. Default 3. */
112
116
  lookEvery?: number;
117
+ /**
118
+ * Steps that grow while the pilot has nothing to do: the floor is the resolved `stepMs`, and `maxMs` the longest
119
+ * step. Looks come on the `lookEvery` cadence at the floor and every step above it; a look that did nothing doubles
120
+ * the step (up to `maxMs`), one that bought or moved sets it back to the floor, a look that reports nothing leaves
121
+ * it at the floor. A step never runs past the next planned minute, the next snapshot or `limitMs`. Absent, the fit
122
+ * steps at `stepMs` as ever. Throws when `maxMs` is below `stepMs`.
123
+ */
124
+ stepping?: {
125
+ maxMs: number;
126
+ };
113
127
  /** With `capture`: a snapshot every this many ms of play (and always one where the run ends). */
114
128
  snapshotEveryMs?: number;
115
129
  /**
@@ -125,6 +139,12 @@ export interface FitProgress {
125
139
  readonly steps: number;
126
140
  readonly stepMs: number;
127
141
  readonly lookEvery: number;
142
+ /** With `stepping`: its ceiling, the step the fit stood at, and the steps since its last look. */
143
+ readonly stepping?: {
144
+ readonly maxMs: number;
145
+ readonly curMs: number;
146
+ readonly sinceLook: number;
147
+ };
128
148
  /** The plan as this fit had it: each gate's key and minute. */
129
149
  readonly plan: readonly (readonly [string, number])[];
130
150
  /** Every gate as it stood. */
@@ -149,7 +169,8 @@ export declare function fitHolds(snapshot: SimSnapshot, gates: readonly FitGate[
149
169
  * Prices a game in one pass. Shuts every gate in the table, orders them by `atMs` (the plan's order between equals),
150
170
  * then steps: with `capture`, a snapshot first when one is due; every `lookEvery`th step `look()`, `step(stepMs)`,
151
171
  * `afterStep()`, then each unopened gate whose minute has come is asked `price()`, and a figure goes into the table
152
- * and opens it at `playedMs()`. Ends on `done()` or at `limitMs`.
172
+ * and opens it at `playedMs()`. Ends on `done()` or at `limitMs`. With `stepping` the step grows while looks do
173
+ * nothing (see `FitOptions.stepping`); the snapshots keep where it stood.
153
174
  */
154
175
  export declare function runFit<X = unknown>(options: FitOptions<X>): FitResult<X>;
155
176
  /** The fit's report: a markdown table of gate, planned minute, the minute it opened (or "never"), and its value. */
@@ -169,8 +190,9 @@ export declare function proofStretches<X>(marks: readonly SimSnapshot<X>[], star
169
190
  /**
170
191
  * Replays one stretch on the table as it stands: `replay` builds a run from the stretch's start (from nothing when
171
192
  * there is none) and plays it, on the fit's own steps and looks, to the end's moment; the stretch holds when the run
172
- * then is the snapshot (its world, its player, and its `extra` when the replay captures one). The differences, empty
173
- * when it holds.
193
+ * then is the snapshot (its world, its player, and its `extra` when the replay captures one). A fit that stepped
194
+ * (`stepping`) is replayed by the same stepper, from the state its start kept, never stepping past the end's moment.
195
+ * The differences, empty when it holds.
174
196
  */
175
197
  export declare function replayStretch<X>(stretch: ProofStretch<X>, replay: (from: SimSnapshot<X> | undefined) => FitRun<X>): string[];
176
198
  /**
package/api/sim/gate.d.ts CHANGED
@@ -26,5 +26,18 @@ export interface GateRunner<J, Res> {
26
26
  export declare function runGate<J, Res>(checks: readonly GateCheck<J, Res>[], { key, run }: GateRunner<J, Res>): Promise<GateResult[]>;
27
27
  /** Runs a script in its own Bun process and parses what it prints as JSON; a non-zero exit throws with its stderr. */
28
28
  export declare function spawnJob<Res>(script: string, args: readonly string[]): Promise<Res>;
29
+ /**
30
+ * Runs one script per seed (`--seed=<seed>` then `args`) through `spawnJob`, at most `workers` at once, and returns
31
+ * the results in seed order whatever order they finish in. The first failure rejects; jobs already running finish,
32
+ * and no new ones start.
33
+ */
34
+ export declare function runSeeds<Res>({ script, seeds, args, workers, }: {
35
+ script: string;
36
+ seeds: readonly string[];
37
+ /** Extra args after `--seed=<seed>`. */
38
+ args?: readonly string[];
39
+ /** Processes at once. Default: the cores (`navigator.hardwareConcurrency`) less one, at least 1. */
40
+ workers?: number;
41
+ }): Promise<Res[]>;
29
42
  /** Each check's count of checks held by a majority, then every check's runs, values and spread. */
30
43
  export declare function formatGate(results: readonly GateResult[]): string;
@@ -1,5 +1,6 @@
1
1
  export * from "./auto";
2
2
  export * from "./bare";
3
+ export * from "./cache";
3
4
  export * from "./contract";
4
5
  export * from "./fit";
5
6
  export * from "./gate";
@@ -0,0 +1,4 @@
1
+ /** Every fit table's change so far, all tables together. */
2
+ export declare const tablesEpoch: () => number;
3
+ /** A fit table changed. */
4
+ export declare const bumpTables: () => void;
@@ -53,6 +53,14 @@ export interface Cells {
53
53
  touchAll(): void;
54
54
  /** Works out every cell that is not current and writes it into its slice of `root`. */
55
55
  settle(root: object): void;
56
+ /**
57
+ * An ad-hoc cell, tied to no slice and never written into the state: `fn` is worked out from the state and its
58
+ * value kept, with the same tracking as a derived value (the fields and slices it read, the cells it read). The
59
+ * returned reader gives the cached value while none of those may have changed, and works it out again when one
60
+ * has. `root` is the plain state (not a view); `fn` is handed it under the same read-tracking a derived recipe
61
+ * gets. `fn` must be a pure read of the state.
62
+ */
63
+ memo<T>(fn: (state: never) => T): (root: object) => T;
56
64
  }
57
65
  /** The cells of a game's features: one set per store (or per sim run), since it remembers what it has seen. */
58
66
  export declare function createCells(features: readonly FeatureSpec[]): Cells;
Binary file
@@ -30,6 +30,12 @@ export interface PlainStore<S extends object> {
30
30
  snapshot(): PlainData;
31
31
  /** Puts the state to what `snapshot` gave (this store's or another's over the same game); derived values follow. */
32
32
  restore(data: PlainData): void;
33
+ /**
34
+ * A value worked out from the state and kept: `fn` is read through the same tracking a derived value gets, and the
35
+ * reader returns the kept value until a field or cell it read may have changed (a write, a `trial`, a reset, a
36
+ * restore). `fn` must be a pure read of the state; what it returns is shared between reads, so do not change it.
37
+ */
38
+ memo<T>(fn: (state: S) => T): () => T;
33
39
  /** Present so the plain store stands in where a store is expected; it never calls back. */
34
40
  subscribe(listener: () => void): () => void;
35
41
  /** Settled already: there is no save to load. */
@@ -91,6 +91,11 @@ export function createPlainStore(game, options) {
91
91
  cells.touchAll();
92
92
  }
93
93
  },
94
+ memo: (fn) => {
95
+ const read = cells.memo(fn);
96
+ // Over the raw state: the cell tracks what `fn` reads itself, and a read through the reader is untracked.
97
+ return () => read(cells.raw(reader));
98
+ },
94
99
  snapshot: () => {
95
100
  const out = {};
96
101
  for (const f of features) {
@@ -25,6 +25,12 @@ export function foldContributions(contributions, options) {
25
25
  }
26
26
  return statIndex(options).over(options.q, { extra: (stat) => byStat.get(stat) ?? [] });
27
27
  }
28
+ /**
29
+ * A function that always gives `n`. Made out here, not inline in `feed`: a closure made inside `feed` keeps `feed`'s
30
+ * whole scope alive, `was` (the last feed) included, so every feed ever made stayed reachable through the next one
31
+ * and a long sim grew without bound.
32
+ */
33
+ const always = (n) => () => n;
28
34
  /** The names a stat cannot take: the feature's own derived values beside the stats. */
29
35
  export const RESERVED_STAT_IDS = ["flags", "feed"];
30
36
  /**
@@ -107,7 +113,7 @@ export function defineStats(def) {
107
113
  const times = r.times;
108
114
  const list = fed[r.effect.stat] ?? [];
109
115
  fed[r.effect.stat] = list;
110
- list.push({ effect: r.effect, meta: { label, owner, group: owner, times: () => times } });
116
+ list.push({ effect: r.effect, meta: { label, owner, group: owner, times: always(times) } });
111
117
  }
112
118
  last = { rows, fed };
113
119
  return fed;
@@ -117,11 +123,17 @@ export function defineStats(def) {
117
123
  muted: def.muted ? (group) => def.muted?.(q, group) ?? false : undefined,
118
124
  extra: (stat) => self(q).feed[stat] ?? [],
119
125
  });
126
+ let lastFlags = null;
120
127
  const derived = {
121
128
  feed,
122
129
  flags: (q) => {
123
130
  const g = graph(q);
124
- return Object.fromEntries(flags.map((f) => [f, g.flag(f)]));
131
+ const next = Object.fromEntries(flags.map((f) => [f, g.flag(f)]));
132
+ // The same flags hand back the same object: a new one would stale every value that reads `flags`.
133
+ if (lastFlags && flags.every((f) => lastFlags?.[f] === next[f]))
134
+ return lastFlags;
135
+ lastFlags = next;
136
+ return next;
125
137
  },
126
138
  };
127
139
  for (const id of ids)
@@ -66,6 +66,13 @@ export interface LookResult {
66
66
  export interface AutoStore<S> {
67
67
  getState(): S;
68
68
  trial?<T>(run: () => T): T;
69
+ /**
70
+ * A value worked out from the state and kept until what it read changes (the plain store has one). The
71
+ * auto-player keeps each feature's move list this way, and drops them all when a fit table changes (prices live
72
+ * outside the state); without it, every look lists them afresh. A game whose moves read anything else outside its
73
+ * state (the wall clock, a module variable) must not hand the auto-player a store with `memo`.
74
+ */
75
+ memo?<T>(fn: (state: S) => T): () => T;
69
76
  }
70
77
  /** The auto-player `autoPlayer` makes. */
71
78
  export interface AutoPlayer<S> {
package/dist/sim/auto.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { ZERO } from "../core/index.js";
2
2
  import { planDay } from "./schedule.js";
3
+ import { tablesEpoch } from "./table-epoch.js";
3
4
  /** Every feature's moves now, in the game's feature order. */
4
5
  export function movesOf(game, state) {
5
6
  const out = [];
@@ -37,6 +38,31 @@ export function autoPlayer(game, { balance: given, maxMoves = 1_000, objective,
37
38
  if (missing.length > 0)
38
39
  console.warn(`autoPlayer: ${missing.map((k) => `"${k}"`).join(", ")} can be bought from and declare${missing.length === 1 ? "s" : ""} no moves, so the auto-player will never buy there. Give the feature \`moves\` (or \`withMoves\`), or pass \`quiet\`.`);
39
40
  };
41
+ /**
42
+ * Each feature's move list, kept per store when it has `memo` (else listed afresh), in the game's feature order;
43
+ * made anew when any fit table has changed since, since a price read from a table is outside the state.
44
+ */
45
+ const listers = new WeakMap();
46
+ const movesFor = (store, state) => {
47
+ let mine = listers.get(store);
48
+ if (!mine || mine.tables !== tablesEpoch()) {
49
+ const lists = [];
50
+ for (const f of game.features) {
51
+ const read = f.moves;
52
+ if (!read)
53
+ continue;
54
+ if (store.memo) {
55
+ const kept = store.memo(read);
56
+ lists.push(() => kept());
57
+ }
58
+ else
59
+ lists.push(read);
60
+ }
61
+ mine = { tables: tablesEpoch(), lists };
62
+ listers.set(store, mine);
63
+ }
64
+ return mine.lists.flatMap((list) => list(state));
65
+ };
40
66
  const trial = (store, run) => {
41
67
  if (store.trial)
42
68
  return store.trial(run);
@@ -92,7 +118,7 @@ export function autoPlayer(game, { balance: given, maxMoves = 1_000, objective,
92
118
  while (total() < maxMoves) {
93
119
  const state = store.getState();
94
120
  let best = null;
95
- for (const move of movesOf(game, state)) {
121
+ for (const move of movesFor(store, state)) {
96
122
  if (isFree(move) || !move.cost || refused.has(move.id))
97
123
  continue;
98
124
  const held = balance(state, move.cost.currency);
@@ -115,7 +141,7 @@ export function autoPlayer(game, { balance: given, maxMoves = 1_000, objective,
115
141
  // Free moves: each one worth taking, best first, once a look unless it repeats.
116
142
  while (total() < maxMoves) {
117
143
  const state = store.getState();
118
- const free = movesOf(game, state)
144
+ const free = movesFor(store, state)
119
145
  .filter((m) => isFree(m) && !refused.has(m.id) && (m.repeat || !taken.has(m.id)))
120
146
  .map((move) => ({ move, worth: worthOf(store, move, state) }))
121
147
  .filter((m) => m.worth > 0)
@@ -0,0 +1,70 @@
1
+ /**
2
+ * A snapshot cache that knows which knobs each snapshot depends on, so a fit can resume from the latest snapshot that
3
+ * is still exactly valid after a change, and play on as the fresh run would have.
4
+ *
5
+ * Three things can change between runs, and each invalidates what it must and no more. The game's code (anything not
6
+ * a tunable) is in the cache's key (`sourceKey`), so a change to it leaves nothing to resume. The plan is checked by
7
+ * `fitHolds`: a gate moved before a snapshot invalidates it. A tunable is read through `tunables`, which notes the
8
+ * play time of each key's first read; changing that key invalidates only the snapshots taken after it.
9
+ *
10
+ * Files only: `simCache` keeps one JSON file per snapshot under `<dir>/<key>/`, and every function that touches disk
11
+ * is async (Bun's file APIs, so the sim stays browser-safe).
12
+ */
13
+ import { type FitGate } from "./fit";
14
+ import { type SimSnapshot } from "./snapshot";
15
+ /** A tunable's value: the knobs a game lets a run turn. */
16
+ export type TunableValue = number | string | boolean;
17
+ /** Tunables as a fit reads them: a read-only view that notes when each key was first read. */
18
+ export interface Tunables<T extends Record<string, TunableValue>> {
19
+ /** Read-only: each key's first read records the play clock's time; a write throws. */
20
+ readonly values: Readonly<T>;
21
+ /** The play clock (a fit passes its `playedMs`). Reads before it is set record 0. */
22
+ setClock(clock: () => number): void;
23
+ /** Each key read so far, with the play time of its first read (a copy). */
24
+ firstRead(): Record<string, number>;
25
+ /** The values as they are (a copy). */
26
+ current(): T;
27
+ }
28
+ /**
29
+ * Tunables over `values`. `clock` (or `setClock` later) gives the play time a first read is noted at; `from.firstRead`
30
+ * starts the map where a resumed run left it, so the run does not under-record.
31
+ */
32
+ export declare function tunables<T extends Record<string, TunableValue>>(values: T, clock?: () => number, from?: {
33
+ firstRead?: Record<string, number>;
34
+ }): Tunables<T>;
35
+ /**
36
+ * The key of a game's code: a hex SHA-256 over every file the glob `patterns` match (under `cwd`, sorted by path; each
37
+ * path and its contents hashed), and `extra` (a version, a flag). Any change to a matched file gives another key.
38
+ */
39
+ export declare function sourceKey(patterns: string[], options?: {
40
+ cwd?: string;
41
+ extra?: string;
42
+ }): Promise<string>;
43
+ /** A snapshot to resume from, with the first-read map to start the run's `tunables` from. */
44
+ export interface Resumed<X = unknown> {
45
+ snapshot: SimSnapshot<X>;
46
+ firstRead: Record<string, number>;
47
+ }
48
+ /** A cache of one game's snapshots under one source key. */
49
+ export interface SimCache<X = unknown> {
50
+ /**
51
+ * Writes `snapshot` with the tunables' values and the first reads made by its moment, so it can be saved as it is
52
+ * taken or after the run.
53
+ */
54
+ save(snapshot: SimSnapshot<X>, t: Tunables<Record<string, TunableValue>>): Promise<void>;
55
+ /**
56
+ * The latest cached snapshot still exactly valid: the plan holds before it (`fitHolds`), and every tunable whose
57
+ * value differs from the one it was taken with (or was not there) was not yet read when it was taken. With the
58
+ * first-read map to start the resumed run's tunables from. Undefined when none is.
59
+ */
60
+ resume(gates: readonly FitGate[], t: Tunables<Record<string, TunableValue>>): Promise<Resumed<X> | undefined>;
61
+ /** Deletes the snapshots after `atMs` (a run that resumes there replaces them). */
62
+ dropAfter(atMs: number): Promise<void>;
63
+ /** Deletes every snapshot under this key. */
64
+ clear(): Promise<void>;
65
+ }
66
+ /** The cache for `key` (a `sourceKey`) under `dir` (default `.watchpot/sim-cache`): `<dir>/<key>/snap-<atMs>.json`. */
67
+ export declare function simCache<X = unknown>(options: {
68
+ key: string;
69
+ dir?: string;
70
+ }): SimCache<X>;
@@ -0,0 +1,119 @@
1
+ /**
2
+ * A snapshot cache that knows which knobs each snapshot depends on, so a fit can resume from the latest snapshot that
3
+ * is still exactly valid after a change, and play on as the fresh run would have.
4
+ *
5
+ * Three things can change between runs, and each invalidates what it must and no more. The game's code (anything not
6
+ * a tunable) is in the cache's key (`sourceKey`), so a change to it leaves nothing to resume. The plan is checked by
7
+ * `fitHolds`: a gate moved before a snapshot invalidates it. A tunable is read through `tunables`, which notes the
8
+ * play time of each key's first read; changing that key invalidates only the snapshots taken after it.
9
+ *
10
+ * Files only: `simCache` keeps one JSON file per snapshot under `<dir>/<key>/`, and every function that touches disk
11
+ * is async (Bun's file APIs, so the sim stays browser-safe).
12
+ */
13
+ import { fitHolds } from "./fit.js";
14
+ import { decodeSnapshot, encodeSnapshot } from "./snapshot.js";
15
+ /**
16
+ * Tunables over `values`. `clock` (or `setClock` later) gives the play time a first read is noted at; `from.firstRead`
17
+ * starts the map where a resumed run left it, so the run does not under-record.
18
+ */
19
+ export function tunables(values, clock, from) {
20
+ let now = clock;
21
+ const first = new Map(Object.entries(from?.firstRead ?? {}));
22
+ const copy = { ...values };
23
+ const refuse = () => {
24
+ throw new Error("tunables are read-only: a run reads them, the caller changes them between runs");
25
+ };
26
+ const view = new Proxy(copy, {
27
+ get(target, key, receiver) {
28
+ if (typeof key === "string" && Object.hasOwn(target, key) && !first.has(key))
29
+ first.set(key, now?.() ?? 0);
30
+ return Reflect.get(target, key, receiver);
31
+ },
32
+ set: refuse,
33
+ defineProperty: refuse,
34
+ deleteProperty: refuse,
35
+ });
36
+ return {
37
+ values: view,
38
+ setClock(c) {
39
+ now = c;
40
+ },
41
+ firstRead: () => Object.fromEntries(first),
42
+ current: () => ({ ...copy }),
43
+ };
44
+ }
45
+ /** Hex SHA-256 over text. */
46
+ function sha(parts) {
47
+ const h = new Bun.CryptoHasher("sha256");
48
+ for (const p of parts)
49
+ h.update(p);
50
+ return h.digest("hex");
51
+ }
52
+ /**
53
+ * The key of a game's code: a hex SHA-256 over every file the glob `patterns` match (under `cwd`, sorted by path; each
54
+ * path and its contents hashed), and `extra` (a version, a flag). Any change to a matched file gives another key.
55
+ */
56
+ export async function sourceKey(patterns, options = {}) {
57
+ const cwd = options.cwd ?? process.cwd();
58
+ const paths = new Set();
59
+ for (const pattern of patterns)
60
+ for await (const p of new Bun.Glob(pattern).scan({ cwd, onlyFiles: true }))
61
+ paths.add(p.replaceAll("\\", "/"));
62
+ const parts = [];
63
+ for (const p of [...paths].sort()) {
64
+ const body = new Uint8Array(await Bun.file(`${cwd}/${p}`).arrayBuffer());
65
+ parts.push(sha([p]), sha([body]));
66
+ }
67
+ parts.push(`extra:${options.extra ?? ""}`);
68
+ return sha(parts);
69
+ }
70
+ /** The cache for `key` (a `sourceKey`) under `dir` (default `.watchpot/sim-cache`): `<dir>/<key>/snap-<atMs>.json`. */
71
+ export function simCache(options) {
72
+ const root = `${options.dir ?? ".watchpot/sim-cache"}/${options.key}`;
73
+ const files = async () => {
74
+ const out = [];
75
+ try {
76
+ for await (const f of new Bun.Glob("snap-*.json").scan({ cwd: root, onlyFiles: true }))
77
+ out.push(f);
78
+ }
79
+ catch {
80
+ // no directory yet: nothing cached
81
+ }
82
+ return out;
83
+ };
84
+ const read = async (f) => JSON.parse(await Bun.file(`${root}/${f}`).text());
85
+ const atOf = (f) => Number(f.slice(5, -5));
86
+ return {
87
+ async save(snapshot, t) {
88
+ // Only the reads made by the snapshot's moment: saved after the run, later reads would otherwise make it look
89
+ // dependent on knobs it never saw.
90
+ const firstRead = Object.fromEntries(Object.entries(t.firstRead()).filter(([, at]) => at <= snapshot.atMs));
91
+ const entry = { snapshot: encodeSnapshot(snapshot), tunables: t.current(), firstRead };
92
+ await Bun.write(`${root}/snap-${snapshot.atMs}.json`, JSON.stringify(entry));
93
+ },
94
+ async resume(gates, t) {
95
+ const now = t.current();
96
+ const names = (await files()).sort((a, b) => atOf(b) - atOf(a));
97
+ for (const f of names) {
98
+ const entry = await read(f);
99
+ const snapshot = decodeSnapshot(entry.snapshot);
100
+ if (fitHolds(snapshot, gates).length > 0)
101
+ continue;
102
+ const stale = Object.keys(now).some((k) => (!Object.hasOwn(entry.tunables, k) || entry.tunables[k] !== now[k]) &&
103
+ Object.hasOwn(entry.firstRead, k));
104
+ if (stale)
105
+ continue;
106
+ return { snapshot, firstRead: entry.firstRead };
107
+ }
108
+ return undefined;
109
+ },
110
+ async dropAfter(atMs) {
111
+ for (const f of await files())
112
+ if (atOf(f) > atMs)
113
+ await Bun.file(`${root}/${f}`).delete();
114
+ },
115
+ async clear() {
116
+ await Bun.$ `rm -rf ${root}`.quiet();
117
+ },
118
+ };
119
+ }