@typeonce/ritmo-devtools 0.14.0 → 0.16.0

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 (109) hide show
  1. package/CHANGELOG.md +283 -0
  2. package/README.md +303 -55
  3. package/dist/Desync.d.ts +23 -3
  4. package/dist/Desync.d.ts.map +1 -1
  5. package/dist/Desync.js +17 -15
  6. package/dist/Desync.js.map +1 -1
  7. package/dist/Determinism.d.ts +20 -6
  8. package/dist/Determinism.d.ts.map +1 -1
  9. package/dist/Determinism.js +11 -3
  10. package/dist/Determinism.js.map +1 -1
  11. package/dist/Format.d.ts +43 -8
  12. package/dist/Format.d.ts.map +1 -1
  13. package/dist/Format.js +66 -31
  14. package/dist/Format.js.map +1 -1
  15. package/dist/Fuzz.d.ts +275 -0
  16. package/dist/Fuzz.d.ts.map +1 -0
  17. package/dist/Fuzz.js +362 -0
  18. package/dist/Fuzz.js.map +1 -0
  19. package/dist/Invariant.d.ts +9 -2
  20. package/dist/Invariant.d.ts.map +1 -1
  21. package/dist/Invariant.js.map +1 -1
  22. package/dist/Lint.d.ts +11 -5
  23. package/dist/Lint.d.ts.map +1 -1
  24. package/dist/Lint.js.map +1 -1
  25. package/dist/PlaywrightEngine.d.ts +29 -0
  26. package/dist/PlaywrightEngine.d.ts.map +1 -0
  27. package/dist/PlaywrightEngine.js +196 -0
  28. package/dist/PlaywrightEngine.js.map +1 -0
  29. package/dist/Replay.d.ts +47 -23
  30. package/dist/Replay.d.ts.map +1 -1
  31. package/dist/Replay.js +26 -30
  32. package/dist/Replay.js.map +1 -1
  33. package/dist/ReplayNodeSink.d.ts.map +1 -1
  34. package/dist/ReplayNodeSink.js +4 -1
  35. package/dist/ReplayNodeSink.js.map +1 -1
  36. package/dist/ReplayVitePlugin.d.ts +1 -0
  37. package/dist/ReplayVitePlugin.d.ts.map +1 -1
  38. package/dist/ReplayVitePlugin.js.map +1 -1
  39. package/dist/Session.d.ts +224 -18
  40. package/dist/Session.d.ts.map +1 -1
  41. package/dist/Session.js +571 -58
  42. package/dist/Session.js.map +1 -1
  43. package/dist/Verify.d.ts +150 -0
  44. package/dist/Verify.d.ts.map +1 -0
  45. package/dist/Verify.js +154 -0
  46. package/dist/Verify.js.map +1 -0
  47. package/dist/cli.js +157 -16
  48. package/dist/cli.js.map +1 -1
  49. package/dist/index.d.ts +3 -2
  50. package/dist/index.d.ts.map +1 -1
  51. package/dist/index.js +3 -2
  52. package/dist/index.js.map +1 -1
  53. package/dist/internal/dependencyScan.d.ts +44 -0
  54. package/dist/internal/dependencyScan.d.ts.map +1 -0
  55. package/dist/internal/dependencyScan.js +313 -0
  56. package/dist/internal/dependencyScan.js.map +1 -0
  57. package/dist/internal/fuzzNetwork.d.ts +56 -0
  58. package/dist/internal/fuzzNetwork.d.ts.map +1 -0
  59. package/dist/internal/fuzzNetwork.js +96 -0
  60. package/dist/internal/fuzzNetwork.js.map +1 -0
  61. package/dist/internal/simulationCoverage.d.ts.map +1 -1
  62. package/dist/internal/simulationCoverage.js +2 -1
  63. package/dist/internal/simulationCoverage.js.map +1 -1
  64. package/dist/internal/skillLink.d.ts +14 -0
  65. package/dist/internal/skillLink.d.ts.map +1 -0
  66. package/dist/internal/skillLink.js +46 -0
  67. package/dist/internal/skillLink.js.map +1 -0
  68. package/dist/internal/values.d.ts +9 -1
  69. package/dist/internal/values.d.ts.map +1 -1
  70. package/dist/internal/values.js +11 -1
  71. package/dist/internal/values.js.map +1 -1
  72. package/dist/internal/verifyRunner.d.ts +19 -0
  73. package/dist/internal/verifyRunner.d.ts.map +1 -0
  74. package/dist/internal/verifyRunner.js +47 -0
  75. package/dist/internal/verifyRunner.js.map +1 -0
  76. package/dist/internal/version.d.ts +1 -1
  77. package/dist/internal/version.js +1 -1
  78. package/package.json +28 -3
  79. package/src/Desync.ts +40 -17
  80. package/src/Determinism.ts +49 -11
  81. package/src/Format.ts +101 -34
  82. package/src/Fuzz.ts +551 -0
  83. package/src/Invariant.ts +9 -2
  84. package/src/Lint.ts +11 -5
  85. package/src/PlaywrightEngine.ts +232 -0
  86. package/src/Replay.ts +100 -47
  87. package/src/ReplayNodeSink.ts +4 -1
  88. package/src/ReplayVitePlugin.ts +1 -0
  89. package/src/Session.ts +816 -73
  90. package/src/Verify.ts +276 -0
  91. package/src/cli.ts +150 -15
  92. package/src/index.ts +3 -2
  93. package/src/internal/dependencyScan.ts +356 -0
  94. package/src/internal/fuzzNetwork.ts +130 -0
  95. package/src/internal/simulationCoverage.ts +2 -1
  96. package/src/internal/skillLink.ts +53 -0
  97. package/src/internal/values.ts +20 -1
  98. package/src/internal/verifyRunner.ts +46 -0
  99. package/src/internal/version.ts +1 -1
  100. package/dist/Monitor.d.ts +0 -101
  101. package/dist/Monitor.d.ts.map +0 -1
  102. package/dist/Monitor.js +0 -602
  103. package/dist/Monitor.js.map +0 -1
  104. package/dist/internal/monitor.d.ts +0 -126
  105. package/dist/internal/monitor.d.ts.map +0 -1
  106. package/dist/internal/monitor.js +0 -279
  107. package/dist/internal/monitor.js.map +0 -1
  108. package/src/Monitor.ts +0 -713
  109. package/src/internal/monitor.ts +0 -370
@@ -0,0 +1,356 @@
1
+ /**
2
+ * The dependency determinism scan behind `ritmo-devtools scan <entry>` (Node
3
+ * only): every file the simulation entry imports, `node_modules` included,
4
+ * checked with the oxlint rules `ritmo/use-ops-for-math`,
5
+ * `ritmo/use-clock-for-time`, and `ritmo/use-random-for-randomness`.
6
+ *
7
+ * The import closure comes from rolldown: a real bundler resolves exactly
8
+ * what a game's build resolves (package `exports`, `browser` fields, CJS and
9
+ * ESM, TypeScript with type-only imports erased), and its module graph
10
+ * (`this.getModuleIds()`) lists every loaded file, including ones tree-shaking
11
+ * would drop. Rolldown is what Vite 8 builds with, so a game with Vite 8 needs
12
+ * nothing new: it is found as Vite's own dependency when the game does not
13
+ * install it directly. esbuild (through tsx) was the alternative, but Vite 8
14
+ * no longer depends on it, so fewer games would have it.
15
+ *
16
+ * The files are checked by spawning the game's own `oxlint` with
17
+ * `@typeonce/oxlint-plugin-ritmo` (both are in every game's setup) and a
18
+ * generated config that turns on only those three rules. Running the rules
19
+ * themselves, not a scanner that mirrors them, keeps one definition of what is
20
+ * flagged: the scan reports exactly what the lint would report if the
21
+ * dependency were the game's code, and what `oxlint --fix` fixes after the
22
+ * dependency is vendored.
23
+ *
24
+ * Each tool is looked up from the entry's directory first, then from devtools
25
+ * (`oxlint` and `rolldown` are optional peer dependencies).
26
+ *
27
+ * @internal
28
+ */
29
+ import { spawnSync } from "node:child_process"
30
+ import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs"
31
+ import { tmpdir } from "node:os"
32
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path"
33
+ import { fileURLToPath, pathToFileURL } from "node:url"
34
+
35
+ import * as Result from "@typeonce/ritmo/Result"
36
+
37
+ /** The rules the scan runs: the determinism rules a dependency can break. */
38
+ export const rules = ["ritmo/use-ops-for-math", "ritmo/use-clock-for-time", "ritmo/use-random-for-randomness"] as const
39
+
40
+ export type Rule = (typeof rules)[number]
41
+
42
+ /** One report of a rule, at a 1-based line and column (UTF-16) in a file relative to the working directory. */
43
+ export interface Finding {
44
+ readonly file: string
45
+ readonly line: number
46
+ readonly column: number
47
+ readonly rule: Rule
48
+ /** The flagged source (`Math.sin`, `x ** 3`, `Date.now`), shortened to one line. */
49
+ readonly snippet: string
50
+ }
51
+
52
+ /** Findings of the files that belong to one package (nearest `package.json` with a `name`). */
53
+ export interface PackageReport {
54
+ readonly name: string
55
+ readonly files: number
56
+ readonly findings: ReadonlyArray<Finding>
57
+ }
58
+
59
+ /** The scan result; `packages` starts with the entry's own package, then the rest by name. */
60
+ export interface Report {
61
+ readonly entry: string
62
+ readonly files: number
63
+ readonly packages: ReadonlyArray<PackageReport>
64
+ }
65
+
66
+ export type ScanError =
67
+ | { readonly _tag: "EntryUnreadable"; readonly message: string }
68
+ | { readonly _tag: "ToolMissing"; readonly tool: string; readonly install: string }
69
+ | { readonly _tag: "ResolveFailed"; readonly message: string }
70
+ | { readonly _tag: "LintFailed"; readonly message: string }
71
+
72
+ const sourceFile = /\.(?:[cm]?[jt]s|[jt]sx)$/
73
+ const chunkSize = 400
74
+ const unnamed = "(no package)"
75
+
76
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
77
+ typeof value === "object" && value !== null && !Array.isArray(value)
78
+
79
+ const readJson = (path: string): unknown => {
80
+ try {
81
+ return JSON.parse(readFileSync(path, "utf8"))
82
+ } catch {
83
+ return undefined
84
+ }
85
+ }
86
+
87
+ /** The real directory of the installed package `name`, looked up through `node_modules` from `from` upward. */
88
+ const findPackage = (name: string, from: string): string | undefined => {
89
+ for (let directory = from; ; directory = dirname(directory)) {
90
+ const candidate = join(directory, "node_modules", name)
91
+ if (existsSync(join(candidate, "package.json"))) return realpathSync(candidate)
92
+ if (dirname(directory) === directory) return undefined
93
+ }
94
+ }
95
+
96
+ const exportTarget = (value: unknown): string | undefined => {
97
+ if (typeof value === "string") return value
98
+ if (Array.isArray(value)) return exportTarget(value[0])
99
+ if (!isRecord(value)) return undefined
100
+ for (const [condition, target] of Object.entries(value)) {
101
+ if (condition === "import" || condition === "node" || condition === "default") {
102
+ const found = exportTarget(target)
103
+ if (found !== undefined) return found
104
+ }
105
+ }
106
+ return undefined
107
+ }
108
+
109
+ /** The file the package's main entry imports (`exports["."]` with `import`/`node`/`default`, then `module`, `main`). */
110
+ const packageEntry = (directory: string): string => {
111
+ const manifest = readJson(join(directory, "package.json"))
112
+ const record = isRecord(manifest) ? manifest : {}
113
+ const exports = record["exports"]
114
+ const main = isRecord(exports) && "." in exports ? exports["."] : exports
115
+ const target = exportTarget(main)
116
+ ?? (typeof record["module"] === "string" ? record["module"] : undefined)
117
+ ?? (typeof record["main"] === "string" ? record["main"] : "index.js")
118
+ return join(directory, target)
119
+ }
120
+
121
+ const devtoolsDirectory = dirname(fileURLToPath(import.meta.url))
122
+
123
+ const locate = (name: string, from: string): string | undefined =>
124
+ findPackage(name, from) ?? findPackage(name, devtoolsDirectory)
125
+
126
+ interface Bundle {
127
+ readonly generate: (options: object) => Promise<unknown>
128
+ readonly close: () => Promise<void>
129
+ }
130
+ type Rolldown = (options: object) => Promise<Bundle>
131
+
132
+ /** Rolldown, installed directly or as Vite 8's dependency. */
133
+ const loadRolldown = async (from: string): Promise<Rolldown | undefined> => {
134
+ const vite = locate("vite", from)
135
+ const directory = locate("rolldown", from) ?? (vite === undefined ? undefined : findPackage("rolldown", vite))
136
+ if (directory === undefined) return undefined
137
+ const loaded: unknown = await import(pathToFileURL(packageEntry(directory)).href)
138
+ const rolldown = isRecord(loaded) ? loaded["rolldown"] : undefined
139
+ // The module is untyped here (an optional peer); only its shape was checked.
140
+ return typeof rolldown === "function" ? rolldown as Rolldown : undefined
141
+ }
142
+
143
+ /** Every source file the entry imports, itself included, as real absolute paths. */
144
+ const closure = async (rolldown: Rolldown, entry: string): Promise<ReadonlyArray<string>> => {
145
+ let ids: ReadonlyArray<string> = []
146
+ const bundle = await rolldown({
147
+ input: entry,
148
+ cwd: dirname(entry),
149
+ // The build that ships to players; Node builtins stay external.
150
+ platform: "browser",
151
+ treeshake: false,
152
+ logLevel: "silent",
153
+ plugins: [{
154
+ name: "ritmo-devtools-scan",
155
+ buildEnd(this: { getModuleIds: () => Iterable<string> }) {
156
+ ids = [...this.getModuleIds()]
157
+ }
158
+ }]
159
+ })
160
+ try {
161
+ await bundle.generate({})
162
+ } finally {
163
+ await bundle.close()
164
+ }
165
+ return [...new Set(ids.filter((id) => isAbsolute(id) && sourceFile.test(id) && existsSync(id)).map((id) => realpathSync(id)))].sort()
166
+ }
167
+
168
+ interface Diagnostic {
169
+ readonly file: string
170
+ readonly rule: Rule
171
+ readonly offset: number
172
+ readonly length: number
173
+ }
174
+
175
+ const parseDiagnostics = (stdout: string): ReadonlyArray<Diagnostic> | undefined => {
176
+ let parsed: unknown
177
+ try {
178
+ parsed = JSON.parse(stdout)
179
+ } catch {
180
+ return undefined
181
+ }
182
+ if (!isRecord(parsed) || !Array.isArray(parsed["diagnostics"])) return undefined
183
+ const out: Array<Diagnostic> = []
184
+ for (const diagnostic of parsed["diagnostics"]) {
185
+ if (!isRecord(diagnostic) || typeof diagnostic["code"] !== "string" || typeof diagnostic["filename"] !== "string") continue
186
+ const rule = diagnostic["code"].replace(/^ritmo\((.*)\)$/, "ritmo/$1")
187
+ const label = Array.isArray(diagnostic["labels"]) ? diagnostic["labels"][0] : undefined
188
+ const span = isRecord(label) && isRecord(label["span"]) ? label["span"] : undefined
189
+ if (!(rules as ReadonlyArray<string>).includes(rule) || span === undefined) continue
190
+ if (typeof span["offset"] !== "number" || typeof span["length"] !== "number") continue
191
+ out.push({ file: diagnostic["filename"], rule: rule as Rule, offset: span["offset"], length: span["length"] })
192
+ }
193
+ return out
194
+ }
195
+
196
+ const lint = (oxlint: string, plugin: string, files: ReadonlyArray<string>): Result.Result<ReadonlyArray<Diagnostic>, ScanError> => {
197
+ const directory = mkdtempSync(join(tmpdir(), "ritmo-scan-"))
198
+ try {
199
+ const config = join(directory, "oxlintrc.json")
200
+ writeFileSync(config, JSON.stringify({
201
+ jsPlugins: [plugin],
202
+ categories: { correctness: "off" },
203
+ rules: Object.fromEntries(rules.map((rule) => [rule, "error"])),
204
+ ignorePatterns: []
205
+ }))
206
+ const diagnostics: Array<Diagnostic> = []
207
+ for (let start = 0; start < files.length; start += chunkSize) {
208
+ const run = spawnSync(
209
+ process.execPath,
210
+ [oxlint, "-c", config, "--format", "json", "--no-ignore", "--disable-nested-config", ...files.slice(start, start + chunkSize)],
211
+ { encoding: "utf8", maxBuffer: 1024 * 1024 * 1024 }
212
+ )
213
+ const parsed = parseDiagnostics(run.stdout ?? "")
214
+ if (parsed === undefined) {
215
+ return Result.failure({ _tag: "LintFailed", message: (run.stderr || run.stdout || run.error?.message || "no output").trim() })
216
+ }
217
+ diagnostics.push(...parsed)
218
+ }
219
+ return Result.success(diagnostics)
220
+ } finally {
221
+ rmSync(directory, { recursive: true, force: true })
222
+ }
223
+ }
224
+
225
+ const shorten = (text: string): string => {
226
+ const line = text.replace(/\s+/g, " ").trim()
227
+ return line.length > 60 ? `${line.slice(0, 59)}…` : line
228
+ }
229
+
230
+ /** Line, column (UTF-16), and snippet of each byte span (oxlint reports UTF-8 offsets), walking the file once. */
231
+ const locateSpans = (path: string, cwd: string, found: ReadonlyArray<Diagnostic>): ReadonlyArray<Finding> => {
232
+ const bytes = readFileSync(path)
233
+ const file = relative(cwd, path)
234
+ const sorted = [...found].sort((a, b) => a.offset - b.offset)
235
+ const out: Array<Finding> = []
236
+ let cursor = 0
237
+ let line = 1
238
+ let column = 1
239
+ for (const diagnostic of sorted) {
240
+ const end = Math.min(diagnostic.offset, bytes.length)
241
+ let lineStart = cursor
242
+ for (let index = cursor; index < end; index++) {
243
+ if (bytes[index] === 0x0a) {
244
+ line++
245
+ column = 1
246
+ lineStart = index + 1
247
+ }
248
+ }
249
+ column += bytes.subarray(lineStart, end).toString("utf8").length
250
+ cursor = end
251
+ out.push({
252
+ file,
253
+ line,
254
+ column,
255
+ rule: diagnostic.rule,
256
+ snippet: shorten(bytes.subarray(diagnostic.offset, diagnostic.offset + diagnostic.length).toString("utf8"))
257
+ })
258
+ }
259
+ return out
260
+ }
261
+
262
+ /** The `name` of the nearest `package.json` above `file` that has one. */
263
+ const packageOf = (cache: Map<string, string | undefined>, file: string): string | undefined => {
264
+ const visited: Array<string> = []
265
+ let name: string | undefined
266
+ for (let directory = dirname(file); ; directory = dirname(directory)) {
267
+ if (cache.has(directory)) {
268
+ name = cache.get(directory)
269
+ break
270
+ }
271
+ visited.push(directory)
272
+ const manifest = readJson(join(directory, "package.json"))
273
+ if (isRecord(manifest) && typeof manifest["name"] === "string" && manifest["name"] !== "") {
274
+ name = manifest["name"]
275
+ break
276
+ }
277
+ if (dirname(directory) === directory) break
278
+ }
279
+ for (const directory of visited) cache.set(directory, name)
280
+ return name
281
+ }
282
+
283
+ /** Scans the import closure of `entry`; paths in the report are relative to `cwd`. */
284
+ export const run = async (entry: string, cwd: string): Promise<Result.Result<Report, ScanError>> => {
285
+ const absolute = resolve(cwd, entry)
286
+ try {
287
+ if (!statSync(absolute).isFile()) return Result.failure({ _tag: "EntryUnreadable", message: `${entry} is not a file` })
288
+ readFileSync(absolute)
289
+ } catch (error) {
290
+ return Result.failure({ _tag: "EntryUnreadable", message: `${entry} could not be read: ${error instanceof Error ? error.message : String(error)}` })
291
+ }
292
+ const from = dirname(realpathSync(absolute))
293
+ const rolldown = await loadRolldown(from)
294
+ if (rolldown === undefined) {
295
+ return Result.failure({ _tag: "ToolMissing", tool: "rolldown (or vite 8, which includes it)", install: "npm install --save-dev rolldown" })
296
+ }
297
+ const oxlint = locate("oxlint", from)
298
+ const plugin = locate("@typeonce/oxlint-plugin-ritmo", from)
299
+ if (oxlint === undefined || plugin === undefined) {
300
+ return Result.failure({ _tag: "ToolMissing", tool: "oxlint with @typeonce/oxlint-plugin-ritmo", install: "npm install --save-dev oxlint @typeonce/oxlint-plugin-ritmo" })
301
+ }
302
+ const manifest = readJson(join(oxlint, "package.json"))
303
+ const bin = isRecord(manifest) ? manifest["bin"] : undefined
304
+ const oxlintBin = join(oxlint, typeof bin === "string" ? bin : isRecord(bin) && typeof bin["oxlint"] === "string" ? bin["oxlint"] : "bin/oxlint")
305
+
306
+ let files: ReadonlyArray<string>
307
+ try {
308
+ files = await closure(rolldown, realpathSync(absolute))
309
+ } catch (error) {
310
+ return Result.failure({ _tag: "ResolveFailed", message: error instanceof Error ? error.message : String(error) })
311
+ }
312
+ const diagnostics = lint(oxlintBin, packageEntry(plugin), files)
313
+ if (!diagnostics.ok) return diagnostics
314
+
315
+ const base = realpathSync(cwd)
316
+ const byFile = new Map<string, Array<Diagnostic>>()
317
+ for (const diagnostic of diagnostics.value) {
318
+ const path = realpathSync(diagnostic.file)
319
+ byFile.set(path, [...(byFile.get(path) ?? []), diagnostic])
320
+ }
321
+ const cache = new Map<string, string | undefined>()
322
+ const own = packageOf(cache, realpathSync(absolute)) ?? unnamed
323
+ const groups = new Map<string, { files: number; findings: Array<Finding> }>([[own, { files: 0, findings: [] }]])
324
+ for (const file of files) {
325
+ const name = packageOf(cache, file) ?? unnamed
326
+ const group = groups.get(name) ?? { files: 0, findings: [] }
327
+ group.files++
328
+ group.findings.push(...locateSpans(file, base, byFile.get(file) ?? []))
329
+ groups.set(name, group)
330
+ }
331
+ const packages = [...groups]
332
+ .sort(([a], [b]) => a === own ? -1 : b === own ? 1 : a.localeCompare(b))
333
+ .map(([name, group]) => ({ name, files: group.files, findings: group.findings }))
334
+ return Result.success({ entry: relative(base, realpathSync(absolute)), files: files.length, packages })
335
+ }
336
+
337
+ const plural = (count: number, word: string): string => `${count} ${word}${count === 1 ? "" : "s"}`
338
+
339
+ /** The text report: findings grouped by package, a summary line, and what to do next. */
340
+ export const format = (report: Report): string => {
341
+ const flagged = report.packages.filter((entry) => entry.findings.length > 0)
342
+ const total = flagged.reduce((sum, entry) => sum + entry.findings.length, 0)
343
+ const lines: Array<string> = []
344
+ for (const entry of flagged) {
345
+ lines.push(`${entry.name} (${plural(entry.findings.length, "finding")})`)
346
+ for (const finding of entry.findings) {
347
+ lines.push(` ${finding.file}:${finding.line}:${finding.column} ${finding.rule} ${finding.snippet}`)
348
+ }
349
+ lines.push("")
350
+ }
351
+ lines.push(`scanned ${plural(report.files, "file")} in ${plural(report.packages.length, "package")} imported by ${report.entry}: ${plural(total, "finding")} in ${plural(flagged.length, "package")}`)
352
+ lines.push(total > 0
353
+ ? "These are hints: code the simulation never calls is fine. For a dependency the simulation calls, vendor it into your source and run `oxlint --fix` with these rules on, or replace it; then confirm with Verify.acrossEngines (`ritmo-devtools verify`) or Netcode.syncTest."
354
+ : "No dependency uses the Math functions, clock, or randomness these rules flag; confirm the whole run with Verify.acrossEngines (`ritmo-devtools verify`) or Netcode.syncTest.")
355
+ return lines.join("\n")
356
+ }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * The network half of `Fuzz.run`: one simulation of every seat as its own
3
+ * peer, each a fresh runtime from the game's factory, joined by a seeded
4
+ * `MemoryNetworkLink` on one test clock and driven by `Netcode.rollback`
5
+ * sessions. Deterministic for a timeline and a network seed, so shrinking
6
+ * can run it again.
7
+ */
8
+ import { HostClock } from "@typeonce/ritmo"
9
+ import type * as Clock from "@typeonce/ritmo/Clock"
10
+ import type * as Descriptor from "@typeonce/ritmo/Descriptor"
11
+ import type { Source } from "@typeonce/ritmo/Schedule"
12
+ import { MemoryNetworkLink, Netcode } from "@typeonce/ritmo-netcode"
13
+
14
+ import type { Invariant } from "../Invariant.ts"
15
+ import type * as Replay from "../Replay.ts"
16
+
17
+ /** What one networked simulation came to: as `Fuzz`'s single-runtime outcome, without a replay. */
18
+ export type NetworkOutcome<Violation> =
19
+ | { readonly kind: "passed" }
20
+ | { readonly kind: "violated"; readonly violation: Violation; readonly frame: number }
21
+ | { readonly kind: "invalid"; readonly message: string }
22
+
23
+ export interface NetworkPlan {
24
+ /** The seats' service, codec, count, and idle input. */
25
+ readonly name: string
26
+ readonly codec: Descriptor.Codec<any, any>
27
+ readonly count: number
28
+ readonly idle: unknown
29
+ /** The game's factory, and the schedules it is fuzzed with. */
30
+ readonly make: (playback: Replay.Playback) => { readonly runtime: unknown; readonly schedules: Readonly<Record<string, unknown>> }
31
+ readonly schedule: string
32
+ readonly setup: string | undefined
33
+ readonly invariants: ReadonlyArray<Invariant>
34
+ readonly step: Clock.Step
35
+ readonly seed: number
36
+ readonly latencyMS: number
37
+ readonly jitterMS: number
38
+ readonly loss: number
39
+ readonly settle: number
40
+ readonly inputDelay: number | undefined
41
+ readonly maxRollback: number | undefined
42
+ readonly checksumEvery: number | undefined
43
+ }
44
+
45
+ /** What the sessions call on a runtime the factory made. `Fuzz.run`'s signature checked the real types. */
46
+ interface Peer {
47
+ readonly tryTick: (schedule: unknown) => { readonly ok: boolean; readonly error?: unknown }
48
+ readonly inspect: (inspector: unknown) => unknown
49
+ }
50
+
51
+ export type NetworkViolation =
52
+ | { readonly _tag: "SessionFailed"; readonly seat: number; readonly error: Netcode.SessionError<unknown> }
53
+ | { readonly _tag: "InvariantViolated"; readonly invariant: string; readonly message: string }
54
+ | { readonly _tag: "Defect"; readonly invariant: string | undefined; readonly error: unknown }
55
+
56
+ /** Plays `timeline` (per frame, the seats input's value: every seat's local input) on one peer per seat, then `settle` idle frames. */
57
+ export const play = (plan: NetworkPlan, timeline: ReadonlyArray<ReadonlyArray<unknown>>): NetworkOutcome<NetworkViolation> => {
58
+ const hostClock = HostClock.test()
59
+ const links = MemoryNetworkLink.make({ peers: plan.count, hostClock, seed: plan.seed, latencyMS: plan.latencyMS, jitterMS: plan.jitterMS, loss: plan.loss })
60
+ if (!links.ok) return { kind: "invalid", message: `network.${links.error.field} is out of range: ${links.error.value}` }
61
+ const peers: Array<{ readonly runtime: Peer; readonly session: Netcode.Session<unknown, unknown> }> = []
62
+ for (let seat = 0; seat < plan.count; seat++) {
63
+ const seats = Netcode.seats(plan.codec, { count: plan.count, idle: plan.idle })
64
+ if (!seats.ok) return { kind: "invalid", message: `the seats' idle input: ${seats.error.reason}` }
65
+ const unknown: Array<string> = []
66
+ const playback: Replay.Playback = {
67
+ source: <const SourceName extends string, Value extends Source<unknown>>(descriptor: Descriptor.Descriptor<"service", SourceName, Value>): Source<Replay.SourceData<Value>> => {
68
+ if (descriptor.name !== plan.name) unknown.push(descriptor.name)
69
+ // `Fuzz.seats` checked that this service is a `Netcode.Source` of the seats' input.
70
+ return seats.value.source as unknown as Source<Replay.SourceData<Value>>
71
+ },
72
+ constant: () => undefined
73
+ }
74
+ const target = plan.make(playback)
75
+ if (unknown.length > 0) return { kind: "invalid", message: `make asked playback.source for ${unknown.join(", ")}: over a network the simulation reads its input from the seats alone` }
76
+ const runtime = target.runtime as Peer
77
+ const schedule = target.schedules[plan.schedule]
78
+ if (schedule === undefined) return { kind: "invalid", message: `make returned no schedule ${plan.schedule}` }
79
+ // Only seat 0 sets up: every peer starts from its save.
80
+ if (seat === 0 && plan.setup !== undefined) {
81
+ const setup = target.schedules[plan.setup]
82
+ if (setup === undefined) return { kind: "invalid", message: `make returned no schedule ${plan.setup}` }
83
+ const ticked = runtime.tryTick(setup)
84
+ if (!ticked.ok) return { kind: "invalid", message: `setup failed with every input neutral: ${JSON.stringify(ticked.error)}` }
85
+ }
86
+ // `Fuzz.run`'s signature checked that the schedule rewinds and the runtime saves, as `Netcode.rollback` does.
87
+ const session = (Netcode.rollback as unknown as (runtime: unknown, options: unknown) => ReturnType<typeof Netcode.rollback>)(runtime, {
88
+ simulate: schedule,
89
+ seats: seats.value,
90
+ seat,
91
+ links: [links.value[seat]!],
92
+ hostClock,
93
+ step: plan.step,
94
+ keepSnapshots: true,
95
+ ...(plan.inputDelay === undefined ? {} : { inputDelay: plan.inputDelay }),
96
+ ...(plan.maxRollback === undefined ? {} : { maxRollback: plan.maxRollback }),
97
+ ...(plan.checksumEvery === undefined ? {} : { checksumEvery: plan.checksumEvery })
98
+ })
99
+ if (!session.ok) return { kind: "invalid", message: `network.${session.error.field}: ${session.error.reason}` }
100
+ peers.push({ runtime, session: session.value as Netcode.Session<unknown, unknown> })
101
+ }
102
+
103
+ const stepMS = plan.step.dt * 1000
104
+ const frames = timeline.length + plan.settle
105
+ for (let frame = 0; frame < frames; frame++) {
106
+ const values = timeline[frame]?.[0] as ReadonlyArray<unknown> | undefined
107
+ for (const [seat, { session }] of peers.entries()) {
108
+ let advanced: ReturnType<typeof session.advance>
109
+ try {
110
+ advanced = session.advance(values === undefined ? plan.idle : values[seat])
111
+ } catch (error) {
112
+ return { kind: "violated", violation: { _tag: "Defect", invariant: undefined, error }, frame: frame + 1 }
113
+ }
114
+ if (!advanced.ok) return { kind: "violated", violation: { _tag: "SessionFailed", seat, error: advanced.error }, frame: frame + 1 }
115
+ }
116
+ for (const { runtime } of peers) {
117
+ for (const invariant of plan.invariants) {
118
+ let message: unknown
119
+ try {
120
+ message = runtime.inspect(invariant.inspector)
121
+ } catch (error) {
122
+ return { kind: "violated", violation: { _tag: "Defect", invariant: invariant.name, error }, frame: frame + 1 }
123
+ }
124
+ if (typeof message === "string") return { kind: "violated", violation: { _tag: "InvariantViolated", invariant: invariant.name, message }, frame: frame + 1 }
125
+ }
126
+ }
127
+ hostClock.adjust(stepMS)
128
+ }
129
+ return { kind: "passed" }
130
+ }
@@ -132,5 +132,6 @@ export const format = (coverage: Coverage): string =>
132
132
  : coverage.uncovered.map((file) =>
133
133
  `uncovered-simulation-module ${file}\n`
134
134
  + ` The simulation loads this file, but the simulation rules in ${configName} do not cover it.\n`
135
- + ` Add it to the simulation override's "files", or stop importing values from it.`
135
+ + ` Add it to the simulation override's "files", or stop importing values from it.\n`
136
+ + ` A host module (render, input glue) imported at the top of the lint entry is loaded too: import it inside lintTarget instead.`
136
137
  ).join("\n")
@@ -0,0 +1,53 @@
1
+ /**
2
+ * The skill check for the `ritmo-devtools lint` CLI (Node only): whether the
3
+ * project links the Ritmo skill from the installed package, as `SETUP.md`
4
+ * step 2 says, so the game's agent reads the playbooks of the installed
5
+ * version. It is a note: it never fails the lint, since where an agent reads
6
+ * skills from is the project's choice.
7
+ */
8
+ import { lstatSync, realpathSync } from "node:fs"
9
+ import { join, sep } from "node:path"
10
+
11
+ /** The folders agents read skills from, relative to the working directory. */
12
+ const folders = [".agents/skills/ritmo", ".claude/skills/ritmo"] as const
13
+
14
+ export type SkillLink =
15
+ | { readonly _tag: "Linked"; readonly path: string }
16
+ | { readonly _tag: "Copied"; readonly path: string }
17
+ | { readonly _tag: "Missing" }
18
+
19
+ // A link into an installed `@typeonce/ritmo` package's skill: `node_modules/@typeonce/ritmo/skills/ritmo`, or pnpm's store path to it.
20
+ const isInstalledSkill = (path: string): boolean =>
21
+ path.includes(`${sep}node_modules${sep}`) && path.endsWith(join("@typeonce", "ritmo", "skills", "ritmo"))
22
+
23
+ /** Where the skill is in `cwd`: linked from the installed package, copied in, or missing. */
24
+ export const check = (cwd: string): SkillLink => {
25
+ let copied: string | undefined
26
+ for (const folder of folders) {
27
+ const path = join(cwd, folder)
28
+ try {
29
+ const stat = lstatSync(path)
30
+ if (stat.isSymbolicLink() && isInstalledSkill(realpathSync(path))) return { _tag: "Linked", path: folder }
31
+ copied ??= folder
32
+ } catch {
33
+ // Not there (or a dangling link): look at the next folder.
34
+ }
35
+ }
36
+ return copied === undefined ? { _tag: "Missing" } : { _tag: "Copied", path: copied }
37
+ }
38
+
39
+ /** The CLI text for a skill check: nothing when linked, a note otherwise. */
40
+ export const format = (link: SkillLink): string => {
41
+ switch (link._tag) {
42
+ case "Linked":
43
+ return ""
44
+ case "Missing":
45
+ return `note skill-not-linked\n`
46
+ + ` No ${folders.join(" or ")} links to node_modules/@typeonce/ritmo/skills/ritmo.\n`
47
+ + ` Link it (SETUP.md step 2) so your agent reads the playbooks for this Ritmo version.`
48
+ case "Copied":
49
+ return `note skill-copied ${link.path}\n`
50
+ + ` This is a copy of the Ritmo skill, or a link to somewhere else: it goes stale on the next upgrade.\n`
51
+ + ` Replace it with a link to node_modules/@typeonce/ritmo/skills/ritmo (SETUP.md step 2).`
52
+ }
53
+ }
@@ -1,4 +1,5 @@
1
- /** Value checks shared by sessions and the monitor. */
1
+ /** Value checks used by sessions. */
2
+ import type * as Debug from "@typeonce/ritmo/Debug"
2
3
 
3
4
  /**
4
5
  * The path of the first NaN or infinite number inside a value (`""` for the
@@ -15,3 +16,21 @@ export const nonFinitePath = (value: unknown, depth = 6, seen: Set<object> = new
15
16
  }
16
17
  return undefined
17
18
  }
19
+
20
+ /** The declared ranges (`meta` with `range`) of one descriptor's fields. */
21
+ export type FieldRanges = ReadonlyArray<readonly [field: string, min: number, max: number]>
22
+
23
+ const rangesBy = (entries: ReadonlyArray<{ readonly name: string; readonly meta: Debug.ComponentDescription["meta"] }>): ReadonlyMap<string, FieldRanges> => {
24
+ const ranges = new Map<string, FieldRanges>()
25
+ for (const { name, meta } of entries) {
26
+ const fields = Object.entries(meta).flatMap(([field, entry]) => entry.range === undefined ? [] : [[field, entry.range[0], entry.range[1]] as const])
27
+ if (fields.length > 0) ranges.set(name, fields)
28
+ }
29
+ return ranges
30
+ }
31
+
32
+ /** Every declared field range, by component and by resource name; descriptors without one are left out. */
33
+ export const rangesOf = (description: Debug.Description): {
34
+ readonly component: ReadonlyMap<string, FieldRanges>
35
+ readonly resource: ReadonlyMap<string, FieldRanges>
36
+ } => ({ component: rangesBy(description.components), resource: rangesBy(description.resources) })
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The page side of `PlaywrightEngine`: loaded in a browser by the Vite dev
3
+ * server it starts, it imports the game's entry and runs `Verify.trace` and
4
+ * `Verify.snapshotAt` there with the entry's `replayTarget`. What it returns
5
+ * crosses to Node as JSON, so it returns plain results and never throws a
6
+ * value Node cannot read.
7
+ */
8
+ import * as Result from "@typeonce/ritmo/Result"
9
+ import type * as Snapshot from "@typeonce/ritmo/Snapshot"
10
+
11
+ import type * as Replay from "../Replay.ts"
12
+ import * as Verify from "../Verify.ts"
13
+
14
+ /** What the page exposes to `PlaywrightEngine`. */
15
+ export interface Runner {
16
+ readonly trace: (file: Replay.ReplayFile) => Result.Result<Verify.Hashes, string>
17
+ readonly snapshotAt: (file: Replay.ReplayFile, tick: number) => Result.Result<Snapshot.WorldSnapshot, string>
18
+ }
19
+
20
+ const describe = (error: unknown): string => error instanceof Error ? `${error.message}\n${error.stack ?? ""}` : JSON.stringify(error)
21
+
22
+ /** Imports the entry at `url` (a dev server path) and checks it exports `replayTarget`. */
23
+ export const start = async (url: string): Promise<Result.Result<Runner, string>> => {
24
+ let loaded: unknown
25
+ try {
26
+ loaded = await import(/* @vite-ignore */ url)
27
+ } catch (error) {
28
+ return Result.failure(`the entry did not load in the browser: ${describe(error)}`)
29
+ }
30
+ const make: unknown = typeof loaded === "object" && loaded !== null ? Reflect.get(loaded, "replayTarget") : undefined
31
+ if (typeof make !== "function") return Result.failure("the entry must export replayTarget: (playback) => { runtime, schedules, hostClock } (see the Verify module)")
32
+ // The CLI checked the same entry in Node, where its type is checked too.
33
+ const target = make as (playback: Replay.Playback) => Replay.Target<any, any>
34
+ const guard = <A>(run: () => Result.Result<A, unknown>): Result.Result<A, string> => {
35
+ try {
36
+ const result = run()
37
+ return result.ok ? result : Result.failure(`the replay did not open: ${JSON.stringify(result.error)}`)
38
+ } catch (error) {
39
+ return Result.failure(`the game threw: ${describe(error)}`)
40
+ }
41
+ }
42
+ return Result.success({
43
+ trace: (file) => guard(() => Verify.trace(target, file)),
44
+ snapshotAt: (file, tick) => guard(() => Verify.snapshotAt(target, file, tick))
45
+ })
46
+ }
@@ -3,4 +3,4 @@
3
3
  * `package.json` by `scripts/sync-version.ts` (run by \`pnpm version-packages\`)
4
4
  * and checked by a test.
5
5
  */
6
- export const libraryVersion = "0.14.0"
6
+ export const libraryVersion = "0.16.0"