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,2365 @@
1
+ // The director of a production: the creator asks for a game ("this kind of
2
+ // game, in this style", maybe with a picture) and the director runs it the
3
+ // way a good game team would, in code, asking a model only at the points
4
+ // where judgement is needed (orchestrator spec 2):
5
+ //
6
+ // INTERPRET after a small cost card for reading and planning (those
7
+ // decisions run on top-tier models), the reference measured
8
+ // (nw_reference), then one top-tier decision turns the
9
+ // request and the facts into the brief, which code holds to
10
+ // the facts and a read-back decision to the picture (one
11
+ // repair for both); code sets what the picture decides
12
+ // VISION one decision proposes concepts, pillars, signature moments
13
+ // and what to add beyond the request; the creator's card
14
+ // PLAN one decision, shown the picture, writes the board, which
15
+ // code validates; every modelled asset says how it is made,
16
+ // chosen from the capability list code builds (methods.mjs)
17
+ // ESTIMATE the cards a method needs (a key, Codex's consent), then the
18
+ // whole production priced per model and paid tool, on a cost
19
+ // card the creator approves before any task is spent on; then
20
+ // code writes the seams between roles
21
+ // DISPATCH ready tasks run in lanes (preview, blender, free), each
22
+ // attempt its own session on the router's model; between
23
+ // rounds the director reviews the notes that came to it (a
24
+ // role's request of it, the critic's word that the brief
25
+ // contradicts the reference) and may change the brief
26
+ // GATE tool checks, then a top-tier critic; code decides pass,
27
+ // progress and the best so far, and the router climbs a rung
28
+ // when there is none; a task out of rounds with its tool
29
+ // checks passed is kept below the critic's bar, its best in
30
+ // the game, and a made model goes in at its placement; after a
31
+ // modeller round that did not pass the director may switch how
32
+ // its asset is made, a paid way on a new cost card first
33
+ // FINAL the whole game checked, one polish cycle, then the report
34
+ //
35
+ // Done is never the model's word: every pass is a gate's, and the final
36
+ // reply says what was seen, with which camera or playtest. A production
37
+ // whose game runs but is below the bar ends kept, never done.
38
+
39
+ import fs, { readFileSync } from 'node:fs'
40
+ import fsp from 'node:fs/promises'
41
+ import { createRequire } from 'node:module'
42
+ import os from 'node:os'
43
+ import path from 'node:path'
44
+ import { stopAll as stopCodex } from '../assets/images/codex.mjs'
45
+ import { IMAGE_PROVIDERS } from '../assets/images/index.mjs'
46
+ import { readLedgerState, sha256File } from '../assets/ledger.mjs'
47
+ import { PRICES as ASSET_PRICES, PROVIDERS } from '../assets/providers/index.mjs'
48
+ import { readOnlyCommand } from '../guard.mjs'
49
+ import { createLanguageWatch } from '../language.mjs'
50
+ import { READ_ONLY_TOOLS } from '../ledger.mjs'
51
+ import { MODELS, PRICING, TEMPLATE_MAIN } from '../shared.mjs'
52
+ import { createStopGate } from '../stopGate.mjs'
53
+ import { playParams } from '../tools/eyes.mjs'
54
+ import { runDef } from '../tools/index.mjs'
55
+ import { BUILDER_FILES, DONE, ENDED, LOOK_KEYS, blockedTasks, blockersOf, inside, isDirectorFile, matches, overlaps, placementsOf, readyTasks, relPath, throughSeam, validateBoard, withDefaults } from './board.mjs'
56
+ import { GROSS_FLAGS, Interpretation, METHOD_IDS, MethodReview, NotesReview, PERFORMANCE_DEFAULT, PlanOutput, ROLE_IDS, ReadBack, ReferenceFacts, ReportOutput, Subject, Vision, VisionCard, normalizeCheck } from './contracts.mjs'
57
+ import { attemptUsd, costItems, directionItems, estimateProduction, paidFromEstimate, remainingUsd } from './estimate.mjs'
58
+ import { catalogueText, createGate } from './gate.mjs'
59
+ import { cardsFor, capabilitiesOf, capabilityText, methodErrors, methodLine, methodRequests, pictureDir, usesPictures, writeCrop } from './methods.mjs'
60
+ import { INTERPRET_PROMPT, METHOD_PROMPT, NOTES_PROMPT, PLAN_PROMPT, READBACK_PROMPT, REPORT_PROMPT, VISION_PROMPT, interpretText, methodText, notesText, planText, readbackText, reportText, visionText } from './prompts.mjs'
61
+ import { boxText, markOf, readbackErrors, readingErrors, settleBrief, subjectsPicture, unanswered } from './reading.mjs'
62
+ import { POLICY, createRouter } from './router.mjs'
63
+ import { PLACEMENTS_SEAM, anchorOf, flipSeam, isFlipped, seamOf, stubSeam, writePlacements } from './seams.mjs'
64
+ import { createAttemptRunner, createSessions, diffStat, lookMode, projectRel, restore, snapshot } from './session.mjs'
65
+ import { createStore, openStore } from './store.mjs'
66
+ import { createTeamLedger } from './teamLedger.mjs'
67
+
68
+ export const LIMITS = JSON.parse(readFileSync(new URL('./limits.json', import.meta.url), 'utf8'))
69
+ /** Sessions at once: 3 on a machine with 16 GB of memory or more, else 2 (decision D7). */
70
+ export const defaultMaxSessions = (memory = os.totalmem()) => (memory >= 16 * 2 ** 30 ? 3 : 2)
71
+
72
+ const ASK_TIMEOUT_MS = 31 * 60_000
73
+ /** Why no new work starts once the creator said no to a new cost card. */
74
+ const DECLINED = 'the creator did not approve the new cost card'
75
+ const BOARD_EVERY_MS = 500
76
+ const COST_EVERY_MS = 2000
77
+ const usd = (n) => `$${(Number(n) || 0).toFixed(2)}`
78
+ const require = createRequire(import.meta.url)
79
+
80
+ /** One holder at a time, in the order asked. */
81
+ export function createMutex() {
82
+ let tail = Promise.resolve()
83
+ return {
84
+ run(fn) {
85
+ const next = tail.then(() => fn())
86
+ tail = next.catch(() => {})
87
+ return next
88
+ },
89
+ }
90
+ }
91
+
92
+ /** A picture with its long edge at most `edge`, through sharp when it is
93
+ * there; as it came otherwise. */
94
+ async function fitImage(image, edge) {
95
+ if (!image?.data) return null
96
+ let sharp = null
97
+ try {
98
+ sharp = require('sharp')
99
+ } catch {
100
+ return image
101
+ }
102
+ try {
103
+ const bytes = Buffer.from(image.data, 'base64')
104
+ const meta = await sharp(bytes).metadata()
105
+ if (Math.max(meta.width ?? 0, meta.height ?? 0) <= edge && image.mime !== 'image/webp') return image
106
+ const out = await sharp(bytes).resize({ width: edge, height: edge, fit: 'inside', withoutEnlargement: true }).jpeg({ quality: 88 }).toBuffer()
107
+ return { mime: 'image/jpeg', data: out.toString('base64') }
108
+ } catch {
109
+ return image
110
+ }
111
+ }
112
+
113
+ /** The ReferenceFacts in nw_reference's answer: its `facts` field, else the
114
+ * JSON object in its text. */
115
+ export function factsFrom(result) {
116
+ if (result?.facts && typeof result.facts === 'object') return result.facts
117
+ const text = String(result?.text ?? '')
118
+ const start = text.indexOf('{')
119
+ if (start < 0) return null
120
+ for (let end = text.lastIndexOf('}'), tries = 0; end > start && tries < 60; end = text.lastIndexOf('}', end - 1), tries++) {
121
+ try {
122
+ return JSON.parse(text.slice(start, end + 1))
123
+ } catch {
124
+ // a shorter span
125
+ }
126
+ }
127
+ return null
128
+ }
129
+
130
+ /** What the project already holds, for the decisions. */
131
+ async function projectFacts(projectRoot) {
132
+ const out = { blank: false, tiles: null, src: [], placements: 0, look: null }
133
+ try {
134
+ const [mine, template] = await Promise.all([fsp.readFile(path.join(projectRoot, 'src', 'main.ts')), fsp.readFile(TEMPLATE_MAIN)])
135
+ out.blank = mine.equals(template)
136
+ } catch {
137
+ // no main.ts
138
+ }
139
+ try {
140
+ const config = JSON.parse(await fsp.readFile(path.join(projectRoot, 'game.config.json'), 'utf8'))
141
+ out.tiles = config.tiles ?? null
142
+ out.look = config.look && typeof config.look === 'object' && Object.keys(config.look).length ? config.look : null
143
+ } catch {
144
+ // no config
145
+ }
146
+ try {
147
+ out.placements = (JSON.parse(await fsp.readFile(path.join(projectRoot, 'scene.json'), 'utf8')).objects ?? []).length
148
+ } catch {
149
+ // no scene
150
+ }
151
+ const walk = async (rel) => {
152
+ for (const e of await fsp.readdir(path.join(projectRoot, rel), { withFileTypes: true }).catch(() => [])) {
153
+ const child = `${rel}/${e.name}`
154
+ if (e.isDirectory()) await walk(child)
155
+ else if (out.src.length < 80) out.src.push(child)
156
+ }
157
+ }
158
+ await walk('src')
159
+ return out
160
+ }
161
+
162
+ const SKIP_DIRS = new Set(['node_modules', '.git', '.nowhere', 'dist'])
163
+ /** Files only tools write, whoever's task ran them: the asset ledger and its
164
+ * credits, and the config whose look keys look_apply sets. */
165
+ const TOOL_FILES = ['assets.lock.json', 'CREDITS.md', 'game.config.json']
166
+
167
+ /** "size:mtime" of every project file outside .git, .nowhere and the like. */
168
+ async function projectStats(projectRoot) {
169
+ const out = new Map()
170
+ const walk = async (rel) => {
171
+ for (const e of await fsp.readdir(path.join(projectRoot, rel), { withFileTypes: true }).catch(() => [])) {
172
+ if (SKIP_DIRS.has(e.name) || e.name === '.DS_Store') continue
173
+ const child = rel ? `${rel}/${e.name}` : e.name
174
+ if (e.isDirectory()) await walk(child)
175
+ else if (e.isFile() && out.size < 20_000) {
176
+ const st = await fsp.stat(path.join(projectRoot, child)).catch(() => null)
177
+ if (st) out.set(child, `${st.size}:${st.mtimeMs}`)
178
+ }
179
+ }
180
+ }
181
+ await walk('')
182
+ return out
183
+ }
184
+
185
+ /** brief.md as the roles and the creator read it. */
186
+ export function renderBrief(brief, vision = null) {
187
+ const out = ['# Art brief', '', 'Written by the director of this production from the request and the reference; every value cites where it comes from.', '', '## Subject', '', brief.subject, '']
188
+ out.push('## Play', '', `- Verbs: ${brief.play.verbs.join(', ')}`, `- Goal: ${brief.play.goal}`, `- Loop: ${brief.play.loop}`, '')
189
+ out.push('## Request elements', '', ...brief.requestElements.map((e) => `- ${e.id}: ${e.text} (${e.from}${e.subject ? `, subject ${e.subject}` : ''}${e.fact ? `, fact ${e.fact}` : ''})`), '')
190
+ if (brief.subjects?.length) {
191
+ out.push(
192
+ '## Subjects of the reference',
193
+ '',
194
+ 'Each is a box of the picture, [x0, y0, x1, y1] in fractions from its top left. Keep: the game has it, in its place and proportion. Transform: an original thing of the same role, place and size takes its place.',
195
+ '',
196
+ ...brief.subjects.map(
197
+ (x) =>
198
+ `- ${x.id}: ${x.what} (${x.kind}, ${x.role}${x.replacement ? `: ${x.replacement}` : ''}), box ${boxText(x.box)}${x.form ? `, sized by "${x.form}"` : ''}${x.proportion ? `; ${x.proportion.picture} times as tall as wide in the picture${x.proportion.form !== null ? `, its form ${x.proportion.form}` : ''}` : ''}`,
199
+ ),
200
+ '',
201
+ )
202
+ }
203
+ out.push('## Palette', '', '| colour | share | where | from |', '|---|---|---|---|', ...brief.palette.map((c) => `| ${c.hex} | ${Math.round(c.share * 100)}% | ${c.role} | ${c.fact} |`), '')
204
+ out.push('## Values', '', `Key ${brief.values.key}, L* ${brief.values.range.join(' to ')}, ${brief.values.contrast} contrast (${brief.values.fact}).`, '')
205
+ const l = brief.light
206
+ out.push('## Light', '', `Sun at ${l.sunElevationDeg} degrees up, ${l.sunAzimuthDeg} degrees round, about ${l.colourTempK} K; ambient ${l.ambient}; shadow softness ${l.shadowSoftness} (${l.fact}).`, '')
207
+ const a = brief.atmosphere
208
+ const fog = a.fog ? `fog ${a.fog.colour} from ${a.fog.nearM} m to ${a.fog.farM} m${a.fog.height ? ', height fog' : ''}` : 'no fog'
209
+ out.push('## Atmosphere', '', `${a.hazeLayers !== undefined ? `${a.hazeLayers} haze layers, ` : ''}${fog} (${a.fact}).`, '')
210
+ out.push('## Forms', '', brief.forms.language, '', ...brief.forms.scale.map((s) => `- ${s.element}: ${Object.entries(s.sizeM).map(([k, v]) => `${k} ${v} m`).join(', ')}${s.count ? `, ${s.count} of them` : ''}`), ...brief.forms.silhouettes.map((s) => `- silhouette: ${s}`), '')
211
+ if (brief.map) out.push('## Map', '', `About ${brief.map.sideM} m a side: tiles ${brief.map.tiles} in game.config.json (${brief.map.why}).`, '')
212
+ out.push('## Materials', '', ...brief.materials.map((m) => `- ${m.surface}: ${m.colours.join(', ')}, roughness ${m.roughness.join(' to ')}${m.metal ? ', metal' : ''}; ${m.detail}`), '')
213
+ out.push('## Detail', '', `- Near: ${brief.detail.near}`, `- Mid: ${brief.detail.mid}`, `- Far: ${brief.detail.far}`, '')
214
+ out.push('## Cameras', '', ...brief.cameras.map((c) => `- ${c.id} (${c.purpose})${c.subject ? `: ${c.subject}` : ''}${c.heightM !== undefined ? `, ${c.heightM} m high` : ''}${c.pitchDeg !== undefined ? `, pitch ${c.pitchDeg}` : ''}${c.fovDeg !== undefined ? `, fov ${c.fovDeg}` : ''}${c.horizonY !== undefined ? `, horizon at ${c.horizonY} of the height` : ''}${c.aspect ? `, ${c.aspect} frame` : ''}`), '')
215
+ out.push('## Sound', '', `${brief.sound.mood}. Sources: ${brief.sound.sources.join(', ') || 'none'}.`, ...brief.sound.events.map((e) => `- ${e.id}: ${e.when}${e.loop ? ' (loops)' : ''}`), '')
216
+ out.push('## Performance', '', `Tier ${brief.performance.tier}: at most ${brief.performance.drawCalls} draw calls and ${brief.performance.triangles} triangles.`, '')
217
+ if (brief.exclusions.length) out.push('## Leave out', '', ...brief.exclusions.map((x) => `- ${x}`), '')
218
+ if (brief.assumptions.length) out.push('## Assumptions', '', ...brief.assumptions.map((x) => `- ${x.what} (${x.why}; ${x.confidence})`), '')
219
+ if (vision) {
220
+ out.push('## Vision', '', ...vision.pillars.map((p) => `- ${p}`), '', ...vision.moments.map((m) => `- Moment ${m.id} at ${m.camera}: ${m.sees}; ${m.does}. Done when: ${m.acceptance}`), '', ...vision.additions.map((x) => `- Added: ${x.what} (${x.why})`), '')
221
+ }
222
+ return out.join('\n')
223
+ }
224
+
225
+ /** What code checks in an interpretation beyond its schema. */
226
+ export function interpretationErrors(interp, { hasImage }) {
227
+ const errors = []
228
+ const ids = interp.brief.cameras.map((c) => c.id)
229
+ if (ids.length < 3) errors.push('The brief needs at least three cameras.')
230
+ if (!ids.includes('player')) errors.push('The brief needs a camera with id "player".')
231
+ if (hasImage && !ids.includes('reference')) errors.push('With a reference picture, the brief needs a camera with id "reference" that matches its framing.')
232
+ if (new Set(ids).size !== ids.length) errors.push('Two cameras share an id.')
233
+ const elements = interp.brief.requestElements.map((e) => e.id)
234
+ if (new Set(elements).size !== elements.length) errors.push('Two request elements share an id.')
235
+ if (!interp.readings.some((r) => r.id === interp.chosen)) errors.push(`chosen is "${interp.chosen}", which is not one of the readings.`)
236
+ return errors
237
+ }
238
+
239
+ /** A request that asks for more than an inexpensive laptop. */
240
+ const ASKS_FOR_MORE = /\b(high[- ]end|powerful (?:pc|computer|machine|gpu)|gaming (?:pc|rig)|desktop gpu|rtx|4k|ultra settings)\b|고사양|고성능|ハイエンド|高性能|高配置/i
241
+
242
+ /**
243
+ * The brief's performance held to the inexpensive laptop's budget (the low
244
+ * tier: 150 draw calls, 500000 triangles, engine-direction 2.11) unless
245
+ * the request asked for more: the perf gate holds the game to whatever the
246
+ * brief says, so a brief sized to a large world would pass a heavy game.
247
+ * Returns the performance and, when it was lowered, the assumption to note.
248
+ */
249
+ export function boundPerformance(performance, requestText) {
250
+ const given = performance ?? PERFORMANCE_DEFAULT
251
+ if (ASKS_FOR_MORE.test(String(requestText ?? ''))) return { performance: given, assumption: null }
252
+ const bound = { tier: 'low', drawCalls: Math.min(given.drawCalls, PERFORMANCE_DEFAULT.drawCalls), triangles: Math.min(given.triangles, PERFORMANCE_DEFAULT.triangles) }
253
+ const same = bound.tier === given.tier && bound.drawCalls === given.drawCalls && bound.triangles === given.triangles
254
+ return {
255
+ performance: bound,
256
+ assumption: same ? null : { what: `the low performance tier: at most ${bound.drawCalls} draw calls and ${bound.triangles} triangles, not ${given.drawCalls} and ${given.triangles}`, why: 'the game runs on an inexpensive laptop unless the creator asks for more', confidence: 'high' },
257
+ }
258
+ }
259
+
260
+ /** What code checks in a vision beyond its schema: each moment is at a brief camera. */
261
+ export function visionErrors(vision, brief) {
262
+ const ids = (brief?.cameras ?? []).map((c) => c.id)
263
+ return (vision?.moments ?? []).filter((m) => !ids.includes(m.camera)).map((m) => `The moment ${m.id} is at the camera "${m.camera}", which the brief does not have; use one of ${ids.join(', ')}.`)
264
+ }
265
+
266
+ /** The vision as its card carries it (cards.cjs holds it to these bounds). */
267
+ export function visionCard(v) {
268
+ const cut = (s, n) => String(s ?? '').slice(0, n)
269
+ return VisionCard.parse({
270
+ concepts: v.concepts.slice(0, 3).map((c) => ({ id: c.id, title: cut(c.title, 80), pitch: cut(c.pitch, 200) })),
271
+ chosen: v.chosen,
272
+ reasons: cut(v.reasons, 600),
273
+ pillars: v.pillars.slice(0, 6).map((p) => cut(p, 200)),
274
+ moments: v.moments.slice(0, 6).map((m) => ({ id: m.id, label: cut(m.label, 80), sees: cut(m.sees, 200) })),
275
+ additions: v.additions.slice(0, 6).map((a) => ({ what: cut(a.what, 200), why: cut(a.why, 200) })),
276
+ scopeIn: v.scope.in.slice(0, 6).map((s) => cut(s, 200)),
277
+ scopeOut: v.scope.out.slice(0, 6).map((s) => cut(s, 200)),
278
+ })
279
+ }
280
+
281
+ /**
282
+ * @param {object} deps orchestrator spec 3.8: query, rpc, send, log, now,
283
+ * defs, ctxBase, guard, childEnv, pluginDir, withPlugin, roles, critic,
284
+ * roleChecks, settings, depth, blender, limits; codex (the creator's
285
+ * Codex: { info, find }, as blender is); ledger (a team ledger the host
286
+ * already booked the triage in), writtenIn (locale.cjs), and for checks
287
+ * sleep and boardEveryMs. ctxBase may carry codex() and codexState(), the
288
+ * host's consent for Codex, as web() and webState are for the web. Its
289
+ * locale and languageName are the screen language the cards, the board and
290
+ * the vision are in; replyLocale and replyLanguage, the creator's language
291
+ * the report is in (the screen language when absent).
292
+ */
293
+ export function createDirector(deps) {
294
+ const {
295
+ query,
296
+ rpc,
297
+ send,
298
+ log = () => {},
299
+ now = () => Date.now(),
300
+ sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
301
+ defs = [],
302
+ ctxBase,
303
+ guard,
304
+ childEnv = {},
305
+ pluginDir = null,
306
+ withPlugin = false,
307
+ roles,
308
+ critic,
309
+ roleChecks = {},
310
+ settings = {},
311
+ depth = null,
312
+ blender = {},
313
+ codex = {},
314
+ limits: limitsIn = {},
315
+ policy = POLICY,
316
+ models = MODELS,
317
+ prices = PRICING,
318
+ boardEveryMs = BOARD_EVERY_MS,
319
+ writtenIn = null,
320
+ } = deps
321
+ let current = null
322
+ // A Stop that came while the production was still being set up, before it
323
+ // could be stopped: it stops the production as soon as it can be.
324
+ let stopAsked = null
325
+
326
+ async function run({ msg, request = {}, resume = null }) {
327
+ const runId = msg.id
328
+ const projectRoot = ctxBase.projectRoot
329
+ // The screen language (locale.cjs screenLocale) for the cards, the board
330
+ // and the vision; the creator's own for the report, the chat reply.
331
+ const locale = ctxBase.locale ?? 'en'
332
+ const languageName = ctxBase.languageName ?? locale
333
+ const replyLocale = ctxBase.replyLocale ?? locale
334
+ const replyName = ctxBase.replyLanguage ?? (ctxBase.replyLocale ? ctxBase.replyLocale : languageName)
335
+ const limits = { ...LIMITS, ...limitsIn }
336
+ limits.maxSessions = settings.maxSessions ?? limitsIn.maxSessions ?? LIMITS.maxSessions ?? defaultMaxSessions()
337
+ const router = createRouter({ policy, models, ceiling: settings.ceiling ?? null, depth })
338
+ // The host's, when it booked the triage in it; else this production's own.
339
+ const ledger = deps.ledger ?? createTeamLedger({ prices })
340
+ const store = resume ? openStore(projectRoot, resume) : await createStore(projectRoot, now())
341
+ const prodGate = await createStopGate(projectRoot, { needView: true })
342
+ const rpcMutex = createMutex()
343
+ const lanes = { preview: createMutex(), blender: createMutex(), free: createMutex() }
344
+ const byName = new Map(defs.map((d) => [d.name, d]))
345
+ const startedAt = now()
346
+ // The project as the production found it, for the backstop at the end.
347
+ const startStats = await projectStats(projectRoot)
348
+
349
+ const P = {
350
+ id: store.id,
351
+ phase: 'triage',
352
+ brief: null,
353
+ vision: null,
354
+ facts: null,
355
+ factsMain: null,
356
+ cameras: null,
357
+ reference: null,
358
+ board: null,
359
+ estimate: null,
360
+ ready: [],
361
+ // The models the director put in at the blockout's placements, by
362
+ // placement id (the placements seam as written); those it took out
363
+ // again because the game measured worse with them, so the same file
364
+ // is not looked at twice; and what it is looking at in the game
365
+ // itself, outside a task's gate.
366
+ placed: {},
367
+ takenOut: {},
368
+ looking: null,
369
+ notes: {},
370
+ approvals: [],
371
+ visionReviewed: null,
372
+ fixTasks: 0,
373
+ followUps: 0,
374
+ minorBugs: [],
375
+ // What came to the director (a role's request of it, the critic's
376
+ // word that the brief contradicts the reference), each { line, from,
377
+ // state: open, routed, amended or report }, the reviews of them so
378
+ // far, and the brief's changes they made.
379
+ directorNotes: [],
380
+ reviews: 0,
381
+ briefChanges: [],
382
+ // What can make a modelled asset here (methods.mjs capabilitiesOf),
383
+ // and the keys the creator was asked for once in this production.
384
+ caps: null,
385
+ keys: {},
386
+ notDone: [],
387
+ stopped: false,
388
+ noMore: null,
389
+ cheaperUsd: null,
390
+ final: null,
391
+ attempts: 0,
392
+ }
393
+
394
+ // ---- the rpc, the ctx and the tools' view of the ledger
395
+
396
+ const wrappedRpc = async (method, params, timeoutMs) => {
397
+ const call = () => rpc(method, params, timeoutMs)
398
+ // A card waits for the creator; nothing else may wait behind it.
399
+ const r = method === 'ask' ? await call() : await rpcMutex.run(call)
400
+ if (method === 'build' && r?.ok && r.ran !== false) await prodGate.noteBuilt().catch(() => {})
401
+ return r
402
+ }
403
+ const ledgerFor = (task) => ({
404
+ spentUsd: () => ledger.spentUsd(),
405
+ approvedUsd: () => ledger.approvedUsd(),
406
+ addGeneration: (amount, what) => ledger.addGeneration(amount, what, { task: task?.id ?? null, role: task?.role ?? 'director' }),
407
+ gate: (name, readOnly) => ledger.gate(name, readOnly),
408
+ breakdown: () => ledger.breakdown(),
409
+ })
410
+ const ctxFor = (task = null, round = 0) => ({
411
+ ...ctxBase,
412
+ runId,
413
+ rpc: wrappedRpc,
414
+ ledger: ledgerFor(task),
415
+ run: { needsBuild: () => prodGate.needsBuild(), record: (kind) => prodGate.record(kind) },
416
+ production: {
417
+ id: P.id,
418
+ dir: store.dir,
419
+ brief: P.brief,
420
+ cameras: P.cameras ?? [],
421
+ facts: P.factsMain,
422
+ reference: P.reference?.rel ?? null,
423
+ task: task ? { id: task.id, role: task.role, round, owns: task.owns ?? [] } : null,
424
+ },
425
+ })
426
+ const readOnlyTool = (name, input) => {
427
+ if (name === 'Bash') return readOnlyCommand(input?.command)
428
+ const short = String(name).replace(/^mcp__nw__/, '')
429
+ if (short === 'asset_generate' || short === 'image_generate') return input?.action === 'estimate'
430
+ // The report is how a session ends: never held back by the spend.
431
+ if (short === 'task_check' || short === 'StructuredOutput') return true
432
+ return READ_ONLY_TOOLS.has(name) || READ_ONLY_TOOLS.has(short) || byName.get(short)?.readOnly === true
433
+ }
434
+
435
+ const sessions = createSessions({ query, send, log, ledger, projectRoot, runDir: ctxBase.runDir, runId, childEnv, guard, pluginDir, withPlugin })
436
+ const laneOf = (task) => roles?.[task.role]?.lane ?? 'preview'
437
+ const gate = createGate({
438
+ projectRoot,
439
+ store,
440
+ rpc: wrappedRpc,
441
+ byName,
442
+ roleChecks,
443
+ critic,
444
+ decide: sessions.decide,
445
+ router,
446
+ lanes,
447
+ laneOf,
448
+ prod: () => ({ brief: P.brief, vision: P.vision, facts: P.factsMain, cameras: P.cameras, board: P.board, reference: P.reference, placed: P.placed, briefChanges: P.briefChanges, locale }),
449
+ ctxFor,
450
+ sleep,
451
+ now,
452
+ log,
453
+ limits,
454
+ policy,
455
+ stopped: () => P.stopped,
456
+ measureBefore: (task, round, measure, tag) => withoutWork(task, round, measure, tag),
457
+ })
458
+ const runAttempt = createAttemptRunner({ sessions, gate, store, roles, projectRoot, defsByName: byName, ctxFor, readOnlyTool, now, log, limits })
459
+
460
+ // ---- what the chat and the production folder are told
461
+
462
+ let boardTimer = null
463
+ let boardAt = 0
464
+ const byModelList = () =>
465
+ Object.entries(ledger.breakdown().byModel).map(([id, n]) => ({ id, name: router.rungs.find((r) => r.model.id === id)?.model.name ?? (models.providers ?? []).flatMap((p) => p.models).find((m) => m.id === id)?.name ?? id, usd: n }))
466
+ const boardView = () => {
467
+ const byTask = ledger.breakdown().byTask
468
+ return {
469
+ productionId: P.id,
470
+ phase: P.phase,
471
+ roleWords: P.board?.roleWords ?? {},
472
+ tasks: (P.board?.tasks ?? []).map((t) => {
473
+ const attempts = t.attempts ?? []
474
+ const last = attempts.at(-1)
475
+ const best = gate.bestOf(attempts)
476
+ const judged = (best ?? last)?.gate?.critic
477
+ return {
478
+ id: t.id,
479
+ role: t.role,
480
+ label: t.label,
481
+ status: t.status,
482
+ round: attempts.length,
483
+ roundLimit: t.roundLimit,
484
+ model: t.live?.model ?? (last ? { id: last.model, name: last.modelName ?? last.model } : null),
485
+ effort: t.live?.effort ?? last?.effort ?? null,
486
+ escalated: Number.isInteger(attempts[0]?.rung) && Number.isInteger(t.live?.rung ?? last?.rung) && (t.live?.rung ?? last.rung) > attempts[0].rung,
487
+ image: t.thumb ?? null,
488
+ scores: judged ? { ...judged.scores, overall: judged.overall } : null,
489
+ pass: t.status === 'passed' ? true : t.status === 'failed' || t.status === 'kept' ? false : null,
490
+ usd: byTask[t.id] ?? 0,
491
+ }
492
+ }),
493
+ cost: { usd: ledger.spentUsd(), approvedUsd: ledger.approvedUsd(), byModel: byModelList() },
494
+ ceiling: router.ceiling ? { id: router.ceiling.id, name: router.ceiling.name } : null,
495
+ // The director looking at the game itself, outside a task's gate: for
496
+ // a model it puts in at its placement, or for the game without a
497
+ // task's work; tag is the name its pictures are saved under.
498
+ looking: P.looking ?? null,
499
+ at: now(),
500
+ }
501
+ }
502
+ const sendBoardNow = () => {
503
+ boardAt = now()
504
+ boardTimer = null
505
+ send({ type: 'board', id: runId, board: boardView() })
506
+ }
507
+ /** At most two a second; a change inside the window goes out at its end. */
508
+ const sendBoard = () => {
509
+ if (boardEveryMs <= 0) return sendBoardNow()
510
+ if (boardTimer) return
511
+ const wait = Math.max(0, boardAt + boardEveryMs - now())
512
+ if (wait === 0) return sendBoardNow()
513
+ boardTimer = setTimeout(sendBoardNow, wait)
514
+ boardTimer.unref?.()
515
+ }
516
+ let costAt = 0
517
+ const sendCost = (force = false) => {
518
+ if (!force && now() - costAt < COST_EVERY_MS) return
519
+ costAt = now()
520
+ const b = ledger.breakdown()
521
+ send({ type: 'cost', id: runId, usd: ledger.spentUsd(), approvedUsd: ledger.approvedUsd(), helperUsd: 0, generationUsd: b.generationUsd, byModel: byModelList(), byRole: b.byRole })
522
+ }
523
+ const writeProduction = (state, extra = {}) =>
524
+ store.writeJson('production.json', {
525
+ id: P.id,
526
+ request: { text: request.text ?? msg.text ?? '', references: (request.references ?? []).map((r) => projectRel(projectRoot, r) ?? r) },
527
+ route: resume ? 'resume' : 'production',
528
+ phase: P.phase,
529
+ state,
530
+ locale,
531
+ limits,
532
+ approvals: P.approvals,
533
+ reference: P.reference ? { rel: P.reference.rel, crop: P.reference.crop } : null,
534
+ ready: P.ready,
535
+ placed: P.placed,
536
+ takenOut: P.takenOut,
537
+ briefChanges: P.briefChanges,
538
+ visionReviewed: P.visionReviewed,
539
+ startedAt,
540
+ updatedAt: now(),
541
+ ...extra,
542
+ })
543
+ const writeBoard = () => (P.board ? store.writeJson('board.json', P.board) : Promise.resolve())
544
+ const setPhase = async (phase) => {
545
+ P.phase = phase
546
+ await store.append({ type: 'phase', phase })
547
+ await writeProduction('running')
548
+ sendBoard()
549
+ }
550
+ const ask = async (card) => {
551
+ // After a Stop no card opens: it is answered as main answers the open ones.
552
+ if (P.stopped) return { answer: 'cancelled' }
553
+ const r = (await wrappedRpc('ask', { runId, locale, spentUsd: ledger.spentUsd(), card }, ASK_TIMEOUT_MS).catch(() => null)) ?? { answer: 'unavailable' }
554
+ await store.append({ type: 'card', kind: card.kind, answer: r.answer ?? (r.ok === false ? 'refused' : null), ...(r.error ? { error: r.error } : {}) })
555
+ return r
556
+ }
557
+ const decision = async (phase, { systemPrompt, userText, images = [], schema }) => {
558
+ const pick = router.decision(phase)
559
+ log(`[director] ${phase} on ${pick.model.name} at ${pick.effort} (${pick.why})`)
560
+ const r = await sessions.decide({ key: phase, role: 'director', systemPrompt, userText, images, schema, pick, timeoutMs: limits.decisionMinutes * 60_000 })
561
+ await store.append({ type: 'decision', phase, model: pick.model.id, effort: pick.effort, ok: r.ok, usd: r.usd, ...(r.ok ? {} : { errors: r.errors }) })
562
+ sendCost()
563
+ return r
564
+ }
565
+ const timeUp = () => now() - startedAt > limits.productionMinutes * 60_000
566
+
567
+ current = {
568
+ id: P.id,
569
+ async stop(reason = 'stopped') {
570
+ if (P.stopped) return
571
+ P.stopped = true
572
+ log(`[director] stopped (${reason})`)
573
+ await store.append({ type: 'stop', reason })
574
+ await sessions.stopAll()
575
+ try {
576
+ await blender?.stopAll?.()
577
+ } catch {
578
+ // a Blender that already ended
579
+ }
580
+ stopCodex()
581
+ for (const t of P.board?.tasks ?? []) if (['running', 'checking', 'ready'].includes(t.status)) t.status = 'stopped'
582
+ sendBoard()
583
+ },
584
+ }
585
+ if (stopAsked) await current.stop(stopAsked)
586
+
587
+ send({ type: 'started', id: runId, sessionId: null, model: 'team', effort: depth?.effort ?? null, depthReason: depth?.reason ?? null, locale, team: { productionId: P.id } })
588
+
589
+ // ---- the direction's cost card
590
+
591
+ /** Before INTERPRET: reading the request and planning are spent on
592
+ * top-tier models, so they are approved first, on their own small card;
593
+ * the whole production's card follows the plan. */
594
+ async function directionPhase() {
595
+ // A picture's reading is read back against it, one decision more.
596
+ const decisions = (request.references ?? []).length || (msg.images ?? []).length ? ['interpret', 'readback', 'vision', 'plan'] : ['interpret', 'vision', 'plan']
597
+ const { items, hi } = directionItems({ router, prices, decisions })
598
+ const a = await ask({ kind: 'cost', origin: 'host', textKey: 'direction', title: 'Reading the request and planning', estimate: { items } })
599
+ if (a.answer !== 'approve') return { ok: false, cancelled: true, why: a.answer === 'cancel' ? 'The creator cancelled the cost of reading the request and planning.' : `The first cost card was not answered (${a.answer ?? a.error ?? 'no answer'}).` }
600
+ const total = Number.isFinite(a.approvedUsd) ? a.approvedUsd : hi
601
+ ledger.approve(total)
602
+ P.approvals.push({ at: now(), usd: total, direction: true })
603
+ sendCost(true)
604
+ return { ok: true }
605
+ }
606
+
607
+ // ---- INTERPRET
608
+
609
+ async function interpret() {
610
+ await setPhase('interpret')
611
+ const refAbs = (request.references ?? [])[0] ?? null
612
+ const refRel = refAbs ? projectRel(projectRoot, refAbs) : null
613
+ const refDef = byName.get('nw_reference')
614
+ if (refRel) {
615
+ const bytes = await fsp.readFile(path.join(projectRoot, refRel)).catch(() => null)
616
+ const mime = /\.png$/i.test(refRel) ? 'image/png' : /\.webp$/i.test(refRel) ? 'image/webp' : 'image/jpeg'
617
+ P.reference = { rel: refRel, crop: null, image: bytes ? await fitImage({ mime, data: bytes.toString('base64') }, 1024) : null }
618
+ }
619
+ if (refRel && refDef) {
620
+ const stem = path.basename(refRel).replace(/\.[^.]+$/, '')
621
+ const first = await runDef(refDef, { image: refRel }, ctxFor())
622
+ const full = first.isError ? null : factsFrom(first)
623
+ if (first.isError) log(`[director] nw_reference: ${String(first.text).split('\n')[0]}`)
624
+ let art = null
625
+ const crop = full?.frame?.suggestedCrop
626
+ if (Array.isArray(crop)) {
627
+ const second = await runDef(refDef, { image: refRel, crop }, ctxFor())
628
+ art = second.isError ? null : factsFrom(second)
629
+ if (art) P.reference.crop = crop
630
+ }
631
+ for (const [name, f] of [['full', full], ['art', art]]) {
632
+ if (!f) continue
633
+ const ok = ReferenceFacts.safeParse(f)
634
+ if (!ok.success) log(`[director] the reference facts do not match their contract: ${ok.error.issues[0]?.path.join('.')}: ${ok.error.issues[0]?.message}`)
635
+ await store.writeJson(`facts/${stem}.${name}.json`, f)
636
+ }
637
+ P.facts = full ? { full, art } : null
638
+ P.factsMain = art ?? full ?? null
639
+ } else if (refRel) log('[director] nw_reference is not in this build: the brief is read from the picture alone')
640
+
641
+ const images = []
642
+ for (const image of (msg.images ?? []).slice(0, 2)) {
643
+ const fitted = await fitImage(image, 1568)
644
+ if (fitted) images.push(fitted)
645
+ }
646
+ const project = await projectFacts(projectRoot)
647
+ const hasImage = !!refRel || images.length > 0
648
+ const ask1 = (errors) =>
649
+ decision('interpret', {
650
+ systemPrompt: INTERPRET_PROMPT,
651
+ userText: interpretText({ request: request.text ?? msg.text ?? '', facts: P.facts, project, blender: blender?.info ?? null, web: ctxBase.webState ?? 'ask', declinePaid: !!settings.declinePaid, languageName: replyName, errors }),
652
+ images,
653
+ schema: Interpretation,
654
+ })
655
+ // An answer's errors: its structure, then (with a picture) what the
656
+ // facts measure against it.
657
+ const errorsOf = (r) => (r.ok ? { structure: interpretationErrors(r.value, { hasImage }), reading: readingErrors(r.value.brief, P.factsMain).map((e) => e.text) } : { structure: r.errors, reading: [] })
658
+ // The read-back, on the first answer that holds together: what the
659
+ // picture clearly shows that the brief lacks or contradicts.
660
+ const readBackOf = async (answer) => (hasImage && !P.stopped ? await readBack(answer.value.brief, images[0] ?? null) : null)
661
+ let r = await ask1(null)
662
+ let found = errorsOf(r)
663
+ let read = found.structure.length ? null : await readBackOf(r)
664
+ if ([...found.structure, ...found.reading, ...(read?.errors ?? [])].length && !P.stopped) {
665
+ const first = { r, found }
666
+ r = await ask1([...found.structure, ...found.reading, ...(read?.errors ?? [])])
667
+ found = errorsOf(r)
668
+ if (found.structure.length && !first.found.structure.length) {
669
+ // A repair that does not hold together leaves the first answer,
670
+ // when that one did, with what it still reads wrong.
671
+ r = first.r
672
+ found = { ...first.found, reading: [...first.found.reading, ...(read?.errors ?? [])] }
673
+ } else if (!found.structure.length) {
674
+ // What the read-back found that the repair still does not answer
675
+ // stays wrong, said. When the first answer did not hold together
676
+ // the repair is the first to be read back, with no repair left.
677
+ const left = read ? unanswered(read.answer, first.r.value.brief, r.value.brief, P.factsMain).map((e) => e.text) : ((read = await readBackOf(r))?.errors ?? [])
678
+ found = { ...found, reading: [...found.reading, ...left] }
679
+ }
680
+ }
681
+ if (found.structure.length) return { ok: false, why: `The request could not be read into a brief: ${found.structure[0]}` }
682
+ const interp = r.value
683
+ // What the reading still gets wrong against the picture goes on, said:
684
+ // the critic judges form against the subjects' crops, and the brief
685
+ // can still change between rounds.
686
+ if (found.reading.length) {
687
+ await store.append({ type: 'reading', left: found.reading })
688
+ P.notDone.push(...found.reading.slice(0, 8).map((e) => `the brief still differs from the reference: ${e}`.slice(0, 600)))
689
+ }
690
+ const bounded = boundPerformance(interp.brief.performance, request.text ?? msg.text ?? '')
691
+ interp.brief.performance = bounded.performance
692
+ if (bounded.assumption) interp.brief.assumptions = [...interp.brief.assumptions, bounded.assumption].slice(-16)
693
+ interp.brief = settleBrief(interp.brief, P.factsMain)
694
+ P.brief = interp.brief
695
+ P.images = images
696
+ await store.writeJson('interpretation.json', { ...interp, ...(read?.errors.length || found.reading.length ? { reading: { readback: read?.errors ?? [], left: found.reading } } : {}) })
697
+ await store.writeJson('brief.json', P.brief)
698
+ const briefMd = path.join(projectRoot, 'brief.md')
699
+ if (fs.existsSync(briefMd)) await store.writeText('brief.before.md', await fsp.readFile(briefMd, 'utf8'))
700
+ await fsp.writeFile(briefMd, renderBrief(P.brief))
701
+ return { ok: true }
702
+ }
703
+
704
+ /**
705
+ * The brief read back against its picture: a fresh decision that sees
706
+ * only the reference (as it is, and with the subjects' boxes drawn) and
707
+ * the brief's subjects, forms and cameras (READBACK_PROMPT), and lists
708
+ * what the picture clearly shows that the brief lacks or contradicts.
709
+ * Its answer and its traits as error lines ({ answer, errors }); null
710
+ * when it does not answer, and the measured checks stand alone.
711
+ */
712
+ async function readBack(brief, attached) {
713
+ const image = P.reference?.image ?? attached
714
+ if (!image) return null
715
+ const drawn = await subjectsPicture(image, brief.subjects ?? [], P.reference?.crop ?? null).catch(() => null)
716
+ const r = await decision('readback', { systemPrompt: READBACK_PROMPT, userText: readbackText({ brief, facts: P.factsMain, marks: markOf }), images: drawn ? [image, drawn] : [image], schema: ReadBack })
717
+ if (!r.ok) {
718
+ log(`[director] the read-back gave no answer (${r.errors?.[0] ?? 'none'}): the measured checks stand alone`)
719
+ return null
720
+ }
721
+ const errors = readbackErrors(r.value, brief, P.factsMain).map((e) => e.text)
722
+ await store.append({ type: 'readback', traits: r.value.traits, errors: errors.length })
723
+ return { answer: r.value, errors }
724
+ }
725
+
726
+ // ---- VISION
727
+
728
+ async function visionPhase() {
729
+ await setPhase('vision')
730
+ let develop = null
731
+ let edit = null
732
+ let again = 0
733
+ const images = P.reference?.image ? [P.reference.image] : (P.images ?? []).slice(0, 1)
734
+ for (;;) {
735
+ // A moment at a camera the brief does not have can never be shot: the
736
+ // final gate would fail on it, and no role could fix it.
737
+ const make = async (extra) => {
738
+ const r = await decision('vision', { systemPrompt: VISION_PROMPT, userText: visionText({ brief: P.brief, request: request.text ?? msg.text ?? '', languageName, develop, edit }) + (extra ?? ''), images, schema: Vision })
739
+ const errors = r.ok ? visionErrors(r.value, P.brief) : []
740
+ return errors.length ? { ok: false, errors } : r
741
+ }
742
+ let r = await make()
743
+ if (!r.ok && !P.stopped) r = await make(`\n\nYour last answer did not hold: ${r.errors.join('; ')}. Answer again.`)
744
+ if (!r.ok) return P.vision ? { ok: true } : { ok: false, why: `The vision could not be set: ${r.errors[0]}` }
745
+ if (!r.value.concepts.some((c) => c.id === r.value.chosen)) r.value.chosen = r.value.concepts[0].id
746
+ P.vision = r.value
747
+ await store.writeJson('vision.json', P.vision)
748
+ if (settings.vision === 'approve' || settings.vision === 'skip') {
749
+ P.visionReviewed = settings.vision === 'approve' ? 'approved by the run' : false
750
+ break
751
+ }
752
+ const answer = await ask({ kind: 'vision', origin: 'host', title: P.vision.card.title, body: P.vision.card.body, vision: visionCard(P.vision) })
753
+ if (answer.answer === 'approve') {
754
+ P.visionReviewed = true
755
+ break
756
+ }
757
+ if (answer.answer === 'cancelled') return { ok: false, cancelled: true, why: 'The creator stopped it at the vision card.' }
758
+ if ((answer.answer === 'pick' || answer.answer === 'edit') && again < 2) {
759
+ again++
760
+ develop = answer.answer === 'pick' ? P.vision.concepts.find((c) => c.id === answer.concept) ?? null : develop
761
+ edit = answer.answer === 'edit' ? String(answer.text ?? '').slice(0, 500) : null
762
+ continue
763
+ }
764
+ // skip, a third change (taken as it is), a timeout or no card at all
765
+ P.visionReviewed = answer.answer === 'pick' || answer.answer === 'edit' ? 'changed twice; the third answer taken as it was' : false
766
+ break
767
+ }
768
+ await fsp.writeFile(path.join(projectRoot, 'brief.md'), renderBrief(P.brief, P.vision))
769
+ return { ok: true }
770
+ }
771
+
772
+ // ---- PLAN
773
+
774
+ /** What can make a modelled asset here, built by code (methods.mjs):
775
+ * the settings, the keys, Blender, Codex and its consent, the prices,
776
+ * and the reference's crop of each subject, measured. */
777
+ const capabilities = async () => {
778
+ // Codex is looked for only while the creator has not said no to it.
779
+ const codexState = (typeof ctxBase.codexState === 'function' ? ctxBase.codexState() : ctxBase.codexState) ?? 'ask'
780
+ return capabilitiesOf({
781
+ projectRoot,
782
+ blender: blender?.info ?? null,
783
+ web: ctxBase.webState ?? 'ask',
784
+ declinePaid: !!settings.declinePaid,
785
+ secret: ctxBase.secret,
786
+ codex: codexState === 'deny' ? null : ((await Promise.resolve(codex?.find?.()).catch(() => null)) ?? codex?.info ?? null),
787
+ codexState,
788
+ brief: P.brief,
789
+ facts: P.factsMain,
790
+ reference: P.reference,
791
+ prices: ASSET_PRICES,
792
+ made: (rel) => (P.board?.tasks ?? []).some((t) => (t.owns ?? []).some((g) => matches(g, rel))),
793
+ })
794
+ }
795
+
796
+ /** A modeller task whose way of making sends pictures owns the folder
797
+ * under blender/ they land in (the reference's crop, the views made for
798
+ * it), and keeps how it was made round by round. */
799
+ const withMethod = (t) => {
800
+ if (t.role !== 'modeller' || !t.method) return t
801
+ const dir = pictureDir(t)
802
+ const owns = [t.method, t.fallback].some(usesPictures) && dir && !(t.owns ?? []).some((g) => matches(g, `${dir}/view.png`)) ? [...(t.owns ?? []), `${dir}/**`] : t.owns
803
+ return { ...t, owns, methods: [{ round: 1, ...t.method }] }
804
+ }
805
+ const prepare = (planned) => ({
806
+ ...planned,
807
+ tasks: planned.tasks.map((t) => ({ ...withDefaults(withMethod(t), roles?.[t.role], P.brief, { interfaces: planned.interfaces ?? [] }), status: 'waiting', attempts: [] })),
808
+ })
809
+
810
+ async function plan() {
811
+ await setPhase('plan')
812
+ const project = await projectFacts(projectRoot)
813
+ const roleCatalogue = Object.values(roles ?? {})
814
+ .map((r) => `- ${r.id} (${r.lane} lane): ${r.catalogue?.does ?? ''} Size: ${r.catalogue?.size ?? ''}. Checks: ${(r.catalogue?.checks ?? []).join(', ')}. May own: ${(r.mayOwn ?? []).join(', ') || 'nothing'}.`)
815
+ .join('\n')
816
+ // The planner sees the picture too: the brief's subjects are boxes of it.
817
+ const images = P.reference?.image ? [P.reference.image] : (P.images ?? []).slice(0, 1)
818
+ P.caps = await capabilities()
819
+ const methods = capabilityText(P.caps)
820
+ const make = (errors) =>
821
+ decision('plan', {
822
+ systemPrompt: PLAN_PROMPT,
823
+ userText: planText({ brief: P.brief, vision: P.vision, facts: P.factsMain, roleCatalogue, checkCatalogue: catalogueText(), routing: router.describe(), project, limits, web: ctxBase.webState ?? 'ask', declinePaid: !!settings.declinePaid, blender: blender?.info ?? null, methods, languageName, errors }),
824
+ images,
825
+ schema: PlanOutput,
826
+ })
827
+ const errorsOf = (r) => (r.ok ? validateBoard(prepare(r.value), { roles, brief: P.brief, vision: P.vision, limits, facts: P.factsMain, declinePaid: !!settings.declinePaid, methods: P.caps }) : r.errors)
828
+ let r = await make(null)
829
+ let errors = errorsOf(r)
830
+ if (errors.length && !P.stopped) {
831
+ await store.append({ type: 'plan-invalid', errors })
832
+ r = await make(errors)
833
+ errors = errorsOf(r)
834
+ }
835
+ if (errors.length) return { ok: false, why: `The plan did not hold together after one repair: ${errors[0]}` }
836
+ P.board = prepare(r.value)
837
+ // Blender, asked just in time, when a modelled asset is to be made in
838
+ // it: without it that asset falls back to the way its plan gave, and
839
+ // the modeller works without nw_blender.
840
+ const inBlender = (t) => (t.method ? [t.method, t.fallback].some((m) => m?.how === 'blender') : (roles?.modeller?.nwTools ?? []).includes('nw_blender'))
841
+ const needsBlender = P.board.tasks.some((t) => t.role === 'modeller' && inBlender(t))
842
+ if (needsBlender && !blender?.info) {
843
+ const a = await ask({ kind: 'choice', origin: 'host', textKey: 'blender', title: 'Blender', options: [{ id: 'install', label: 'Install Blender from blender.org, then continue' }, { id: 'without', label: 'Go on without Blender' }] })
844
+ const picked = Array.isArray(a.answer) ? a.answer[0] : null
845
+ if (picked === 'install' && typeof blender?.find === 'function') blender.info = (await blender.find().catch(() => null)) ?? null
846
+ if (!blender?.info) for (const t of P.board.tasks.filter((x) => x.role === 'modeller')) t.noBlender = true
847
+ }
848
+ await writeBoard()
849
+ sendBoard()
850
+ return { ok: true }
851
+ }
852
+
853
+ /** The seams, once the cost is approved (nothing of the game changes
854
+ * before): a stub for every interface whose producer's work is not in
855
+ * the game, a resume's too, and the module for one whose is; the
856
+ * placements with the models put in so far. */
857
+ async function placeSeams() {
858
+ const written = []
859
+ for (const inf of P.board.interfaces ?? []) {
860
+ if (!seamOf(inf)) continue
861
+ const producer = P.board.tasks.find((t) => t.id === inf.producer)
862
+ await (DONE.has(producer?.status) ? flipSeam(projectRoot, inf) : stubSeam(projectRoot, inf))
863
+ written.push(seamOf(inf))
864
+ }
865
+ if (placementsOf(P.board).length) {
866
+ await writePlacements(projectRoot, placementsOf(P.board), P.placed)
867
+ written.push(PLACEMENTS_SEAM)
868
+ }
869
+ await store.append({ type: 'seams', written })
870
+ }
871
+
872
+ // ---- ESTIMATE
873
+
874
+ /** A vendor's key, asked on a key card once in a production: true when it is here. */
875
+ async function askKey(provider) {
876
+ if (keyHere(provider)) return true
877
+ P.keys[provider.connector] ??= ask({ kind: 'key', connector: provider.connector, title: provider.label }).then((k) => k.answer === 'saved')
878
+ return (await P.keys[provider.connector]) && keyHere(provider)
879
+ }
880
+ const keyHere = (provider) => {
881
+ try {
882
+ const v = ctxBase.secret?.(provider.envVar)
883
+ return typeof v === 'string' && v.trim() !== ''
884
+ } catch {
885
+ return false
886
+ }
887
+ }
888
+
889
+ /** The cards a method needs, asked in turn: null when it may run, else
890
+ * why not (the creator refused one, or it cannot be asked here). */
891
+ async function cardsDone(m) {
892
+ for (const c of cardsFor(m, P.caps)) {
893
+ if (P.stopped) return 'the production stopped'
894
+ if (c.kind === 'key' && !(await askKey(c.provider))) return `the creator did not give ${c.provider.label}'s key`
895
+ if (c.kind === 'codex' || c.kind === 'web') {
896
+ const consent = c.kind === 'codex' ? ctxBase.codex : ctxBase.web
897
+ const a = typeof consent === 'function' ? await Promise.resolve(consent()).catch(() => 'unavailable') : 'unavailable'
898
+ const what = c.kind === 'codex' ? 'Codex' : 'the web'
899
+ if (a !== 'allow') return a === 'deny' ? `the creator did not allow ${what}` : `the creator could not be asked about ${what}`
900
+ }
901
+ if (c.kind === 'blender' && !blender?.info) return 'Blender is not installed'
902
+ }
903
+ return null
904
+ }
905
+
906
+ /** A method's spending, priced through the tools' own estimates (they
907
+ * send nothing): each paid line counts the rounds it may be spent in;
908
+ * one on the creator's plan (Codex) is no line. null when a request
909
+ * could not be priced: a paid way with no line on a card never runs. */
910
+ async function priceMethod(task, m) {
911
+ const out = []
912
+ for (const q of methodRequests(task, m)) {
913
+ const def = byName.get(q.tool)
914
+ if (P.stopped) return null
915
+ const r = def ? await runDef(def, q.request, ctxFor(task)) : { isError: true, text: `${q.tool} is not in this build` }
916
+ const lines = r.isError ? null : paidFromEstimate(r.text)
917
+ if (!lines) {
918
+ log(`[director] ${task.id}: the ${q.provider} estimate gave no lines: ${String(r.text).split('\n')[0]}`)
919
+ return null
920
+ }
921
+ if (!(lines.usd > 0)) continue
922
+ const label = (q.tool === 'image_generate' ? IMAGE_PROVIDERS[q.provider] : PROVIDERS[q.provider])?.label ?? q.provider
923
+ out.push({ provider: q.provider, for: task.id, usd: lines.usd, hi: lines.usd * Math.min(task.roundLimit ?? 1, 2), label })
924
+ }
925
+ return out
926
+ }
927
+
928
+ /** Whether a method may run for a task before anything is spent: its
929
+ * cards asked, and a way that sends pictures priced. { lines } when
930
+ * it may, else { refused } with why. */
931
+ async function readyMethod(task, m) {
932
+ const refused = await cardsDone(m)
933
+ if (refused) return { refused }
934
+ if (!usesPictures(m)) return { lines: [] }
935
+ const lines = await priceMethod(task, m)
936
+ return lines ? { lines } : { refused: P.stopped ? 'the production stopped' : `what ${m.how} would spend could not be priced` }
937
+ }
938
+
939
+ /**
940
+ * Before the cost card, every modelled asset's way of making as it will
941
+ * run: what it needs a card for is asked (a key, Codex's consent, the
942
+ * web; the Blender card came after the plan) and what it spends is
943
+ * priced, and a refused or unpriced one leaves its fallback, said on the
944
+ * board in its place; a task with neither ends without spending
945
+ * anything, its stand-in where it was. Answers the paid lines.
946
+ */
947
+ async function settleMethods() {
948
+ P.caps = await capabilities()
949
+ const out = []
950
+ for (const t of P.board.tasks.filter((x) => x.role === 'modeller' && x.method && !ENDED.has(x.status))) {
951
+ delete t.unpriced
952
+ const first = await readyMethod(t, t.method)
953
+ if (!first.refused) {
954
+ out.push(...first.lines)
955
+ continue
956
+ }
957
+ const second = t.fallback ? await readyMethod(t, t.fallback) : null
958
+ const back = second && !second.refused ? t.fallback : null
959
+ const round = t.attempts.length + 1
960
+ void store.append({ type: 'method', task: t.id, round, from: t.method, to: back, why: first.refused })
961
+ if (back) {
962
+ // The way refused never made anything: the fallback is the round's.
963
+ t.methods = [...(t.methods ?? []).filter((x) => x.round !== round), { round, ...back, why: `${first.refused}, so its fallback: ${back.why}`.slice(0, 200) }]
964
+ t.method = back
965
+ out.push(...second.lines)
966
+ } else {
967
+ t.noMethod = `${first.refused}, and ${t.fallback ? 'its fallback could not run either' : 'it has no fallback'}`
968
+ t.method = null
969
+ }
970
+ }
971
+ P.caps = await capabilities()
972
+ return out
973
+ }
974
+
975
+ async function paidLines() {
976
+ const out = P.board.tasks.some((t) => t.role === 'modeller' && t.method) ? await settleMethods() : []
977
+ const def = byName.get('asset_generate')
978
+ for (const p of P.board?.paid ?? []) {
979
+ if (P.stopped) break
980
+ if (settings.declinePaid || !def) continue
981
+ const provider = PROVIDERS[p.provider]
982
+ const task = P.board.tasks.find((t) => t.id === p.for)
983
+ if (provider && !ctxBase.secret?.(provider.envVar)) {
984
+ const k = await ask({ kind: 'key', connector: provider.connector, title: provider.label })
985
+ if (k.answer !== 'saved') {
986
+ if (task) (P.notes[task.id] ??= []).push(`No ${provider.label} key: model this from Blender or a CC0 library instead of a paid generation.`)
987
+ continue
988
+ }
989
+ }
990
+ const r = await runDef(def, { ...(p.request ?? {}), action: 'estimate', provider: p.provider }, ctxFor(task ?? null))
991
+ const lines = r.isError ? null : paidFromEstimate(r.text)
992
+ if (lines) out.push({ provider: p.provider, for: p.for, usd: lines.usd, label: provider?.label ?? p.provider })
993
+ else log(`[director] the ${p.provider} estimate gave no lines: ${String(r.text).split('\n')[0]}`)
994
+ }
995
+ return out
996
+ }
997
+
998
+ const unfinished = () => (P.board?.tasks ?? []).filter((t) => !ENDED.has(t.status))
999
+ const cardFor = (est, extraTitle = '') => {
1000
+ const { items, hi } = costItems(est, { roleWords: P.board.roleWords, costWords: P.board.costWords, taskLabels: Object.fromEntries(P.board.tasks.map((t) => [t.id, t.label])) })
1001
+ return { card: { kind: 'cost', origin: 'agent', title: `${P.board.card.title}${extraTitle}`.slice(0, 80), body: P.board.card.body, estimate: { items, ...(P.board.card.note ? { note: P.board.card.note } : {}) } }, hi, items }
1002
+ }
1003
+
1004
+ async function estimatePhase() {
1005
+ await setPhase('estimate')
1006
+ const paid = await paidLines()
1007
+ P.estimate = estimateProduction({ board: P.board, router, prices, paid, decisions: [], tasks: unfinished() })
1008
+ const { card, hi, items } = cardFor(P.estimate)
1009
+ const cheapest = estimateProduction({ board: P.board, router, prices, paid: [], decisions: [], tasks: unfinished(), cheapest: true })
1010
+ await store.writeJson('estimate.json', { lo: P.estimate.lo, hi, items, perTask: P.estimate.perTask, finalUsd: P.estimate.finalUsd, cheapestLo: cheapest.lo, lines: P.estimate.lines.map((l) => ({ ...l, model: l.model.id })) })
1011
+ const a = await ask(card)
1012
+ if (a.answer !== 'approve') {
1013
+ P.cheaperUsd = cheapest.lo
1014
+ return { ok: false, why: a.answer === 'cancel' ? 'The creator cancelled the cost card.' : `The cost card was not answered (${a.answer ?? a.error ?? 'no answer'}).`, cancelled: true }
1015
+ }
1016
+ const total = Number.isFinite(a.approvedUsd) ? a.approvedUsd : hi
1017
+ ledger.approve(total)
1018
+ P.approvals.push({ at: now(), usd: total })
1019
+ await placeSeams()
1020
+ await writeProduction('running')
1021
+ sendCost(true)
1022
+ return { ok: true }
1023
+ }
1024
+
1025
+ const cardLock = createMutex()
1026
+ /** Before every new attempt: a new cost card once the projection passes
1027
+ * the approval's reminder line, counting at least the attempt about to
1028
+ * start (`task` on `pick`), so the card comes before it is spent. false
1029
+ * when the creator said no. */
1030
+ const reapprove = (task = null, pick = null) =>
1031
+ cardLock.run(async () => {
1032
+ if (P.noMore) return false
1033
+ const next = task && pick ? { task: task.id, usd: attemptUsd({ task, model: pick.model.id, router, prices }) } : null
1034
+ const left = remainingUsd({ estimate: P.estimate, board: P.board, spentByTask: ledger.breakdown().byTask, next })
1035
+ if (!ledger.overLine(left)) return true
1036
+ // The paid generations still to come stay on the card, and in their tasks' shares.
1037
+ const paid = (P.estimate.paid ?? []).filter((p) => unfinished().some((t) => t.id === p.for))
1038
+ const est = estimateProduction({ board: P.board, router, prices, paid, decisions: [], tasks: unfinished() })
1039
+ const { card, hi } = cardFor(est)
1040
+ log(`[director] the projection ${usd(ledger.spentUsd() + left)} passed the approved ${usd(ledger.approvedUsd())}: a new cost card for what is left`)
1041
+ const a = await ask(card)
1042
+ if (a.answer !== 'approve') {
1043
+ P.noMore = DECLINED
1044
+ return false
1045
+ }
1046
+ const total = Number.isFinite(a.approvedUsd) ? a.approvedUsd : hi
1047
+ ledger.approve(total)
1048
+ P.approvals.push({ at: now(), usd: total, again: true })
1049
+ P.estimate = { ...est, perTask: { ...P.estimate.perTask, ...est.perTask } }
1050
+ return true
1051
+ })
1052
+
1053
+ /** A task's paid lines on a new cost card for what is left, re-priced,
1054
+ * before it spends them; none to show asks nothing. false when the
1055
+ * creator said no. */
1056
+ const approveLines = (task, lines) =>
1057
+ cardLock.run(async () => {
1058
+ if (!lines.length) return true
1059
+ const paid = [...(P.estimate.paid ?? []).filter((p) => p.for !== task.id && unfinished().some((t) => t.id === p.for)), ...lines]
1060
+ const est = estimateProduction({ board: P.board, router, prices, paid, decisions: [], tasks: unfinished() })
1061
+ const { card, hi } = cardFor(est)
1062
+ const a = await ask(card)
1063
+ if (a.answer !== 'approve') return false
1064
+ const total = Number.isFinite(a.approvedUsd) ? a.approvedUsd : hi
1065
+ ledger.approve(total)
1066
+ P.approvals.push({ at: now(), usd: total, method: task.id })
1067
+ P.estimate = { ...est, perTask: { ...P.estimate.perTask, ...est.perTask } }
1068
+ return true
1069
+ })
1070
+
1071
+ // ---- DISPATCH, GATE, REDISPATCH
1072
+
1073
+ const interfaceOf = (task) => (P.board.interfaces ?? []).find((i) => i.id === task.interface && i.producer === task.id) ?? null
1074
+ const toolsPassed = (a) => a.gate && a.gate.checks.every((c) => c.ok) && !a.gate.noReport
1075
+ const snapAbs = (task, round, which) => store.abs(path.join('snap', task.id, `r${round}`, which))
1076
+ /** A task's files as an attempt left them, and back; an artist's look keys too. */
1077
+ const snap = (task, round) => snapshot(projectRoot, task.owns ?? [], snapAbs(task, round, 'after'), { look: lookMode(task, roles) })
1078
+ const putBack = (task, round) => restore(projectRoot, task.owns ?? [], snapAbs(task, round, 'after'), { look: lookMode(task, roles) })
1079
+ const moduleThere = (inf) => fs.existsSync(path.join(projectRoot, relPath(inf.module)))
1080
+
1081
+ /** The blockout's shots of the brief's cameras; a brief camera's aspect
1082
+ * (the reference's is the picture's) is its shot's, as code set it. */
1083
+ async function saveCameras(reported) {
1084
+ const byId = new Map(reported.map((c) => [c.id, c.shot]))
1085
+ const shotOf = (c) => {
1086
+ const shot = byId.get(c.id)
1087
+ return shot && typeof shot === 'object' && c.aspect ? { ...shot, aspect: c.aspect } : shot
1088
+ }
1089
+ P.cameras = (P.brief.cameras ?? []).map((c) => ({ id: c.id, purpose: c.purpose, ...(byId.has(c.id) ? { shot: shotOf(c) } : {}) }))
1090
+ await store.writeJson('cameras.json', P.cameras)
1091
+ }
1092
+
1093
+ async function writeThumb(task, g) {
1094
+ const pic = g.pictures?.find((p) => p.kind !== 'compare' || !String(p.camera).endsWith('-side'))
1095
+ if (!pic) return
1096
+ try {
1097
+ const bytes = await fsp.readFile(path.join(projectRoot, pic.path))
1098
+ const fitted = await fitImage({ mime: 'image/jpeg', data: bytes.toString('base64') }, 320)
1099
+ await store.writeBytes(`thumbs/${task.id}.jpg`, Buffer.from(fitted.data, 'base64'))
1100
+ task.thumb = store.rel(`thumbs/${task.id}.jpg`)
1101
+ } catch {
1102
+ // no thumbnail; the board shows none
1103
+ }
1104
+ }
1105
+
1106
+ const nextTaskId = () => `t${P.board.tasks.length + 1}`
1107
+ /** Unfinished tasks a new task must wait for: those whose files it overlaps. */
1108
+ const waitsFor = (owns, except = []) => P.board.tasks.filter((t) => !except.includes(t.id) && !ENDED.has(t.status) && (t.owns ?? []).some((a) => owns.some((b) => overlaps(a, b)))).map((t) => t.id)
1109
+ /** A task added after the cost card is priced like the board's, so the
1110
+ * projection counts it before it spends. Returns its share. */
1111
+ const addTask = (task) => {
1112
+ // A model made the way its owner's was, with pictures sent to a paid
1113
+ // service, is priced on a card before its first round (runTask).
1114
+ if (task.role === 'modeller' && usesPictures(task.method)) task.unpriced = true
1115
+ P.board.tasks.push(task)
1116
+ const share = estimateProduction({ board: P.board, router, prices, decisions: [], tasks: [task] }).perTask[task.id] ?? 0
1117
+ if (P.estimate) P.estimate.perTask[task.id] = share
1118
+ return share
1119
+ }
1120
+
1121
+ /** The project file a request names, one word of it: the first that is
1122
+ * a file of the project ("scene.json (dome placement, not mine)" names
1123
+ * scene.json), else the first that is a file a role may make or the
1124
+ * director's (a name with an extension, no wildcard); null when none
1125
+ * is. The words around a path are never taken as part of it. */
1126
+ function pathIn(raw) {
1127
+ const rels = String(raw ?? '')
1128
+ .split(/[\s,;:()[\]'"`]+/)
1129
+ .map((w) => w.replace(/\.+$/, ''))
1130
+ .filter((w) => /[./]/.test(w) && !/[*?{}]/.test(w))
1131
+ .map((w) => projectRel(projectRoot, w))
1132
+ .filter(Boolean)
1133
+ const isFile = (rel) => {
1134
+ try {
1135
+ return fs.statSync(path.join(projectRoot, rel)).isFile()
1136
+ } catch {
1137
+ return false
1138
+ }
1139
+ }
1140
+ const mayMake = (rel) => /[^/]\.[A-Za-z0-9]+$/.test(rel) && (isDirectorFile(rel) || ROLE_IDS.some((id) => (roles?.[id]?.mayOwn ?? []).length && inside(rel, roles[id].mayOwn)))
1141
+ return rels.find(isFile) ?? rels.find(mayMake) ?? null
1142
+ }
1143
+
1144
+ /** Whether a request is about the look keys of game.config.json: an
1145
+ * artist's (the look is its own), or one that names a look key. */
1146
+ const aboutLook = (rel, c, task) => rel === 'game.config.json' && (task.role === 'artist' || LOOK_KEYS.some((k) => new RegExp(`\\b${k}\\b`, 'i').test(`${c.path} ${c.what}`)))
1147
+ /** Whether a request is about where the game shows something: its
1148
+ * composition, or the placements seam; never the look keys. */
1149
+ const aboutPlacing = (rel, look) => !!rel && !look && (rel === PLACEMENTS_SEAM || BUILDER_FILES.includes(rel) || inside(rel, roles?.builder?.mayOwn ?? []))
1150
+ const pendingOf = (role, task) => P.board.tasks.find((t) => t.role === role && t.id !== task.id && (t.status === 'waiting' || t.status === 'ready'))
1151
+
1152
+ /** A report's requests of other roles: a note on the owner's next task,
1153
+ * a follow-up task when its work is already in the game, or a line in
1154
+ * the report; one of the director's own is its note, reviewed between
1155
+ * rounds. A modeller's request to put its own model in the game,
1156
+ * to the director or the builder, is the placements seam's, which does
1157
+ * it when the task ends; the builder hears of one asked of it only as
1158
+ * what the seam does not do (the stand-in's spot and turn). One about
1159
+ * the game's composition is the builder's; one about the look keys is
1160
+ * an artist's (look_apply sets them), and an artist's own is the
1161
+ * director's note. In the final phase no task starts any more, so they
1162
+ * go to the report. */
1163
+ function routeChanges(task, report) {
1164
+ for (const c of report?.changesNeeded ?? []) {
1165
+ const rel = pathIn(c.path)
1166
+ const line = `${rel ?? c.path}: ${c.what} (${c.why}), asked by ${task.id}`
1167
+ const look = aboutLook(rel, c, task)
1168
+ let to = c.owner
1169
+ if (task.role === 'modeller' && task.placement && aboutPlacing(rel, look) && (to === 'director' || to === 'builder' || !roles?.[to])) {
1170
+ void store.append({ type: 'seam-request', task: task.id, placement: task.placement, path: c.path, what: c.what })
1171
+ const builder = to === 'builder' && P.phase !== 'final' ? pendingOf('builder', task) : null
1172
+ if (builder) (P.notes[builder.id] ??= []).push(`${line}. The director puts this model in at the placement ${task.placement} through the placements seam, where its stand-in stands, so never add the model again: if this asks for another spot or turn, move or turn the stand-in at ${task.placement}, and the model follows it.`)
1173
+ continue
1174
+ }
1175
+ if (look) {
1176
+ if (task.role === 'artist') {
1177
+ noteForDirector(line, task.id)
1178
+ continue
1179
+ }
1180
+ to = 'artist'
1181
+ } else if (to === 'director' || !roles?.[to]) {
1182
+ if (!aboutPlacing(rel, look)) {
1183
+ noteForDirector(line, task.id)
1184
+ continue
1185
+ }
1186
+ to = 'builder'
1187
+ }
1188
+ if (P.phase === 'final') {
1189
+ P.notDone.push(line)
1190
+ continue
1191
+ }
1192
+ const pending = pendingOf(to, task)
1193
+ if (pending) {
1194
+ ;(P.notes[pending.id] ??= []).push(line)
1195
+ continue
1196
+ }
1197
+ if (!rel) {
1198
+ P.notDone.push(`${line}; "${c.path}" is not a file of the project, so no task was made for it`)
1199
+ continue
1200
+ }
1201
+ const owner = [...P.board.tasks].reverse().find((t) => t.role === to && DONE.has(t.status))
1202
+ const owns = owner && (owner.owns ?? []).some((g) => matches(g, rel)) ? owner.owns : !isDirectorFile(rel) && inside(rel, roles[to].mayOwn ?? []) ? [rel] : null
1203
+ if (!owner || !owns || P.followUps >= limits.followUps || P.board.tasks.length >= limits.maxTasks + limits.followUps + limits.qaTasks) {
1204
+ P.notDone.push(line)
1205
+ continue
1206
+ }
1207
+ P.followUps++
1208
+ const id = nextTaskId()
1209
+ const share = addTask({
1210
+ id,
1211
+ role: to,
1212
+ title: `Follow-up for ${task.id}: ${c.what}`.slice(0, 200),
1213
+ label: `${P.board.roleWords?.[to] ?? to}: ${c.what}`.slice(0, 80),
1214
+ goal: `${c.what}. Why: ${c.why}. Asked by ${task.id} (${task.title}).`.slice(0, 600),
1215
+ covers: [],
1216
+ reads: [rel],
1217
+ owns,
1218
+ deps: [...new Set([owner.id, ...waitsFor(owns, [id])])],
1219
+ accept: { checks: (owner.accept?.checks ?? []).filter((x) => x.kind !== 'compare' || owner.role === 'artist'), critic: [] },
1220
+ tier: 'mid',
1221
+ roundLimit: 2,
1222
+ status: 'waiting',
1223
+ attempts: [],
1224
+ followUp: task.id,
1225
+ // A model made again stands where its owner's stood, so the
1226
+ // director puts it in there again and looks at the game with it,
1227
+ // made the way its owner's was made last.
1228
+ ...(owner.placement && owns === owner.owns ? { placement: owner.placement } : {}),
1229
+ ...(owner.method && owns === owner.owns ? { method: owner.method, methods: [{ round: 1, ...owner.method }] } : {}),
1230
+ })
1231
+ void store.append({ type: 'task', task: id, why: `follow-up for ${task.id}`, owner: to, usd: share })
1232
+ }
1233
+ }
1234
+
1235
+ /** A note for the director, once: reviewed between rounds (reviewNotes),
1236
+ * or, when no round is left to review it in, said in the report. */
1237
+ function noteForDirector(line, from) {
1238
+ if (!P.directorNotes.some((n) => n.line === line)) P.directorNotes.push({ line, from, state: 'open' })
1239
+ }
1240
+ /** The critic's word, on `on`, that the brief contradicts the reference. */
1241
+ const contradiction = (c, on) => `The critic, on ${on}: the brief contradicts the reference: ${c.what} (where: ${c.where}; why: ${c.why}). The brief as it should be: ${c.fix}`
1242
+
1243
+ /** The critic's changes for work another role owns: a note on that
1244
+ * role's next task, never an order to the task judged (its write guard
1245
+ * would refuse the files, and the change would cost it its rounds).
1246
+ * One that says the brief itself contradicts the reference is the
1247
+ * director's, reviewed between rounds. */
1248
+ function routeCritic(task, g) {
1249
+ for (const c of g.critic?.changes ?? []) {
1250
+ if (c.owner === 'director') {
1251
+ noteForDirector(contradiction(c, task.id), task.id)
1252
+ continue
1253
+ }
1254
+ if (c.owner === task.role) continue
1255
+ const pending = P.board.tasks.find((t) => t.role === c.owner && (t.status === 'waiting' || t.status === 'ready'))
1256
+ if (!pending) continue
1257
+ const line = `The critic, on ${task.id}: ${c.what} (where: ${c.where}; why: ${c.why}). Fix: ${c.fix}`
1258
+ const notes = (P.notes[pending.id] ??= [])
1259
+ if (!notes.includes(line)) notes.push(line)
1260
+ }
1261
+ }
1262
+
1263
+ /** The compare flags of a task's gate that are another role's work: a
1264
+ * note on that role's next task, with the numbers (the critic has them
1265
+ * as evidence already). */
1266
+ function routeFlags(task, g) {
1267
+ for (const { flag, owner } of g.outOfScope ?? []) {
1268
+ const pending = P.board.tasks.find((t) => t.role === owner && t.id !== task.id && (t.status === 'waiting' || t.status === 'ready'))
1269
+ if (!pending) continue
1270
+ const m = g.metrics
1271
+ const measure = flag === 'detail-far' || flag === 'structure-far' ? `edges x${m?.structure?.edgeRatio}, L* layout correlation ${m?.structure?.correlation}` : `palette deltaE ${m?.colour?.paletteDeltaE}, mean L* ${m?.colour?.deltaMeanL} against it`
1272
+ const line = `The pixel compare of ${task.id} at the ${m?.camera} camera raises ${flag} (${measure}), which is about the ${owner}'s work, not ${task.id}'s: yours to answer where your task can.`
1273
+ const notes = (P.notes[pending.id] ??= [])
1274
+ if (!notes.includes(line)) notes.push(line)
1275
+ }
1276
+ }
1277
+
1278
+ // ---- the director's notes, between rounds
1279
+
1280
+ const notesLock = createMutex()
1281
+ const sizeText = (m) => Object.entries(m ?? {}).map(([k, v]) => `${k} ${v} m`).join(', ') || 'no size'
1282
+
1283
+ /**
1284
+ * One change of the brief a review asked for: a subject as it should be
1285
+ * and the size of a form. It is kept only when the brief then holds to
1286
+ * the picture's measures no worse (readingErrors: no error it did not
1287
+ * have, and no more of them); then brief.md says it, every task still to
1288
+ * run hears of it, and every modeller task still to run takes the form's
1289
+ * new size in its asset check where it took the old one, as its next
1290
+ * round begins (resize). The line that says what changed, or null.
1291
+ */
1292
+ async function amendBrief(a, note) {
1293
+ const next = structuredClone(P.brief)
1294
+ const said = []
1295
+ if (a.form) {
1296
+ const form = (next.forms?.scale ?? []).find((f) => f.element === a.form.element)
1297
+ const size = Object.fromEntries(Object.entries(a.form.sizeM ?? {}).filter(([, v]) => Number(v) > 0))
1298
+ if (!form || !Object.keys(size).length) return null
1299
+ const was = { ...form.sizeM }
1300
+ form.sizeM = { ...form.sizeM, ...size }
1301
+ said.push(`"${form.element}" is ${sizeText(form.sizeM)}, not ${sizeText(was)}`)
1302
+ }
1303
+ if (a.subject) {
1304
+ const parsed = Subject.safeParse(a.subject)
1305
+ if (!parsed.success) return null
1306
+ const at = (next.subjects ?? []).findIndex((x) => x.id === parsed.data.id)
1307
+ next.subjects = at >= 0 ? next.subjects.map((x, i) => (i === at ? parsed.data : x)) : [...(next.subjects ?? []), parsed.data]
1308
+ said.push(`${at >= 0 ? 'the subject' : 'a new subject'} ${parsed.data.id} is ${parsed.data.what} at ${boxText(parsed.data.box)}${parsed.data.form ? `, sized by "${parsed.data.form}"` : ''}`)
1309
+ }
1310
+ if (!said.length) return null
1311
+ const before = readingErrors(P.brief, P.factsMain)
1312
+ const after = readingErrors(next, P.factsMain)
1313
+ const had = new Set(before.map((e) => e.key))
1314
+ if (after.length > before.length || after.some((e) => !had.has(e.key))) return null
1315
+ const old = (P.brief.forms?.scale ?? []).find((f) => f.element === a.form?.element)?.sizeM ?? null
1316
+ P.brief = settleBrief(next, P.factsMain)
1317
+ const line = `${said.join('; ')} (${a.why}; from ${note.from})`
1318
+ P.briefChanges.push(line)
1319
+ // The asset checks planned from the form's old size follow it, from
1320
+ // the next round of each modeller task (one running now is judged on
1321
+ // the size its session was told).
1322
+ const size = a.form ? (P.brief.forms.scale.find((f) => f.element === a.form.element)?.sizeM ?? null) : null
1323
+ if (old && size) for (const t of P.board.tasks.filter((x) => x.role === 'modeller' && !ENDED.has(x.status))) (t.resizes ??= []).push({ old, size })
1324
+ // Every task still to run hears of it (the one about to start, too: it reads its notes after this).
1325
+ for (const t of P.board.tasks.filter((x) => !ENDED.has(x.status))) (P.notes[t.id] ??= []).push(`The director changed the brief (brief.md says it now): ${line}.`)
1326
+ await store.writeJson('brief.json', P.brief)
1327
+ await fsp.writeFile(path.join(projectRoot, 'brief.md'), renderBrief(P.brief, P.vision))
1328
+ await store.append({ type: 'brief-amend', note: note.line, change: said, why: a.why })
1329
+ return line
1330
+ }
1331
+
1332
+ /** A task's asset checks as its round begins: each that took a form's
1333
+ * old size takes the new one the brief changed to since (amendBrief),
1334
+ * with the note that tells the round so. */
1335
+ function resize(task) {
1336
+ const keys = { h: 'height', w: 'width', d: 'depth' }
1337
+ for (const { old, size } of task.resizes ?? []) {
1338
+ for (const c of (task.accept?.checks ?? []).filter((x) => x.kind === 'asset' && x.size)) {
1339
+ const given = Object.entries(keys).filter(([, name]) => c.size[name] !== undefined)
1340
+ if (!given.length || !given.every(([k, name]) => c.size[name] === old[k])) continue
1341
+ c.size = Object.fromEntries(Object.entries(keys).filter(([k]) => size[k] !== undefined).map(([k, name]) => [name, size[k]]))
1342
+ }
1343
+ }
1344
+ delete task.resizes
1345
+ }
1346
+
1347
+ /**
1348
+ * Before a round: the director's open notes reviewed in one decision
1349
+ * (NOTES_PROMPT), at most limits.noteReviews times in a production. A
1350
+ * note to amend the brief is kept only as amendBrief allows; a note
1351
+ * routed goes to its role's next task; the rest wait for the report, as
1352
+ * do the notes of a review that does not answer.
1353
+ */
1354
+ const reviewNotes = () =>
1355
+ notesLock.run(async () => {
1356
+ const open = P.directorNotes.filter((n) => n.state === 'open')
1357
+ if (!open.length || P.stopped || P.noMore || P.phase === 'final' || P.reviews >= (limits.noteReviews ?? 2)) return
1358
+ P.reviews++
1359
+ for (const n of open) n.state = 'report'
1360
+ const pending = ROLE_IDS.filter((role) => P.board.tasks.some((t) => t.role === role && (t.status === 'waiting' || t.status === 'ready')))
1361
+ const images = P.reference?.image ? [P.reference.image] : []
1362
+ const r = await decision('notes', { systemPrompt: NOTES_PROMPT, userText: notesText({ brief: P.brief, roles: pending, notes: open }), images, schema: NotesReview })
1363
+ if (!r.ok) {
1364
+ log(`[director] the review of ${open.length} note${open.length === 1 ? '' : 's'} gave no answer (${r.errors?.[0] ?? 'none'}): they go to the report`)
1365
+ return
1366
+ }
1367
+ for (const a of r.value.notes) {
1368
+ const note = open[a.note - 1]
1369
+ if (!note || note.state !== 'report') continue
1370
+ if (a.action === 'route' && a.owner) {
1371
+ const next = P.board.tasks.find((t) => t.role === a.owner && (t.status === 'waiting' || t.status === 'ready'))
1372
+ if (next) {
1373
+ ;(P.notes[next.id] ??= []).push(`${note.line} (the director: ${a.why})`)
1374
+ note.state = 'routed'
1375
+ }
1376
+ } else if (a.action === 'amend' && (await amendBrief(a, note))) note.state = 'amended'
1377
+ }
1378
+ await store.append({ type: 'notes', reviewed: open.length, states: open.map((n) => n.state) })
1379
+ })
1380
+
1381
+ /** QA's bugs: a blocker or major one becomes a fix task for its owner,
1382
+ * a minor one goes to the report. The fix task replays the QA scripts
1383
+ * that showed the bug, so it passes only when the bug is gone; with no
1384
+ * script to replay it is unverified, and the report says so. In the
1385
+ * final phase no task starts any more, so they go to the report. */
1386
+ function routeBugs(qaTask, report) {
1387
+ const failing = (report?.scripts ?? []).filter((s) => (report?.results ?? []).some((r) => r.script === s.id && r.ok === false))
1388
+ const routed = (report?.bugs ?? []).filter((b) => b.severity !== 'minor')
1389
+ for (const bug of report?.bugs ?? []) {
1390
+ const line = `${bug.title}: ${bug.actual} (expected ${bug.expected})`
1391
+ if (bug.severity === 'minor') {
1392
+ P.minorBugs.push(line)
1393
+ continue
1394
+ }
1395
+ const owner = [...P.board.tasks].reverse().find((t) => t.role === bug.owner && DONE.has(t.status) && !t.fixFor)
1396
+ if (P.phase === 'final' || !owner || P.fixTasks >= limits.qaTasks) {
1397
+ P.notDone.push(`${bug.severity} bug: ${line}`)
1398
+ continue
1399
+ }
1400
+ P.fixTasks++
1401
+ const id = nextTaskId()
1402
+ const passing = [...(owner.attempts ?? [])].reverse().find((a) => a.gate?.pass)
1403
+ // The scripts that show this bug: the one it names, any its words
1404
+ // name, or every failing one when it is the only bug to fix. A play
1405
+ // check needs the preview, so only a preview-lane owner replays them.
1406
+ const named = failing.filter((s) => s.id === bug.script || `${bug.title} ${bug.repro} ${bug.actual}`.includes(s.id))
1407
+ const scripts = laneOf(owner) !== 'preview' ? [] : named.length ? named : routed.length === 1 ? failing : []
1408
+ const replays = scripts
1409
+ .filter((s) => playParams({ steps: s.steps, frames: 0 }).ok && (s.expect ?? []).length > 0)
1410
+ .map((s) => ({ id: `qa-${s.id}`.slice(0, 40), kind: 'play', steps: s.steps, expect: s.expect }))
1411
+ const share = addTask({
1412
+ id,
1413
+ role: bug.owner,
1414
+ title: `Fix: ${bug.title}`.slice(0, 200),
1415
+ label: `${P.board.roleWords?.[bug.owner] ?? bug.owner}: ${bug.title}`.slice(0, 80),
1416
+ goal: `Fix the ${bug.severity} bug QA found. Repro: ${bug.repro} Expected: ${bug.expected}. Actual: ${bug.actual}.`.slice(0, 600),
1417
+ covers: [],
1418
+ reads: bug.files ?? [],
1419
+ owns: owner.owns,
1420
+ deps: [...new Set([qaTask.id, ...waitsFor(owner.owns, [id, owner.id])])],
1421
+ accept: { checks: [...replays, ...(owner.accept?.checks ?? []).filter((x) => x.kind !== 'compare' && !replays.some((r) => r.id === x.id))], critic: [] },
1422
+ tier: 'mid',
1423
+ roundLimit: 2,
1424
+ status: 'waiting',
1425
+ attempts: [],
1426
+ fixFor: bug.id,
1427
+ // A model fixed stands where its owner's stood, and goes in there
1428
+ // again, made the way its owner's was made last.
1429
+ ...(owner.placement ? { placement: owner.placement } : {}),
1430
+ ...(owner.method ? { method: owner.method, methods: [{ round: 1, ...owner.method }] } : {}),
1431
+ ...(replays.length ? {} : { unverified: true }),
1432
+ ...(Number.isInteger(passing?.rung) ? { startRung: passing.rung } : {}),
1433
+ })
1434
+ void store.append({ type: 'task', task: id, why: `QA bug ${bug.id} (${bug.severity})`, owner: bug.owner, replays: replays.map((r) => r.id), usd: share })
1435
+ }
1436
+ }
1437
+
1438
+ /** What the next attempt is told about the last one. The critic's
1439
+ * changes are the last judgement's (after a put back, the best's, whose
1440
+ * files these are again), and only those this task's role owns. */
1441
+ async function previousOf(task) {
1442
+ const last = task.attempts.at(-1)
1443
+ if (!last) return null
1444
+ const best = gate.bestOf(task.attempts)
1445
+ const judged = last.restored && best ? best.gate.critic : last.gate?.critic ?? [...task.attempts].reverse().find((a) => a.gate?.critic)?.gate.critic ?? null
1446
+ return {
1447
+ sessionId: last.sessionId,
1448
+ reports: task.attempts.map((a) => a.report).filter(Boolean),
1449
+ gate: last.gate,
1450
+ changes: (judged?.changes ?? []).filter((c) => c.owner === task.role),
1451
+ restored: last.restored === true,
1452
+ failures: [...(last.gate?.checks ?? []).filter((c) => !c.ok), ...(last.gate?.noReport ? [{ id: 'report', kind: 'report', text: last.gate.reportError }] : []), ...(last.gate?.criticError ? [{ id: 'critic', kind: 'critic', text: last.gate.criticError }] : [])],
1453
+ diffStat: await diffStat(projectRoot, task.owns ?? [], snapAbs(task, 1, 'before')).catch(() => ''),
1454
+ }
1455
+ }
1456
+
1457
+ /**
1458
+ * The models a task made that the game may use: each model it owns by
1459
+ * its path or checks with an asset check, that is on disk and that
1460
+ * assets.lock.json records as it is (its bytes and hash), with that
1461
+ * entry. What its report says is only a cross-check.
1462
+ * { ready: [{ rel, entry }], problems: [line] }.
1463
+ */
1464
+ async function madeModels(task, report = null) {
1465
+ const files = (await readLedgerState(projectRoot).catch(() => null))?.lock?.files ?? {}
1466
+ const ready = []
1467
+ const problems = []
1468
+ const named = [...(task.owns ?? []).filter((g) => !/[*?[{]/.test(g)), ...(task.accept?.checks ?? []).map(normalizeCheck).filter((c) => c.kind === 'asset' && c.path).map((c) => c.path)].map(relPath)
1469
+ const models = [...new Set(named)].filter((rel) => /^assets\/.+\.(glb|gltf)$/i.test(rel) && (task.owns ?? []).some((g) => matches(g, rel)))
1470
+ for (const rel of models) {
1471
+ const abs = path.join(projectRoot, rel)
1472
+ const entry = files[rel]
1473
+ if (!fs.existsSync(abs)) continue
1474
+ if (!entry) {
1475
+ problems.push(`${rel} is not in assets.lock.json: it was never exported with nw_blender or brought in with asset_import`)
1476
+ continue
1477
+ }
1478
+ const sha = await sha256File(abs).catch(() => null)
1479
+ if (sha !== entry.sha256) {
1480
+ problems.push(`${rel} is not the file assets.lock.json records (it changed after it was exported)`)
1481
+ continue
1482
+ }
1483
+ ready.push({ rel, entry })
1484
+ }
1485
+ for (const a of report?.assets ?? []) {
1486
+ const rel = relPath(a.path)
1487
+ if (!ready.some((r) => r.rel === rel)) problems.push(`its report gives ${rel}, which is not a model it owns that assets.lock.json records as it is`)
1488
+ }
1489
+ return { ready, problems }
1490
+ }
1491
+
1492
+ /** A task whose work is now in the game: its seam is its module, and
1493
+ * what it made is ready for the others (a model once assets.lock.json
1494
+ * records it as it is). */
1495
+ async function accept(task, attempt, inf) {
1496
+ if (inf) {
1497
+ await flipSeam(projectRoot, inf)
1498
+ if (!P.ready.some((r) => r.path === inf.module)) P.ready.push({ path: inf.module, kind: inf.kind })
1499
+ }
1500
+ if (task.role !== 'modeller' && !(attempt?.report?.assets ?? []).length) return
1501
+ const { ready, problems } = await madeModels(task, attempt?.report)
1502
+ for (const line of problems) P.notDone.push(`${task.id}: ${line}, so no other task was given it`)
1503
+ for (const { rel, entry } of ready) {
1504
+ const r = { path: rel, kind: `asset:${entry.meta?.class ?? 'model'}`, ...(task.placement ? { placement: task.placement } : {}) }
1505
+ P.ready = [...P.ready.filter((x) => x.path !== rel), r]
1506
+ }
1507
+ }
1508
+
1509
+ /** The task's files and look keys as they were before its first round
1510
+ * (and its seam a stub), when that snapshot is there. */
1511
+ async function putBackBefore(task, inf, flips) {
1512
+ const before = snapAbs(task, 1, 'before')
1513
+ if (fs.existsSync(path.join(before, 'manifest.json'))) await restore(projectRoot, task.owns ?? [], before, { look: lookMode(task, roles) })
1514
+ if (flips) await stubSeam(projectRoot, inf)
1515
+ }
1516
+
1517
+ /** The board says the director is looking at the game itself, and
1518
+ * under which name its pictures are saved (null: no longer). */
1519
+ const lookingAs = (looking) => {
1520
+ P.looking = looking
1521
+ sendBoardNow()
1522
+ }
1523
+
1524
+ /**
1525
+ * The game with a task's own work taken out, measured: its files and
1526
+ * look keys as before its first round and its seam a stub, built,
1527
+ * `measure()`d (its pictures saved as `tag`), then everything put back
1528
+ * as it was and built again. The task's lane holds the preview. null
1529
+ * when there is no before to go back to, or the game without the work
1530
+ * does not build.
1531
+ */
1532
+ async function withoutWork(task, round, measure, tag) {
1533
+ const before = snapAbs(task, 1, 'before')
1534
+ if (!fs.existsSync(path.join(before, 'manifest.json')) || P.stopped) return null
1535
+ const inf = interfaceOf(task)
1536
+ const flipped = !!inf && laneOf(task) === 'preview' && isFlipped(projectRoot, inf)
1537
+ const look = lookMode(task, roles)
1538
+ const hold = store.abs(path.join('snap', task.id, `r${round}`, 'held'))
1539
+ await snapshot(projectRoot, task.owns ?? [], hold, { look })
1540
+ lookingAs({ task: task.id, why: 'without', tag })
1541
+ try {
1542
+ await restore(projectRoot, task.owns ?? [], before, { look })
1543
+ if (flipped) await stubSeam(projectRoot, inf)
1544
+ const built = await wrappedRpc('build', {}, 120_000).catch(() => null)
1545
+ if (!built?.ok) return null
1546
+ return (await measure()) ?? null
1547
+ } finally {
1548
+ await restore(projectRoot, task.owns ?? [], hold, { look })
1549
+ if (flipped) await flipSeam(projectRoot, inf)
1550
+ await wrappedRpc('build', {}, 120_000).catch(() => null)
1551
+ lookingAs(null)
1552
+ }
1553
+ }
1554
+
1555
+ /**
1556
+ * Whether a task's best attempt measures at least as close to the
1557
+ * reference as the game without its work (its stub state): the module
1558
+ * and its look keys are one state, kept or taken out together. Only
1559
+ * work that reaches the game through the director measures (an
1560
+ * artist's, an interface's producer's), in the preview lane with a
1561
+ * compare check: a builder's work is what the tasks after it stand on,
1562
+ * so the pixels never take it out. The stub state wins only by more
1563
+ * than the noise between two renders.
1564
+ */
1565
+ async function betterThanStub(task, best) {
1566
+ const check = (task.accept?.checks ?? []).map(normalizeCheck).find((c) => c.kind === 'compare')
1567
+ const kept = best?.gate?.metrics
1568
+ if (!check || !kept || !P.reference || !throughSeam(task) || laneOf(task) !== 'preview' || P.stopped) return true
1569
+ // The task runs in the preview lane, which it holds already.
1570
+ const stub = await withoutWork(task, best.round, () => gate.compare(task, best.round, check.camera, `${task.id}-stub`).then((r) => r.metrics), `${task.id}-stub`)
1571
+ if (!stub) return true
1572
+ const noise = policy?.rules?.stagnantDistance ?? 0.02
1573
+ const better = !(stub.distance < kept.distance - noise)
1574
+ await store.append({ type: 'stub-state', task: task.id, round: best.round, camera: check.camera, kept: kept.distance, stub: stub.distance, better })
1575
+ if (!better) P.notDone.push(`${task.id} ${task.title}: its best round (${best.round}) measured further from the reference at ${check.camera} than the game without it (distance ${kept.distance} against ${stub.distance}), so its work was taken out`)
1576
+ return better
1577
+ }
1578
+
1579
+ /**
1580
+ * The files of a task that ends without a pass: its best attempt whose
1581
+ * tool checks passed is put back, its seam its module, and (for work
1582
+ * through the director the pixels can judge) only while it measures no
1583
+ * worse than the game without it. With none, `revert` takes its work
1584
+ * out as one: its files, its look keys and its seam as before it began
1585
+ * (a Stop leaves them as they are, for a resume). Returns the attempt
1586
+ * kept, or null.
1587
+ */
1588
+ async function keepBest(task, inf, flips, { revert = true } = {}) {
1589
+ let best = gate.bestOf(task.attempts) ?? [...task.attempts].reverse().find(toolsPassed) ?? null
1590
+ if (best) {
1591
+ await putBack(task, best.round)
1592
+ if (flips) await (moduleThere(inf) ? flipSeam(projectRoot, inf) : stubSeam(projectRoot, inf))
1593
+ if (revert && !(await betterThanStub(task, best))) best = null
1594
+ }
1595
+ if (!best && revert) await putBackBefore(task, inf, flips)
1596
+ else if (!best && flips) await stubSeam(projectRoot, inf)
1597
+ return best
1598
+ }
1599
+
1600
+ /** A polish attempt that did not pass: the task's files as it passed,
1601
+ * or as it was kept below the bar. */
1602
+ async function unpolish(task, record = null) {
1603
+ const earlier = task.attempts.filter((a) => a !== record)
1604
+ const passing = [...earlier].reverse().find((a) => a.gate?.pass) ?? (task.belowBar ? (earlier.find((a) => a.round === task.keptRound) ?? gate.bestOf(earlier)) : null)
1605
+ if (passing) await putBack(task, passing.round)
1606
+ }
1607
+
1608
+ /** A Stop: the task's files go back to its best and it waits for a
1609
+ * resume; a task stopped in its polish stays as it ended before it. */
1610
+ async function stopTask(task, inf, flips, polish) {
1611
+ if (polish) {
1612
+ await unpolish(task)
1613
+ task.status = task.belowBar ? 'kept' : 'passed'
1614
+ return
1615
+ }
1616
+ await keepBest(task, inf, flips, { revert: false })
1617
+ task.status = 'stopped'
1618
+ }
1619
+
1620
+ /** How a task ends with no round to pass in (out of rounds, the
1621
+ * attempt limit, the time, a refused card): a task the critic judges
1622
+ * whose best attempt passed its tool checks is kept below the critic's
1623
+ * bar, its work in the game, so the tasks after it go on and the
1624
+ * polish can still pick it; any other ends as `otherwise`, a failed
1625
+ * one with its work taken out. */
1626
+ async function settle(task, inf, flips, otherwise) {
1627
+ if (task.attempts.some((a) => a.gate?.pass) || task.belowBar) {
1628
+ task.status = task.attempts.some((a) => a.gate?.pass) ? 'passed' : 'kept'
1629
+ return
1630
+ }
1631
+ const best = await keepBest(task, inf, flips, { revert: otherwise === 'failed' })
1632
+ if (best && toolsPassed(best) && (task.accept?.critic ?? []).length > 0) {
1633
+ task.status = 'kept'
1634
+ task.belowBar = true
1635
+ task.keptRound = best.round
1636
+ const charged = best.gate.metrics ? { ...best.gate.metrics, flags: best.gate.charged ?? best.gate.metrics.flags } : null
1637
+ const why = best.gate.critic && typeof critic?.whyNot === 'function' ? critic.whyNot(best.gate.critic, charged, task).join(' ') : (best.gate.criticError ?? 'the critic did not pass it')
1638
+ P.notDone.push(`${task.id} ${task.title} is below the critic's bar: ${why}`.slice(0, 600))
1639
+ await store.append({ type: 'below-bar', task: task.id, round: best.round })
1640
+ await accept(task, best, inf)
1641
+ return
1642
+ }
1643
+ task.status = otherwise
1644
+ }
1645
+
1646
+ // ---- the placements
1647
+
1648
+ /** The game as it is now, for a placement's change: built, run, seen at
1649
+ * the brief's cameras and, with a reference picture, compared at its
1650
+ * camera. The caller holds the preview. */
1651
+ async function lookAtGame(tag) {
1652
+ const cams = P.brief?.cameras ?? []
1653
+ const ref = cams.find((c) => c.purpose === 'reference')?.id ?? null
1654
+ const checks = [
1655
+ { id: 'build', kind: 'build' },
1656
+ { id: 'runtime', kind: 'runtime' },
1657
+ { id: 'view', kind: 'view', cameras: cams.map((c) => c.id) },
1658
+ ...(ref && P.reference ? [{ id: 'compare', kind: 'compare', camera: ref }] : []),
1659
+ ]
1660
+ const placements = { id: 'placements', role: 'director', title: 'The placements', goal: '', owns: [], accept: { checks, critic: [] } }
1661
+ const out = await gate.runChecks(placements, 1, { tag, checks, holdsPreview: true })
1662
+ const of = (id) => out.find((c) => c.id === id) ?? null
1663
+ return { build: of('build'), runtime: of('runtime'), view: of('view'), metrics: of('compare')?.metrics ?? null, shots: out.flatMap((c) => (c.pictures ?? []).filter((x) => x.path).map((x) => x.path)) }
1664
+ }
1665
+
1666
+ /** Why the game measures worse with a change than before it, or null:
1667
+ * it no longer builds or runs clean, the preview froze, or the
1668
+ * reference camera raised a gross flag or moved further from the
1669
+ * reference than two renders of one game differ. */
1670
+ function worseWith(before, after) {
1671
+ if (before.build?.ok !== false && after.build?.ok === false) return `the game no longer builds (${after.build.text})`
1672
+ if (before.runtime?.ok !== false && after.runtime?.ok === false) return `the game no longer runs clean (${after.runtime.text})`
1673
+ if (!/frozen/.test(before.view?.text ?? '') && /frozen/.test(after.view?.text ?? '')) return after.view.text
1674
+ if (before.metrics && after.metrics) {
1675
+ const raised = after.metrics.flags.filter((f) => GROSS_FLAGS.includes(f) && !before.metrics.flags.includes(f))
1676
+ if (raised.length) return `the ${after.metrics.camera} camera raises ${raised.join(', ')} with it`
1677
+ const noise = policy?.rules?.stagnantDistance ?? 0.02
1678
+ if (after.metrics.distance > before.metrics.distance + noise) return `the ${after.metrics.camera} camera is further from the reference with it (distance ${before.metrics.distance} to ${after.metrics.distance})`
1679
+ }
1680
+ return null
1681
+ }
1682
+
1683
+ /**
1684
+ * A modeller task that ended with its model in hand (passed or kept):
1685
+ * the director puts the model in at its placement through the
1686
+ * placements seam, where the stand-in stood, at the size the file has
1687
+ * (its anchor measured from the file, its real size from the ledger's
1688
+ * record), never from what a report says; then looks at the game again
1689
+ * at the brief's cameras. The model stays unless the game measures
1690
+ * worse with it, and then the placement shows what it showed before
1691
+ * and that file is not tried there again. The caller holds the preview.
1692
+ */
1693
+ async function putInPlace(task) {
1694
+ const placement = placementsOf(P.board).find((p) => p.id === task.placement)
1695
+ if (!placement || !DONE.has(task.status) || P.stopped) return
1696
+ // A look again (a resume, a polish) says what it found once.
1697
+ const note = (line) => {
1698
+ if (!P.notDone.includes(line)) P.notDone.push(line)
1699
+ }
1700
+ const { ready } = await madeModels(task)
1701
+ const model = ready[0]
1702
+ if (!model) {
1703
+ note(`${task.id}: no model of it is in assets.lock.json as it is on disk, so the placement ${placement.id} keeps its stand-in`)
1704
+ return
1705
+ }
1706
+ const anchor = placement.anchor ?? 'base'
1707
+ const a = await anchorOf(projectRoot, model.rel, anchor)
1708
+ if (a.error) {
1709
+ note(`${task.id}: ${a.error}, so the placement ${placement.id} keeps its stand-in`)
1710
+ return
1711
+ }
1712
+ const was = P.placed[placement.id] ?? null
1713
+ const isThis = (x) => !!x && x.sha256 === model.entry.sha256 && x.anchor === anchor
1714
+ // In already, or this very file measured worse there already.
1715
+ if (isThis(was) || isThis(P.takenOut[placement.id])) return
1716
+ const m = model.entry.meta?.size_m
1717
+ const size = m && [m.width, m.height, m.depth].every((n) => Number(n) > 0) ? [m.width, m.height, m.depth] : a.size
1718
+ // The ledger measured it when it was made; the file is what the game loads.
1719
+ const off = size.some((n, i) => Math.abs(n - a.size[i]) > Math.max(0.05 * n, 0.01))
1720
+ if (off) note(`${task.id}: assets.lock.json measures ${model.rel} at ${size.map((n) => n.toFixed(2)).join(' x ')} m, the file at ${a.size.map((n) => n.toFixed(2)).join(' x ')} m; the game shows the file`)
1721
+ const tag = `placed-${placement.id}-${task.id}-r${task.attempts.length}`
1722
+ lookingAs({ task: task.id, why: 'placement', placement: placement.id, tag: `${tag}-before` })
1723
+ const before = await lookAtGame(`${tag}-before`)
1724
+ const next = { asset: model.rel, at: a.at, anchor, task: task.id, size: a.size, sha256: model.entry.sha256 }
1725
+ P.placed = { ...P.placed, [placement.id]: next }
1726
+ await writePlacements(projectRoot, placementsOf(P.board), P.placed)
1727
+ lookingAs({ task: task.id, why: 'placement', placement: placement.id, tag })
1728
+ const after = await lookAtGame(tag)
1729
+ lookingAs(null)
1730
+ const worse = P.stopped ? 'the production stopped while it was being looked at' : worseWith(before, after)
1731
+ const out = { ...P.takenOut }
1732
+ if (worse) {
1733
+ const back = { ...P.placed }
1734
+ if (was) back[placement.id] = was
1735
+ else delete back[placement.id]
1736
+ P.placed = back
1737
+ await writePlacements(projectRoot, placementsOf(P.board), P.placed)
1738
+ await wrappedRpc('build', {}, 120_000).catch(() => null)
1739
+ P.notDone.push(`${task.id}: ${model.rel} was put in at the placement ${placement.id} and taken out again: ${worse}`)
1740
+ // A Stop measured nothing: a resume looks at it again.
1741
+ if (!P.stopped) out[placement.id] = { asset: model.rel, anchor, task: task.id, sha256: model.entry.sha256, why: worse }
1742
+ } else delete out[placement.id]
1743
+ P.takenOut = out
1744
+ log(`[director] ${task.id}: ${model.rel} ${worse ? `taken out of the placement ${placement.id} again (${worse})` : `in at the placement ${placement.id}${after.view?.ok ? '' : `, not seen in the game (${after.view?.text ?? 'no pictures'})`}`}`)
1745
+ await store.append({
1746
+ type: 'placed',
1747
+ task: task.id,
1748
+ placement: placement.id,
1749
+ asset: model.rel,
1750
+ anchor,
1751
+ at: next.at,
1752
+ size: a.size,
1753
+ kept: !worse,
1754
+ ...(worse ? { why: worse } : {}),
1755
+ seen: after.view?.ok === true,
1756
+ before: before.metrics ? { distance: before.metrics.distance, flags: before.metrics.flags } : null,
1757
+ after: after.metrics ? { distance: after.metrics.distance, flags: after.metrics.flags } : null,
1758
+ shots: after.shots,
1759
+ })
1760
+ await writeProduction('running')
1761
+ sendBoard()
1762
+ }
1763
+
1764
+ // ---- how a modelled asset is made
1765
+
1766
+ /** The reference's crop of the subject a task's method starts from,
1767
+ * written beside its pictures once (methods.mjs writeCrop); its path on
1768
+ * the task for the role's message. */
1769
+ async function cropFor(task) {
1770
+ const m = task.method
1771
+ if (!usesPictures(m) || !m.subject || !P.reference?.rel) return null
1772
+ const subject = (P.brief?.subjects ?? []).find((x) => x.id === m.subject)
1773
+ if (!subject || subject.role === 'transform') return null
1774
+ const r = await writeCrop({ projectRoot, reference: P.reference, subject, dir: pictureDir(task) })
1775
+ if (r.error) {
1776
+ log(`[director] ${task.id}: the crop of ${subject.id} could not be written (${r.error})`)
1777
+ return null
1778
+ }
1779
+ task.crop = r.rel
1780
+ return r.rel
1781
+ }
1782
+
1783
+ /**
1784
+ * After a modeller round that did not pass, while a round is left: the
1785
+ * director looks at how its asset is made (one decision, at most
1786
+ * limits.methodReviews times a task, and only when another way can run
1787
+ * here) and may switch it. A switch code checks as it checks the plan's,
1788
+ * asks the cards it needs, and puts a paid one on a new cost card for
1789
+ * what is left, re-priced, before it spends; it is said on the board and
1790
+ * to the next round, which starts a fresh session. true when it switched.
1791
+ */
1792
+ async function reviewMethod(task, attempt) {
1793
+ if (!task.method || P.stopped || P.noMore || (task.methodReviews ?? 0) >= (limits.methodReviews ?? 1)) return false
1794
+ P.caps = await capabilities()
1795
+ await cropFor(task)
1796
+ const others = METHOD_IDS.filter((id) => P.caps.methods[id].state !== 'off' && (id !== task.method.how || usesPictures({ how: id })))
1797
+ if (!others.length) return false
1798
+ task.methodReviews = (task.methodReviews ?? 0) + 1
1799
+ const images = []
1800
+ if (task.crop) {
1801
+ const bytes = await fsp.readFile(path.join(projectRoot, task.crop)).catch(() => null)
1802
+ if (bytes) images.push({ mime: 'image/png', data: bytes.toString('base64') })
1803
+ }
1804
+ const sheet = attempt.gate?.pictures?.find((p) => p.camera === 'colour')?.path
1805
+ if (sheet) {
1806
+ const bytes = await fsp.readFile(path.join(projectRoot, sheet)).catch(() => null)
1807
+ if (bytes) images.push({ mime: 'image/jpeg', data: bytes.toString('base64') })
1808
+ }
1809
+ const why = attempt.gate?.critic && typeof critic?.whyNot === 'function' ? critic.whyNot(attempt.gate.critic, null, task) : []
1810
+ const tried = (task.methods ?? []).map((x) => `round ${x.round}: ${methodLine(x)}`)
1811
+ const r = await decision('method', { systemPrompt: METHOD_PROMPT, userText: methodText({ task, method: methodLine(task.method), tried, gate: attempt.gate, why, capabilities: capabilityText(P.caps) }), images, schema: MethodReview })
1812
+ if (!r.ok) {
1813
+ log(`[director] ${task.id}: the review of how it is made gave no answer (${r.errors?.[0] ?? 'none'}); it goes on as it is`)
1814
+ return false
1815
+ }
1816
+ const m = r.value.method
1817
+ const same = !!m && ['how', 'subject', 'image', 'mesh', 'file'].every((k) => (m[k] ?? null) === (task.method[k] ?? null)) && (m.views ?? 1) === (task.method.views ?? 1)
1818
+ const errors = r.value.action === 'switch' && m && !same ? methodErrors(task, m, { caps: P.caps, brief: P.brief }) : []
1819
+ await store.append({ type: 'method-review', task: task.id, round: attempt.round, action: r.value.action, why: r.value.why, ...(m ? { method: m } : {}), ...(errors.length ? { errors } : {}) })
1820
+ if (r.value.action !== 'switch' || !m || same || errors.length) {
1821
+ if (errors.length) log(`[director] ${task.id}: the switch it was given cannot run (${errors[0]}); it goes on as it is`)
1822
+ return false
1823
+ }
1824
+ // A paid way is priced again for what is left and approved first; one
1825
+ // that cannot be priced is no way to switch to.
1826
+ const ready = await readyMethod(task, m)
1827
+ if (ready.refused) {
1828
+ log(`[director] ${task.id}: no switch to ${m.how}: ${ready.refused}`)
1829
+ await store.append({ type: 'method', task: task.id, round: attempt.round + 1, from: task.method, to: null, why: ready.refused })
1830
+ return false
1831
+ }
1832
+ if (!(await approveLines(task, ready.lines))) {
1833
+ await store.append({ type: 'method', task: task.id, round: attempt.round + 1, from: task.method, to: null, why: `the creator did not approve the cost of ${m.how}` })
1834
+ return false
1835
+ }
1836
+ const was = task.method
1837
+ task.method = m
1838
+ task.methods = [...(task.methods ?? []), { round: attempt.round + 1, ...m }]
1839
+ const dir = pictureDir(task)
1840
+ if (usesPictures(m) && dir && !(task.owns ?? []).some((g) => matches(g, `${dir}/view.png`))) task.owns = [...(task.owns ?? []), `${dir}/**`]
1841
+ await cropFor(task)
1842
+ ;(P.notes[task.id] ??= []).push(`The director changed how this asset is made, from ${methodLine(was)} to ${methodLine(m)}: ${r.value.why}. Make it that way from this round.`)
1843
+ await store.append({ type: 'method', task: task.id, round: attempt.round + 1, from: was, to: m, why: r.value.why })
1844
+ await writeBoard()
1845
+ sendBoard()
1846
+ return true
1847
+ }
1848
+
1849
+ /** Every attempt of one task, until it passes or has no round left. */
1850
+ async function runTask(task, { polish = null } = {}) {
1851
+ // A follow-up or a fix made the way its owner's was made, paid, is
1852
+ // priced on a cost card before it spends: no card had its lines.
1853
+ if (task.unpriced) {
1854
+ delete task.unpriced
1855
+ const ready = await readyMethod(task, task.method)
1856
+ const refused = ready.refused ?? ((await approveLines(task, ready.lines)) ? null : `the creator did not approve the cost of ${task.method.how}`)
1857
+ if (refused) {
1858
+ void store.append({ type: 'method', task: task.id, round: task.attempts.length + 1, from: task.method, to: null, why: refused })
1859
+ task.noMethod = refused
1860
+ task.method = null
1861
+ }
1862
+ }
1863
+ // A modelled asset no way of making was allowed for ends unmade, with
1864
+ // nothing spent: its placement keeps what stands there (its stand-in,
1865
+ // or the model a follow-up was to make again).
1866
+ if (task.role === 'modeller' && task.noMethod) {
1867
+ task.status = 'failed'
1868
+ const there = task.placement ? (P.placed[task.placement]?.asset ?? 'its stand-in') : null
1869
+ P.notDone.push(`${task.id} ${task.title}: not made, since ${task.noMethod}${there ? `; the placement ${task.placement} keeps ${there}` : ''}`)
1870
+ await writeBoard()
1871
+ sendBoard()
1872
+ return
1873
+ }
1874
+ const inf = interfaceOf(task)
1875
+ const flips = !!inf && laneOf(task) === 'preview'
1876
+ const last = task.attempts.at(-1)
1877
+ // An attempt a Stop cut short measured nothing: the task goes on at
1878
+ // the same rung, in a fresh session.
1879
+ const again = last && !last.gate && Number.isInteger(last.rung) ? router.rungs.find((r) => r.rung === last.rung) : null
1880
+ let pick =
1881
+ polish?.pick ??
1882
+ (again ? { ...again, resume: false, escalated: false, why: 'the attempt before was stopped' } : null) ??
1883
+ (task.attempts.length ? router.next(task) : null) ??
1884
+ (Number.isInteger(task.startRung) ? { ...(router.rungs.find((r) => r.rung === task.startRung) ?? router.rungs[0]), resume: false, escalated: false } : router.start(task, P.board))
1885
+ for (;;) {
1886
+ if (P.stopped) {
1887
+ await stopTask(task, inf, flips, polish)
1888
+ break
1889
+ }
1890
+ if (P.attempts >= limits.attempts || (timeUp() && !polish)) {
1891
+ P.noMore ??= P.attempts >= limits.attempts ? 'the attempt limit was reached' : 'the production ran out of time'
1892
+ await settle(task, inf, flips, 'failed')
1893
+ break
1894
+ }
1895
+ if (!(await reapprove(task, pick))) {
1896
+ await settle(task, inf, flips, 'waiting')
1897
+ break
1898
+ }
1899
+ // The crop its method starts from, cut again when a put back took it.
1900
+ await cropFor(task)
1901
+ task.status = 'running'
1902
+ task.live = { model: { id: pick.model.id, name: pick.model.name }, effort: pick.effort, rung: pick.rung }
1903
+ sendBoard()
1904
+ // The seam points at the module only once the module is there: a
1905
+ // seam at a missing file breaks every build, the role's own looks
1906
+ // first. The first write of the module flips it, and the gate's
1907
+ // build sees the seam as the files are.
1908
+ let flipping = null
1909
+ if (flips) await (moduleThere(inf) ? flipSeam(projectRoot, inf) : stubSeam(projectRoot, inf))
1910
+ const onWrite = flips ? (rel) => (relPath(rel) === relPath(inf.module) ? (flipping ??= flipSeam(projectRoot, inf).catch(() => {})) : null) : null
1911
+ // What came to the director since the last round, reviewed before
1912
+ // this round hears its notes.
1913
+ if (!polish) await reviewNotes()
1914
+ resize(task)
1915
+ P.attempts++
1916
+ const notes = [...(P.notes[task.id] ?? []), ...(polish?.notes ?? [])]
1917
+ delete P.notes[task.id]
1918
+ const previous = polish ? { ...(await previousOf(task)), gate: { critic: { changes: polish.changes } }, changes: polish.changes, failures: [] } : await previousOf(task)
1919
+ const { attempt, stopped } = await runAttempt(task, pick, {
1920
+ board: P.board,
1921
+ brief: P.brief,
1922
+ vision: P.vision,
1923
+ facts: P.factsMain,
1924
+ cameras: P.cameras,
1925
+ ready: P.ready,
1926
+ references: P.reference ? [P.reference.rel] : [],
1927
+ refImages: P.reference?.image ? [P.reference.image] : [],
1928
+ declinePaid: !!settings.declinePaid,
1929
+ locale,
1930
+ previous,
1931
+ notes,
1932
+ dropTools: task.noBlender ? ['nw_blender'] : [],
1933
+ onWrite,
1934
+ })
1935
+ await flipping
1936
+ if (flips) await (moduleThere(inf) ? flipSeam(projectRoot, inf) : stubSeam(projectRoot, inf))
1937
+ if (stopped || P.stopped) {
1938
+ task.attempts.push({ ...attempt, writes: [...attempt.writes], gate: null })
1939
+ await stopTask(task, inf, flips, polish)
1940
+ break
1941
+ }
1942
+ if (task.makesCameras && attempt.report?.cameras?.length) await saveCameras(attempt.report.cameras)
1943
+ task.status = 'checking'
1944
+ sendBoard()
1945
+ const g = await gate.judge(task, attempt, task.attempts)
1946
+ // A Stop during the gate measured nothing either.
1947
+ if (P.stopped) {
1948
+ task.attempts.push({ ...attempt, writes: [...attempt.writes], gate: null })
1949
+ await stopTask(task, inf, flips, polish)
1950
+ break
1951
+ }
1952
+ g.usd = attempt.usd + (ledger.sessionsOf(task.id).filter((s) => s.key === `critic:${task.id}:r${attempt.round}`).reduce((s, x) => s + x.usd, 0))
1953
+ await snap(task, attempt.round)
1954
+ const record = { ...attempt, writes: [...attempt.writes], gate: g }
1955
+ task.attempts.push(record)
1956
+ delete task.live
1957
+ await store.append({ type: 'attempt', task: task.id, round: attempt.round, rung: attempt.rung, model: attempt.model, effort: attempt.effort, resumed: attempt.resumed, sessionId: attempt.sessionId, usd: attempt.usd, turns: attempt.turns, report: attempt.report ? { summary: attempt.report.summary } : null, failure: attempt.failure ?? null, why: attempt.why })
1958
+ await store.append({ type: 'gate', task: task.id, round: attempt.round, pass: g.pass, progress: g.progress, best: g.best, checks: g.checks.map((c) => ({ id: c.id, kind: c.kind, ok: c.ok, text: c.text })), scores: g.critic ? { ...g.critic.scores, overall: g.critic.overall } : null, pairwise: g.critic?.pairwise ?? null, distance: g.metrics?.distance ?? null, usd: g.usd })
1959
+ // The board's picture of a task: its best judged attempt, or for a
1960
+ // task the critic does not judge, the attempt that passed.
1961
+ if (g.best || (g.pass && !g.critic)) await writeThumb(task, g)
1962
+ routeChanges(task, attempt.report)
1963
+ routeCritic(task, g)
1964
+ routeFlags(task, g)
1965
+ sendCost()
1966
+ if (g.pass) {
1967
+ task.status = 'passed'
1968
+ // A polish that lifted a kept task over the bar takes back its line.
1969
+ if (task.belowBar) P.notDone = P.notDone.filter((l) => !l.startsWith(`${task.id} ${task.title} is below the critic's bar`))
1970
+ delete task.belowBar
1971
+ delete task.keptRound
1972
+ await accept(task, attempt, inf)
1973
+ if (task.role === 'qa') routeBugs(task, attempt.report)
1974
+ break
1975
+ }
1976
+ if (polish) {
1977
+ // A polish attempt that does not pass leaves the task as it ended.
1978
+ await unpolish(task, record)
1979
+ if (flips) await (moduleThere(inf) ? flipSeam(projectRoot, inf) : stubSeam(projectRoot, inf))
1980
+ task.status = task.belowBar ? 'kept' : 'passed'
1981
+ break
1982
+ }
1983
+ if (g.restore) {
1984
+ const best = gate.bestOf(task.attempts)
1985
+ if (best) {
1986
+ const changed = await putBack(task, best.round)
1987
+ record.restored = true
1988
+ await store.append({ type: 'restore', task: task.id, round: attempt.round, to: best.round, files: changed })
1989
+ if (flips) await (moduleThere(inf) ? flipSeam(projectRoot, inf) : stubSeam(projectRoot, inf))
1990
+ }
1991
+ }
1992
+ const next = router.next(task)
1993
+ if (!next) {
1994
+ await settle(task, inf, flips, 'failed')
1995
+ break
1996
+ }
1997
+ // How a modelled asset is made may change before its next round.
1998
+ if (task.role === 'modeller' && !g.pass && (await reviewMethod(task, record))) next.resume = false
1999
+ if (Number.isInteger(next.rung) && Number.isInteger(attempt.rung) && next.rung > attempt.rung) {
2000
+ await store.append({ type: 'escalation', task: task.id, from: { rung: attempt.rung, model: attempt.model, effort: attempt.effort }, to: { rung: next.rung, model: next.model.id, effort: next.effort }, why: next.why })
2001
+ }
2002
+ pick = next
2003
+ }
2004
+ delete task.live
2005
+ await writeBoard()
2006
+ sendBoard()
2007
+ }
2008
+
2009
+ /** A modeller task whose model is in hand goes in at its placement, in
2010
+ * the preview lane, once its own lane let it go; `placing` holds the
2011
+ * work until it is done. */
2012
+ const placing = new Set()
2013
+ function placeWhenDone(task) {
2014
+ if (task.role !== 'modeller' || !task.placement || !DONE.has(task.status)) return
2015
+ const work = lanes.preview.run(() => putInPlace(task)).catch((err) => log(`[director] ${task.id}: its placement failed in the director: ${err?.stack ?? err}`))
2016
+ placing.add(work)
2017
+ void work.finally(() => placing.delete(work))
2018
+ }
2019
+
2020
+ /** Every task a dependency it needs now keeps from starting, and the
2021
+ * ones those keep in turn. */
2022
+ function markBlocked() {
2023
+ for (let blocked = blockedTasks(P.board); blocked.length; blocked = blockedTasks(P.board)) {
2024
+ for (const t of blocked) {
2025
+ t.status = 'blocked'
2026
+ void store.append({ type: 'task', task: t.id, status: 'blocked', by: blockersOf(P.board, t) })
2027
+ }
2028
+ }
2029
+ }
2030
+
2031
+ async function dispatch() {
2032
+ await setPhase('build')
2033
+ // A resume: the models of tasks that ended before it go in first, if
2034
+ // a Stop kept them out of their placements (one already in, or one
2035
+ // that measured worse there, is left as it is).
2036
+ for (const t of P.board.tasks) placeWhenDone(t)
2037
+ const active = new Map()
2038
+ const busy = { preview: false, blender: false, free: false }
2039
+ for (;;) {
2040
+ if (P.stopped) break
2041
+ markBlocked()
2042
+ if (!P.noMore) {
2043
+ for (const t of readyTasks(P.board)) {
2044
+ if (active.has(t.id) || active.size >= limits.maxSessions) continue
2045
+ const lane = laneOf(t)
2046
+ if (busy[lane]) continue
2047
+ busy[lane] = true
2048
+ t.status = 'ready'
2049
+ const work = lanes[lane]
2050
+ .run(() => runTask(t))
2051
+ .catch((err) => {
2052
+ log(`[director] ${t.id} failed in the director: ${err?.stack ?? err}`)
2053
+ t.status = 'failed'
2054
+ })
2055
+ .then(() => placeWhenDone(t))
2056
+ active.set(
2057
+ t.id,
2058
+ work.finally(() => {
2059
+ busy[lane] = false
2060
+ active.delete(t.id)
2061
+ }),
2062
+ )
2063
+ }
2064
+ }
2065
+ if (active.size === 0) break
2066
+ await Promise.race(active.values())
2067
+ }
2068
+ await Promise.allSettled([...active.values()])
2069
+ await Promise.allSettled([...placing])
2070
+ if (!P.stopped) markBlocked()
2071
+ // What never got to start: its dependency failed, or the production stopped starting work.
2072
+ for (const t of P.board.tasks) if (t.status === 'waiting' || t.status === 'ready') t.status = P.stopped ? 'stopped' : 'skipped'
2073
+ await writeBoard()
2074
+ }
2075
+
2076
+ // ---- FINAL
2077
+
2078
+ async function finalPhase() {
2079
+ await setPhase('final')
2080
+ const qaTasks = P.board.tasks.filter((t) => t.role === 'qa')
2081
+ const fixes = P.board.tasks.filter((t) => t.fixFor)
2082
+ const qaOk = qaTasks.every((t) => t.status === 'passed') && fixes.every((t) => t.status === 'passed')
2083
+ // A fix no replayed QA script judged passed its owner's checks only.
2084
+ const unverified = fixes.filter((t) => t.unverified).length
2085
+ const qa = qaTasks.length
2086
+ ? { ok: qaOk, text: qaOk ? `QA passed${fixes.length ? `, and its ${fixes.length} fix task${fixes.length === 1 ? '' : 's'} passed${unverified ? ` (${unverified} on its owner's checks only: no QA script replays the bug)` : ', each replaying the QA script that showed its bug'}` : ''}.` : 'QA or one of its fix tasks did not pass.' }
2087
+ : null
2088
+ // After the creator said no to more spend, only the free tool checks run.
2089
+ const judged = P.noMore !== DECLINED
2090
+ let g = await gate.final(1, { qa, critic: judged })
2091
+ await store.append({ type: 'final', round: 1, pass: g.pass, checks: g.checks.map((c) => ({ id: c.id, kind: c.kind, ok: c.ok, text: c.text })), scores: g.critic ? { ...g.critic.scores, overall: g.critic.overall } : null })
2092
+ if (!g.pass && g.critic && limits.polishCycles > 0 && !P.stopped && !P.noMore && !timeUp()) {
2093
+ const before = P.attempts
2094
+ // The director's changes are the brief's, never a polish: no round is left to review them in.
2095
+ const owners = [...new Set(g.critic.changes.map((c) => c.owner))].filter((o) => o !== 'director').slice(0, 3)
2096
+ for (const owner of owners) {
2097
+ if (P.stopped || P.noMore) break
2098
+ const task = [...P.board.tasks].reverse().find((t) => t.role === owner && DONE.has(t.status))
2099
+ if (!task) continue
2100
+ const last = task.attempts.at(-1)
2101
+ const pick = router.rungs.find((r) => r.rung === last?.rung) ?? router.start(task, P.board)
2102
+ task.roundLimit += 1
2103
+ await lanes[laneOf(task)].run(() => runTask(task, { polish: { pick: { ...pick, resume: false }, changes: g.critic.changes.filter((c) => c.owner === owner), notes: [] } }))
2104
+ // A polished model goes in at its placement again.
2105
+ placeWhenDone(task)
2106
+ await Promise.allSettled([...placing])
2107
+ }
2108
+ // The whole game again only when a polish attempt changed it.
2109
+ if (P.attempts > before && !P.stopped) {
2110
+ g = await gate.final(2, { qa, critic: P.noMore !== DECLINED })
2111
+ await store.append({ type: 'final', round: 2, pass: g.pass, checks: g.checks.map((c) => ({ id: c.id, kind: c.kind, ok: c.ok, text: c.text })), scores: g.critic ? { ...g.critic.scores, overall: g.critic.overall } : null })
2112
+ }
2113
+ }
2114
+ P.final = g
2115
+ // The final critic's word that the brief contradicts the reference goes to the report as not done.
2116
+ for (const c of g.critic?.changes ?? []) if (c.owner === 'director') noteForDirector(contradiction(c, 'the final gate'), 'final')
2117
+ }
2118
+
2119
+ // ---- DELIVER
2120
+
2121
+ /** The backstop of the write guard: every file that changed since the
2122
+ * production began lies in a task's files, the director's or the
2123
+ * tools'; anything else is named in the report. */
2124
+ async function strays() {
2125
+ const nowStats = await projectStats(projectRoot)
2126
+ const changed = [...new Set([...nowStats.keys(), ...startStats.keys()])].filter((rel) => nowStats.get(rel) !== startStats.get(rel))
2127
+ const owned = (rel) => isDirectorFile(rel) || TOOL_FILES.includes(rel) || (P.board?.tasks ?? []).some((t) => (t.owns ?? []).some((g) => matches(g, rel)))
2128
+ return changed.filter((rel) => !owned(rel)).sort()
2129
+ }
2130
+
2131
+ async function deliver({ status, why = null }) {
2132
+ if (P.phase !== 'stopped') await setPhase(status === 'stopped' ? 'stopped' : 'deliver')
2133
+ const probesBack = await prodGate.revertProbes().catch(() => [])
2134
+ const outside = await strays()
2135
+ if (outside.length) {
2136
+ P.notDone.push(`files changed outside every task's own: ${outside.slice(0, 12).join(', ')}${outside.length > 12 ? `, and ${outside.length - 12} more` : ''}`)
2137
+ await store.append({ type: 'strays', files: outside })
2138
+ }
2139
+ const b = ledger.breakdown()
2140
+ const tasks = P.board?.tasks ?? []
2141
+ const passed = tasks.filter((t) => t.status === 'passed')
2142
+ const kept = tasks.filter((t) => t.status === 'kept')
2143
+ const failed = tasks.filter((t) => ['failed', 'blocked', 'skipped', 'stopped'].includes(t.status))
2144
+ const finalChecks = P.final?.checks ?? []
2145
+ const ok = (id) => finalChecks.find((c) => c.id === id)?.ok === true
2146
+ const runs = ok('build') && ok('runtime')
2147
+ const verified = { check: ok('build'), view: ok('cameras') || ok('moments') }
2148
+ // A task's score is the one of the attempt whose work is in the game.
2149
+ const inGame = (t) => [...t.attempts].reverse().find((a) => a.gate?.pass) ?? t.attempts.find((a) => a.round === t.keptRound) ?? gate.bestOf(t.attempts) ?? t.attempts.at(-1)
2150
+ const scoreOf = (t) => (inGame(t)?.gate?.critic ? `, critic ${inGame(t).gate.critic.overall}/5` : '')
2151
+ const placedLines = Object.entries(P.placed).map(([id, m]) => `${m.asset} (${m.task}) is in the game at the placement ${id}`)
2152
+ const input = {
2153
+ languageName: replyName,
2154
+ request: request.text ?? msg.text ?? '',
2155
+ verified: [
2156
+ ...finalChecks.filter((c) => c.ok).map((c) => `${c.id}: ${c.text}`),
2157
+ ...passed.map((t) => `${t.id} ${t.title}: passed in round ${inGame(t)?.round ?? t.attempts.length}${scoreOf(t)}${t.unverified ? ', on its owner\'s checks only (no QA script replays the bug)' : ''}`),
2158
+ ...placedLines,
2159
+ ],
2160
+ kept: kept.map((t) => `${t.id} ${t.title}: kept below the critic's bar after ${t.attempts.length} rounds, its round ${inGame(t)?.round ?? '?'} in the game${scoreOf(t)}`),
2161
+ assumed: [
2162
+ ...(P.brief?.assumptions ?? []).map((a) => `${a.what} (${a.why})`),
2163
+ ...(P.vision?.additions ?? []).map((a) => `added: ${a.what} (${a.why})`),
2164
+ ...P.briefChanges.map((l) => `the director changed the brief: ${l}`),
2165
+ // How each modelled asset was made, and where the way changed.
2166
+ ...tasks
2167
+ .filter((t) => t.role === 'modeller')
2168
+ .map((t) => [t, (t.methods ?? []).filter((m) => m.round <= t.attempts.length)])
2169
+ .filter(([, ran]) => ran.length)
2170
+ .map(([t, ran]) => `${t.id} ${t.title}: made by ${ran.map((m) => `${methodLine(m)}${m.round > 1 ? ` from round ${m.round}` : ''}`).join(', then ')}`.slice(0, 600)),
2171
+ ],
2172
+ notDone: [
2173
+ ...(why ? [why] : []),
2174
+ ...failed.map((t) => `${t.id} ${t.title}: ${t.status}${t.status === 'blocked' && blockersOf(P.board, t).length ? ` (it needed ${blockersOf(P.board, t).join(', ')})` : ''}${t.attempts?.at(-1)?.gate ? `, ${t.attempts.at(-1).gate.checks.filter((c) => !c.ok).map((c) => c.text).join(' ').slice(0, 160)}` : ''}`),
2175
+ ...finalChecks.filter((c) => !c.ok).map((c) => `${c.id}: ${c.text}`),
2176
+ ...(P.final?.critic && !P.final.pass ? [`the whole-scene critic: ${P.final.critic.changes.slice(0, 3).map((c) => c.what).join('; ')}`] : []),
2177
+ ...P.minorBugs.map((x) => `minor bug: ${x}`),
2178
+ ...P.directorNotes.filter((n) => n.state !== 'routed' && n.state !== 'amended').map((n) => n.line),
2179
+ ...P.notDone,
2180
+ ...(P.noMore ? [`stopped starting new work: ${P.noMore}`] : []),
2181
+ ],
2182
+ visionReviewed: P.visionReviewed,
2183
+ cost: { totalUsd: ledger.spentUsd(), byModel: byModelList().map((m) => ({ model: m.name, usd: Number(m.usd.toFixed(4)) })), generationUsd: b.generationUsd },
2184
+ ...(P.cheaperUsd !== null ? { cheaperVersionUsd: Number(P.cheaperUsd.toFixed(2)) } : {}),
2185
+ }
2186
+ let report = null
2187
+ let englishWhy = null
2188
+ if (status !== 'stopped') {
2189
+ const watch = createLanguageWatch({ locale: replyLocale, languageName: replyName, writtenIn })
2190
+ let r = await decision('report', { systemPrompt: REPORT_PROMPT, userText: reportText(input), schema: ReportOutput })
2191
+ let again = r.ok ? watch.finalReason(r.value.text) : null
2192
+ if (again && !P.stopped) {
2193
+ r = await decision('report', { systemPrompt: REPORT_PROMPT, userText: `${reportText(input)}\n\n${again}`, schema: ReportOutput })
2194
+ again = r.ok ? watch.finalReason(r.value.text) : null
2195
+ if (r.ok && createLanguageWatch({ locale: replyLocale, languageName: replyName, writtenIn }).finalReason(r.value.text)) englishWhy = `the report came back twice in another language than ${replyName}`
2196
+ }
2197
+ if (r.ok && !englishWhy) report = r.value
2198
+ else englishWhy ??= `the report could not be written (${r.errors?.[0] ?? 'no answer'})`
2199
+ }
2200
+ if (!report) {
2201
+ const lines = [
2202
+ status === 'stopped' ? 'Stopped before it finished.' : `The report is in English because ${englishWhy}.`,
2203
+ input.verified.length ? `Verified: ${input.verified.slice(0, 8).join('; ')}.` : 'Nothing was verified.',
2204
+ input.kept.length ? `Kept below the bar, in the game as the best attempt there was: ${input.kept.slice(0, 8).join('; ')}.` : '',
2205
+ input.notDone.length ? `Not done: ${input.notDone.slice(0, 8).join('; ')}.` : '',
2206
+ `Cost: ${usd(input.cost.totalUsd)}.`,
2207
+ P.cheaperUsd !== null ? `A smaller version (every task on the cheapest model, one attempt each) would cost about ${usd(P.cheaperUsd)}.` : '',
2208
+ 'Ask to continue to pick it up where it stopped.',
2209
+ ].filter(Boolean)
2210
+ report = { text: lines.join(' '), verified: input.verified, assumed: input.assumed, notDone: input.notDone, english: true }
2211
+ }
2212
+ const breakdown = ledger.breakdown()
2213
+ await store.writeJson('cost.json', { ...breakdown, approvedUsd: ledger.approvedUsd(), names: Object.fromEntries(byModelList().map((m) => [m.id, m.name])) })
2214
+ await store.writeJson('report.json', { ...report, status, ...(P.cheaperUsd !== null ? { cheaperUsd: P.cheaperUsd } : {}), ...(englishWhy ? { englishWhy } : {}) })
2215
+ await store.writeText(
2216
+ 'report.md',
2217
+ [`# Production ${P.id}`, '', report.text, '', '## Verified', '', ...report.verified.map((x) => `- ${x}`), '', '## Assumed or added', '', ...report.assumed.map((x) => `- ${x}`), '', '## Not done', '', ...(report.notDone.length ? report.notDone.map((x) => `- ${x}`) : ['- nothing']), '', `Cost: ${usd(breakdown.total)}${P.cheaperUsd !== null ? `; a smaller version about ${usd(P.cheaperUsd)}` : ''}.`, ''].join('\n'),
2218
+ )
2219
+ // Done only when the whole game passed its final gate with every task's
2220
+ // work in it, each passed; a game that runs with every task in but some
2221
+ // of it below the bar (a kept task, or the final gate) is kept; one
2222
+ // with a task that failed or never ran is unfinished.
2223
+ const finished = status === 'done' && runs && !P.stopped
2224
+ const ended = P.stopped ? 'stopped' : !finished ? (status === 'failed' ? 'failed' : 'unfinished') : failed.length ? 'unfinished' : P.final?.pass && kept.length === 0 ? 'done' : 'kept'
2225
+ const outcome = { status: ended, productionId: P.id, report: report.text, verified, turns: sessions.turns }
2226
+ P.phase = P.stopped ? 'stopped' : 'done'
2227
+ await writeBoard()
2228
+ await writeProduction(outcome.status, { outcome })
2229
+ await store.settle()
2230
+ sendBoardNow()
2231
+ sendCost(true)
2232
+ send({ type: 'text', id: runId, delta: report.text })
2233
+ const team = { productionId: P.id, passed: passed.length, kept: kept.length, failed: failed.length }
2234
+ if (outcome.status === 'done') {
2235
+ send({ type: 'done', id: runId, subtype: 'success', costUsd: ledger.spentUsd(), helperUsd: 0, generationUsd: breakdown.generationUsd, turns: sessions.turns, effort: depth?.effort ?? null, verified, stopBlocks: 0, team })
2236
+ } else {
2237
+ const message = P.stopped
2238
+ ? 'Stopped before it finished.'
2239
+ : (why ??
2240
+ (ended === 'kept'
2241
+ ? "The game is made and runs, but some of it is below the critic's bar: the best attempts are kept in it."
2242
+ : failed.length && runs
2243
+ ? `The production did not finish: ${failed.map((t) => `${t.id} ${t.status}`).join(', ')}.`
2244
+ : 'The production did not finish: the game does not build and run at the end.'))
2245
+ send({
2246
+ type: 'error',
2247
+ id: runId,
2248
+ message,
2249
+ failure: P.stopped ? 'stopped' : ended === 'kept' ? 'kept' : 'other',
2250
+ unfinished: true,
2251
+ costUsd: ledger.spentUsd(),
2252
+ helperUsd: 0,
2253
+ generationUsd: breakdown.generationUsd,
2254
+ turns: sessions.turns,
2255
+ cleanup: 'skipped',
2256
+ markers: await prodGate.newMarkers().catch(() => []),
2257
+ ...(probesBack.length ? { probesBack } : {}),
2258
+ team,
2259
+ })
2260
+ }
2261
+ return outcome
2262
+ }
2263
+
2264
+ // ---- RESUME
2265
+
2266
+ async function load() {
2267
+ const record = await store.readJson('production.json')
2268
+ P.brief = await store.readJson('brief.json')
2269
+ P.vision = await store.readJson('vision.json')
2270
+ P.board = await store.readJson('board.json')
2271
+ P.cameras = await store.readJson('cameras.json')
2272
+ if (!P.brief || !P.vision || !P.board) return { ok: false, why: `The production ${P.id} cannot be resumed: its brief, vision or board is missing.` }
2273
+ if (record?.reference?.rel) {
2274
+ const bytes = await fsp.readFile(path.join(projectRoot, record.reference.rel)).catch(() => null)
2275
+ const mime = /\.png$/i.test(record.reference.rel) ? 'image/png' : /\.webp$/i.test(record.reference.rel) ? 'image/webp' : 'image/jpeg'
2276
+ P.reference = { rel: record.reference.rel, crop: record.reference.crop ?? null, image: bytes ? await fitImage({ mime, data: bytes.toString('base64') }, 1024) : null }
2277
+ const stem = path.basename(record.reference.rel).replace(/\.[^.]+$/, '')
2278
+ const full = await store.readJson(`facts/${stem}.full.json`)
2279
+ const art = await store.readJson(`facts/${stem}.art.json`)
2280
+ P.facts = full ? { full, art } : null
2281
+ P.factsMain = art ?? full ?? null
2282
+ }
2283
+ P.ready = record?.ready ?? []
2284
+ P.placed = record?.placed ?? {}
2285
+ P.takenOut = record?.takenOut ?? {}
2286
+ P.briefChanges = record?.briefChanges ?? []
2287
+ P.approvals = record?.approvals ?? []
2288
+ P.visionReviewed = record?.visionReviewed ?? null
2289
+ for (const t of P.board.tasks) {
2290
+ t.attempts ??= []
2291
+ // A board from before the kept status says passed, below the bar.
2292
+ if (t.status === 'passed' && t.belowBar) t.status = 'kept'
2293
+ if (DONE.has(t.status)) continue
2294
+ // A modelled asset left unmade for a refused card is asked again:
2295
+ // the creator may give the key, the consent or the cost now.
2296
+ if (t.noMethod) {
2297
+ const { round: _round, ...was } = t.methods?.at(-1) ?? {}
2298
+ if (was.how) t.method = was
2299
+ delete t.noMethod
2300
+ }
2301
+ const left = Math.max(1, t.roundLimit - t.attempts.length)
2302
+ t.roundLimit = t.attempts.length + left
2303
+ t.status = 'waiting'
2304
+ delete t.live
2305
+ }
2306
+ await store.append({ type: 'resume', unfinished: P.board.tasks.filter((t) => !DONE.has(t.status)).map((t) => t.id) })
2307
+ return { ok: true }
2308
+ }
2309
+
2310
+ // ---- the whole production
2311
+
2312
+ try {
2313
+ if (resume) {
2314
+ const r = await load()
2315
+ if (!r.ok) return await deliver({ status: 'failed', why: r.why })
2316
+ } else {
2317
+ // A no to the first card spends nothing more, not even the report.
2318
+ const d = await directionPhase()
2319
+ if (!d.ok) {
2320
+ await current.stop('cancelled at the first cost card')
2321
+ return await deliver({ status: 'stopped', why: d.why })
2322
+ }
2323
+ const i = await interpret()
2324
+ if (!i.ok) return await deliver({ status: P.stopped ? 'stopped' : 'failed', why: i.why })
2325
+ const v = await visionPhase()
2326
+ if (!v.ok) {
2327
+ if (v.cancelled) await current.stop('cancelled at the vision card')
2328
+ return await deliver({ status: P.stopped ? 'stopped' : 'failed', why: v.why })
2329
+ }
2330
+ const p = await plan()
2331
+ if (!p.ok || P.stopped) return await deliver({ status: P.stopped ? 'stopped' : 'failed', why: p.why })
2332
+ }
2333
+ const e = await estimatePhase()
2334
+ if (!e.ok) return await deliver({ status: P.stopped ? 'stopped' : 'unfinished', why: e.why })
2335
+ await dispatch()
2336
+ if (P.stopped) return await deliver({ status: 'stopped' })
2337
+ await finalPhase()
2338
+ return await deliver({ status: P.stopped ? 'stopped' : 'done' })
2339
+ } catch (err) {
2340
+ log(`[director] the production failed: ${err?.stack ?? err}`)
2341
+ return await deliver({ status: P.stopped ? 'stopped' : 'failed', why: `The director failed: ${err?.message ?? err}` }).catch((e2) => {
2342
+ send({ type: 'error', id: runId, message: `The director failed: ${err?.message ?? err}`, failure: 'other', unfinished: true, cleanup: 'skipped', markers: [] })
2343
+ log(`[director] and its report failed too: ${e2?.message ?? e2}`)
2344
+ return { status: 'failed', productionId: P.id, report: '', verified: { check: false, view: false }, turns: sessions.turns }
2345
+ })
2346
+ } finally {
2347
+ if (boardTimer) clearTimeout(boardTimer)
2348
+ current = null
2349
+ }
2350
+ }
2351
+
2352
+ return {
2353
+ run,
2354
+ /** Stops the running production: every session interrupted and closed,
2355
+ * Blender stopped, nothing new started. */
2356
+ stop(reason = 'stopped') {
2357
+ if (current) return current.stop(reason)
2358
+ stopAsked = reason
2359
+ return Promise.resolve()
2360
+ },
2361
+ get productionId() {
2362
+ return current?.id ?? null
2363
+ },
2364
+ }
2365
+ }