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,410 @@
1
+ // The reference board: every picture a space is measured from, wherever it
2
+ // came from. The creator attaches pictures to messages (the host keeps each
3
+ // in .nowhere/refs/, named by its content), and the agent gathers more after
4
+ // the web consent card (under refs/). A space's brief is written from all of
5
+ // them at once, so the agent is told about all of them, every request, with
6
+ // what each one measured, and not only the pictures of the last message: a
7
+ // courtyard asked for over three messages with eight photos each was being
8
+ // briefed from the newest six.
9
+ //
10
+ // Each picture is measured once (referenceFacts, the numbers nw_reference
11
+ // reads), and a short digest of the facts is kept beside the pictures in
12
+ // .nowhere/board/<content hash>.json, so the next request reads it
13
+ // instead of measuring again; .nowhere/board/index.json remembers each
14
+ // picture's size, time and hash, so a picture that has not changed is not
15
+ // even read again (every request starts by reading the board). A picture
16
+ // that may not be fed to a model (a blocked site, a grade C on
17
+ // refs/board.json) is listed with why, never measured. Measuring at the
18
+ // start of a request has a time limit and stops at a Stop: a picture it did
19
+ // not reach is listed as not measured yet, and nw_reference measures it
20
+ // (board: true measures them all). Only the host keeps what it measured;
21
+ // nw_reference is read-only and keeps its own measurements in memory.
22
+ //
23
+ // A picture set aside on the studio's board (refBoard.cjs, use false: the
24
+ // creator's "for the brief" switch, or a picture card's web find nobody
25
+ // took) is not on the agent's board: it is counted, not listed or measured,
26
+ // unless the brief cites it or it is attached to this message. A picture
27
+ // under refs/ that a picture card copied onto the studio's board is listed
28
+ // as that copy only (its switch is the copy's), unless the brief cites it.
29
+
30
+ import { createHash } from 'node:crypto'
31
+ import fs from 'node:fs'
32
+ import fsp from 'node:fs/promises'
33
+ import path from 'node:path'
34
+ import refBoard from '../../refBoard.cjs'
35
+ import { decodeImage } from './decode.mjs'
36
+ import { referenceFacts } from './facts.mjs'
37
+ import { deltaE2000, hexToLab } from '../../schema/dist/index.js'
38
+ import { readReference, referenceRules } from '../tools/look.mjs'
39
+
40
+ /** The folders a reference lives in: what the creator attached, and the project's own. */
41
+ export const BOARD_DIRS = ['.nowhere/refs', 'refs']
42
+ /** Where each picture's measured digest is kept, by its content: beside the
43
+ * pictures' folder, not in it, so .nowhere/refs/ holds only pictures. */
44
+ export const FACTS_DIR = '.nowhere/board'
45
+ /** The digest's shape: a change to what it keeps measures every picture again. */
46
+ export const DIGEST_VERSION = 'board-2'
47
+ /** Each picture's size, time and content hash, so an unchanged one is not read. */
48
+ const INDEX_FILE = 'index.json'
49
+ const PICTURE = /\.(png|jpe?g|webp|gif)$/i
50
+ /** Deeper folders under refs/ are not references. */
51
+ const REFS_DEPTH = 2
52
+ /** A board this big is not a board: the rest is counted, not listed. */
53
+ const MAX_PICTURES = 200
54
+
55
+ /**
56
+ * What the creator may attach and what goes in the message itself. The
57
+ * renderer (src/imageAttach.ts), main (main.cjs checkImages) and `nowhere
58
+ * make` (make.mjs) hold the same perMessage; space-check compares them.
59
+ * Every attached picture is kept on the board and measured; the message
60
+ * itself carries the first `inline` of them, within `inlineBytes`, since
61
+ * every later call of the session sends them again and one API request
62
+ * holds 32 MB at most. The rest the agent opens by path (Read) like any
63
+ * picture on the board.
64
+ */
65
+ export const REFERENCE_LIMITS = Object.freeze({ perMessage: 24, inline: 8, inlineBytes: 16 * 1024 * 1024 })
66
+
67
+ /** The attached pictures that go in the message itself, in order. */
68
+ export function inlineImages(images, limits = REFERENCE_LIMITS) {
69
+ const out = []
70
+ let bytes = 0
71
+ for (const image of Array.isArray(images) ? images : []) {
72
+ if (out.length >= limits.inline) break
73
+ const size = Math.ceil((String(image?.data ?? '').length * 3) / 4)
74
+ if (out.length > 0 && bytes + size > limits.inlineBytes) break
75
+ out.push(image)
76
+ bytes += size
77
+ }
78
+ return out
79
+ }
80
+
81
+ /** The paths brief.json's references cite, read as plain JSON. */
82
+ async function briefPaths(projectRoot) {
83
+ try {
84
+ const brief = JSON.parse(await fsp.readFile(path.join(projectRoot, 'brief.json'), 'utf8'))
85
+ return new Set((Array.isArray(brief?.references) ? brief.references : []).map((r) => String(r?.path ?? '').replace(/\\/g, '/').replace(/^\.\//, '')).filter(Boolean))
86
+ } catch {
87
+ return new Set()
88
+ }
89
+ }
90
+
91
+ async function picturesIn(root, dir, depth, out) {
92
+ let entries
93
+ try {
94
+ entries = await fsp.readdir(path.join(root, dir), { withFileTypes: true })
95
+ } catch {
96
+ return out
97
+ }
98
+ for (const e of entries) {
99
+ if (e.name.startsWith('.')) continue
100
+ const child = `${dir}/${e.name}`
101
+ if (e.isDirectory() && depth > 1) await picturesIn(root, child, depth - 1, out)
102
+ else if (e.isFile() && PICTURE.test(e.name)) out.push(child)
103
+ }
104
+ return out
105
+ }
106
+
107
+ /**
108
+ * Every picture on the board: the ones this message attached (`fresh`,
109
+ * absolute paths, in the order they came) first, then the rest newest first.
110
+ * Each as { abs, rel, fresh, mtimeMs }; `more` counts what is past the cap,
111
+ * `aside` what the studio's board set aside (refBoard.cjs excluded).
112
+ */
113
+ export async function boardPictures(projectRoot, { fresh = [] } = {}) {
114
+ const found = []
115
+ await picturesIn(projectRoot, BOARD_DIRS[0], 1, found)
116
+ await picturesIn(projectRoot, BOARD_DIRS[1], REFS_DEPTH, found)
117
+ const freshSet = new Set(fresh.map((f) => path.resolve(f)))
118
+ let excluded = new Set()
119
+ let copied = new Set()
120
+ try {
121
+ excluded = refBoard.excluded(projectRoot)
122
+ copied = refBoard.copiedFrom(projectRoot)
123
+ } catch {
124
+ // no record of the studio's board: nothing is set aside or copied
125
+ }
126
+ const cited = copied.size ? await briefPaths(projectRoot) : new Set()
127
+ const setAside = (r) => r.startsWith(`${BOARD_DIRS[0]}/`) && excluded.has(r.slice(BOARD_DIRS[0].length + 1))
128
+ const items = []
129
+ let aside = 0
130
+ for (const r of found) {
131
+ const abs = path.join(projectRoot, r)
132
+ if (!freshSet.has(path.resolve(abs)) && setAside(r)) {
133
+ aside++
134
+ continue
135
+ }
136
+ if (r.startsWith(`${BOARD_DIRS[1]}/`) && copied.has(r) && !cited.has(r)) continue
137
+ let mtimeMs = 0
138
+ try {
139
+ mtimeMs = (await fsp.stat(abs)).mtimeMs
140
+ } catch {
141
+ continue
142
+ }
143
+ items.push({ abs, rel: r, fresh: freshSet.has(path.resolve(abs)), mtimeMs })
144
+ }
145
+ const order = (a) => fresh.findIndex((f) => path.resolve(f) === path.resolve(a.abs))
146
+ items.sort((a, b) => (a.fresh !== b.fresh ? (a.fresh ? -1 : 1) : a.fresh ? order(a) - order(b) : b.mtimeMs - a.mtimeMs || a.rel.localeCompare(b.rel)))
147
+ return { pictures: items.slice(0, MAX_PICTURES), more: Math.max(0, items.length - MAX_PICTURES), aside }
148
+ }
149
+
150
+ const round = (v, d = 2) => (typeof v === 'number' && Number.isFinite(v) ? Number(v.toFixed(d)) : null)
151
+
152
+ /** The few facts of a picture a brief starts from, out of referenceFacts. */
153
+ export function digestOf(facts) {
154
+ return {
155
+ version: DIGEST_VERSION,
156
+ size: { width: facts.size.width, height: facts.size.height, shape: facts.size.shape },
157
+ palette: (facts.palette ?? []).slice(0, 5).map((p) => ({ hex: p.hex, share: round(p.share, 3) })),
158
+ accents: (facts.accents ?? []).slice(0, 3).map((a) => a.hex),
159
+ value: { key: facts.value.key, mean: round(facts.value.meanL, 1), p5: round(facts.value.p5, 1), p50: round(facts.value.p50, 1), p95: round(facts.value.p95, 1) },
160
+ contrast: round(facts.contrast.stdL, 1),
161
+ chroma: round(facts.saturation.meanChroma, 1),
162
+ warmth: round(facts.temperature.warmth, 1),
163
+ tint: round(facts.temperature.tint, 1),
164
+ haze: { score: round(facts.haze?.score, 2), direction: facts.haze?.direction ?? 'none' },
165
+ horizon: { y: round(facts.horizon?.y, 3), confidence: round(facts.horizon?.confidence, 2) },
166
+ camera: { guess: facts.camera?.guess ?? null, pitchDeg: round(facts.camera?.pitchDeg, 1), confidence: round(facts.camera?.confidence, 2) },
167
+ lettering: (facts.text?.boxes ?? []).length,
168
+ crop: facts.frame?.suggestedCrop ?? null,
169
+ }
170
+ }
171
+
172
+ const pct = (v) => `${Math.round(v * 100)}%`
173
+
174
+ /** One line of a digest: what the context and the board's answer say of a picture. */
175
+ export function digestLine(d) {
176
+ if (!d) return 'not measured yet'
177
+ const parts = [`${d.size.width} x ${d.size.height} ${d.size.shape}`]
178
+ if (d.palette.length) parts.push(`palette ${d.palette.map((p) => `${p.hex} ${pct(p.share)}`).join(', ')}`)
179
+ if (d.accents.length) parts.push(`accents ${d.accents.join(', ')}`)
180
+ parts.push(`${d.value.key} key, L* ${d.value.p5}/${d.value.p50}/${d.value.p95} (5th/median/95th), contrast ${d.contrast}`)
181
+ parts.push(`warmth b* ${d.warmth}, tint a* ${d.tint}, chroma ${d.chroma}`)
182
+ parts.push(`haze ${d.haze.score}${d.haze.direction && d.haze.direction !== 'none' ? ` ${d.haze.direction}` : ''}`)
183
+ if (d.horizon.y !== null) parts.push(`horizon ${pct(d.horizon.y)}${d.horizon.confidence !== null && d.horizon.confidence < 0.5 ? ' (advisory)' : ''}`)
184
+ if (d.camera.guess) parts.push(`camera ${d.camera.guess}`)
185
+ if (d.lettering) parts.push(`lettering masked (${d.lettering})`)
186
+ if (d.crop) parts.push(`a border: read the crop [${d.crop.join(', ')}]`)
187
+ return parts.join('; ')
188
+ }
189
+
190
+ async function readDigest(file) {
191
+ try {
192
+ const d = JSON.parse(await fsp.readFile(file, 'utf8'))
193
+ return d?.version === DIGEST_VERSION ? d : null
194
+ } catch {
195
+ return null
196
+ }
197
+ }
198
+
199
+ async function readIndex(projectRoot) {
200
+ try {
201
+ const index = JSON.parse(await fsp.readFile(path.join(projectRoot, FACTS_DIR, INDEX_FILE), 'utf8'))
202
+ return index?.version === DIGEST_VERSION && index.files && typeof index.files === 'object' ? index.files : {}
203
+ } catch {
204
+ return {}
205
+ }
206
+ }
207
+
208
+ /** What nw_reference measured without keeping it, by content hash, for the
209
+ * life of the process: a second board read in a session measures nothing. */
210
+ const MEMO = new Map()
211
+
212
+ /**
213
+ * brief.json's measured block for one picture, from its digest: the numbers
214
+ * in the brief's own units (valueKey and horizonY from 0 to 1, the palette
215
+ * as hex and share), so it copies across as it is. A horizon read under
216
+ * confidence 0.5 is left out.
217
+ */
218
+ export function briefMeasured(d) {
219
+ if (!d) return null
220
+ const unit = (v) => (typeof v === 'number' && Number.isFinite(v) ? Math.min(1, Math.max(0, v)) : null)
221
+ const out = {}
222
+ if (d.palette?.length) out.palette = d.palette.slice(0, 16).map((p) => (typeof p.share === 'number' ? { hex: p.hex, share: unit(p.share) } : { hex: p.hex }))
223
+ const mean = d.value?.mean ?? d.value?.p50
224
+ if (unit(typeof mean === 'number' ? mean / 100 : null) !== null) out.valueKey = round(unit(mean / 100), 3)
225
+ if (typeof d.contrast === 'number' && d.contrast >= 0) out.contrast = d.contrast
226
+ if (typeof d.chroma === 'number' && d.chroma >= 0) out.saturation = d.chroma
227
+ if (typeof d.warmth === 'number') out.warmth = d.warmth
228
+ if (unit(d.haze?.score) !== null) out.haze = unit(d.haze.score)
229
+ if (unit(d.horizon?.y) !== null && !(typeof d.horizon.confidence === 'number' && d.horizon.confidence < 0.5)) out.horizonY = unit(d.horizon.y)
230
+ return out
231
+ }
232
+
233
+ /**
234
+ * The R ids of the board's pictures: a picture brief.json already lists (by
235
+ * its path) keeps its id, and a new one takes the next number after the
236
+ * highest the brief uses, in the board's order. So adding pictures never
237
+ * renumbers the ones a brief and its hero views already cite.
238
+ * @param {{ rel: string }[]} pictures
239
+ * @param {{ references?: { id?: string, path?: string }[] } | null} brief
240
+ */
241
+ export function boardIds(pictures, brief) {
242
+ const known = new Map()
243
+ let top = 0
244
+ for (const r of Array.isArray(brief?.references) ? brief.references : []) {
245
+ const n = /^R(\d{1,3})$/.exec(String(r?.id ?? ''))?.[1]
246
+ if (!n) continue
247
+ top = Math.max(top, Number(n))
248
+ if (typeof r.path === 'string' && !known.has(r.path)) known.set(r.path, `R${n}`)
249
+ }
250
+ return pictures.map((p) => known.get(p.rel) ?? `R${++top}`)
251
+ }
252
+
253
+ /**
254
+ * The board measured: each picture with its digest, or why it has none.
255
+ * A digest kept from before is read; a new picture is measured until
256
+ * `timeMs` has gone (null: no limit; 0: nothing new) or `cancelled()` says
257
+ * so, and its digest kept when `keep` (the host; nw_reference keeps none and
258
+ * remembers in memory). rpc is the host's, for decoding where sharp is not
259
+ * there. Never throws.
260
+ * Returns { root, pictures: [{ abs, rel, fresh, digest, line, why? }], more, aside, measured, kept }.
261
+ */
262
+ export async function measureBoard(projectRoot, { fresh = [], rpc = null, timeMs = 20_000, now = () => Date.now(), cancelled = () => false, keep = true } = {}) {
263
+ const started = now()
264
+ const { pictures, more, aside } = await boardPictures(projectRoot, { fresh })
265
+ const index = await readIndex(projectRoot)
266
+ const nextIndex = {}
267
+ let rules = null
268
+ const out = []
269
+ let measured = 0
270
+ let kept = 0
271
+ for (const p of pictures) {
272
+ const item = { abs: p.abs, rel: p.rel, fresh: p.fresh, digest: null, line: 'not measured yet' }
273
+ out.push(item)
274
+ // A picture whose size and time are as the index has them is the same
275
+ // picture: its hash is the index's, and the rules are asked of that.
276
+ let stat = null
277
+ try {
278
+ stat = await fsp.stat(p.abs)
279
+ } catch {
280
+ // gone since the listing
281
+ }
282
+ const was = index[p.rel]
283
+ if (stat && was && was.size === stat.size && was.mtimeMs === stat.mtimeMs && typeof was.sha === 'string') {
284
+ nextIndex[p.rel] = was
285
+ rules ??= await referenceRules(projectRoot, 'the reference board')
286
+ const refused = rules({ given: p.rel, rel: p.rel, name: path.basename(p.rel), sha: was.sha })
287
+ if (refused) {
288
+ item.why = refused
289
+ item.line = `not measured: ${refused}`
290
+ continue
291
+ }
292
+ const known = MEMO.get(was.sha.slice(0, 24)) ?? (await readDigest(path.join(projectRoot, FACTS_DIR, `${was.sha.slice(0, 24)}.json`)))
293
+ if (known) {
294
+ item.digest = known
295
+ item.line = digestLine(known)
296
+ kept++
297
+ continue
298
+ }
299
+ }
300
+ if (timeMs !== null && now() - started >= timeMs) {
301
+ item.line = 'not measured yet (nw_reference with board true measures it)'
302
+ continue
303
+ }
304
+ if (cancelled()) {
305
+ item.line = 'not measured yet (nw_reference with board true measures it)'
306
+ continue
307
+ }
308
+ // readReference holds the board to the reference rules: inside the
309
+ // project, a picture, and never one from a site that forbids AI use.
310
+ let ref
311
+ try {
312
+ ref = await readReference(projectRoot, p.rel, 'the reference board')
313
+ } catch (err) {
314
+ ref = { error: err?.message ?? String(err) }
315
+ }
316
+ if (ref.error) {
317
+ item.why = ref.error
318
+ item.line = `not measured: ${ref.error}`
319
+ continue
320
+ }
321
+ const sha = createHash('sha256').update(Buffer.from(ref.data, 'base64')).digest('hex')
322
+ const hash = sha.slice(0, 24)
323
+ if (stat) nextIndex[p.rel] = { size: stat.size, mtimeMs: stat.mtimeMs, sha }
324
+ const file = path.join(projectRoot, FACTS_DIR, `${hash}.json`)
325
+ const known = MEMO.get(hash) ?? (await readDigest(file))
326
+ if (known) {
327
+ item.digest = known
328
+ item.line = digestLine(known)
329
+ kept++
330
+ continue
331
+ }
332
+ try {
333
+ const pic = await decodeImage(Buffer.from(ref.data, 'base64'), { mime: ref.mime, maxEdge: 1568, rpc })
334
+ if (!pic.ok) {
335
+ item.why = pic.error
336
+ item.line = `not measured: ${pic.error}`
337
+ continue
338
+ }
339
+ const digest = digestOf(referenceFacts(pic, { source: p.rel }))
340
+ item.digest = digest
341
+ item.line = digestLine(digest)
342
+ measured++
343
+ if (!keep) {
344
+ MEMO.set(hash, digest)
345
+ continue
346
+ }
347
+ try {
348
+ await fsp.mkdir(path.dirname(file), { recursive: true })
349
+ await fsp.writeFile(file, JSON.stringify({ ...digest, source: p.rel }))
350
+ } catch {
351
+ // a digest that cannot be kept is measured again next time
352
+ }
353
+ } catch (err) {
354
+ item.why = err?.message ?? String(err)
355
+ item.line = `not measured: ${item.why}`
356
+ }
357
+ }
358
+ // Pictures gone from the board leave the index; one not reached keeps its entry.
359
+ for (const p of out) if (!(p.rel in nextIndex) && index[p.rel]) nextIndex[p.rel] = index[p.rel]
360
+ const same = Object.keys(nextIndex).length === Object.keys(index).length && Object.entries(nextIndex).every(([rel, e]) => index[rel] === e)
361
+ if (keep && !same) {
362
+ try {
363
+ await fsp.mkdir(path.join(projectRoot, FACTS_DIR), { recursive: true })
364
+ await fsp.writeFile(path.join(projectRoot, FACTS_DIR, INDEX_FILE), JSON.stringify({ version: DIGEST_VERSION, files: nextIndex }))
365
+ } catch {
366
+ // without the index, the next request reads the pictures again
367
+ }
368
+ }
369
+ return { root: projectRoot, pictures: out, more, aside, measured, kept }
370
+ }
371
+
372
+ /**
373
+ * The board's palette: every picture's colours pooled by their share of
374
+ * their own picture (each picture weighs the same), merged where they are
375
+ * within deltaE2000 `merge` of each other, biggest first. What a brief's
376
+ * palette starts from when several pictures show one place.
377
+ */
378
+ export function boardPalette(digests, { merge = 8, max = 10 } = {}) {
379
+ const pool = []
380
+ const list = digests.filter(Boolean)
381
+ for (const d of list) {
382
+ const total = d.palette.reduce((s, p) => s + (p.share ?? 0), 0) || 1
383
+ for (const p of d.palette) pool.push({ hex: p.hex, lab: hexToLab(p.hex), weight: (p.share ?? 0) / total / list.length })
384
+ }
385
+ pool.sort((a, b) => b.weight - a.weight)
386
+ const out = []
387
+ for (const c of pool) {
388
+ const near = out.find((o) => deltaE2000(o.lab, c.lab) <= merge)
389
+ if (near) near.weight += c.weight
390
+ else out.push({ ...c })
391
+ }
392
+ return out
393
+ .sort((a, b) => b.weight - a.weight)
394
+ .slice(0, max)
395
+ .map((c) => ({ hex: c.hex, share: round(c.weight, 3) }))
396
+ }
397
+
398
+ /** The range a number takes over the board's pictures, as "lo to hi". */
399
+ export function rangeOf(digests, pick, digits = 1) {
400
+ const values = digests.filter(Boolean).map(pick).filter((v) => typeof v === 'number' && Number.isFinite(v))
401
+ if (!values.length) return null
402
+ const lo = Math.min(...values)
403
+ const hi = Math.max(...values)
404
+ return lo === hi ? `${round(lo, digits)}` : `${round(lo, digits)} to ${round(hi, digits)}`
405
+ }
406
+
407
+ /** Whether a project has a board at all, without reading it. */
408
+ export function hasBoard(projectRoot) {
409
+ return BOARD_DIRS.some((d) => fs.existsSync(path.join(projectRoot, d)))
410
+ }