oda-engine 0.0.0-stage → 0.1.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 (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 +90 -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-CB77cP9U.js +1 -0
  197. package/web-dist/assets/KTX2Loader-6OIWUF7s.js +2 -0
  198. package/web-dist/assets/SPZLoader-zYj0Alfv.js +1 -0
  199. package/web-dist/assets/gaussianSplat-CJTI1sEh.js +1 -0
  200. package/web-dist/assets/index-CcjyyQco.css +1 -0
  201. package/web-dist/assets/index-DMyJcoZJ.js +693 -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,466 @@
1
+ // assets.lock.json: the record of every file the game carries and every file
2
+ // a model was baked from, where it came from and under which licence. This
3
+ // module is the only writer. asset_import, nw_blender, nw_take_download and
4
+ // the creator's drop all call recordAsset; publishing reads the result.
5
+ //
6
+ // The rules about what a valid entry is and what publishing makes of it live
7
+ // in @nowhere/schema (assets.ts), the same copy the Edge Function runs. This
8
+ // file adds the disk: an atomic write, a first-time backfill of whatever
9
+ // assets/ already holds, and the generated section of CREDITS.md.
10
+ //
11
+ // Every function here answers rather than throws, so a ledger problem never
12
+ // takes down the tool that was recording into it.
13
+
14
+ import { createHash } from 'node:crypto'
15
+ import { createReadStream } from 'node:fs'
16
+ import fsp from 'node:fs/promises'
17
+ import path from 'node:path'
18
+ import {
19
+ AssetEntry,
20
+ AssetLock,
21
+ CREDITS_SHOWN,
22
+ LEDGER_FILE,
23
+ assetKindOf,
24
+ checkLedger,
25
+ creditsFor,
26
+ isPublishablePath,
27
+ licenseVerdict,
28
+ } from '../../schema/dist/index.js'
29
+ import { webLookOnlyAll } from '../reference/web.mjs'
30
+
31
+ export const LEDGER = LEDGER_FILE
32
+ export const CREDITS_FILE = 'CREDITS.md'
33
+ export const CREDITS_START = '<!-- nowhere:credits -->'
34
+ export const CREDITS_END = '<!-- /nowhere:credits -->'
35
+
36
+ const SCHEMA = 'nowhere/assets@1'
37
+ const emptyLock = () => ({ schema: SCHEMA, files: {} })
38
+
39
+ /** Today as the ledger writes dates: yyyy-mm-dd, local time. */
40
+ export function today(now = new Date()) {
41
+ const p = (n) => String(n).padStart(2, '0')
42
+ return `${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())}`
43
+ }
44
+
45
+ const slash = (p) => p.split(path.sep).join('/')
46
+
47
+ export async function sha256File(abs) {
48
+ const hash = createHash('sha256')
49
+ for await (const chunk of createReadStream(abs)) hash.update(chunk)
50
+ return hash.digest('hex')
51
+ }
52
+
53
+ /**
54
+ * The ledger as it is on disk, with what was found as a second field:
55
+ * { lock, status: 'ok' | 'absent' | 'invalid', error? }. An absent or invalid
56
+ * file reads as an empty lock, so a caller can always look entries up.
57
+ */
58
+ export async function readLedgerState(projectRoot) {
59
+ let text
60
+ try {
61
+ text = await fsp.readFile(path.join(projectRoot, LEDGER), 'utf8')
62
+ } catch (err) {
63
+ if (err?.code === 'ENOENT') return { lock: emptyLock(), status: 'absent' }
64
+ return { lock: emptyLock(), status: 'invalid', error: `${LEDGER} could not be read (${err?.code ?? err?.message})` }
65
+ }
66
+ let raw
67
+ try {
68
+ raw = JSON.parse(text)
69
+ } catch (err) {
70
+ return { lock: emptyLock(), status: 'invalid', error: `${LEDGER} is not valid JSON (${err.message})` }
71
+ }
72
+ const parsed = AssetLock.safeParse(raw)
73
+ if (!parsed.success) {
74
+ const first = parsed.error.issues[0]
75
+ return { lock: emptyLock(), status: 'invalid', error: `${LEDGER} does not match its schema at ${first?.path.join('.') || 'the top'}: ${first?.message}` }
76
+ }
77
+ return { lock: parsed.data, status: 'ok' }
78
+ }
79
+
80
+ /** The lock itself (empty when absent or invalid). Its `status` and `error`
81
+ * ride along as properties that are not enumerable, so they never end up in
82
+ * a JSON copy of it. */
83
+ export async function readLedger(projectRoot) {
84
+ const { lock, status, error } = await readLedgerState(projectRoot)
85
+ Object.defineProperty(lock, 'status', { value: status, enumerable: false })
86
+ if (error) Object.defineProperty(lock, 'error', { value: error, enumerable: false })
87
+ return lock
88
+ }
89
+
90
+ // One write at a time per project: two tools recording at once (a helper's
91
+ // nw_blender beside an asset_import) must not lose each other's entry.
92
+ const queues = new Map()
93
+ function serial(projectRoot, job) {
94
+ const key = path.resolve(projectRoot)
95
+ const next = (queues.get(key) ?? Promise.resolve()).then(job, job)
96
+ queues.set(
97
+ key,
98
+ next.catch(() => {}),
99
+ )
100
+ return next
101
+ }
102
+
103
+ async function writeAtomic(projectRoot, rel, text) {
104
+ const scratch = path.join(projectRoot, '.nowhere')
105
+ await fsp.mkdir(scratch, { recursive: true })
106
+ const temp = path.join(scratch, `.write-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`)
107
+ await fsp.writeFile(temp, text, 'utf8')
108
+ await fsp.rename(temp, path.join(projectRoot, rel))
109
+ }
110
+
111
+ /** Every regular file under a folder, project-relative, dotfiles left out. */
112
+ async function filesUnder(projectRoot, dir) {
113
+ const out = []
114
+ const walk = async (abs, rel) => {
115
+ let entries
116
+ try {
117
+ entries = await fsp.readdir(abs, { withFileTypes: true })
118
+ } catch {
119
+ return
120
+ }
121
+ for (const e of entries) {
122
+ if (e.name.startsWith('.')) continue
123
+ const childRel = `${rel}/${e.name}`
124
+ if (e.isDirectory()) await walk(path.join(abs, e.name), childRel)
125
+ else if (e.isFile()) out.push(childRel)
126
+ }
127
+ }
128
+ await walk(path.join(projectRoot, dir), dir)
129
+ return out.sort()
130
+ }
131
+
132
+ /** The kind an entry has, by where it is and what it is called. */
133
+ export function ledgerKindOf(rel) {
134
+ const kind = assetKindOf(rel)
135
+ if (rel.startsWith('assets/')) return kind
136
+ // blender/ holds the inputs nw_blender reads: textures are plain images
137
+ // there, and a .blend is a kind of its own.
138
+ if (/\.blend$/i.test(rel)) return 'blend'
139
+ if (kind === 'texture' || /\.(jpe?g|png|webp|tiff?)$/i.test(rel)) return 'image'
140
+ return kind
141
+ }
142
+
143
+ /** The licences the studio itself records: the creator's drop
144
+ * (Creator-Declared, and legacy files), what nw_blender makes (Own) and what
145
+ * a paid generator made (Generated-Owned). A download never carries one. */
146
+ export const OWNED_LICENSES = ['LicenseRef-Own', 'LicenseRef-Creator-Declared', 'LicenseRef-Generated-Owned']
147
+
148
+ /** The sentence that refuses one of OWNED_LICENSES given for a download, or
149
+ * null for any other licence. */
150
+ export function ownedLicenseRefusal(spdx) {
151
+ const id = String(spdx ?? '').trim()
152
+ if (!OWNED_LICENSES.includes(id)) return null
153
+ return `${id} is what the studio records for the creator's own files, nw_blender's models and paid generations, never for a download. Read the licence on the page it came from and pass that (CC0-1.0, CC-BY-4.0 with a credit, ...).`
154
+ }
155
+
156
+ /** The entries for files assets/ held before the ledger existed: the
157
+ * creator's, as far as anyone knows. */
158
+ async function backfill(projectRoot, lock) {
159
+ const day = today()
160
+ const rels = await filesUnder(projectRoot, 'assets')
161
+ // A web reference kept to look at only, copied in, is not the creator's.
162
+ const web = new Set((await webLookOnlyAll(projectRoot, rels.map((rel) => path.join(projectRoot, rel)))).map((w) => w.file))
163
+ for (const rel of rels) {
164
+ if (lock.files[rel] || !isPublishablePath(rel)) continue
165
+ const kind = assetKindOf(rel)
166
+ if (!kind) continue
167
+ const abs = path.join(projectRoot, rel)
168
+ if (web.has(abs)) continue
169
+ const [st, sha256] = await Promise.all([fsp.stat(abs), sha256File(abs)])
170
+ lock.files[rel] = AssetEntry.parse({
171
+ kind,
172
+ bytes: st.size,
173
+ sha256,
174
+ origin: 'legacy',
175
+ license: { spdx: 'LicenseRef-Creator-Declared', checkedAt: day },
176
+ steps: [{ op: 'backfill', at: new Date().toISOString(), detail: 'in assets/ before the ledger existed' }],
177
+ })
178
+ }
179
+ }
180
+
181
+ /** Rewrites the generated section of CREDITS.md; the creator's text outside
182
+ * the markers stays exactly as it is. */
183
+ export async function writeCredits(projectRoot, lock) {
184
+ const file = path.join(projectRoot, CREDITS_FILE)
185
+ let before = ''
186
+ try {
187
+ before = await fsp.readFile(file, 'utf8')
188
+ } catch {
189
+ before = ''
190
+ }
191
+ const section = `${CREDITS_START}\n<!-- Written by the studio from ${LEDGER}; edit outside these markers. -->\n\n${creditsFor(lock).markdown}\n\n${CREDITS_END}`
192
+ const start = before.indexOf(CREDITS_START)
193
+ const end = before.indexOf(CREDITS_END)
194
+ let after
195
+ if (start >= 0 && end > start) {
196
+ after = before.slice(0, start) + section + before.slice(end + CREDITS_END.length)
197
+ } else if (before.trim()) {
198
+ after = `${before.replace(/\s*$/, '')}\n\n${section}\n`
199
+ } else {
200
+ after = `# Credits\n\n${section}\n`
201
+ }
202
+ if (after !== before) await writeAtomic(projectRoot, CREDITS_FILE, after)
203
+ }
204
+
205
+ /**
206
+ * Writes one entry, measured from the file on disk (its size and hash are the
207
+ * file's, whatever the caller passed). The first write creates the lock and
208
+ * backfills every file already under assets/ as origin 'legacy'. Regenerates
209
+ * the CREDITS.md section. Never throws.
210
+ *
211
+ * @returns {Promise<{ ok: true, entry: object } | { ok: false, error: string }>}
212
+ */
213
+ export function recordAsset(projectRoot, rel, entry) {
214
+ return serial(projectRoot, async () => {
215
+ try {
216
+ const clean = String(rel ?? '').replace(/\\/g, '/').replace(/^\.\//, '')
217
+ if (!/^(assets|blender)\/[^]+/.test(clean) || clean.split('/').some((p) => p === '..' || p === '')) {
218
+ return { ok: false, error: `"${rel}" is not a file under assets/ or blender/.` }
219
+ }
220
+ const abs = path.join(projectRoot, ...clean.split('/'))
221
+ let st
222
+ try {
223
+ st = await fsp.stat(abs)
224
+ } catch {
225
+ return { ok: false, error: `${clean} is not there to record.` }
226
+ }
227
+ if (!st.isFile()) return { ok: false, error: `${clean} is not a file.` }
228
+ const kind = entry?.kind ?? ledgerKindOf(clean)
229
+ const parsed = AssetEntry.safeParse({
230
+ ...entry,
231
+ kind,
232
+ bytes: st.size,
233
+ sha256: await sha256File(abs),
234
+ license: { checkedAt: today(), ...(entry?.license ?? {}) },
235
+ })
236
+ if (!parsed.success) {
237
+ const first = parsed.error.issues[0]
238
+ return { ok: false, error: `The ledger entry for ${clean} is not valid at ${first?.path.join('.') || 'the top'}: ${first?.message}` }
239
+ }
240
+ const state = await readLedgerState(projectRoot)
241
+ if (state.status === 'invalid') return { ok: false, error: `${state.error}; fix or remove it before recording more.` }
242
+ const lock = state.lock
243
+ if (state.status === 'absent') await backfill(projectRoot, lock)
244
+ lock.files[clean] = parsed.data
245
+ const sorted = { schema: SCHEMA, files: Object.fromEntries(Object.entries(lock.files).sort(([a], [b]) => a.localeCompare(b))) }
246
+ await writeAtomic(projectRoot, LEDGER, `${JSON.stringify(sorted, null, 2)}\n`)
247
+ try {
248
+ await writeCredits(projectRoot, sorted)
249
+ } catch {
250
+ // The ledger is the record; CREDITS.md is its readable copy and is
251
+ // written again by the next record.
252
+ }
253
+ return { ok: true, entry: parsed.data }
254
+ } catch (err) {
255
+ return { ok: false, error: `The ledger could not be written: ${err?.message ?? err}` }
256
+ }
257
+ })
258
+ }
259
+
260
+ /** Starts the ledger when there is none, as the first record would: every
261
+ * file assets/ holds is backfilled as the creator's (legacy). Publishing
262
+ * calls it when the game's code loads a file the scene does not place, which
263
+ * a planet carries only with a ledger. `write: false` makes the same ledger
264
+ * and hands it back without writing it (nowhere check, which changes
265
+ * nothing). Answers { ok, started, lock }. */
266
+ export function startLedger(projectRoot, { write = true } = {}) {
267
+ return serial(projectRoot, async () => {
268
+ try {
269
+ const state = await readLedgerState(projectRoot)
270
+ if (state.status === 'invalid') return { ok: false, error: `${state.error}.` }
271
+ if (state.status === 'ok') return { ok: true, started: false, lock: state.lock }
272
+ await backfill(projectRoot, state.lock)
273
+ const sorted = { schema: SCHEMA, files: Object.fromEntries(Object.entries(state.lock.files).sort(([a], [b]) => a.localeCompare(b))) }
274
+ if (write) {
275
+ await writeAtomic(projectRoot, LEDGER, `${JSON.stringify(sorted, null, 2)}\n`)
276
+ await writeCredits(projectRoot, sorted).catch(() => {})
277
+ }
278
+ return { ok: true, started: true, lock: sorted }
279
+ } catch (err) {
280
+ return { ok: false, error: `The ledger could not be written: ${err?.message ?? err}` }
281
+ }
282
+ })
283
+ }
284
+
285
+ /** Origins whose files are the creator's to change: their drops, and what
286
+ * sat in assets/ before the ledger. */
287
+ const OWN_ORIGINS = new Set(['creator', 'legacy'])
288
+
289
+ /** Measures the creator's own files again (OWN_ORIGINS) where they changed
290
+ * since they were recorded (re-exported from Blender over the same name),
291
+ * their licence as it was. Anything else that changed stays a change the
292
+ * publish refuses. `write: false` measures without writing, and the ledger
293
+ * as it would be is handed back. Answers { ok, refreshed: [paths], lock }
294
+ * (lock null without a valid ledger). */
295
+ export function refreshOwn(projectRoot, { write = true } = {}) {
296
+ return serial(projectRoot, async () => {
297
+ try {
298
+ const state = await readLedgerState(projectRoot)
299
+ if (state.status !== 'ok') return { ok: true, refreshed: [], lock: null }
300
+ const refreshed = []
301
+ for (const [rel, entry] of Object.entries(state.lock.files)) {
302
+ if (!OWN_ORIGINS.has(entry.origin)) continue
303
+ const abs = path.join(projectRoot, ...rel.split('/'))
304
+ let st
305
+ try {
306
+ st = await fsp.stat(abs)
307
+ } catch {
308
+ continue
309
+ }
310
+ if (!st.isFile()) continue
311
+ const sha256 = st.size === entry.bytes ? await sha256File(abs) : null
312
+ if (st.size === entry.bytes && sha256 === entry.sha256) continue
313
+ const step = { op: 'changed', at: new Date().toISOString(), detail: 'changed by the creator since it was recorded; measured again' }
314
+ state.lock.files[rel] = { ...entry, bytes: st.size, sha256: sha256 ?? (await sha256File(abs)), steps: [...(entry.steps ?? []), step].slice(-50) }
315
+ refreshed.push(rel)
316
+ }
317
+ if (refreshed.length && write) await writeAtomic(projectRoot, LEDGER, `${JSON.stringify(state.lock, null, 2)}\n`)
318
+ return { ok: true, refreshed, lock: state.lock }
319
+ } catch (err) {
320
+ return { ok: false, error: `The ledger could not be written: ${err?.message ?? err}` }
321
+ }
322
+ })
323
+ }
324
+
325
+ /**
326
+ * Puts entries back as they were recorded, beside the files they record
327
+ * (the director's put back of a task's files to an earlier round: the model
328
+ * and what the ledger knew of it go back together). `set` maps a path to
329
+ * its entry; `remove` lists paths whose entries go. Never throws.
330
+ */
331
+ export function putEntries(projectRoot, { set = {}, remove = [] } = {}) {
332
+ return serial(projectRoot, async () => {
333
+ try {
334
+ const state = await readLedgerState(projectRoot)
335
+ if (state.status === 'invalid') return { ok: false, error: `${state.error}; fix or remove it before recording more.` }
336
+ const files = { ...state.lock.files }
337
+ let changed = false
338
+ for (const [rel, entry] of Object.entries(set)) {
339
+ const parsed = AssetEntry.safeParse(entry)
340
+ if (!parsed.success || JSON.stringify(files[rel]) === JSON.stringify(parsed.data)) continue
341
+ files[rel] = parsed.data
342
+ changed = true
343
+ }
344
+ for (const rel of remove) {
345
+ if (!(rel in files)) continue
346
+ delete files[rel]
347
+ changed = true
348
+ }
349
+ if (!changed) return { ok: true, changed: false }
350
+ const sorted = { schema: SCHEMA, files: Object.fromEntries(Object.entries(files).sort(([a], [b]) => a.localeCompare(b))) }
351
+ await writeAtomic(projectRoot, LEDGER, `${JSON.stringify(sorted, null, 2)}\n`)
352
+ await writeCredits(projectRoot, sorted).catch(() => {})
353
+ return { ok: true, changed: true }
354
+ } catch (err) {
355
+ return { ok: false, error: `The ledger could not be written: ${err?.message ?? err}` }
356
+ }
357
+ })
358
+ }
359
+
360
+ /** Removes entries whose files are gone (a renamed or deleted import). */
361
+ export function forgetMissing(projectRoot) {
362
+ return serial(projectRoot, async () => {
363
+ const state = await readLedgerState(projectRoot)
364
+ if (state.status !== 'ok') return { ok: true, removed: [] }
365
+ const removed = []
366
+ for (const rel of Object.keys(state.lock.files)) {
367
+ try {
368
+ await fsp.stat(path.join(projectRoot, rel))
369
+ } catch {
370
+ removed.push(rel)
371
+ delete state.lock.files[rel]
372
+ }
373
+ }
374
+ if (removed.length) {
375
+ await writeAtomic(projectRoot, LEDGER, `${JSON.stringify(state.lock, null, 2)}\n`)
376
+ await writeCredits(projectRoot, state.lock).catch(() => {})
377
+ }
378
+ return { ok: true, removed }
379
+ })
380
+ }
381
+
382
+ // The licences a derived file can carry, strictest first. A refused input
383
+ // taints whatever is made from it; share-alike passes its terms on; a credit
384
+ // has to travel; QAL forbids redistribution outside one planet; the creator's
385
+ // own and generated work are theirs; public domain and CC0 ask nothing.
386
+ function rank(spdx) {
387
+ const verdict = licenseVerdict({ spdx, credit: 'x', confirmedByCreator: true })
388
+ if (!verdict.ok) return 0
389
+ if (/-SA-/.test(spdx)) return 1
390
+ if (verdict.credit) return 2
391
+ const order = ['LicenseRef-QAL-1.0', 'LicenseRef-Creator-Declared', 'LicenseRef-Generated-Owned', 'LicenseRef-Own', 'LicenseRef-PD', 'CC0-1.0']
392
+ const at = order.indexOf(spdx)
393
+ return at < 0 ? 0 : 3 + at
394
+ }
395
+
396
+ /** The licence a derived file inherits from its inputs: the strictest one,
397
+ * with every input's credit joined, and share-alike confirmed only when
398
+ * every share-alike input was. */
399
+ export function deriveLicense(inputs) {
400
+ const list = (Array.isArray(inputs) ? inputs : []).filter((l) => l && typeof l.spdx === 'string')
401
+ if (list.length === 0) return { spdx: 'LicenseRef-Own', checkedAt: today() }
402
+ let strictest = list[0]
403
+ for (const l of list) if (rank(l.spdx) < rank(strictest.spdx)) strictest = l
404
+ const credits = [...new Set(list.map((l) => l.credit?.trim()).filter(Boolean))]
405
+ const shareAlike = list.filter((l) => /-SA-/.test(l.spdx))
406
+ const out = { spdx: strictest.spdx, checkedAt: today() }
407
+ if (strictest.url) out.url = strictest.url
408
+ if (strictest.textSha256) out.textSha256 = strictest.textSha256
409
+ if (credits.length) out.credit = credits.join('; ').slice(0, 300)
410
+ if (shareAlike.length && shareAlike.every((l) => l.confirmedByCreator === true)) out.confirmedByCreator = true
411
+ return out
412
+ }
413
+
414
+ /**
415
+ * What would stop a publish, found now: files under assets/ the ledger does
416
+ * not know (refused once the scene, the config or the code names them),
417
+ * imported files that changed since they were recorded (the creator's own
418
+ * are measured again instead), refused licences, and CC BY files that cannot
419
+ * be published yet. Empty without a ledger (a project that never imported
420
+ * anything publishes as it always did).
421
+ */
422
+ export async function ledgerProblems(projectRoot) {
423
+ const state = await readLedgerState(projectRoot)
424
+ if (state.status === 'absent') return []
425
+ if (state.status === 'invalid') return [{ code: 'ledger:missing', path: LEDGER, message: `${state.error}.` }]
426
+ const uploads = []
427
+ for (const rel of await filesUnder(projectRoot, 'assets')) {
428
+ if (!isPublishablePath(rel)) continue
429
+ const abs = path.join(projectRoot, rel)
430
+ try {
431
+ const st = await fsp.stat(abs)
432
+ uploads.push({ path: rel, bytes: st.size, sha256: await sha256File(abs) })
433
+ } catch {
434
+ // gone between the listing and the read
435
+ }
436
+ }
437
+ // An entry marked to stay on the machine is a choice, not a problem, until
438
+ // something tries to publish it; the creator's own files that changed are
439
+ // measured again when they publish (refreshOwn).
440
+ const staying = new Set(Object.entries(state.lock.files).filter(([, e]) => e.publish === false || (OWN_ORIGINS.has(e.origin) && licenseVerdict(e.license).ok)).map(([p]) => p))
441
+ return checkLedger(state.lock, uploads.filter((u) => !staying.has(u.path)), { creditsShown: CREDITS_SHOWN })
442
+ }
443
+
444
+ /**
445
+ * What a picture a generation started from was, as its generation's inputs
446
+ * keep it: the path and the hash of the bytes sent, and from its ledger
447
+ * entry the reference's subject and box it is a crop of, or the vendor and
448
+ * model that made it.
449
+ */
450
+ export function inputRecordOf(rel, sha256, entry = null) {
451
+ const meta = entry?.meta ?? {}
452
+ return {
453
+ path: String(rel).slice(0, 200),
454
+ sha256,
455
+ ...(typeof meta.subject === 'string' ? { subject: meta.subject.slice(0, 40) } : {}),
456
+ ...(Array.isArray(meta.box) && meta.box.length === 4 && meta.box.every(Number.isFinite) ? { box: meta.box } : {}),
457
+ ...(typeof meta.of === 'string' ? { of: meta.of.slice(0, 200) } : {}),
458
+ ...(entry?.generation ? { vendor: String(entry.generation.vendor).slice(0, 40), model: String(entry.generation.model).slice(0, 80) } : {}),
459
+ }
460
+ }
461
+
462
+ /** The entry for a path, or null. */
463
+ export async function entryFor(projectRoot, rel) {
464
+ const { lock } = await readLedgerState(projectRoot)
465
+ return lock.files[slash(rel)] ?? null
466
+ }