@animastor/orchestration 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,36 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.1.0 (2026-11-07) — этап 2a: изображения (`iu_image`)
4
+
5
+ ADR `architecture/ORCHESTRATION_V2.md` (§4.3, §7, §12 «2a», §13 п.9). Minor: только
6
+ добавления, контракт портов 1.0.0 не меняется (новые поля юнита опциональны).
7
+
8
+ - **Проверка PNG** (`media.inspectPng`, `defaults.createPngValidator`; порт по умолчанию
9
+ для `iu_image`): сигнатура, IHDR первым, CRC каждого чанка, IDAT, IEND; ширина и высота
10
+ в 1…16384; поток пикселей распаковывается ровно в размер из IHDR; **не пустой кадр** —
11
+ стандартное отклонение яркости по выборке пикселей ≥ `minLumaStddev` (по умолчанию
12
+ `2.0` по шкале 0…255; чёрный / однотонный кадр = 0). Причины отказа: `not_png`,
13
+ `truncated`, `bad_crc`, `no_ihdr`, `bad_dimensions`, `bad_header`, `no_idat`, `no_iend`,
14
+ `corrupt_data`, `blank_frame` → `invalid_result` (один повтор, затем failed — как
15
+ тишина у аудио). Чересстрочные и < 8 бит — только структурная проверка
16
+ (`flat_check: 'skipped'`). 1.0.0 проверяла только сигнатуру.
17
+ - **Пропуск готового по части** (`input.part_hash`): без `force` юнит пропускается, если в
18
+ `scene_assets.metadata.gen_parts[unit_key].part_hash` той же сборки записан тот же хэш
19
+ (строка не `stale`). Приём сохраняет `part_hash` в запись части. Юниты без `part_hash`
20
+ (аудио) — прежнее правило по `scene_hash` сцены.
21
+ - **Готовность сцены без склейки** (`input.scene_parts = [{unit_key, part_hash}]`): приём
22
+ части, закрывающий набор, ставит строке сцены `ready` + `sha256` (манифест
23
+ «unit_key:sha256» по порядку) + `job_id` + `path` (файл первой части) + `format`
24
+ (`png`); незакрытый набор → `pending`, `sha256`/`job_id` = NULL. Параллельный приём
25
+ двух частей одной сцены сериализуется блокировкой строки.
26
+ - `cancel({commandId})` дополнительно возвращает `layers` остановленной команды.
27
+ - `src/gen` может использовать встроенный `zlib` (граница зависимостей).
28
+ - **legacy** (`src/legacy/runtime/scene-window`): `initSceneWindow`, `slideWindow`,
29
+ `trySlideWindowOnComplete`, `reconcileWindowStatuses`, `restoreChunkStatusForScene` для
30
+ v2-книги ничего не делают (тот же предикат `isV2Book`, fail-closed) — read-repair
31
+ chunk-статусов по файлам и сдвиг окна больше не пишут legacy-ключи v2-книги
32
+ (`POST /book/:id/generate-next`).
33
+
3
34
  ## 1.0.0 (2026-11-06) — первая публикация: оркестрация v2, ядро `gen` (этапы 1a–1c)
4
35
 
5
36
  Опубликованный пакет: `src/` (`src/gen` с миграциями `sql/001–003`, `src/legacy` — код 0.3.x),
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @animastor/orchestration
2
2
 
3
- ## 1.0.0 — orchestration v2 (`gen`)
3
+ ## 1.x — orchestration v2 (`gen`)
4
4
 
5
5
  ADR: animastor-docs `architecture/ORCHESTRATION_V2.md`. The new core lives in
6
6
  `src/gen/` and is exported as `gen`. The 0.3.x contour described below ships
@@ -25,6 +25,12 @@ await orch.acceptResult(jobId, attempt, uploadToken, readableStream);
25
25
  orch.startSweeper(10_000);
26
26
  ```
27
27
 
28
+ **1.1.0 (images, stage 2a).** `iu_image` results are checked by `inspectPng`
29
+ (structure + CRC, dimensions > 0, pixel data, not a blank frame — luma stddev ≥
30
+ `minLumaStddev`, default 2.0); a unit may carry `input.part_hash` (part-level
31
+ «already done» skip) and `input.scene_parts` (scene asset `ready` once every
32
+ listed part is accepted — for part kinds without a merge stage).
33
+
28
34
  `gen` requires only node builtins and its own files: no `src/legacy`, Redis,
29
35
  Express or ComfyUI. Tests: `npm run test:gen` (env `PG_*` of the animastor-test
30
36
  stack; refuses a DB not ending in `_test` or port 5432).
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@animastor/orchestration",
3
- "version": "1.0.0",
4
- "description": "Animastor Orchestration 1.0.0 — generation orchestration v2 (ADR ORCHESTRATION_V2): `gen` namespace — PG is the single source of truth (gen_commands, gen_jobs), commands / claim (FOR UPDATE SKIP LOCKED) / one-transaction acceptance / sweeper / progress over a host-supplied pg pool and host ports; no Redis, no Express, no ComfyUI. The 0.3.x orchestration (dispatch/reconcile/lease/FSM, O-2..O-10 ports, host bindings) ships unchanged under src/legacy/ with the same root exports until migration stage 4.",
3
+ "version": "1.1.0",
4
+ "description": "Animastor Orchestration 1.1.0 — generation orchestration v2 (ADR ORCHESTRATION_V2): `gen` namespace — PG is the single source of truth (gen_commands, gen_jobs), commands / claim (FOR UPDATE SKIP LOCKED) / one-transaction acceptance / sweeper / progress over a host-supplied pg pool and host ports; no Redis, no Express, no ComfyUI. The 0.3.x orchestration (dispatch/reconcile/lease/FSM, O-2..O-10 ports, host bindings) ships unchanged under src/legacy/ with the same root exports until migration stage 4.",
5
5
  "keywords": [
6
6
  "animastor",
7
7
  "dispatch",
package/src/gen/accept.js CHANGED
@@ -25,6 +25,18 @@ const { checkLane } = require('./ports');
25
25
 
26
26
  const PART_KINDS = new Set(['audio_chunk', 'iu_image', 'video_group']);
27
27
  const FINAL_FORMAT = { audio_merge: 'mp3', video_merge: 'mp4' };
28
+ const PART_FORMAT = { iu_image: 'png' };
29
+
30
+ /** input.scene_parts → [{unit_key, part_hash}] (non-empty, string fields) or null. */
31
+ function partsManifest(v) {
32
+ if (!Array.isArray(v) || v.length === 0) return null;
33
+ const out = [];
34
+ for (const p of v) {
35
+ if (!p || typeof p.unit_key !== 'string' || !p.unit_key || typeof p.part_hash !== 'string' || !p.part_hash) return null;
36
+ out.push({ unit_key: p.unit_key, part_hash: p.part_hash });
37
+ }
38
+ return out;
39
+ }
28
40
  const DEFAULT_MAX_UPLOAD_BYTES = 2 * 1024 * 1024 * 1024;
29
41
 
30
42
  function epochS() { return Math.floor(Date.now() / 1000); }
@@ -89,7 +101,50 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
89
101
  const sceneHash = job.input.scene_hash || null;
90
102
  if (PART_KINDS.has(job.kind)) {
91
103
  // a part (chunk / IU / group) is recorded, the scene asset is not ready yet
92
- const part = { [job.unit_key]: { kind: job.kind, path: finalPath, sha256: sha, bytes, job_id: job.job_id, attempt: job.attempt } };
104
+ const entry = { kind: job.kind, path: finalPath, sha256: sha, bytes, job_id: job.job_id, attempt: job.attempt };
105
+ if (typeof job.input.part_hash === 'string' && job.input.part_hash) entry.part_hash = job.input.part_hash;
106
+ const part = { [job.unit_key]: entry };
107
+ const sceneParts = partsManifest(job.input.scene_parts);
108
+ if (sceneParts) {
109
+ // 1.1.0 — a part kind WITHOUT a merge stage (iu_image): the scene asset is
110
+ // `ready` exactly when every part the planner listed for the scene
111
+ // (input.scene_parts = [{unit_key, part_hash}] in scene order) has an
112
+ // accepted entry with that part_hash; the acceptance that completes the
113
+ // set writes ready + sha256 (of the parts manifest «unit_key:sha256» per
114
+ // line, scene order) + job_id + path (the first part's file). Not complete
115
+ // → 'pending' (a half-regenerated scene is not ready for the new content).
116
+ // The row lock taken by the upsert serialises two IUs of one scene accepted
117
+ // in parallel; the second one sees the first one's part (READ COMMITTED
118
+ // re-reads the committed row on conflict).
119
+ const up = (await client.query(
120
+ `INSERT INTO scene_assets (book_id, chapter_id, scene_id, asset_type, build_id, scene_hash, status, metadata, updated_at)
121
+ VALUES ($1, $2, $3, $4, $5, $6, 'pending', jsonb_build_object('gen_parts', $7::jsonb), $8)
122
+ ON CONFLICT (book_id, chapter_id, scene_id, asset_type, build_id) DO UPDATE SET
123
+ metadata = jsonb_set(
124
+ CASE WHEN jsonb_typeof(scene_assets.metadata) = 'object' THEN scene_assets.metadata ELSE '{}'::jsonb END,
125
+ '{gen_parts}',
126
+ COALESCE(CASE WHEN jsonb_typeof(scene_assets.metadata->'gen_parts') = 'object'
127
+ THEN scene_assets.metadata->'gen_parts' END, '{}'::jsonb) || $7::jsonb),
128
+ updated_at = EXCLUDED.updated_at
129
+ RETURNING id, metadata->'gen_parts' AS parts`,
130
+ [job.book_id, job.chapter_id, job.scene_id, assetType, build, sceneHash, JSON.stringify(part), epochS()])).rows[0];
131
+ const parts = up.parts && typeof up.parts === 'object' ? up.parts : {};
132
+ const complete = sceneParts.every((p) => parts[p.unit_key] && parts[p.unit_key].part_hash === p.part_hash);
133
+ if (complete) {
134
+ const manifest = sceneParts.map((p) => `${p.unit_key}:${parts[p.unit_key].sha256 || ''}`).join('\n');
135
+ await client.query(
136
+ `UPDATE scene_assets SET scene_hash = $2, status = 'ready', error = NULL, sha256 = $3, job_id = $4,
137
+ path = $5, format = $6
138
+ WHERE id = $1`,
139
+ [up.id, sceneHash, crypto.createHash('sha256').update(manifest).digest('hex'), job.job_id,
140
+ parts[sceneParts[0].unit_key].path || finalPath, PART_FORMAT[job.kind] || null]);
141
+ } else {
142
+ await client.query(
143
+ `UPDATE scene_assets SET scene_hash = $2, status = 'pending', sha256 = NULL, job_id = NULL WHERE id = $1`,
144
+ [up.id, sceneHash]);
145
+ }
146
+ return;
147
+ }
93
148
  await client.query(
94
149
  `INSERT INTO scene_assets (book_id, chapter_id, scene_id, asset_type, build_id, scene_hash, status, metadata, updated_at)
95
150
  VALUES ($1, $2, $3, $4, $5, $6, 'pending', jsonb_build_object('gen_parts', $7::jsonb), $8)
@@ -196,6 +196,32 @@ function createCommands({ pool, ports }) {
196
196
  if (readyKeys.has(gkey(u))) { skipped += 1; return false; }
197
197
  return true;
198
198
  });
199
+ // 1.1.0 — part-level readiness (opt-in: the unit carries input.part_hash).
200
+ // A part (e.g. one IU picture) whose accepted snapshot hash is recorded in
201
+ // scene_assets.metadata.gen_parts[unit_key].part_hash for the same build is
202
+ // already done for the current content — skip it even if its scene is not
203
+ // complete («сгенерировать недостающее» = only the missing / changed parts).
204
+ // A row the host marked 'stale' proves nothing. Units without part_hash
205
+ // (audio) keep the scene-level rule above unchanged.
206
+ const parted = todo.filter((u) => typeof u.input.part_hash === 'string' && u.input.part_hash);
207
+ if (parted.length) {
208
+ const r = await client.query(
209
+ `SELECT t.ord FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])
210
+ WITH ORDINALITY AS t(chapter_id, scene_id, asset_type, build_id, unit_key, part_hash, ord)
211
+ WHERE EXISTS (SELECT 1 FROM scene_assets a
212
+ WHERE a.book_id = $1 AND a.chapter_id = t.chapter_id AND a.scene_id = t.scene_id
213
+ AND a.asset_type = t.asset_type AND a.build_id = t.build_id
214
+ AND a.status IN ('pending', 'ready')
215
+ AND jsonb_typeof(a.metadata->'gen_parts') = 'object'
216
+ AND a.metadata->'gen_parts'->t.unit_key->>'part_hash' = t.part_hash)`,
217
+ [bookId, parted.map((u) => u.chapter_id), parted.map((u) => u.scene_id), parted.map((u) => LAYER_OF_KIND[u.kind]),
218
+ parted.map((u) => u.build_id), parted.map((u) => u.unit_key), parted.map((u) => u.input.part_hash)]);
219
+ const done = new Set(r.rows.map((row) => parted[Number(row.ord) - 1]));
220
+ if (done.size) {
221
+ skipped += done.size;
222
+ todo = todo.filter((u) => !done.has(u));
223
+ }
224
+ }
199
225
  }
200
226
 
201
227
  // lanes, one lookup per worker type (§4.2: computed at creation)
@@ -271,7 +297,8 @@ function createCommands({ pool, ports }) {
271
297
  * command waits for them (gen_command_jobs) — shared jobs keep running
272
298
  * @param {object} target
273
299
  * @param {{cancelledBy?:string}} [opts]
274
- * @returns {Promise<{commands_cancelled:number, jobs_cancelled:number, job_ids:string[], kept_shared:number}>}
300
+ * @returns {Promise<{commands_cancelled:number, jobs_cancelled:number, job_ids:string[], kept_shared:number, layers?:string[]}>}
301
+ * layers (1.1.0, {commandId} only): the layers of the command that was stopped
275
302
  */
276
303
  async function cancel(target = {}, opts = {}) {
277
304
  const by = opts.cancelledBy == null ? null : String(opts.cancelledBy).slice(0, 200);
@@ -294,7 +321,7 @@ function createCommands({ pool, ports }) {
294
321
  if (commandId !== undefined) {
295
322
  commands = (await client.query(
296
323
  `UPDATE gen_commands SET status = 'cancelled', finished_at = now(), cancelled_by = $2
297
- WHERE command_id = $1 AND status = 'active' RETURNING command_id, book_id`, [commandId, by])).rows;
324
+ WHERE command_id = $1 AND status = 'active' RETURNING command_id, book_id, layers`, [commandId, by])).rows;
298
325
  jobs = await client.query(
299
326
  `UPDATE gen_jobs j SET status = 'cancelled', finished_at = now()
300
327
  FROM gen_command_jobs l
@@ -321,12 +348,14 @@ function createCommands({ pool, ports }) {
321
348
  }
322
349
  const books = new Set([...commands.map((c) => c.book_id), ...jobs.rows.map((j) => j.book_id)]);
323
350
  for (const b of books) await notifyProgress(client, b, commandId || null);
324
- return {
351
+ const out = {
325
352
  commands_cancelled: commands.length,
326
353
  jobs_cancelled: jobs.rowCount,
327
354
  job_ids: jobs.rows.map((j) => j.job_id),
328
355
  kept_shared: keptShared,
329
356
  };
357
+ if (commandId !== undefined) out.layers = commands.length ? commands[0].layers : []; // 1.1.0
358
+ return out;
330
359
  });
331
360
  }
332
361
 
package/src/gen/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // ======================================================
2
- // @animastor/orchestration · gen — orchestration v2 core (1.0.0)
2
+ // @animastor/orchestration · gen — orchestration v2 core (1.1.0)
3
3
  // ======================================================
4
4
  // ADR: animastor-docs architecture/ORCHESTRATION_V2.md. The single source of
5
5
  // truth is PG (gen_commands, gen_jobs). This namespace depends ONLY on the
@@ -95,12 +95,15 @@ module.exports = Object.freeze({
95
95
  ...portsMod.defaults,
96
96
  createDefaultValidateResult: media.createDefaultValidateResult,
97
97
  createAudioValidator: media.createAudioValidator,
98
+ createPngValidator: media.createPngValidator,
98
99
  }),
99
100
  media: Object.freeze({
100
101
  inspectMp3: media.inspectMp3,
101
102
  rmsDbfs: media.rmsDbfs,
102
103
  ffmpegDecodePcm: media.ffmpegDecodePcm,
103
104
  DEFAULT_RMS_THRESHOLD_DBFS: media.DEFAULT_RMS_THRESHOLD_DBFS,
105
+ inspectPng: media.inspectPng,
106
+ DEFAULT_MIN_LUMA_STDDEV: media.DEFAULT_MIN_LUMA_STDDEV,
104
107
  }),
105
108
  GenError: util.GenError,
106
109
  PROGRESS_CHANNEL: util.PROGRESS_CHANNEL,
package/src/gen/ports.js CHANGED
@@ -10,6 +10,12 @@
10
10
  // scope = {level, chapter_id?, scene_id?, unit_id?, scene_ids?} (level 'scenes' → scene_ids, book order)
11
11
  // Unit = {chapter_id, scene_id, kind, unit_key, build_id, input, scene_hash?}
12
12
  // build_id = the book build at command time (gen_jobs.build_id, §4.2)
13
+ // input.part_hash? (1.1.0) snapshot hash of THIS part: without force the unit is
14
+ // skipped when scene_assets.metadata.gen_parts[unit_key].part_hash
15
+ // of the same build equals it (row not 'stale'); acceptance stores it
16
+ // input.scene_parts? (1.1.0) [{unit_key, part_hash}] — every part of the scene in scene
17
+ // order, for a part kind WITHOUT a merge stage (iu_image): the
18
+ // acceptance that completes the set marks the scene asset ready
13
19
  // buildPayload(job) → Promise<object> ComfyUI params etc. (claim, §8.1)
14
20
  // artifactPath(job) → string absolute final path (accept, §7 п.3)
15
21
  // validateResult(job, tmpPath) → Promise<{ok, reason?}> (§7 п.1; default: validate-media)
@@ -3,7 +3,9 @@
3
3
  // ======================================================
4
4
  // Audio: MP3 magic bytes (ID3v2 tag or MPEG Layer III frame sync), duration
5
5
  // > 0 from the frame headers, and NOT silence — RMS of the decoded PCM above
6
- // a threshold (parameter, dBFS). Image: PNG signature. Video: MP4 `ftyp` box.
6
+ // a threshold (parameter, dBFS). Image (1.1.0): PNG structure + CRC, dimensions > 0,
7
+ // pixel data inflates to the IHDR size, NOT a blank / single-colour frame (luma
8
+ // stddev threshold, parameter). Video: MP4 `ftyp` box.
7
9
  //
8
10
  // PCM decoding is injected (`decodePcm(path) → Int16Array`); the default
9
11
  // spawns the `ffmpeg` binary (node builtin child_process, no npm dependency).
@@ -13,6 +15,7 @@
13
15
  'use strict';
14
16
 
15
17
  const fs = require('fs');
18
+ const zlib = require('zlib');
16
19
  const { spawn } = require('child_process');
17
20
 
18
21
  const DEFAULT_RMS_THRESHOLD_DBFS = -50;
@@ -132,6 +135,188 @@ function createAudioValidator(opts = {}) {
132
135
 
133
136
  const PNG_SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
134
137
 
138
+ // ── PNG (1.1.0): structure + dimensions + «not a blank frame» ────────────
139
+ // A GPU image result is accepted only if it is a well-formed PNG (signature,
140
+ // IHDR first, CRC of every chunk, IDAT present, IEND last), its dimensions are
141
+ // > 0, the pixel stream inflates to exactly the size IHDR promises, and the
142
+ // frame is not one flat colour: the standard deviation of the luma over
143
+ // sampled pixels must reach `minLumaStddev` (default 2.0 on a 0..255 scale).
144
+ // A black / single-colour frame (a VAE or safety-filter failure) has stddev 0;
145
+ // any real picture is far above 2. The same «blank = invalid_result» rule as
146
+ // silence for audio (ADR §7 п.1, §13.4): one retry, then failed.
147
+ const DEFAULT_MIN_LUMA_STDDEV = 2.0;
148
+ const PNG_MAX_SIDE = 16384;
149
+ const PNG_MAX_DECODE_PIXELS = 64 * 1024 * 1024;
150
+ const PNG_SAMPLE_TARGET = 1 << 16; // ~65k pixels sampled for the flatness check
151
+ const PNG_CHANNELS = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 };
152
+ const PNG_DEPTHS = { 0: [1, 2, 4, 8, 16], 2: [8, 16], 3: [1, 2, 4, 8], 4: [8, 16], 6: [8, 16] };
153
+
154
+ const CRC_TABLE = (() => {
155
+ const t = new Uint32Array(256);
156
+ for (let n = 0; n < 256; n += 1) {
157
+ let c = n;
158
+ for (let k = 0; k < 8; k += 1) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1);
159
+ t[n] = c >>> 0;
160
+ }
161
+ return t;
162
+ })();
163
+ function crc32(buf, start, end) {
164
+ let c = 0xffffffff;
165
+ for (let i = start; i < end; i += 1) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
166
+ return (c ^ 0xffffffff) >>> 0;
167
+ }
168
+
169
+ function paeth(a, b, c) {
170
+ const p = a + b - c;
171
+ const pa = Math.abs(p - a); const pb = Math.abs(p - b); const pc = Math.abs(p - c);
172
+ if (pa <= pb && pa <= pc) return a;
173
+ return pb <= pc ? b : c;
174
+ }
175
+
176
+ /** Undo the per-scanline filters in place. @returns {Buffer|null} raw rows (no filter bytes) */
177
+ function unfilter(data, width, height, bpp, rowBytes) {
178
+ const out = Buffer.alloc(rowBytes * height);
179
+ let prev = null;
180
+ for (let y = 0; y < height; y += 1) {
181
+ const off = y * (rowBytes + 1);
182
+ const type = data[off];
183
+ const row = out.subarray(y * rowBytes, (y + 1) * rowBytes);
184
+ for (let x = 0; x < rowBytes; x += 1) {
185
+ const raw = data[off + 1 + x];
186
+ const a = x >= bpp ? row[x - bpp] : 0;
187
+ const b = prev ? prev[x] : 0;
188
+ const c = prev && x >= bpp ? prev[x - bpp] : 0;
189
+ let v;
190
+ switch (type) {
191
+ case 0: v = raw; break;
192
+ case 1: v = raw + a; break;
193
+ case 2: v = raw + b; break;
194
+ case 3: v = raw + ((a + b) >> 1); break;
195
+ case 4: v = raw + paeth(a, b, c); break;
196
+ default: return null;
197
+ }
198
+ row[x] = v & 0xff;
199
+ }
200
+ prev = row;
201
+ }
202
+ return out;
203
+ }
204
+
205
+ /**
206
+ * Luma standard deviation over sampled pixels (8/16-bit, non-palette or palette).
207
+ * @returns {number}
208
+ */
209
+ function lumaStddev(rows, width, height, colorType, depth, rowBytes, palette) {
210
+ const ch = PNG_CHANNELS[colorType];
211
+ const bytesPerSample = depth === 16 ? 2 : 1;
212
+ const step = Math.max(1, Math.floor(Math.sqrt((width * height) / PNG_SAMPLE_TARGET)));
213
+ const sample = (rowOff, idx) => (depth === 16 ? rows[rowOff + idx * 2] : rows[rowOff + idx]); // high byte
214
+ let n = 0; let sum = 0; let sumSq = 0;
215
+ for (let y = 0; y < height; y += step) {
216
+ const rowOff = y * rowBytes;
217
+ for (let x = 0; x < width; x += step) {
218
+ let l;
219
+ if (colorType === 3) {
220
+ const i = rows[rowOff + x];
221
+ const p = palette && i * 3 + 2 < palette.length ? i * 3 : 0;
222
+ l = palette ? 0.299 * palette[p] + 0.587 * palette[p + 1] + 0.114 * palette[p + 2] : i;
223
+ } else if (colorType === 0 || colorType === 4) {
224
+ l = sample(rowOff, x * ch);
225
+ } else {
226
+ const base = x * ch;
227
+ l = 0.299 * sample(rowOff, base) + 0.587 * sample(rowOff, base + 1) + 0.114 * sample(rowOff, base + 2);
228
+ }
229
+ n += 1; sum += l; sumSq += l * l;
230
+ }
231
+ }
232
+ if (n === 0) return 0;
233
+ const mean = sum / n;
234
+ return Math.sqrt(Math.max(0, sumSq / n - mean * mean));
235
+ }
236
+
237
+ /**
238
+ * Inspect a PNG buffer.
239
+ * @param {Buffer} buf
240
+ * @param {{minLumaStddev?:number}} [opts]
241
+ * @returns {{ok:true, width:number, height:number, lumaStddev:number|null, flat_check:string}
242
+ * |{ok:false, reason:string, width?:number, height?:number, lumaStddev?:number}}
243
+ * reason ∈ not_png | truncated | bad_crc | no_ihdr | bad_dimensions | bad_header | no_idat
244
+ * | no_iend | corrupt_data | blank_frame
245
+ */
246
+ function inspectPng(buf, opts = {}) {
247
+ const minStd = Number.isFinite(opts.minLumaStddev) ? opts.minLumaStddev : DEFAULT_MIN_LUMA_STDDEV;
248
+ if (!Buffer.isBuffer(buf) || buf.length < 8 || !buf.subarray(0, 8).equals(PNG_SIG)) return { ok: false, reason: 'not_png' };
249
+ let off = 8;
250
+ let ihdr = null; let palette = null; let sawIend = false;
251
+ const idat = [];
252
+ let first = true;
253
+ while (off < buf.length) {
254
+ if (off + 12 > buf.length) return { ok: false, reason: 'truncated' };
255
+ const len = buf.readUInt32BE(off);
256
+ const type = buf.toString('latin1', off + 4, off + 8);
257
+ if (len > 0x7fffffff || off + 12 + len > buf.length) return { ok: false, reason: 'truncated' };
258
+ const crc = buf.readUInt32BE(off + 8 + len);
259
+ if (crc32(buf, off + 4, off + 8 + len) !== crc) return { ok: false, reason: 'bad_crc' };
260
+ const data = buf.subarray(off + 8, off + 8 + len);
261
+ if (first && type !== 'IHDR') return { ok: false, reason: 'no_ihdr' };
262
+ first = false;
263
+ if (type === 'IHDR') {
264
+ if (len !== 13) return { ok: false, reason: 'bad_header' };
265
+ ihdr = {
266
+ width: data.readUInt32BE(0), height: data.readUInt32BE(4), depth: data[8], colorType: data[9],
267
+ compression: data[10], filter: data[11], interlace: data[12],
268
+ };
269
+ } else if (type === 'PLTE') {
270
+ palette = data;
271
+ } else if (type === 'IDAT') {
272
+ idat.push(data);
273
+ } else if (type === 'IEND') {
274
+ sawIend = true;
275
+ break;
276
+ }
277
+ off += 12 + len;
278
+ }
279
+ if (!ihdr) return { ok: false, reason: 'no_ihdr' };
280
+ const { width, height, depth, colorType } = ihdr;
281
+ if (!(width > 0 && height > 0) || width > PNG_MAX_SIDE || height > PNG_MAX_SIDE) {
282
+ return { ok: false, reason: 'bad_dimensions', width, height };
283
+ }
284
+ if (!PNG_CHANNELS[colorType] || !PNG_DEPTHS[colorType].includes(depth) || ihdr.compression !== 0 || ihdr.filter !== 0 || ihdr.interlace > 1) {
285
+ return { ok: false, reason: 'bad_header', width, height };
286
+ }
287
+ if (!idat.length) return { ok: false, reason: 'no_idat', width, height };
288
+ if (!sawIend) return { ok: false, reason: 'no_iend', width, height };
289
+
290
+ const bitsPerPixel = PNG_CHANNELS[colorType] * depth;
291
+ const rowBytes = Math.ceil((width * bitsPerPixel) / 8);
292
+ // flatness is measured on non-interlaced, byte-aligned frames (ComfyUI SaveImage:
293
+ // 8-bit RGB/RGBA, no interlace); other layouts are checked structurally only
294
+ const flatCheckable = ihdr.interlace === 0 && depth >= 8 && width * height <= PNG_MAX_DECODE_PIXELS;
295
+ if (!flatCheckable) return { ok: true, width, height, lumaStddev: null, flat_check: 'skipped' };
296
+ let raw;
297
+ try {
298
+ raw = zlib.inflateSync(Buffer.concat(idat), { maxOutputLength: (rowBytes + 1) * height + 1 });
299
+ } catch (_) {
300
+ return { ok: false, reason: 'corrupt_data', width, height };
301
+ }
302
+ if (raw.length !== (rowBytes + 1) * height) return { ok: false, reason: 'corrupt_data', width, height };
303
+ const rows = unfilter(raw, width, height, Math.max(1, bitsPerPixel >> 3), rowBytes);
304
+ if (!rows) return { ok: false, reason: 'corrupt_data', width, height };
305
+ const std = lumaStddev(rows, width, height, colorType, depth, rowBytes, palette);
306
+ if (!(std >= minStd)) return { ok: false, reason: 'blank_frame', width, height, lumaStddev: std };
307
+ return { ok: true, width, height, lumaStddev: std, flat_check: 'done' };
308
+ }
309
+
310
+ /**
311
+ * @param {{minLumaStddev?:number}} [opts]
312
+ * @returns {(tmpPath:string)=>Promise<object>} the iu_image validator (inspectPng of the file)
313
+ */
314
+ function createPngValidator(opts = {}) {
315
+ return async function validatePngFile(tmpPath) {
316
+ return inspectPng(await fs.promises.readFile(tmpPath), opts);
317
+ };
318
+ }
319
+
135
320
  async function readHead(filePath, n) {
136
321
  const fh = await fs.promises.open(filePath, 'r');
137
322
  try {
@@ -141,10 +326,8 @@ async function readHead(filePath, n) {
141
326
  } finally { await fh.close(); }
142
327
  }
143
328
 
144
- async function validatePng(tmpPath) {
145
- const head = await readHead(tmpPath, 8);
146
- return head.equals(PNG_SIG) ? { ok: true } : { ok: false, reason: 'not_png' };
147
- }
329
+ /** Full PNG check with the default threshold (1.0.0 checked the signature only). */
330
+ const validatePng = createPngValidator();
148
331
 
149
332
  async function validateMp4(tmpPath) {
150
333
  const head = await readHead(tmpPath, 12);
@@ -153,15 +336,16 @@ async function validateMp4(tmpPath) {
153
336
 
154
337
  /**
155
338
  * Default validateResult port: dispatches by job.kind.
156
- * @param {object} [opts] forwarded to createAudioValidator
339
+ * @param {object} [opts] forwarded to createAudioValidator; opts.minLumaStddev → createPngValidator
157
340
  */
158
341
  function createDefaultValidateResult(opts = {}) {
159
342
  const audio = createAudioValidator(opts);
343
+ const png = createPngValidator({ minLumaStddev: opts.minLumaStddev });
160
344
  return async function validateResult(job, tmpPath) {
161
345
  switch (job && job.kind) {
162
346
  case 'audio_chunk':
163
347
  case 'audio_merge': return audio(tmpPath);
164
- case 'iu_image': return validatePng(tmpPath);
348
+ case 'iu_image': return png(tmpPath);
165
349
  case 'video_group':
166
350
  case 'video_merge': return validateMp4(tmpPath);
167
351
  default: return { ok: false, reason: 'unknown_kind' };
@@ -178,4 +362,7 @@ module.exports = {
178
362
  createDefaultValidateResult,
179
363
  validatePng,
180
364
  validateMp4,
365
+ inspectPng,
366
+ createPngValidator,
367
+ DEFAULT_MIN_LUMA_STDDEV,
181
368
  };
@@ -75,7 +75,19 @@ function error(msg) {
75
75
  console.error(`${logPrefix} ❌ ${msg}`);
76
76
  }
77
77
 
78
+ // Orchestration v2 (2a): the window / read-repair functions below rewrite legacy
79
+ // chunk statuses and asset-state from the files on disk («file exists → image
80
+ // ready»). A v2 book's files are written by the gen core, its readiness lives in
81
+ // PG scene_assets — legacy keeps its hands off ALL its layers (one predicate,
82
+ // fail-closed inside isV2Book).
83
+ async function isV2(bookId, what) {
84
+ if (!(await require('./persistence-port').isV2Book(bookId))) return false;
85
+ log(`${what} skipped: ${bookId} is on orchestration v2`);
86
+ return true;
87
+ }
88
+
78
89
  async function initSceneWindow(redis, scenes, loadedBook, buildId, bookId, scopeInfo) {
90
+ if (await isV2(bookId, 'initSceneWindow')) return 0;
79
91
  const scope = scopeInfo || (await genScope.getScope(redis, bookId));
80
92
  const bounds = genScope.scopeBounds(scope, scenes);
81
93
  const totalScenes = bounds.endIndex;
@@ -340,6 +352,7 @@ async function _checkAssetVersionStale(bookId, chapterId, sceneId, buildId) {
340
352
  * do NOT override the pending state — the scene stays pending for regeneration.
341
353
  */
342
354
  async function restoreChunkStatusForScene(redis, buildId, bookId, chapterId, sceneId) {
355
+ if (await isV2(bookId, 'restoreChunkStatusForScene')) return;
343
356
  const buildDir = path.join(OUTPUT_DIR, buildId);
344
357
  if (!fs.existsSync(buildDir)) return;
345
358
 
@@ -477,6 +490,7 @@ async function isWindowComplete(redis, bookId) {
477
490
  * Try to slide window forward if all current window scenes have audio + image complete.
478
491
  */
479
492
  async function trySlideWindowOnComplete(redis, bookId, loadedBook, buildId) {
493
+ if (await isV2(bookId, 'trySlideWindowOnComplete')) return { started: 0, remaining: 0, reason: 'orchestration_v2' };
480
494
  // Command-only generation: sliding the window forward after its scenes
481
495
  // complete is an automatic start of the next scenes. Behind the
482
496
  // WINDOW_AUTO_NEXT_ENABLED flag, default OFF (owner decision pending).
@@ -516,6 +530,7 @@ async function trySlideWindowOnComplete(redis, bookId, loadedBook, buildId) {
516
530
  }
517
531
 
518
532
  async function slideWindow(redis, bookId, loadedBook, buildId) {
533
+ if (await isV2(bookId, 'slideWindow')) return { started: 0, remaining: 0, reason: 'orchestration_v2' };
519
534
  if (await isCancelled(redis, bookId)) {
520
535
  log(`Slide skipped: generation cancelled for ${bookId}`);
521
536
  return { started: 0, remaining: 0, reason: 'cancelled' };
@@ -603,6 +618,7 @@ async function slideWindow(redis, bookId, loadedBook, buildId) {
603
618
  * were missed (e.g. after Cancel→Generate cycles).
604
619
  */
605
620
  async function reconcileWindowStatuses(redis, bookId, buildId) {
621
+ if (await isV2(bookId, 'reconcileWindowStatuses')) return { reconciled: 0, reason: 'orchestration_v2' };
606
622
  const buildDir = path.join(OUTPUT_DIR, buildId);
607
623
  if (!fs.existsSync(buildDir)) return { reconciled: 0 };
608
624
 
@@ -683,10 +699,7 @@ async function reconcileWindowStatuses(redis, bookId, buildId) {
683
699
  }
684
700
 
685
701
  async function startScene(redis, s, buildId, bookId) {
686
- if (await require('./persistence-port').isV2Book(bookId)) {
687
- log(`startScene skipped: ${bookId} is on orchestration v2`);
688
- return false;
689
- }
702
+ if (await isV2(bookId, 'startScene')) return false;
690
703
  if (await isCancelled(redis, bookId)) {
691
704
  log(`startScene skipped: generation cancelled for ${bookId}`);
692
705
  return false;