oda-engine 0.0.0-stage → 0.1.1

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 (204) hide show
  1. package/README.md +151 -2
  2. package/bin/nowhere.mjs +352 -0
  3. package/lib/account.mjs +57 -0
  4. package/lib/agentModules.mjs +57 -0
  5. package/lib/devServer.mjs +351 -0
  6. package/lib/headless.mjs +231 -0
  7. package/lib/headlessPreview.mjs +212 -0
  8. package/lib/keys.mjs +517 -0
  9. package/lib/make.mjs +855 -0
  10. package/lib/mcp.mjs +537 -0
  11. package/lib/open.mjs +22 -0
  12. package/lib/preview.mjs +87 -0
  13. package/lib/previewRpc.mjs +134 -0
  14. package/lib/project.mjs +359 -0
  15. package/lib/publishFlow.mjs +131 -0
  16. package/lib/resources.mjs +50 -0
  17. package/lib/rules.mjs +60 -0
  18. package/lib/scaffold.mjs +42 -0
  19. package/lib/setup.mjs +59 -0
  20. package/lib/tools.mjs +668 -0
  21. package/package.json +51 -4
  22. package/template/game.config.json +9 -0
  23. package/template/scene.json +4 -0
  24. package/template/src/main.ts +11 -0
  25. package/vendor/DOCS.md +447 -0
  26. package/vendor/agent/appRun.mjs +520 -0
  27. package/vendor/agent/assets/brief.mjs +242 -0
  28. package/vendor/agent/assets/collider.mjs +531 -0
  29. package/vendor/agent/assets/environments/index.mjs +12 -0
  30. package/vendor/agent/assets/environments/worldlabs.mjs +161 -0
  31. package/vendor/agent/assets/fetch.mjs +168 -0
  32. package/vendor/agent/assets/footprint.mjs +13 -0
  33. package/vendor/agent/assets/gltf.mjs +547 -0
  34. package/vendor/agent/assets/hdr.mjs +269 -0
  35. package/vendor/agent/assets/imageOps.mjs +171 -0
  36. package/vendor/agent/assets/images/codex.mjs +307 -0
  37. package/vendor/agent/assets/images/fal.mjs +75 -0
  38. package/vendor/agent/assets/images/gemini.mjs +84 -0
  39. package/vendor/agent/assets/images/index.mjs +25 -0
  40. package/vendor/agent/assets/images/openai.mjs +75 -0
  41. package/vendor/agent/assets/images/stability.mjs +71 -0
  42. package/vendor/agent/assets/images/views.mjs +31 -0
  43. package/vendor/agent/assets/import.mjs +1352 -0
  44. package/vendor/agent/assets/inspect.mjs +465 -0
  45. package/vendor/agent/assets/jobs.mjs +196 -0
  46. package/vendor/agent/assets/ktx2.mjs +290 -0
  47. package/vendor/agent/assets/ledger.mjs +466 -0
  48. package/vendor/agent/assets/net.mjs +254 -0
  49. package/vendor/agent/assets/prices.json +39 -0
  50. package/vendor/agent/assets/providers/fal.mjs +115 -0
  51. package/vendor/agent/assets/providers/index.mjs +22 -0
  52. package/vendor/agent/assets/providers/meshy.mjs +119 -0
  53. package/vendor/agent/assets/providers/tripo.mjs +188 -0
  54. package/vendor/agent/assets/sources/ambientcg.mjs +129 -0
  55. package/vendor/agent/assets/sources/index.mjs +23 -0
  56. package/vendor/agent/assets/sources/polyhaven.mjs +237 -0
  57. package/vendor/agent/assets/sources/polypizza.mjs +121 -0
  58. package/vendor/agent/assets/splat.mjs +631 -0
  59. package/vendor/agent/assets/targets.mjs +122 -0
  60. package/vendor/agent/assets/tile.mjs +261 -0
  61. package/vendor/agent/assets/unzip.mjs +180 -0
  62. package/vendor/agent/blender/cleanup.py +360 -0
  63. package/vendor/agent/blender/convert.py +167 -0
  64. package/vendor/agent/blender/find.mjs +192 -0
  65. package/vendor/agent/blender/nw_export.py +104 -0
  66. package/vendor/agent/blender/nw_rubric.py +426 -0
  67. package/vendor/agent/blender/run.mjs +193 -0
  68. package/vendor/agent/blender/runner.py +252 -0
  69. package/vendor/agent/blender/sheet.py +743 -0
  70. package/vendor/agent/depth.mjs +134 -0
  71. package/vendor/agent/director/board.mjs +451 -0
  72. package/vendor/agent/director/contracts.mjs +663 -0
  73. package/vendor/agent/director/director.mjs +2365 -0
  74. package/vendor/agent/director/estimate.mjs +200 -0
  75. package/vendor/agent/director/gate.mjs +802 -0
  76. package/vendor/agent/director/limits.json +16 -0
  77. package/vendor/agent/director/methods.mjs +457 -0
  78. package/vendor/agent/director/policy.json +33 -0
  79. package/vendor/agent/director/prompts.mjs +244 -0
  80. package/vendor/agent/director/reading.mjs +341 -0
  81. package/vendor/agent/director/router.mjs +184 -0
  82. package/vendor/agent/director/seams.mjs +243 -0
  83. package/vendor/agent/director/session.mjs +643 -0
  84. package/vendor/agent/director/store.mjs +119 -0
  85. package/vendor/agent/director/taskGate.mjs +110 -0
  86. package/vendor/agent/director/teamLedger.mjs +118 -0
  87. package/vendor/agent/director/triage.mjs +63 -0
  88. package/vendor/agent/downloads.cjs +363 -0
  89. package/vendor/agent/flow.mjs +78 -0
  90. package/vendor/agent/guard.mjs +613 -0
  91. package/vendor/agent/host.mjs +1736 -0
  92. package/vendor/agent/language.mjs +58 -0
  93. package/vendor/agent/ledger.mjs +360 -0
  94. package/vendor/agent/locale.cjs +186 -0
  95. package/vendor/agent/loop/capacity.mjs +74 -0
  96. package/vendor/agent/loop/compose.mjs +127 -0
  97. package/vendor/agent/loop/gate.mjs +205 -0
  98. package/vendor/agent/loop/judge.mjs +189 -0
  99. package/vendor/agent/loop/levels.mjs +273 -0
  100. package/vendor/agent/loop/state.mjs +358 -0
  101. package/vendor/agent/notes.cjs +278 -0
  102. package/vendor/agent/pace.mjs +258 -0
  103. package/vendor/agent/panels.mjs +431 -0
  104. package/vendor/agent/prompt.mjs +342 -0
  105. package/vendor/agent/reference/board.mjs +410 -0
  106. package/vendor/agent/reference/compose.mjs +364 -0
  107. package/vendor/agent/reference/decode.mjs +56 -0
  108. package/vendor/agent/reference/facts.mjs +1874 -0
  109. package/vendor/agent/reference/png.mjs +107 -0
  110. package/vendor/agent/reference/records.mjs +63 -0
  111. package/vendor/agent/reference/web.mjs +252 -0
  112. package/vendor/agent/roles/artist.mjs +69 -0
  113. package/vendor/agent/roles/builder.mjs +79 -0
  114. package/vendor/agent/roles/checks.mjs +223 -0
  115. package/vendor/agent/roles/common.mjs +188 -0
  116. package/vendor/agent/roles/critic.mjs +171 -0
  117. package/vendor/agent/roles/index.mjs +39 -0
  118. package/vendor/agent/roles/modeller.mjs +142 -0
  119. package/vendor/agent/roles/qa.mjs +58 -0
  120. package/vendor/agent/roles/rubrics.mjs +79 -0
  121. package/vendor/agent/roles/sound.mjs +69 -0
  122. package/vendor/agent/rounds.cjs +333 -0
  123. package/vendor/agent/shared.mjs +284 -0
  124. package/vendor/agent/stopGate.mjs +574 -0
  125. package/vendor/agent/subagents.mjs +129 -0
  126. package/vendor/agent/tools/assets.mjs +499 -0
  127. package/vendor/agent/tools/blender.mjs +754 -0
  128. package/vendor/agent/tools/cards.mjs +479 -0
  129. package/vendor/agent/tools/choices.mjs +479 -0
  130. package/vendor/agent/tools/compose.mjs +74 -0
  131. package/vendor/agent/tools/environment.mjs +488 -0
  132. package/vendor/agent/tools/eyes.mjs +733 -0
  133. package/vendor/agent/tools/generate.mjs +338 -0
  134. package/vendor/agent/tools/guide.mjs +46 -0
  135. package/vendor/agent/tools/harness.mjs +193 -0
  136. package/vendor/agent/tools/image.mjs +643 -0
  137. package/vendor/agent/tools/index.mjs +162 -0
  138. package/vendor/agent/tools/look.mjs +578 -0
  139. package/vendor/agent/tools/loop.mjs +858 -0
  140. package/vendor/agent/tools/others.mjs +123 -0
  141. package/vendor/agent/tools/pictures.mjs +535 -0
  142. package/vendor/agent/tools/reference.mjs +366 -0
  143. package/vendor/agent/transcripts.mjs +118 -0
  144. package/vendor/agent-loop.mjs +602 -0
  145. package/vendor/agent-plugin/.claude-plugin/plugin.json +5 -0
  146. package/vendor/agent-plugin/skills/art-direction/SKILL.md +82 -0
  147. package/vendor/agent-plugin/skills/asset-legality/SKILL.md +101 -0
  148. package/vendor/agent-plugin/skills/asset-sources/SKILL.md +111 -0
  149. package/vendor/agent-plugin/skills/blender-modeling/SKILL.md +97 -0
  150. package/vendor/agent-plugin/skills/look-dev/SKILL.md +104 -0
  151. package/vendor/agent-plugin/skills/playtesting/SKILL.md +74 -0
  152. package/vendor/agent-plugin/skills/reference-loop/SKILL.md +102 -0
  153. package/vendor/agent-plugin/skills/sound-design/SKILL.md +60 -0
  154. package/vendor/agent-plugin/skills/style/SKILL.md +35 -0
  155. package/vendor/agent-plugin/skills/tsl-r185/SKILL.md +107 -0
  156. package/vendor/auth.cjs +570 -0
  157. package/vendor/build.cjs +953 -0
  158. package/vendor/catalog.json +455 -0
  159. package/vendor/connectors.cjs +688 -0
  160. package/vendor/eyes.mjs +733 -0
  161. package/vendor/gameExports.json +1390 -0
  162. package/vendor/git.cjs +222 -0
  163. package/vendor/models.json +57 -0
  164. package/vendor/publish.cjs +1018 -0
  165. package/vendor/refBoard.cjs +301 -0
  166. package/vendor/schema/dist/assets.d.ts +335 -0
  167. package/vendor/schema/dist/assets.js +439 -0
  168. package/vendor/schema/dist/brief.d.ts +357 -0
  169. package/vendor/schema/dist/brief.js +302 -0
  170. package/vendor/schema/dist/common.d.ts +9 -0
  171. package/vendor/schema/dist/common.js +13 -0
  172. package/vendor/schema/dist/config.d.ts +406 -0
  173. package/vendor/schema/dist/config.js +355 -0
  174. package/vendor/schema/dist/contract.d.ts +599 -0
  175. package/vendor/schema/dist/contract.js +1146 -0
  176. package/vendor/schema/dist/index.d.ts +14 -0
  177. package/vendor/schema/dist/index.js +21 -0
  178. package/vendor/schema/dist/look.d.ts +463 -0
  179. package/vendor/schema/dist/look.js +681 -0
  180. package/vendor/schema/dist/lookStats.d.ts +230 -0
  181. package/vendor/schema/dist/lookStats.js +768 -0
  182. package/vendor/schema/dist/pilot.d.ts +32 -0
  183. package/vendor/schema/dist/pilot.js +44 -0
  184. package/vendor/schema/dist/publish.d.ts +214 -0
  185. package/vendor/schema/dist/publish.js +291 -0
  186. package/vendor/schema/dist/scene.d.ts +75 -0
  187. package/vendor/schema/dist/scene.js +120 -0
  188. package/vendor/schema/dist/skyLight.d.ts +141 -0
  189. package/vendor/schema/dist/skyLight.js +436 -0
  190. package/vendor/schema/dist/style.d.ts +131 -0
  191. package/vendor/schema/dist/style.js +155 -0
  192. package/vendor/schema/package.json +1 -0
  193. package/vendor/selectionPrompt.mjs +51 -0
  194. package/vendor/useTools.mjs +195 -0
  195. package/vendor/userMessage.mjs +26 -0
  196. package/web-dist/assets/GaussianSplatUtils-CptQkDVX.js +1 -0
  197. package/web-dist/assets/KTX2Loader-C53LJqss.js +2 -0
  198. package/web-dist/assets/SPZLoader-BQ3tjaTv.js +1 -0
  199. package/web-dist/assets/gaussianSplat-_9tcWegB.js +1 -0
  200. package/web-dist/assets/index-Baka-ZO7.js +693 -0
  201. package/web-dist/assets/index-CcjyyQco.css +1 -0
  202. package/web-dist/assets/meshopt_decoder.module-BvwdjiD3.js +1 -0
  203. package/web-dist/assets/zstddec.module-CfFeQW7d.js +1 -0
  204. package/web-dist/index.html +34 -0
@@ -0,0 +1,574 @@
1
+ // "Done" with a bar the host enforces. A request that changed the game may
2
+ // end only after a passing nw_check and an nw_view at the project as it is
3
+ // now, with no debug markers it added left in the source. The SDK's Stop hook
4
+ // (host.mjs) and the other vendors' loop ask this gate before they let the
5
+ // agent finish, and send its reason back as the next turn when it says no:
6
+ // at most twice, so a run that cannot get there still ends (the done event
7
+ // then says what was not verified).
8
+ //
9
+ // "As it is now" is a fingerprint of the game's files (sizes and times), so a
10
+ // check or a look that came before the last edit does not count. A file the
11
+ // studio itself saved during the request (the creator moved an object or
12
+ // turned a knob while the agent answered a question) is the creator's
13
+ // change, not the agent's: main reports each such save, and the gate reads
14
+ // that file as it was at the start until something else changes it again.
15
+ //
16
+ // A space is also held to its brief (SPACE_FIRST.md W5, the last step of the
17
+ // order for a space). A request that builds a space (host.mjs: depth.space,
18
+ // not every big one: modelling a chair is big and has no brief) does not end
19
+ // without brief.json, nor while the brief fails its schema or the look leaves
20
+ // values to the engine's defaults. Any other request that changed the space
21
+ // answers only for what it did: a brief.json it broke or left broken after
22
+ // editing it, and a look value it left to the defaults that was set when it
23
+ // began. A "move the tree" is never sent off to set a sky nobody asked about.
24
+ // Of lookWarnings, only what is left to the defaults holds a request back:
25
+ // the advice beside it (a fill under a measured sky; probe GI is drawn and
26
+ // has no line) may be what the space means, and a sky of none is not left
27
+ // to anything when the brief itself picks none. The same at most two blocks
28
+ // hold.
29
+
30
+ import { createHash } from 'node:crypto'
31
+ import fsp from 'node:fs/promises'
32
+ import { createRequire } from 'node:module'
33
+ import path from 'node:path'
34
+ import { BRIEF_FILE, STYLE_FILE, lookAdvice, styleAdvice, validateBrief, validateStyle } from '../schema/dist/index.js'
35
+
36
+ const TRACKED_DIRS = ['src', 'assets']
37
+ const TRACKED_FILES = ['game.config.json', 'scene.json']
38
+ const SKIP = new Set(['node_modules', '.git', '.nowhere', 'dist', '.DS_Store'])
39
+ const TEXT = /\.(m?[jt]sx?|c[jt]s|json|glsl|wgsl|vert|frag|css|html?)$/i
40
+
41
+ /** Debug code an agent leaves behind when it probes instead of looking. */
42
+ export const MARKER =
43
+ /\bDBG\b|\/\/\s*DEBUG\b|\/\*\s*DEBUG|\bdebugger;|console\.(log|warn|error)\(\s*['"`](DBG|DEBUG)|throw new Error\(\s*['"`]DBG/
44
+
45
+ async function walk(root, rel, out) {
46
+ let entries
47
+ try {
48
+ entries = await fsp.readdir(path.join(root, rel), { withFileTypes: true })
49
+ } catch {
50
+ return out
51
+ }
52
+ for (const e of entries) {
53
+ if (SKIP.has(e.name)) continue
54
+ const child = `${rel}/${e.name}`
55
+ if (e.isDirectory()) await walk(root, child, out)
56
+ else if (e.isFile()) out.push(child)
57
+ if (out.length > 20_000) break
58
+ }
59
+ return out
60
+ }
61
+
62
+ /** "size:mtime" of each of the game's files, by project-relative path. */
63
+ async function statsOf(root) {
64
+ const files = []
65
+ for (const dir of TRACKED_DIRS) await walk(root, dir, files)
66
+ files.push(...TRACKED_FILES)
67
+ const stats = new Map()
68
+ for (const rel of files) {
69
+ try {
70
+ const s = await fsp.stat(path.join(root, rel))
71
+ stats.set(rel, `${s.size}:${s.mtimeMs}`)
72
+ } catch {
73
+ // not there
74
+ }
75
+ }
76
+ return stats
77
+ }
78
+
79
+ const hashOf = (stats) =>
80
+ createHash('sha1')
81
+ .update([...stats.keys()].sort().map((rel) => `${rel}:${stats.get(rel)}`).join('\n'))
82
+ .digest('hex')
83
+
84
+ /** sha1 over the sorted "path:size:mtime" of the game's files. */
85
+ export async function fingerprint(root) {
86
+ return hashOf(await statsOf(root))
87
+ }
88
+
89
+ /** A path as the gate keys it: project-relative, forward slashes, no ./ in front. */
90
+ const relKey = (rel) => String(rel).replace(/\\/g, '/').replace(/^(\.\/)+/, '')
91
+
92
+ /** Every debug marker in the game's source, as { file, line, text }. */
93
+ export async function markers(root) {
94
+ const found = []
95
+ for (const rel of await walk(root, 'src', [])) {
96
+ if (!TEXT.test(rel)) continue
97
+ let text
98
+ try {
99
+ const abs = path.join(root, rel)
100
+ if ((await fsp.stat(abs)).size > 1_000_000) continue
101
+ text = await fsp.readFile(abs, 'utf8')
102
+ } catch {
103
+ continue
104
+ }
105
+ text.split('\n').forEach((line, i) => {
106
+ if (MARKER.test(line)) found.push({ file: rel, line: i + 1, text: line.trim() })
107
+ })
108
+ }
109
+ return found
110
+ }
111
+
112
+ const key = (m) => `${m.file}\n${m.text}`
113
+
114
+ // ---- putting probes back ---------------------------------------------------
115
+ // A request that ends before it is done (out of credit, a key refused, the
116
+ // creator's Stop, a failure) used to leave its probes in the game: a debug
117
+ // throw left by a run that ran out of credit stopped the creator's Play
118
+ // after twenty footsteps, every run (2026-10-16). The cleanup turn that
119
+ // removes them needs a model, which is what was missing. This needs none:
120
+ // against the files as the request found them, every change made only of
121
+ // probe lines is put back the way it was. Only where that is safe: a change
122
+ // that also holds real code stays (putting it back would lose that code, or
123
+ // leave a name it imports or declares used and undefined), so does one that
124
+ // declared a name something else still uses, a file the request made or
125
+ // that was too big to keep a copy of, and a whole file that would no longer
126
+ // parse.
127
+
128
+ const MAX_SOURCE_BYTES = 1_000_000
129
+ const MAX_SOURCES_BYTES = 20_000_000
130
+
131
+ /** The text of every source file under src/, by project-relative path. */
132
+ async function sourcesOf(root) {
133
+ const out = new Map()
134
+ let total = 0
135
+ for (const rel of await walk(root, 'src', [])) {
136
+ if (!TEXT.test(rel)) continue
137
+ try {
138
+ const abs = path.join(root, rel)
139
+ const size = (await fsp.stat(abs)).size
140
+ if (size > MAX_SOURCE_BYTES || total + size > MAX_SOURCES_BYTES) continue
141
+ total += size
142
+ out.set(rel, await fsp.readFile(abs, 'utf8'))
143
+ } catch {
144
+ // gone, or unreadable: nothing to put back from
145
+ }
146
+ }
147
+ return out
148
+ }
149
+
150
+ /**
151
+ * The changes from lines `a` to lines `b`, as [aStart, aEnd, bStart, bEnd]
152
+ * (half-open): a[aStart..aEnd) became b[bStart..bEnd). A longest common
153
+ * subsequence of lines, after the common head and tail are set aside, so an
154
+ * edit of a few lines in a long file costs little. Null when the middle is
155
+ * too big to compare.
156
+ */
157
+ export function lineChanges(a, b) {
158
+ let head = 0
159
+ while (head < a.length && head < b.length && a[head] === b[head]) head++
160
+ let tail = 0
161
+ while (tail < a.length - head && tail < b.length - head && a[a.length - 1 - tail] === b[b.length - 1 - tail]) tail++
162
+ const n = a.length - head - tail
163
+ const m = b.length - head - tail
164
+ if (n === 0 && m === 0) return []
165
+ if (n * m > 6_000_000) return null
166
+ // lcs[i][j]: the common length of a[head+i..] and b[head+j..], flattened.
167
+ const w = m + 1
168
+ const lcs = new Uint32Array((n + 1) * w)
169
+ for (let i = n - 1; i >= 0; i--) {
170
+ for (let j = m - 1; j >= 0; j--) {
171
+ lcs[i * w + j] = a[head + i] === b[head + j] ? lcs[(i + 1) * w + j + 1] + 1 : Math.max(lcs[(i + 1) * w + j], lcs[i * w + j + 1])
172
+ }
173
+ }
174
+ const changes = []
175
+ let i = 0
176
+ let j = 0
177
+ let open = null
178
+ const close = () => {
179
+ if (open) changes.push([head + open[0], head + i, head + open[1], head + j])
180
+ open = null
181
+ }
182
+ while (i < n || j < m) {
183
+ if (i < n && j < m && a[head + i] === b[head + j]) {
184
+ close()
185
+ i++
186
+ j++
187
+ } else if (j < m && (i === n || lcs[i * w + j + 1] >= lcs[(i + 1) * w + j])) {
188
+ open ??= [i, j]
189
+ j++
190
+ } else {
191
+ open ??= [i, j]
192
+ i++
193
+ }
194
+ }
195
+ close()
196
+ return changes
197
+ }
198
+
199
+ /** The names a line of code declares, imports included. */
200
+ const declared = (line) => {
201
+ const names = [...line.matchAll(/\b(?:let|const|var|function|class)\s+([A-Za-z_$][\w$]*)/g)].map((m) => m[1])
202
+ const imported = /^\s*import\s+(.+?)\s+from\s/.exec(line)
203
+ if (imported) {
204
+ for (const part of imported[1].replace(/[{}*]/g, ',').split(',')) {
205
+ const name = part.trim().split(/\s+/).pop()
206
+ if (name && name !== 'type' && /^[A-Za-z_$][\w$]*$/.test(name)) names.push(name)
207
+ }
208
+ }
209
+ return names
210
+ }
211
+
212
+ /** A line a probe brings along without a marker of its own: a blank, or a
213
+ * name set to a plain value (let dbgDone = false), which is only put back
214
+ * when nothing kept uses the name. */
215
+ const PROBE_HELPER = /^\s*$|^\s*(?:let|var|const)\s+[A-Za-z_$][\w$]*(?:\s*=\s*(?:-?\d[\d_.e]*|true|false|null|undefined|''|""|``|\[\]|\{\}))?\s*;?\s*$/
216
+
217
+ let transformSync = undefined
218
+ /** Whether `text` still parses as the file's language; null when there is no
219
+ * esbuild to ask. */
220
+ function parses(text, rel) {
221
+ if (transformSync === undefined) {
222
+ try {
223
+ transformSync = createRequire(import.meta.url)('esbuild').transformSync
224
+ } catch {
225
+ transformSync = null
226
+ }
227
+ }
228
+ if (!transformSync) return null
229
+ const ext = path.extname(rel).slice(1).toLowerCase()
230
+ const loader = { ts: 'ts', mts: 'ts', cts: 'ts', tsx: 'tsx', js: 'js', mjs: 'js', cjs: 'js', jsx: 'jsx', json: 'json' }[ext]
231
+ if (!loader) return null
232
+ try {
233
+ transformSync(text, { loader, logLevel: 'silent' })
234
+ return true
235
+ } catch {
236
+ return false
237
+ }
238
+ }
239
+
240
+ /**
241
+ * `now` with every change from `start` made only of probe lines (a marker not
242
+ * in `start`, or PROBE_HELPER) put back, as far as that is safe. A change
243
+ * that carries a marker beside real code is left whole. Returns the text and
244
+ * the marked lines (1-based, in `now`) that were put back and that were left.
245
+ */
246
+ export function revertProbesIn(start, now, rel = 'src/main.ts') {
247
+ const a = start.split('\n')
248
+ const b = now.split('\n')
249
+ const known = new Set(a.filter((line) => MARKER.test(line)).map((line) => line.trim()))
250
+ const fresh = (line) => MARKER.test(line) && !known.has(line.trim())
251
+ const changes = lineChanges(a, b)
252
+ if (!changes) return { text: now, reverted: [], kept: b.flatMap((line, k) => (fresh(line) ? [k + 1] : [])) }
253
+ const probes = changes.filter(([, , b0, b1]) => b.slice(b0, b1).some(fresh))
254
+ // Only a change that is all probe: one that also changed real code (the
255
+ // import it widened, the line it rewrote beside a console.log) would lose
256
+ // that code if it were put back.
257
+ let chosen = new Set(probes.filter(([, , b0, b1]) => b.slice(b0, b1).every((line) => fresh(line) || PROBE_HELPER.test(line))))
258
+ const build = () => {
259
+ const out = []
260
+ let at = 0
261
+ for (const change of changes) {
262
+ if (!chosen.has(change)) continue
263
+ const [a0, a1, b0, b1] = change
264
+ out.push(...b.slice(at, b0), ...a.slice(a0, a1))
265
+ at = b1
266
+ }
267
+ out.push(...b.slice(at))
268
+ return out.join('\n')
269
+ }
270
+ // A change that took a name away (let stamps = 0 // DBG) while a line kept
271
+ // still uses it is not put back: that would leave a name nothing defines.
272
+ for (let pass = 0; pass < probes.length + 1; pass++) {
273
+ const text = build()
274
+ const unsafe = [...chosen].find(([a0, a1, b0, b1]) => {
275
+ const kept = new Set(a.slice(a0, a1).flatMap(declared))
276
+ return b
277
+ .slice(b0, b1)
278
+ .flatMap(declared)
279
+ .some((name) => !kept.has(name) && new RegExp(`(^|[^\\w$])${name.replace(/\$/g, '\\$')}([^\\w$]|$)`).test(text))
280
+ })
281
+ if (!unsafe) break
282
+ chosen.delete(unsafe)
283
+ }
284
+ let text = build()
285
+ if (chosen.size > 0 && parses(text, rel) !== true) {
286
+ chosen = new Set()
287
+ text = now
288
+ }
289
+ const lines = (set) => [...set].flatMap(([, , b0, b1]) => b.slice(b0, b1).flatMap((line, k) => (fresh(line) ? [b0 + k + 1] : [])))
290
+ return { text, reverted: lines(chosen), kept: lines(new Set(probes.filter((c) => !chosen.has(c)))) }
291
+ }
292
+
293
+ // What of lookAdvice is a value left to the defaults, read from its lines:
294
+ // the sky of none, the look block missing, and the two lists of keys. The
295
+ // lines are the schema's (packages/schema/src/look.ts lookAdvice);
296
+ // space-check holds these patterns to what it says, so a reworded line fails
297
+ // a check instead of slipping past the gate.
298
+ const LEFT_LISTS = [/^Look values left to the engine's defaults: (.+?)\. Set each/, /^Light and glow left to the schema's defaults: (.+?)\. Set them/]
299
+
300
+ /**
301
+ * The look values lookAdvice says are left to the defaults, as keys (sky,
302
+ * look, look.exposure, lighting.sun.direction, ...). The sky is not one when
303
+ * the brief picks a sky of none. Advice that is not a default left (a fill
304
+ * under a measured sky, or any line still to come) gives none.
305
+ * @param {string[]} lines lookAdvice's
306
+ * @param {{ skyKind?: string | null }} [brief]
307
+ */
308
+ export function leftToDefaults(lines, { skyKind = null } = {}) {
309
+ const keys = []
310
+ for (const line of lines ?? []) {
311
+ const text = String(line)
312
+ if (/^sky is none\b/.test(text)) {
313
+ if (skyKind !== 'none') keys.push('sky')
314
+ } else if (/has no look block/.test(text)) keys.push('look')
315
+ else {
316
+ for (const re of LEFT_LISTS) {
317
+ const m = re.exec(text)
318
+ if (m) keys.push(...m[1].split(', ').map((k) => k.replace(/\s*\(.*$/, '').trim()).filter(Boolean))
319
+ }
320
+ }
321
+ }
322
+ return [...new Set(keys)]
323
+ }
324
+
325
+ /**
326
+ * Where the space stands against its brief: brief.json 'absent', 'invalid'
327
+ * or 'ok'; what the look leaves to the defaults and the advice beside it
328
+ * (lookAdvice over game.config.json, as nw_status's lookWarnings, without the
329
+ * sky of none when the brief picks none); and of those, the keys left to the
330
+ * defaults (leftToDefaults), which are what the gate holds. Read only when
331
+ * there is a brief. Never throws.
332
+ */
333
+ export async function briefState(projectRoot) {
334
+ let brief = 'absent'
335
+ let skyKind = null
336
+ try {
337
+ const checked = validateBrief(JSON.parse(await fsp.readFile(path.join(projectRoot, BRIEF_FILE), 'utf8')))
338
+ brief = checked.ok ? 'ok' : 'invalid'
339
+ skyKind = checked.brief?.light?.sky?.kind ?? null
340
+ } catch (err) {
341
+ brief = err?.code === 'ENOENT' ? 'absent' : 'invalid'
342
+ }
343
+ let lookWarnings = []
344
+ if (brief !== 'absent') {
345
+ try {
346
+ lookWarnings = lookAdvice(JSON.parse(await fsp.readFile(path.join(projectRoot, 'game.config.json'), 'utf8')))
347
+ } catch {
348
+ // a config that cannot be read is the build's to say (nw_check)
349
+ }
350
+ }
351
+ // As nw_status and nw_check read it (assets/brief.mjs adviceUnderBrief).
352
+ if (skyKind === 'none') lookWarnings = lookWarnings.filter((w) => !/^sky is none\b/.test(String(w)))
353
+ const { style, styleWarnings } = await styleState(projectRoot)
354
+ return { brief, style, styleWarnings, lookWarnings, left: leftToDefaults(lookWarnings, { skyKind }) }
355
+ }
356
+
357
+ /**
358
+ * style.json 'absent', 'invalid' or 'ok', and where game.config.json's look
359
+ * draws otherwise than it says (styleAdvice). Never throws.
360
+ */
361
+ export async function styleState(projectRoot) {
362
+ let style = 'absent'
363
+ let doc = null
364
+ try {
365
+ const checked = validateStyle(JSON.parse(await fsp.readFile(path.join(projectRoot, STYLE_FILE), 'utf8')))
366
+ style = checked.ok ? 'ok' : 'invalid'
367
+ doc = checked.style ?? null
368
+ } catch (err) {
369
+ style = err?.code === 'ENOENT' ? 'absent' : 'invalid'
370
+ }
371
+ let styleWarnings = []
372
+ if (doc) {
373
+ try {
374
+ styleWarnings = styleAdvice(doc, JSON.parse(await fsp.readFile(path.join(projectRoot, 'game.config.json'), 'utf8')))
375
+ } catch {
376
+ // a config that cannot be read is the build's to say (nw_check)
377
+ }
378
+ }
379
+ return { style, styleWarnings }
380
+ }
381
+
382
+ /** brief.json's size and time, to tell whether a request touched it. */
383
+ async function briefStamp(projectRoot) {
384
+ try {
385
+ const s = await fsp.stat(path.join(projectRoot, BRIEF_FILE))
386
+ return `${s.size}:${s.mtimeMs}`
387
+ } catch {
388
+ return null
389
+ }
390
+ }
391
+
392
+ /**
393
+ * What the brief still asks before a request that changed the space ends.
394
+ * `start` is where it stood when the request began: a request that does not
395
+ * build a space answers only for what changed since.
396
+ */
397
+ async function briefItems(projectRoot, space, start) {
398
+ const { brief, left, style, styleWarnings } = await briefState(projectRoot)
399
+ const items = []
400
+ if (style === 'absent' && space) {
401
+ items.push('write style.json (nw_schema kind "style"): how this space is drawn, read from the creator\'s pictures or the style they named, or chosen from directions you researched and proposed, as the order for a space has it; then draw the targets and set the look from it')
402
+ }
403
+ if (style === 'invalid' && (space || start.style !== 'invalid')) items.push('make style.json pass its schema (nw_status says what fails)')
404
+ if (styleWarnings.length && (space || styleWarnings.some((w) => !start.styleWarnings.includes(w)))) items.push(...styleWarnings)
405
+ if (brief === 'absent' && space) {
406
+ items.push('write brief.json (nw_schema kind "brief") and brief.md from the references measured with nw_reference (board true), as the order for a space has it, then set the look from it')
407
+ }
408
+ const touched = (await briefStamp(projectRoot)) !== start.stamp
409
+ if (brief === 'invalid' && (space || start.brief !== 'invalid' || touched)) items.push('make brief.json pass its schema (nw_check says what fails)')
410
+ const held = space ? left : left.filter((k) => !start.left.includes(k))
411
+ if (held.length) {
412
+ items.push(
413
+ space
414
+ ? `set from the brief what the look leaves to the defaults (nw_status lookWarnings): ${held.slice(0, 12).join(', ')}`
415
+ : `set back from the brief what this request left to the defaults (nw_status lookWarnings): ${held.slice(0, 12).join(', ')}`,
416
+ )
417
+ }
418
+ return items
419
+ }
420
+
421
+ /**
422
+ * @param {string} projectRoot
423
+ * @param {{ needView?: boolean, space?: boolean }} [options] needView: false
424
+ * when no tool can look (a tree without the eyes yet), so the gate never
425
+ * asks for a look the agent has no way to take. space: the request builds
426
+ * a space (host.mjs: depth.space), so it ends with a brief.json and the
427
+ * whole look set from it.
428
+ */
429
+ export async function createStopGate(projectRoot, { needView = true, space = false } = {}) {
430
+ const startStats = await statsOf(projectRoot)
431
+ // The brief and the look as the request found them. What the look left to
432
+ // the defaults is read with or without a brief: a request that writes the
433
+ // first brief.json answers for its own edits, not for the whole look.
434
+ const found = await briefState(projectRoot)
435
+ let leftBefore = found.left
436
+ if (found.brief === 'absent') {
437
+ try {
438
+ leftBefore = leftToDefaults(lookAdvice(JSON.parse(await fsp.readFile(path.join(projectRoot, 'game.config.json'), 'utf8'))))
439
+ } catch {
440
+ leftBefore = []
441
+ }
442
+ }
443
+ const startBrief = { brief: found.brief, left: leftBefore, stamp: await briefStamp(projectRoot), style: found.style, styleWarnings: found.styleWarnings }
444
+ // Files the studio saved during the request, with the stat it left them at.
445
+ const studio = new Map()
446
+ /** The fingerprint with the studio's own saves read as they were at the start. */
447
+ const current = async () => {
448
+ const stats = await statsOf(projectRoot)
449
+ for (const [rel, left] of studio) {
450
+ if (stats.get(rel) !== left) continue // changed again since: not the studio's alone
451
+ if (startStats.has(rel)) stats.set(rel, startStats.get(rel))
452
+ else stats.delete(rel)
453
+ }
454
+ return hashOf(stats)
455
+ }
456
+ const start = hashOf(startStats)
457
+ const before = new Set((await markers(projectRoot)).map(key))
458
+ // The source as the request found it, for putting its probes back.
459
+ const startSources = await sourcesOf(projectRoot)
460
+ let built = start
461
+ let checked = null
462
+ let viewed = null
463
+ let blocks = 0
464
+
465
+ const fresh = async () => (await markers(projectRoot)).filter((m) => !before.has(key(m)))
466
+
467
+ const gate = {
468
+ get blocks() {
469
+ return blocks
470
+ },
471
+ /** A passing nw_check ('check') or a look ('view') at the project as it is now. */
472
+ async record(kind) {
473
+ const fp = await current()
474
+ if (kind === 'check') checked = fp
475
+ else if (kind === 'view') viewed = fp
476
+ },
477
+ /** The studio saved these files itself (main's watcher of its own writes). */
478
+ async noteStudioWrite(files) {
479
+ const stats = await statsOf(projectRoot)
480
+ for (const f of files) {
481
+ const rel = relKey(f)
482
+ if (stats.has(rel)) studio.set(rel, stats.get(rel))
483
+ }
484
+ },
485
+ /** A 'build' rpc came back ok: the preview shows the project as it is now. */
486
+ async noteBuilt() {
487
+ built = await current()
488
+ },
489
+ /** Whether the preview is behind the files (ctx.run.needsBuild). */
490
+ async needsBuild() {
491
+ return (await current()) !== built
492
+ },
493
+ async changed() {
494
+ return (await current()) !== start
495
+ },
496
+ /** The game's files as they are now, the studio's own saves read as at the start. */
497
+ fingerprint: () => current(),
498
+ /** Debug markers added during this request, as "file:line". */
499
+ async newMarkers() {
500
+ return (await fresh()).map((m) => `${m.file}:${m.line}`)
501
+ },
502
+ /**
503
+ * Puts back every change this request made whose new lines carry a debug
504
+ * marker, where that is safe (revertProbesIn), without a model. For a
505
+ * request that ends unfinished, and as the last word on one that is done.
506
+ * Returns the lines put back, as "file:line" of the file before.
507
+ */
508
+ async revertProbes() {
509
+ const reverted = []
510
+ const files = new Set((await fresh()).map((m) => m.file))
511
+ for (const rel of files) {
512
+ // A file the request made has no "before" to go back to (against
513
+ // nothing, the whole file is one probe and would be emptied), and
514
+ // neither has one too big to have been kept: their markers stay,
515
+ // and are reported as left.
516
+ const original = startSources.get(rel)
517
+ if (original === undefined) continue
518
+ const abs = path.join(projectRoot, rel)
519
+ let now
520
+ try {
521
+ now = await fsp.readFile(abs, 'utf8')
522
+ } catch {
523
+ continue
524
+ }
525
+ const r = revertProbesIn(original, now, rel)
526
+ if (r.reverted.length === 0 || r.text === now) continue
527
+ try {
528
+ await fsp.writeFile(abs, r.text)
529
+ reverted.push(...r.reverted.map((line) => `${rel}:${line}`))
530
+ } catch {
531
+ // read-only or gone: the markers stay, and are reported as left
532
+ }
533
+ }
534
+ return reverted
535
+ },
536
+ /**
537
+ * @param {{ markersOnly?: boolean }} [options] markersOnly: the cleanup
538
+ * turn, which only has to leave no debug code behind.
539
+ * @returns {Promise<{ ok: true } | { ok: false, reason: string }>}
540
+ */
541
+ async check({ markersOnly = false } = {}) {
542
+ const fp = await current()
543
+ if (fp === start && !markersOnly) return { ok: true }
544
+ const items = []
545
+ if (!markersOnly && checked !== fp) items.push('run nw_check')
546
+ if (!markersOnly && needView && viewed !== fp) items.push('look with nw_view: a close-up of what you changed and the player view')
547
+ const unseen = items.length
548
+ const left = await fresh()
549
+ if (left.length) items.push(`remove the debug code at ${left.slice(0, 10).map((m) => `${m.file}:${m.line}`).join(', ')}`)
550
+ const briefLeft = markersOnly ? [] : await briefItems(projectRoot, space, startBrief)
551
+ items.push(...briefLeft)
552
+ if (items.length === 0) return { ok: true }
553
+ const lead = unseen ? 'You changed the space after your last check or look.' : left.length && !briefLeft.length ? 'There is debug code left in the space.' : left.length ? 'There is debug code left, and the space is not held to its brief yet.' : 'The space is not held to its brief yet.'
554
+ return { ok: false, reason: `${lead} Before you finish: ${items.join('; ')}. Then compare with the reference and finish your reply.` }
555
+ },
556
+ /** The Stop decision: a reason to go on, or null to let the run end.
557
+ * Blocks at most `max` times in a request. */
558
+ async stopReason({ max = 2, markersOnly = false } = {}) {
559
+ if (blocks >= max) return null
560
+ const r = await gate.check({ markersOnly })
561
+ if (r.ok) return null
562
+ blocks++
563
+ return r.reason
564
+ },
565
+ /** For the done event: whether the end state was checked and looked at. */
566
+ async verified() {
567
+ const fp = await current()
568
+ const same = fp === start
569
+ const { brief, lookWarnings, left } = await briefState(projectRoot)
570
+ return { check: same || checked === fp, view: same || !needView || viewed === fp, brief, lookWarnings: lookWarnings.length, lookLeft: left.length }
571
+ },
572
+ }
573
+ return gate
574
+ }