watchpot 1.0.0-rc.5 → 1.0.0-rc.7

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.
Files changed (87) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +1 -0
  3. package/api/core/cells.d.ts +8 -0
  4. package/api/core/index.d.ts +1 -0
  5. package/api/core/knobs.d.ts +39 -0
  6. package/api/core/plain.d.ts +6 -0
  7. package/api/devtools/DevPanel.d.ts +1 -0
  8. package/api/devtools/SoundDesk.d.ts +1 -0
  9. package/api/sim/auto.d.ts +7 -0
  10. package/api/sim/cache.d.ts +71 -0
  11. package/api/sim/desk.d.ts +62 -0
  12. package/api/sim/fit.d.ts +43 -16
  13. package/api/sim/index.d.ts +2 -0
  14. package/api/sim/table-epoch.d.ts +4 -0
  15. package/dist/cli/index.js +20 -0
  16. package/dist/core/cells.d.ts +8 -0
  17. package/dist/core/cells.js +0 -0
  18. package/dist/core/index.d.ts +1 -0
  19. package/dist/core/index.js +1 -0
  20. package/dist/core/knobs.d.ts +39 -0
  21. package/dist/core/knobs.js +48 -0
  22. package/dist/core/plain.d.ts +6 -0
  23. package/dist/core/plain.js +5 -0
  24. package/dist/core/stats.js +7 -1
  25. package/dist/devtools/DevPanel.d.ts +1 -0
  26. package/dist/devtools/DevPanel.js +2 -1
  27. package/dist/devtools/DevPanel.module.css +56 -49
  28. package/dist/devtools/SoundDesk.d.ts +1 -0
  29. package/dist/devtools/SoundDesk.js +6 -3
  30. package/dist/devtools/SoundDesk.module.css +345 -251
  31. package/dist/devtools/desk/SoundDeskView.js +1 -1
  32. package/dist/devtools/tokens.css +64 -0
  33. package/dist/sim/auto.d.ts +7 -0
  34. package/dist/sim/auto.js +28 -2
  35. package/dist/sim/cache.d.ts +71 -0
  36. package/dist/sim/cache.js +119 -0
  37. package/dist/sim/desk.d.ts +62 -0
  38. package/dist/sim/desk.js +19 -0
  39. package/dist/sim/fit.d.ts +43 -16
  40. package/dist/sim/fit.js +75 -20
  41. package/dist/sim/index.d.ts +2 -0
  42. package/dist/sim/index.js +2 -0
  43. package/dist/sim/table-epoch.d.ts +4 -0
  44. package/dist/sim/table-epoch.js +12 -0
  45. package/dist/sim/table.js +3 -0
  46. package/docs/core.md +9 -0
  47. package/docs/imports.md +3 -1
  48. package/docs/sim.md +11 -0
  49. package/package.json +1 -1
  50. package/src/cli/index.ts +14 -0
  51. package/src/core/cells.ts +0 -0
  52. package/src/core/index.ts +1 -0
  53. package/src/core/knobs.ts +76 -0
  54. package/src/core/plain.ts +11 -0
  55. package/src/core/stats.ts +6 -1
  56. package/src/desk/page/App.tsx +638 -0
  57. package/src/desk/page/Filter.tsx +121 -0
  58. package/src/desk/page/Graph.tsx +642 -0
  59. package/src/desk/page/Panel.tsx +241 -0
  60. package/src/desk/page/Tables.tsx +286 -0
  61. package/src/desk/page/desk.css +1123 -0
  62. package/src/desk/page/fonts/archivo-LICENSE.txt +93 -0
  63. package/src/desk/page/fonts/archivo-latin-standard-normal.woff2 +0 -0
  64. package/src/desk/page/fonts/chivo-mono-LICENSE.txt +93 -0
  65. package/src/desk/page/fonts/chivo-mono-latin-wght-normal.woff2 +0 -0
  66. package/src/desk/page/index.html +12 -0
  67. package/src/desk/page/link.ts +39 -0
  68. package/src/desk/page/main.tsx +6 -0
  69. package/src/desk/page/run.ts +87 -0
  70. package/src/desk/page/series.ts +607 -0
  71. package/src/desk/protocol.ts +84 -0
  72. package/src/desk/server.ts +347 -0
  73. package/src/desk/worker.ts +189 -0
  74. package/src/devtools/DevPanel.module.css +56 -49
  75. package/src/devtools/DevPanel.tsx +2 -1
  76. package/src/devtools/SoundDesk.module.css +345 -251
  77. package/src/devtools/SoundDesk.tsx +6 -3
  78. package/src/devtools/desk/SoundDeskView.tsx +1 -0
  79. package/src/devtools/tokens.css +64 -0
  80. package/src/sim/auto.ts +36 -2
  81. package/src/sim/cache.ts +181 -0
  82. package/src/sim/desk.ts +72 -0
  83. package/src/sim/fit.ts +132 -33
  84. package/src/sim/index.ts +2 -0
  85. package/src/sim/table-epoch.ts +14 -0
  86. package/src/sim/table.ts +3 -0
  87. package/templates/game/gitignore +1 -0
package/CHANGELOG.md CHANGED
@@ -2,6 +2,24 @@
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.7
6
+
7
+ The sim desk: `bunx watchpot sim` serves a game's pacing as graphs and tables with knobs and gate pins that rerun from the snapshot cache and save to `sim.tuning.json`; the developer tools wear one token sheet (grey in a dark system).
8
+
9
+ - Orbital Orchard is on the sim desk: `bun run desk` in the example opens `watchpot sim` on five tuning knobs (price growth, offline rate, pull price, drip interval, prestige bonus), declared in `src/content/knobs.ts` and read where used, with a straight 24 h auto-player run drawn as pace graphs; Save writes `sim.tuning.json`, which the game imports.
10
+ - `watchpot sim` saves what is set by hand to `sim.tuning.json` beside the desk file (`POST /api/tuning`: only knobs that differ from the code, and the pins; `GET /api/desk` gains `code`, `pins` and `tuningFile`), and a rerun that resumes from a cached snapshot replays the windows before it (`cached: true`) from `.watchpot/sim-cache/<key>/win-<fromMs>.json`. A game's `source` globs must not match `sim.tuning.json`, or every save clears the cache.
11
+ - `watchpot sim`'s page has a knob panel: knobs by group with a slider and a number field each, and a `Pin` on every gate for its price or hour. What is set by hand is marked (a filled square, the value in bold, the code's value struck beside it) and one click from being put back; any change reruns the pacing from the cache after 500 ms and draws it over the run before it (a dashed hairline, a `now`, `before` and difference in orders of magnitude in the readout, a `Δ` column in the table); `Save` writes the lot to the game's `sim.tuning.json`.
12
+ - The dev panel and the sound desk wear the site's look: both read the shared `src/devtools/tokens.css` (the blueline in a light system, the blueprint in a dark one), so the sound desk now follows the system scheme instead of being dark only. Restyle only: hairline rules, 2px corners, controls that invert under the pointer and drop a pixel on a press, dashed and ruled-through disabled controls, hatched empty, locked and silenced areas, and `--dp-live` for what is running.
13
+ - `watchpot sim` serves a real page: it runs the desk on load and draws the pacing as the windows stream in: currencies over time (a hairline per seed and the median, gate markers), each buyable's wallet against its next cost with the stall hatched, a crosshair readout, an hourly table and a gates table, in the developer tools' look (`src/desk/page/`).
14
+ - `watchpot sim`: serves a game's sim desk (`sim.desk.ts`) on localhost with `/api/desk` and a plain HTML page, and opens the browser (Bun only). A WebSocket at `/ws` runs the desk: one Worker per seed plays the fit window by window from the snapshot cache and streams each window (`src/desk/protocol.ts`); a newer `run` cancels the running one.
15
+ - `defineKnobs` (`watchpot/core`) and `defineDesk` (`watchpot/sim`): the types a game uses to describe its knobs and its runs to the sim desk. Game code reads a knob with `knobs.get(key)`; the sim binds a run's `tunables` to track each read.
16
+ - `runFit` takes `pinned`: a gate's price or minute set by hand is used as given and never overwritten, and the fit reports what it pinned and what it would have priced itself (`fitValue`); `fitHolds` and `SimCache.resume` see a changed pin as a changed plan. `FitGate`, `FittedGate`, `FitOptions` and `runFit` take the gate keys as `K`.
17
+
18
+ ## 1.0.0-rc.6
19
+
20
+ - 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.
21
+ - `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.
22
+
5
23
  ## 1.0.0-rc.5
6
24
 
7
25
  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.
package/README.md CHANGED
@@ -34,6 +34,7 @@ Run inside a game, as `bunx watchpot <cmd>` or `npx watchpot <cmd>`:
34
34
 
35
35
  - `doctor` checks the game's setup (Bun, the engine and whether it is behind, `tsconfig.json`, the agent skills) and exits 1 on a problem.
36
36
  - `skills add|update` copies the engine's agent skills into the game (`--to` picks the folders), or refreshes the ones it already holds.
37
+ - `sim [--port <n>] [--no-open] [--desk <file>]` serves the game's sim desk (`sim.desk.ts`) on localhost and opens it in the browser. Bun only.
37
38
 
38
39
  ## The smallest game
39
40
 
@@ -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;
@@ -25,6 +25,7 @@ export * from "./graph/nodes";
25
25
  export * from "./graph/stats";
26
26
  export * from "./graph/yields";
27
27
  export * from "./journal";
28
+ export * from "./knobs";
28
29
  export * from "./layers";
29
30
  export * from "./levels";
30
31
  export * from "./loadout";
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Knobs: numbers a game exposes as config for the sim to turn, such as a price growth or a delay. They are never store
3
+ * state (so no `select`, no save): game code reads one with `knobs.get(key)` at the moment it needs it. One run binds
4
+ * at a time: `bind` gives the reader (the sim's `tunables`) the values, `bind(null)` returns to the defaults.
5
+ */
6
+ /** What a knob's number means, for display. */
7
+ export type KnobUnit = "ms" | "x" | "%";
8
+ /** One knob: its default `value`, how to show it, and the range the sim may move it in. */
9
+ export interface KnobSpec {
10
+ readonly value: number;
11
+ readonly label: string;
12
+ readonly group: string;
13
+ readonly min?: number;
14
+ readonly max?: number;
15
+ readonly step?: number;
16
+ readonly unit?: KnobUnit;
17
+ }
18
+ /** Knob specs by key. */
19
+ export type KnobSpecs = Readonly<Record<string, KnobSpec>>;
20
+ /** The keys of a knob spec. */
21
+ export type KnobKey<S extends KnobSpecs> = Extract<keyof S, string>;
22
+ /** A number for every knob. */
23
+ export type KnobValues<S extends KnobSpecs> = {
24
+ readonly [P in KnobKey<S>]: number;
25
+ };
26
+ /** The knobs of a game: read with `get`, bound to a run's values with `bind`. */
27
+ export interface Knobs<S extends KnobSpecs> {
28
+ /** The bound reader's value, or the default when unbound. Throws on an unknown key. */
29
+ get(key: KnobKey<S>): number;
30
+ readonly spec: S;
31
+ /** A copy: the spec values with `saved` laid over. */
32
+ defaults(): KnobValues<S>;
33
+ /** Reads from `reader.values` until the next `bind`; null unbinds. */
34
+ bind(reader: {
35
+ readonly values: Readonly<Record<string, number | string | boolean>>;
36
+ } | null): void;
37
+ }
38
+ /** Defines a game's knobs. `saved` overrides spec values. Throws on a bad spec; it does not clamp. */
39
+ export declare function defineKnobs<const S extends KnobSpecs>(spec: S, saved?: Readonly<Record<string, number>>): Knobs<S>;
@@ -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. */
@@ -1,3 +1,4 @@
1
+ import "./tokens.css";
1
2
  /** Props of `DevPanel`. */
2
3
  export interface DevPanelProps {
3
4
  /** Closes the panel (the game drops its `#dev` route). Absent, no close button. */
@@ -1,4 +1,5 @@
1
1
  import type { Desk, MixFile, SampleHost } from "../sound/desk";
2
+ import "./tokens.css";
2
3
  /**
3
4
  * A switch of the game's own in the desk's top bar: one of a few named states, set from the desk (which scene the
4
5
  * sound is in, say, so a mix can be worked on without playing to it). `options` and `value` are read on every draw.
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,71 @@
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, type GatePin } 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, minutes and `pinned` prices alike
57
+ * (`fitHolds`), and every tunable whose value differs from the one it was taken with (or was not there) was not yet
58
+ * read when it was taken. With the
59
+ * first-read map to start the resumed run's tunables from. Undefined when none is.
60
+ */
61
+ resume<K extends string = string>(gates: readonly FitGate<K>[], t: Tunables<Record<string, TunableValue>>, pinned?: Readonly<Partial<Record<K, GatePin>>>): Promise<Resumed<X> | undefined>;
62
+ /** Deletes the snapshots after `atMs` (a run that resumes there replaces them). */
63
+ dropAfter(atMs: number): Promise<void>;
64
+ /** Deletes every snapshot under this key. */
65
+ clear(): Promise<void>;
66
+ }
67
+ /** The cache for `key` (a `sourceKey`) under `dir` (default `.watchpot/sim-cache`): `<dir>/<key>/snap-<atMs>.json`. */
68
+ export declare function simCache<X = unknown>(options: {
69
+ key: string;
70
+ dir?: string;
71
+ }): SimCache<X>;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * The sim desk's contract: a game's `sim.desk.ts` default-exports `defineDesk({...})`, which says what to run, which
3
+ * knobs the sim may turn, and where the run ends.
4
+ */
5
+ import type { AnyVocab, Balances, CurrencyOf, Decimal, KnobSpecs, Knobs } from "../core";
6
+ import type { FitGate, FitOptions, FitRun } from "./fit";
7
+ import type { SimSnapshot } from "./snapshot";
8
+ import type { FitTable } from "./table";
9
+ /** What the desk reads off a run at a moment: every currency, and the price of what is next to buy. */
10
+ export interface DeskSample<C extends string> {
11
+ currencies: Balances<C>;
12
+ next?: Record<string, {
13
+ currency: C;
14
+ cost: Decimal;
15
+ }>;
16
+ }
17
+ /** A run the desk plays: a `FitRun` with its table and gates, and a sample of the holdings. */
18
+ export interface DeskRun<C extends string, X = unknown> extends FitRun<X> {
19
+ readonly table: FitTable;
20
+ readonly gates: readonly FitGate[];
21
+ /** The game is finished. */
22
+ done?(): boolean;
23
+ sample(): DeskSample<C>;
24
+ }
25
+ /** The fit settings a desk may set. */
26
+ export type DeskFit = Pick<FitOptions, "quality" | "stepMs" | "stepping" | "lookEvery" | "snapshotEveryMs">;
27
+ /** What a game gives `defineDesk`. */
28
+ export interface DeskDef<V extends AnyVocab, S extends KnobSpecs, X> {
29
+ vocab: V;
30
+ knobs: Knobs<S>;
31
+ /** The currency progress is measured in. */
32
+ currency: CurrencyOf<V>;
33
+ /** `sourceKey` globs of the files whose change invalidates a cached run. */
34
+ source: readonly string[];
35
+ /** Hours of play a window covers. Default 2. */
36
+ windowHours?: number;
37
+ /** Where a run ends. */
38
+ end: {
39
+ hours: number;
40
+ };
41
+ /** Seeds per run: `tuning` while turning knobs (default 1), `full` for a report (default 8). */
42
+ seeds?: {
43
+ tuning?: number;
44
+ full?: number;
45
+ };
46
+ fit?: DeskFit;
47
+ /** A fresh run for `seed`, resumed from `from` when given. */
48
+ run(options: {
49
+ seed: number;
50
+ from?: SimSnapshot<X>;
51
+ }): DeskRun<CurrencyOf<V>, X>;
52
+ }
53
+ /** A desk with its defaults filled. */
54
+ export interface Desk<V extends AnyVocab, S extends KnobSpecs, X> extends DeskDef<V, S, X> {
55
+ windowHours: number;
56
+ seeds: {
57
+ tuning: number;
58
+ full: number;
59
+ };
60
+ }
61
+ /** Checks and freezes a desk, filling `windowHours` (2) and `seeds` (1, 8). Does not call `run`. */
62
+ export declare function defineDesk<V extends AnyVocab, S extends KnobSpecs, X = unknown>(def: DeskDef<V, S, X>): Desk<V, S, X>;
package/api/sim/fit.d.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  * fit carries on from one (`from`) instead of playing from nothing, and the proof (`proveFit`) replays the finished
11
11
  * table between them.
12
12
  */
13
- import { Decimal } from "../core";
13
+ import { Decimal, type DecimalSource } from "../core";
14
14
  import type { LookResult } from "./auto";
15
15
  import { type SimSnapshot, type SnapshotParts } from "./snapshot";
16
16
  import type { FitTable, FitTableData } from "./table";
@@ -59,9 +59,9 @@ export interface Holdings<R extends string> {
59
59
  /** Holdings over `refs`, read through `read`, keeping the last `window` samples (default 90). */
60
60
  export declare function holdings<R extends string>(refs: readonly R[], read: (ref: R) => Decimal, { window, from }?: HoldingsOptions): Holdings<R>;
61
61
  /** A gate in the plan. The loop shuts it and writes its price into the table; the game says what the price is. */
62
- export interface FitGate {
62
+ export interface FitGate<K extends string = string> {
63
63
  /** The plan's key for the gate; the table's key. */
64
- readonly key: string;
64
+ readonly key: K;
65
65
  /** The planned minute, in ms of play. */
66
66
  readonly atMs: number;
67
67
  /**
@@ -70,12 +70,30 @@ export interface FitGate {
70
70
  */
71
71
  price(): string | null;
72
72
  }
73
- /** A gate after the fit: when it opened and the value its `price()` gave, if it did. */
74
- export interface FittedGate {
75
- readonly key: string;
73
+ /** A gate set by hand: what the fit uses as given instead of the plan's minute or its own price. */
74
+ export type GatePin = {
75
+ /** The price to open the gate at, never overwritten by the fit. Written once as a figure string (`D(price)`). */
76
+ readonly price?: DecimalSource;
77
+ /** The minute the gate opens at, in ms of play, in place of the plan's. */
78
+ readonly atMs?: number;
79
+ };
80
+ /**
81
+ * A gate after the fit: when it opened and the value its `price()` gave, if it did (for a price-pinned gate, the
82
+ * pinned figure).
83
+ */
84
+ export interface FittedGate<K extends string = string> {
85
+ readonly key: K;
86
+ /** The gate's minute: the pinned one when `atMs` was pinned. */
76
87
  readonly atMs: number;
77
88
  openedMs?: number;
78
89
  value?: string;
90
+ /** What was pinned on this gate, each set only when pinned. */
91
+ pinned?: {
92
+ price?: true;
93
+ atMs?: true;
94
+ };
95
+ /** For a price-pinned gate, what its `price()` gave once its minute came (never written to the table). */
96
+ fitValue?: string;
79
97
  }
80
98
  /**
81
99
  * A run a fit plays, or a proof replays: the game's step and pilot, its played clock, and (to leave snapshots) what
@@ -100,10 +118,16 @@ export interface FitRun<X = unknown> {
100
118
  capture?(): SnapshotParts<X>;
101
119
  }
102
120
  /** What `runFit` plays: the table, the gates, the run, the clock, and where to start. */
103
- export interface FitOptions<X = unknown> extends FitRun<X> {
121
+ export interface FitOptions<X = unknown, K extends string = string> extends FitRun<X> {
104
122
  /** The live table the game reads its prices from: the fit shuts every gate in it and prices each into it. */
105
- table: FitTable;
106
- gates: readonly FitGate[];
123
+ table: FitTable<NoInfer<K>>;
124
+ gates: readonly FitGate<K>[];
125
+ /**
126
+ * Gates set by hand, by key. A pinned `atMs` is the gate's minute everywhere; a pinned `price` opens the gate at
127
+ * that figure at its minute and is never overwritten, while `price()` is still asked for the report (`fitValue`).
128
+ * Throws when a key is not a gate in `gates`.
129
+ */
130
+ pinned?: Readonly<Partial<Record<K, GatePin>>>;
107
131
  /** The game is finished. */
108
132
  done(): boolean;
109
133
  /** The run stops here, finished or not (ms of play). */
@@ -129,7 +153,7 @@ export interface FitOptions<X = unknown> extends FitRun<X> {
129
153
  /**
130
154
  * A snapshot to carry on from (one this fit's `capture` took, decoded). Build the run from it first (its world,
131
155
  * player and extra); the fit takes its own progress and table from it, prices only what was still unpriced there,
132
- * and plays on as if it had never stopped. Throws when the plan moved before it (`fitHolds`).
156
+ * and plays on as if it had never stopped. Throws when the plan or the pins moved before it (`fitHolds`).
133
157
  */
134
158
  from?: SimSnapshot<X>;
135
159
  }
@@ -145,8 +169,8 @@ export interface FitProgress {
145
169
  readonly curMs: number;
146
170
  readonly sinceLook: number;
147
171
  };
148
- /** The plan as this fit had it: each gate's key and minute. */
149
- readonly plan: readonly (readonly [string, number])[];
172
+ /** The plan as this fit had it: each gate's key and minute, and the pinned price figure of a price-pinned gate. */
173
+ readonly plan: readonly (readonly [string, number, string?])[];
150
174
  /** Every gate as it stood. */
151
175
  readonly gates: readonly FittedGate[];
152
176
  /** The table as it stood: what was priced by then. */
@@ -162,17 +186,20 @@ export interface FitResult<X = unknown> {
162
186
  }
163
187
  /**
164
188
  * Whether a fit can carry on from a snapshot under this plan: the gates it had planned up to its moment must be the
165
- * gates planned up to it now, at the same minutes. The reasons it cannot, empty when it can.
189
+ * gates planned up to it now, at the same minutes and pinned at the same prices (`pinned` is applied as `runFit`
190
+ * applies it). The reasons it cannot, empty when it can.
166
191
  */
167
- export declare function fitHolds(snapshot: SimSnapshot, gates: readonly FitGate[]): string[];
192
+ export declare function fitHolds<K extends string = string>(snapshot: SimSnapshot, gates: readonly FitGate<K>[], pinned?: Readonly<Partial<Record<K, GatePin>>>): string[];
168
193
  /**
169
- * Prices a game in one pass. Shuts every gate in the table, orders them by `atMs` (the plan's order between equals),
194
+ * Prices a game in one pass. A price-pinned gate (`pinned`) opens at its figure on the first step at or after its
195
+ * minute and is never written again; `price()` is asked from then until it answers, kept as `fitValue`. Shuts every
196
+ * gate in the table, orders them by `atMs` (the plan's order between equals),
170
197
  * then steps: with `capture`, a snapshot first when one is due; every `lookEvery`th step `look()`, `step(stepMs)`,
171
198
  * `afterStep()`, then each unopened gate whose minute has come is asked `price()`, and a figure goes into the table
172
199
  * and opens it at `playedMs()`. Ends on `done()` or at `limitMs`. With `stepping` the step grows while looks do
173
200
  * nothing (see `FitOptions.stepping`); the snapshots keep where it stood.
174
201
  */
175
- export declare function runFit<X = unknown>(options: FitOptions<X>): FitResult<X>;
202
+ export declare function runFit<X = unknown, K extends string = string>(options: FitOptions<X, K>): FitResult<X>;
176
203
  /** The fit's report: a markdown table of gate, planned minute, the minute it opened (or "never"), and its value. */
177
204
  export declare function formatFit(result: Pick<FitResult, "gates">): string;
178
205
  /** A proof's outcome: how many stretches it replayed, and a line for each that parted from the fit's run. */
@@ -1,6 +1,8 @@
1
1
  export * from "./auto";
2
2
  export * from "./bare";
3
+ export * from "./cache";
3
4
  export * from "./contract";
5
+ export * from "./desk";
4
6
  export * from "./fit";
5
7
  export * from "./gate";
6
8
  export * from "./print";
@@ -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;
package/dist/cli/index.js CHANGED
@@ -1,3 +1,11 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
1
9
  // The `watchpot` command, run inside a game: `bunx watchpot <cmd>` or `npx watchpot <cmd>`. `bin/watchpot.mjs` calls
2
10
  // `main`; the tests call it in-process with their own output and fetch. Node 20+ and Bun; Node built-ins only.
3
11
  import { doctor } from "./doctor.js";
@@ -7,6 +15,7 @@ const USAGE = [
7
15
  "",
8
16
  " watchpot doctor check this game's setup: Bun, the engine, tsconfig, agent skills",
9
17
  " watchpot skills add|update [--to <dir>[,<dir>]] install the engine's agent skills, or refresh the ones held",
18
+ " watchpot sim [--port <n>] [--no-open] [--desk <file>] serve the sim desk for this game on localhost",
10
19
  ];
11
20
  const defaults = () => ({
12
21
  out: (line) => console.log(line),
@@ -28,6 +37,17 @@ export async function main(argv, cwd = process.cwd(), io = {}) {
28
37
  return await doctor(cwd, all.env, all.fetch, all.out);
29
38
  if (cmd === "skills")
30
39
  return skills(rest, cwd, all.env, all.out);
40
+ if (cmd === "sim") {
41
+ if (process.versions.bun === undefined) {
42
+ all.err("watchpot: sim needs Bun (the desk runs the game's TypeScript): run bunx watchpot sim");
43
+ return 1;
44
+ }
45
+ // The desk is Bun-only and ships as source, not in dist (its page is an HTML import only Bun bundles): a
46
+ // specifier the build cannot see keeps it out of tsc's program, and Bun runs the command from `src/` anyway.
47
+ const server = "../desk/server.ts";
48
+ const { sim } = (await import(__rewriteRelativeImportExtension(new URL(server, import.meta.url).href)));
49
+ return await sim(rest, cwd, all);
50
+ }
31
51
  all.err(`watchpot: unknown command "${cmd}"`);
32
52
  for (const line of USAGE)
33
53
  all.err(line);
@@ -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
@@ -25,6 +25,7 @@ export * from "./graph/nodes";
25
25
  export * from "./graph/stats";
26
26
  export * from "./graph/yields";
27
27
  export * from "./journal";
28
+ export * from "./knobs";
28
29
  export * from "./layers";
29
30
  export * from "./levels";
30
31
  export * from "./loadout";
@@ -25,6 +25,7 @@ export * from "./graph/nodes.js";
25
25
  export * from "./graph/stats.js";
26
26
  export * from "./graph/yields.js";
27
27
  export * from "./journal.js";
28
+ export * from "./knobs.js";
28
29
  export * from "./layers/index.js";
29
30
  export * from "./levels.js";
30
31
  export * from "./loadout.js";
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Knobs: numbers a game exposes as config for the sim to turn, such as a price growth or a delay. They are never store
3
+ * state (so no `select`, no save): game code reads one with `knobs.get(key)` at the moment it needs it. One run binds
4
+ * at a time: `bind` gives the reader (the sim's `tunables`) the values, `bind(null)` returns to the defaults.
5
+ */
6
+ /** What a knob's number means, for display. */
7
+ export type KnobUnit = "ms" | "x" | "%";
8
+ /** One knob: its default `value`, how to show it, and the range the sim may move it in. */
9
+ export interface KnobSpec {
10
+ readonly value: number;
11
+ readonly label: string;
12
+ readonly group: string;
13
+ readonly min?: number;
14
+ readonly max?: number;
15
+ readonly step?: number;
16
+ readonly unit?: KnobUnit;
17
+ }
18
+ /** Knob specs by key. */
19
+ export type KnobSpecs = Readonly<Record<string, KnobSpec>>;
20
+ /** The keys of a knob spec. */
21
+ export type KnobKey<S extends KnobSpecs> = Extract<keyof S, string>;
22
+ /** A number for every knob. */
23
+ export type KnobValues<S extends KnobSpecs> = {
24
+ readonly [P in KnobKey<S>]: number;
25
+ };
26
+ /** The knobs of a game: read with `get`, bound to a run's values with `bind`. */
27
+ export interface Knobs<S extends KnobSpecs> {
28
+ /** The bound reader's value, or the default when unbound. Throws on an unknown key. */
29
+ get(key: KnobKey<S>): number;
30
+ readonly spec: S;
31
+ /** A copy: the spec values with `saved` laid over. */
32
+ defaults(): KnobValues<S>;
33
+ /** Reads from `reader.values` until the next `bind`; null unbinds. */
34
+ bind(reader: {
35
+ readonly values: Readonly<Record<string, number | string | boolean>>;
36
+ } | null): void;
37
+ }
38
+ /** Defines a game's knobs. `saved` overrides spec values. Throws on a bad spec; it does not clamp. */
39
+ export declare function defineKnobs<const S extends KnobSpecs>(spec: S, saved?: Readonly<Record<string, number>>): Knobs<S>;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Knobs: numbers a game exposes as config for the sim to turn, such as a price growth or a delay. They are never store
3
+ * state (so no `select`, no save): game code reads one with `knobs.get(key)` at the moment it needs it. One run binds
4
+ * at a time: `bind` gives the reader (the sim's `tunables`) the values, `bind(null)` returns to the defaults.
5
+ */
6
+ /** Defines a game's knobs. `saved` overrides spec values. Throws on a bad spec; it does not clamp. */
7
+ export function defineKnobs(spec, saved) {
8
+ for (const [key, k] of Object.entries(spec)) {
9
+ if (!Number.isFinite(k.value))
10
+ throw new Error(`knobs: "${key}" value is not finite`);
11
+ if (k.min !== undefined && !Number.isFinite(k.min))
12
+ throw new Error(`knobs: "${key}" min is not finite`);
13
+ if (k.max !== undefined && !Number.isFinite(k.max))
14
+ throw new Error(`knobs: "${key}" max is not finite`);
15
+ if (k.min !== undefined && k.max !== undefined && k.min > k.max)
16
+ throw new Error(`knobs: "${key}" min ${k.min} is above max ${k.max}`);
17
+ if (k.step !== undefined && !(k.step > 0))
18
+ throw new Error(`knobs: "${key}" step must be above 0`);
19
+ }
20
+ const base = {};
21
+ for (const [key, k] of Object.entries(spec))
22
+ base[key] = k.value;
23
+ for (const [key, v] of Object.entries(saved ?? {})) {
24
+ if (!Object.hasOwn(spec, key))
25
+ throw new Error(`knobs: saved value for "${key}" names no knob`);
26
+ if (!Number.isFinite(v))
27
+ throw new Error(`knobs: saved value for "${key}" is not finite`);
28
+ base[key] = v;
29
+ }
30
+ let reader = null;
31
+ return {
32
+ spec,
33
+ get(key) {
34
+ if (!Object.hasOwn(spec, key))
35
+ throw new Error(`knobs: no knob "${key}"`);
36
+ if (!reader)
37
+ return base[key];
38
+ const v = reader.values[key];
39
+ if (typeof v !== "number")
40
+ throw new Error(`knobs: "${key}" is bound to a ${typeof v}, not a number`);
41
+ return v;
42
+ },
43
+ defaults: () => ({ ...base }),
44
+ bind(r) {
45
+ reader = r;
46
+ },
47
+ };
48
+ }
@@ -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) {
@@ -123,11 +123,17 @@ export function defineStats(def) {
123
123
  muted: def.muted ? (group) => def.muted?.(q, group) ?? false : undefined,
124
124
  extra: (stat) => self(q).feed[stat] ?? [],
125
125
  });
126
+ let lastFlags = null;
126
127
  const derived = {
127
128
  feed,
128
129
  flags: (q) => {
129
130
  const g = graph(q);
130
- 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;
131
137
  },
132
138
  };
133
139
  for (const id of ids)
@@ -1,3 +1,4 @@
1
+ import "./tokens.css";
1
2
  /** Props of `DevPanel`. */
2
3
  export interface DevPanelProps {
3
4
  /** Closes the panel (the game drops its `#dev` route). Absent, no close button. */