watchpot 1.0.0-rc.3 → 1.0.0-rc.5

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,16 @@
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.5
6
+
7
+ 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.
8
+
9
+ ## 1.0.0-rc.4
10
+
11
+ - 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.
12
+ - `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.
13
+ - `runSeeds({ script, seeds, workers })` runs a sim script per seed across cores, results in seed order.
14
+
5
15
  ## 1.0.0-rc.3
6
16
 
7
17
  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
 
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;
@@ -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;
package/dist/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/dist/sim/fit.js CHANGED
@@ -115,11 +115,38 @@ export function fitHolds(snapshot, gates) {
115
115
  out.push(`"${key}" was planned at ${fmtClock(at)}, before the snapshot, and is not now`);
116
116
  return out;
117
117
  }
118
+ /** Where a stepper starts: from what a snapshot kept, else at the floor, looking first if the cadence says so. */
119
+ function stepStart(floor, lookEvery, steps, kept) {
120
+ if (kept)
121
+ return { curMs: kept.curMs, sinceLook: kept.sinceLook };
122
+ const r = steps % lookEvery;
123
+ return { curMs: floor, sinceLook: r === 0 ? lookEvery : r };
124
+ }
125
+ /**
126
+ * One turn of the stepper, shared by the fit and its proof so both take the same steps: looks if due, moves the
127
+ * state by what the look did, and gives the ms to step. `boundary` is the next moment a step must not pass (a
128
+ * snapshot); `limitMs` the end. Without a ceiling the step is the floor, whatever the plan.
129
+ */
130
+ function stride(st, cfg, look, now, boundary, limitMs) {
131
+ const { floor, maxMs, lookEvery, minutes } = cfg;
132
+ if (st.curMs > floor || st.sinceLook >= lookEvery) {
133
+ st.sinceLook = 0;
134
+ const res = look();
135
+ if (maxMs !== undefined && res && typeof res === "object")
136
+ st.curMs = res.bought + res.free > 0 ? floor : Math.min(st.curMs * 2, maxMs);
137
+ }
138
+ st.sinceLook++;
139
+ if (maxMs === undefined)
140
+ return floor;
141
+ const gate = minutes.find((m) => m > now) ?? Infinity;
142
+ return Math.max(1, Math.min(st.curMs, gate - now, boundary - now, limitMs - now));
143
+ }
118
144
  /**
119
145
  * Prices a game in one pass. Shuts every gate in the table, orders them by `atMs` (the plan's order between equals),
120
146
  * then steps: with `capture`, a snapshot first when one is due; every `lookEvery`th step `look()`, `step(stepMs)`,
121
147
  * `afterStep()`, then each unopened gate whose minute has come is asked `price()`, and a figure goes into the table
122
- * and opens it at `playedMs()`. Ends on `done()` or at `limitMs`.
148
+ * and opens it at `playedMs()`. Ends on `done()` or at `limitMs`. With `stepping` the step grows while looks do
149
+ * nothing (see `FitOptions.stepping`); the snapshots keep where it stood.
123
150
  */
124
151
  export function runFit(options) {
125
152
  const { table, gates, step, look, playedMs, done, limitMs, afterStep, capture, from } = options;
@@ -128,6 +155,11 @@ export function runFit(options) {
128
155
  const order = gates.toSorted((a, b) => a.atMs - b.atMs);
129
156
  const fitted = order.map((g) => ({ key: g.key, atMs: g.atMs }));
130
157
  let steps = 0;
158
+ const maxMs = options.stepping?.maxMs;
159
+ if (maxMs !== undefined && !(maxMs >= stepMs))
160
+ throw new Error(`runFit: stepping.maxMs (${maxMs}) is below the step (${stepMs})`);
161
+ const cfg = { floor: stepMs, maxMs, lookEvery, minutes: order.map((g) => g.atMs) };
162
+ let st = stepStart(stepMs, lookEvery, 0);
131
163
  if (from) {
132
164
  const problems = fitHolds(from, gates);
133
165
  if (problems.length > 0)
@@ -135,7 +167,10 @@ export function runFit(options) {
135
167
  const fit = from.fit;
136
168
  if (fit.stepMs !== stepMs || fit.lookEvery !== lookEvery)
137
169
  throw new Error(`runFit: the snapshot was taken stepping ${fit.stepMs} ms with a look every ${fit.lookEvery} steps, not ${stepMs} and ${lookEvery}`);
170
+ if (fit.stepping?.maxMs !== maxMs)
171
+ throw new Error(`runFit: the snapshot was taken ${fit.stepping ? `stepping up to ${fit.stepping.maxMs} ms` : "without stepping"}, not ${maxMs === undefined ? "without" : `up to ${maxMs} ms`}`);
138
172
  steps = fit.steps;
173
+ st = stepStart(stepMs, lookEvery, steps, fit.stepping);
139
174
  table.load(fit.table);
140
175
  const was = new Map(fit.gates.map((g) => [g.key, g]));
141
176
  fitted.forEach((f, i) => {
@@ -159,16 +194,23 @@ export function runFit(options) {
159
194
  format: SNAPSHOT_FORMAT,
160
195
  atMs: at,
161
196
  ...capture(),
162
- fit: { steps, stepMs, lookEvery, plan, gates: fitted.map((f) => ({ ...f })), table: table.data() },
197
+ fit: {
198
+ steps,
199
+ stepMs,
200
+ lookEvery,
201
+ ...(maxMs !== undefined && { stepping: { maxMs, curMs: st.curMs, sinceLook: st.sinceLook } }),
202
+ plan,
203
+ gates: fitted.map((f) => ({ ...f })),
204
+ table: table.data(),
205
+ },
163
206
  });
164
207
  };
165
208
  const cadence = capture && options.snapshotEveryMs ? snapshotCadence(options.snapshotEveryMs, from?.atMs ?? 0) : null;
166
209
  for (; playedMs() < limitMs && !done(); steps++) {
167
210
  if (cadence?.due(playedMs()))
168
211
  take();
169
- if (steps % lookEvery === 0)
170
- look();
171
- step(stepMs);
212
+ const dt = stride(st, cfg, look, playedMs(), cadence?.next() ?? Infinity, limitMs);
213
+ step(dt);
172
214
  afterStep?.();
173
215
  const now = playedMs();
174
216
  order.forEach((g, i) => {
@@ -209,8 +251,9 @@ export function proofStretches(marks, start) {
209
251
  /**
210
252
  * Replays one stretch on the table as it stands: `replay` builds a run from the stretch's start (from nothing when
211
253
  * 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
212
- * then is the snapshot (its world, its player, and its `extra` when the replay captures one). The differences, empty
213
- * when it holds.
254
+ * then is the snapshot (its world, its player, and its `extra` when the replay captures one). A fit that stepped
255
+ * (`stepping`) is replayed by the same stepper, from the state its start kept, never stepping past the end's moment.
256
+ * The differences, empty when it holds.
214
257
  */
215
258
  export function replayStretch(stretch, replay) {
216
259
  const { from, to } = stretch;
@@ -219,10 +262,15 @@ export function replayStretch(stretch, replay) {
219
262
  throw new Error("proveFit: a mark was not taken by a fit");
220
263
  const run = replay(from);
221
264
  let steps = from?.fit?.steps ?? 0;
265
+ const cfg = {
266
+ floor: fit.stepMs,
267
+ maxMs: fit.stepping?.maxMs,
268
+ lookEvery: fit.lookEvery,
269
+ minutes: fit.plan.map(([, at]) => at).toSorted((a, b) => a - b),
270
+ };
271
+ const st = stepStart(fit.stepMs, fit.lookEvery, steps, from?.fit?.stepping);
222
272
  while (run.playedMs() < to.atMs) {
223
- if (steps % fit.lookEvery === 0)
224
- run.look();
225
- run.step(fit.stepMs);
273
+ run.step(stride(st, cfg, () => run.look(), run.playedMs(), to.atMs, Infinity));
226
274
  run.afterStep?.();
227
275
  steps++;
228
276
  }
@@ -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;
package/dist/sim/gate.js CHANGED
@@ -20,6 +20,33 @@ export async function spawnJob(script, args) {
20
20
  throw new Error(`gate job ${[script, ...args].join(" ")} exited ${code}: ${err}`);
21
21
  return JSON.parse(out);
22
22
  }
23
+ /**
24
+ * Runs one script per seed (`--seed=<seed>` then `args`) through `spawnJob`, at most `workers` at once, and returns
25
+ * the results in seed order whatever order they finish in. The first failure rejects; jobs already running finish,
26
+ * and no new ones start.
27
+ */
28
+ export async function runSeeds({ script, seeds, args = [], workers = Math.max(1, (globalThis.navigator?.hardwareConcurrency ?? 2) - 1), }) {
29
+ if (workers < 1)
30
+ throw new RangeError(`runSeeds needs at least 1 worker, got ${workers}`);
31
+ const results = new Array(seeds.length);
32
+ let next = 0;
33
+ let failure = null;
34
+ const lane = async () => {
35
+ while (!failure && next < seeds.length) {
36
+ const i = next++;
37
+ try {
38
+ results[i] = await spawnJob(script, [`--seed=${seeds[i]}`, ...args]);
39
+ }
40
+ catch (error) {
41
+ failure ??= { error };
42
+ }
43
+ }
44
+ };
45
+ await Promise.all(Array.from({ length: Math.min(workers, seeds.length) }, lane));
46
+ if (failure)
47
+ throw failure.error;
48
+ return results;
49
+ }
23
50
  /** Each check's count of checks held by a majority, then every check's runs, values and spread. */
24
51
  export function formatGate(results) {
25
52
  return results
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "watchpot",
3
- "version": "1.0.0-rc.3",
3
+ "version": "1.0.0-rc.5",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "engines": {
@@ -39,6 +39,7 @@
39
39
  "postpack": "bun scripts/pack-manifest.ts restore",
40
40
  "api": "bun scripts/api-report.ts",
41
41
  "api:check": "bun scripts/api-report.ts check",
42
+ "bench:heavy": "bun bench/heavy/run.ts",
42
43
  "dsp": "bun scripts/dsp.ts",
43
44
  "dsp:test": "cargo test --release --manifest-path dsp/Cargo.toml",
44
45
  "verify": "bun run typecheck && bun run lint && bun run test:changed && bun test test/rules",
package/src/core/stats.ts CHANGED
@@ -72,6 +72,13 @@ export function foldContributions<S extends string, Q = null>(
72
72
  return statIndex<S, never, Q>(options).over(options.q as Q, { extra: (stat) => byStat.get(stat) ?? [] });
73
73
  }
74
74
 
75
+ /**
76
+ * A function that always gives `n`. Made out here, not inline in `feed`: a closure made inside `feed` keeps `feed`'s
77
+ * whole scope alive, `was` (the last feed) included, so every feed ever made stayed reachable through the next one
78
+ * and a long sim grew without bound.
79
+ */
80
+ const always = (n: number) => (): number => n;
81
+
75
82
  /** The names a stat cannot take: the feature's own derived values beside the stats. */
76
83
  export const RESERVED_STAT_IDS: readonly string[] = ["flags", "feed"];
77
84
 
@@ -234,7 +241,7 @@ export function defineStats<
234
241
  const times = r.times;
235
242
  const list = fed[r.effect.stat] ?? [];
236
243
  fed[r.effect.stat] = list;
237
- list.push({ effect: r.effect, meta: { label, owner, group: owner as G, times: () => times } });
244
+ list.push({ effect: r.effect, meta: { label, owner, group: owner as G, times: always(times) } });
238
245
  }
239
246
  last = { rows, fed };
240
247
  return fed;
package/src/sim/fit.ts CHANGED
@@ -12,6 +12,7 @@
12
12
  */
13
13
 
14
14
  import { D, Decimal } from "../core";
15
+ import type { LookResult } from "./auto";
15
16
  import { fmtClock } from "./print";
16
17
  import {
17
18
  type SimSnapshot,
@@ -173,8 +174,12 @@ export interface FittedGate {
173
174
  export interface FitRun<X = unknown> {
174
175
  /** Advances the game `dtMs`. */
175
176
  step(dtMs: number): void;
176
- /** One look by the pilot: buys what it would buy. */
177
- look(): void;
177
+ /**
178
+ * One look by the pilot: buys what it would buy. It may return what it did (`LookResult`); with `stepping`, a look
179
+ * that did nothing lets the steps grow and one that bought or moved sends them back to the floor.
180
+ */
181
+ // biome-ignore lint/suspicious/noConfusingVoidType: a look may return nothing or what it did
182
+ look(): void | LookResult;
178
183
  /** Ms of play so far. */
179
184
  playedMs(): number;
180
185
  /** After each step, before the gates are asked (sample the holdings here). */
@@ -201,6 +206,14 @@ export interface FitOptions<X = unknown> extends FitRun<X> {
201
206
  stepMs?: number;
202
207
  /** A look every this many steps. Default 3. */
203
208
  lookEvery?: number;
209
+ /**
210
+ * Steps that grow while the pilot has nothing to do: the floor is the resolved `stepMs`, and `maxMs` the longest
211
+ * step. Looks come on the `lookEvery` cadence at the floor and every step above it; a look that did nothing doubles
212
+ * the step (up to `maxMs`), one that bought or moved sets it back to the floor, a look that reports nothing leaves
213
+ * it at the floor. A step never runs past the next planned minute, the next snapshot or `limitMs`. Absent, the fit
214
+ * steps at `stepMs` as ever. Throws when `maxMs` is below `stepMs`.
215
+ */
216
+ stepping?: { maxMs: number };
204
217
  /** With `capture`: a snapshot every this many ms of play (and always one where the run ends). */
205
218
  snapshotEveryMs?: number;
206
219
  /**
@@ -217,6 +230,8 @@ export interface FitProgress {
217
230
  readonly steps: number;
218
231
  readonly stepMs: number;
219
232
  readonly lookEvery: number;
233
+ /** With `stepping`: its ceiling, the step the fit stood at, and the steps since its last look. */
234
+ readonly stepping?: { readonly maxMs: number; readonly curMs: number; readonly sinceLook: number };
220
235
  /** The plan as this fit had it: each gate's key and minute. */
221
236
  readonly plan: readonly (readonly [string, number])[];
222
237
  /** Every gate as it stood. */
@@ -254,11 +269,65 @@ export function fitHolds(snapshot: SimSnapshot, gates: readonly FitGate[]): stri
254
269
  return out;
255
270
  }
256
271
 
272
+ /** The stepper's state: the step it stands at and the steps since the last look. */
273
+ interface StepState {
274
+ curMs: number;
275
+ sinceLook: number;
276
+ }
277
+
278
+ /** The stepper's fixed side: the floor, the ceiling (none: fixed steps), the look cadence and the plan's minutes. */
279
+ interface StepConfig {
280
+ readonly floor: number;
281
+ readonly maxMs: number | undefined;
282
+ readonly lookEvery: number;
283
+ /** Every gate's minute, ascending. */
284
+ readonly minutes: readonly number[];
285
+ }
286
+
287
+ /** Where a stepper starts: from what a snapshot kept, else at the floor, looking first if the cadence says so. */
288
+ function stepStart(
289
+ floor: number,
290
+ lookEvery: number,
291
+ steps: number,
292
+ kept?: FitProgress["stepping"],
293
+ ): StepState {
294
+ if (kept) return { curMs: kept.curMs, sinceLook: kept.sinceLook };
295
+ const r = steps % lookEvery;
296
+ return { curMs: floor, sinceLook: r === 0 ? lookEvery : r };
297
+ }
298
+
299
+ /**
300
+ * One turn of the stepper, shared by the fit and its proof so both take the same steps: looks if due, moves the
301
+ * state by what the look did, and gives the ms to step. `boundary` is the next moment a step must not pass (a
302
+ * snapshot); `limitMs` the end. Without a ceiling the step is the floor, whatever the plan.
303
+ */
304
+ function stride(
305
+ st: StepState,
306
+ cfg: StepConfig,
307
+ look: FitRun["look"],
308
+ now: number,
309
+ boundary: number,
310
+ limitMs: number,
311
+ ): number {
312
+ const { floor, maxMs, lookEvery, minutes } = cfg;
313
+ if (st.curMs > floor || st.sinceLook >= lookEvery) {
314
+ st.sinceLook = 0;
315
+ const res = look();
316
+ if (maxMs !== undefined && res && typeof res === "object")
317
+ st.curMs = res.bought + res.free > 0 ? floor : Math.min(st.curMs * 2, maxMs);
318
+ }
319
+ st.sinceLook++;
320
+ if (maxMs === undefined) return floor;
321
+ const gate = minutes.find((m) => m > now) ?? Infinity;
322
+ return Math.max(1, Math.min(st.curMs, gate - now, boundary - now, limitMs - now));
323
+ }
324
+
257
325
  /**
258
326
  * Prices a game in one pass. Shuts every gate in the table, orders them by `atMs` (the plan's order between equals),
259
327
  * then steps: with `capture`, a snapshot first when one is due; every `lookEvery`th step `look()`, `step(stepMs)`,
260
328
  * `afterStep()`, then each unopened gate whose minute has come is asked `price()`, and a figure goes into the table
261
- * and opens it at `playedMs()`. Ends on `done()` or at `limitMs`.
329
+ * and opens it at `playedMs()`. Ends on `done()` or at `limitMs`. With `stepping` the step grows while looks do
330
+ * nothing (see `FitOptions.stepping`); the snapshots keep where it stood.
262
331
  */
263
332
  export function runFit<X = unknown>(options: FitOptions<X>): FitResult<X> {
264
333
  const { table, gates, step, look, playedMs, done, limitMs, afterStep, capture, from } = options;
@@ -267,6 +336,11 @@ export function runFit<X = unknown>(options: FitOptions<X>): FitResult<X> {
267
336
  const order = gates.toSorted((a, b) => a.atMs - b.atMs);
268
337
  const fitted: FittedGate[] = order.map((g) => ({ key: g.key, atMs: g.atMs }));
269
338
  let steps = 0;
339
+ const maxMs = options.stepping?.maxMs;
340
+ if (maxMs !== undefined && !(maxMs >= stepMs))
341
+ throw new Error(`runFit: stepping.maxMs (${maxMs}) is below the step (${stepMs})`);
342
+ const cfg: StepConfig = { floor: stepMs, maxMs, lookEvery, minutes: order.map((g) => g.atMs) };
343
+ let st = stepStart(stepMs, lookEvery, 0);
270
344
 
271
345
  if (from) {
272
346
  const problems = fitHolds(from as SimSnapshot, gates);
@@ -279,7 +353,12 @@ export function runFit<X = unknown>(options: FitOptions<X>): FitResult<X> {
279
353
  throw new Error(
280
354
  `runFit: the snapshot was taken stepping ${fit.stepMs} ms with a look every ${fit.lookEvery} steps, not ${stepMs} and ${lookEvery}`,
281
355
  );
356
+ if (fit.stepping?.maxMs !== maxMs)
357
+ throw new Error(
358
+ `runFit: the snapshot was taken ${fit.stepping ? `stepping up to ${fit.stepping.maxMs} ms` : "without stepping"}, not ${maxMs === undefined ? "without" : `up to ${maxMs} ms`}`,
359
+ );
282
360
  steps = fit.steps;
361
+ st = stepStart(stepMs, lookEvery, steps, fit.stepping);
283
362
  table.load(fit.table);
284
363
  const was = new Map(fit.gates.map((g) => [g.key, g]));
285
364
  fitted.forEach((f, i) => {
@@ -299,7 +378,15 @@ export function runFit<X = unknown>(options: FitOptions<X>): FitResult<X> {
299
378
  format: SNAPSHOT_FORMAT,
300
379
  atMs: at,
301
380
  ...capture(),
302
- fit: { steps, stepMs, lookEvery, plan, gates: fitted.map((f) => ({ ...f })), table: table.data() },
381
+ fit: {
382
+ steps,
383
+ stepMs,
384
+ lookEvery,
385
+ ...(maxMs !== undefined && { stepping: { maxMs, curMs: st.curMs, sinceLook: st.sinceLook } }),
386
+ plan,
387
+ gates: fitted.map((f) => ({ ...f })),
388
+ table: table.data(),
389
+ },
303
390
  });
304
391
  };
305
392
  const cadence =
@@ -307,8 +394,8 @@ export function runFit<X = unknown>(options: FitOptions<X>): FitResult<X> {
307
394
 
308
395
  for (; playedMs() < limitMs && !done(); steps++) {
309
396
  if (cadence?.due(playedMs())) take();
310
- if (steps % lookEvery === 0) look();
311
- step(stepMs);
397
+ const dt = stride(st, cfg, look, playedMs(), cadence?.next() ?? Infinity, limitMs);
398
+ step(dt);
312
399
  afterStep?.();
313
400
  const now = playedMs();
314
401
  order.forEach((g, i) => {
@@ -371,8 +458,9 @@ export function proofStretches<X>(
371
458
  /**
372
459
  * Replays one stretch on the table as it stands: `replay` builds a run from the stretch's start (from nothing when
373
460
  * 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
374
- * then is the snapshot (its world, its player, and its `extra` when the replay captures one). The differences, empty
375
- * when it holds.
461
+ * then is the snapshot (its world, its player, and its `extra` when the replay captures one). A fit that stepped
462
+ * (`stepping`) is replayed by the same stepper, from the state its start kept, never stepping past the end's moment.
463
+ * The differences, empty when it holds.
376
464
  */
377
465
  export function replayStretch<X>(
378
466
  stretch: ProofStretch<X>,
@@ -383,9 +471,15 @@ export function replayStretch<X>(
383
471
  if (!fit) throw new Error("proveFit: a mark was not taken by a fit");
384
472
  const run = replay(from);
385
473
  let steps = from?.fit?.steps ?? 0;
474
+ const cfg: StepConfig = {
475
+ floor: fit.stepMs,
476
+ maxMs: fit.stepping?.maxMs,
477
+ lookEvery: fit.lookEvery,
478
+ minutes: fit.plan.map(([, at]) => at).toSorted((a, b) => a - b),
479
+ };
480
+ const st = stepStart(fit.stepMs, fit.lookEvery, steps, from?.fit?.stepping);
386
481
  while (run.playedMs() < to.atMs) {
387
- if (steps % fit.lookEvery === 0) run.look();
388
- run.step(fit.stepMs);
482
+ run.step(stride(st, cfg, () => run.look(), run.playedMs(), to.atMs, Infinity));
389
483
  run.afterStep?.();
390
484
  steps++;
391
485
  }
package/src/sim/gate.ts CHANGED
@@ -51,6 +51,43 @@ export async function spawnJob<Res>(script: string, args: readonly string[]): Pr
51
51
  return JSON.parse(out) as Res;
52
52
  }
53
53
 
54
+ /**
55
+ * Runs one script per seed (`--seed=<seed>` then `args`) through `spawnJob`, at most `workers` at once, and returns
56
+ * the results in seed order whatever order they finish in. The first failure rejects; jobs already running finish,
57
+ * and no new ones start.
58
+ */
59
+ export async function runSeeds<Res>({
60
+ script,
61
+ seeds,
62
+ args = [],
63
+ workers = Math.max(1, (globalThis.navigator?.hardwareConcurrency ?? 2) - 1),
64
+ }: {
65
+ script: string;
66
+ seeds: readonly string[];
67
+ /** Extra args after `--seed=<seed>`. */
68
+ args?: readonly string[];
69
+ /** Processes at once. Default: the cores (`navigator.hardwareConcurrency`) less one, at least 1. */
70
+ workers?: number;
71
+ }): Promise<Res[]> {
72
+ if (workers < 1) throw new RangeError(`runSeeds needs at least 1 worker, got ${workers}`);
73
+ const results: Res[] = new Array(seeds.length);
74
+ let next = 0;
75
+ let failure: { error: unknown } | null = null;
76
+ const lane = async (): Promise<void> => {
77
+ while (!failure && next < seeds.length) {
78
+ const i = next++;
79
+ try {
80
+ results[i] = await spawnJob<Res>(script, [`--seed=${seeds[i]}`, ...args]);
81
+ } catch (error) {
82
+ failure ??= { error };
83
+ }
84
+ }
85
+ };
86
+ await Promise.all(Array.from({ length: Math.min(workers, seeds.length) }, lane));
87
+ if (failure) throw (failure as { error: unknown }).error;
88
+ return results;
89
+ }
90
+
54
91
  /** Each check's count of checks held by a majority, then every check's runs, values and spread. */
55
92
  export function formatGate(results: readonly GateResult[]): string {
56
93
  return results