@animastor/orchestration 1.0.0 → 1.2.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,57 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.2.0 (2026-11-07) — наблюдаемость v2 (О3)
4
+
5
+ Основание: `reports/2026-11-07/orch-v2-image-scene-run.md` О3 и «мелочи». Minor: только
6
+ добавления, контракт портов 1.0.0 не меняется.
7
+
8
+ - **Строки `[gen-v2]`** через порт логгера (`createOrchestration({ logger })`, метод `info`,
9
+ иначе `log`; без логгера — молча): `command-created` (book, command, layers, scope,
10
+ jobs_created/joined/skipped_ready, existing для повторного клика), `claim` (job, kind,
11
+ unit_key, attempt/max_attempts, worker_id, ms), `accept` (sha256, bytes, width/height,
12
+ idempotent, stage_jobs_created, ms приёма, run_ms от claim), `error` (каждая неудачная
13
+ попытка: error_class, job_status, retry; 409 — `code=stale_attempt`), `requeue`
14
+ (возврат в очередь, delay_ms), `command-finished` (status, done/failed/cancelled, run_ms).
15
+ Печатаются только поля из белого списка (`gen/log.js` `FIELDS`): токены загрузки, пути
16
+ файлов и параметры задач в строки не попадают. Форматер — `gen.formatGenEvent`.
17
+ - Ядро `src/gen` больше не вызывает `console` само: `sweeper`/`local runner` пишут ошибки
18
+ через тот же порт (по умолчанию `createOrchestration` по-прежнему берёт `console`).
19
+ - **`scene_assets.width/height`** для изображений: размеры из PNG-валидатора сохраняются в
20
+ `gen_parts[unit_key]` и в строке сцены при `ready` (размер файла `path`, т. е. первой
21
+ части); для финальных видов — `COALESCE` из результата проверки, если он их знает.
22
+ - **Права принятых файлов 0644** (как у legacy); временный файл в `.incoming` — 0640.
23
+
24
+ ## 1.1.0 (2026-11-07) — этап 2a: изображения (`iu_image`)
25
+
26
+ ADR `architecture/ORCHESTRATION_V2.md` (§4.3, §7, §12 «2a», §13 п.9). Minor: только
27
+ добавления, контракт портов 1.0.0 не меняется (новые поля юнита опциональны).
28
+
29
+ - **Проверка PNG** (`media.inspectPng`, `defaults.createPngValidator`; порт по умолчанию
30
+ для `iu_image`): сигнатура, IHDR первым, CRC каждого чанка, IDAT, IEND; ширина и высота
31
+ в 1…16384; поток пикселей распаковывается ровно в размер из IHDR; **не пустой кадр** —
32
+ стандартное отклонение яркости по выборке пикселей ≥ `minLumaStddev` (по умолчанию
33
+ `2.0` по шкале 0…255; чёрный / однотонный кадр = 0). Причины отказа: `not_png`,
34
+ `truncated`, `bad_crc`, `no_ihdr`, `bad_dimensions`, `bad_header`, `no_idat`, `no_iend`,
35
+ `corrupt_data`, `blank_frame` → `invalid_result` (один повтор, затем failed — как
36
+ тишина у аудио). Чересстрочные и < 8 бит — только структурная проверка
37
+ (`flat_check: 'skipped'`). 1.0.0 проверяла только сигнатуру.
38
+ - **Пропуск готового по части** (`input.part_hash`): без `force` юнит пропускается, если в
39
+ `scene_assets.metadata.gen_parts[unit_key].part_hash` той же сборки записан тот же хэш
40
+ (строка не `stale`). Приём сохраняет `part_hash` в запись части. Юниты без `part_hash`
41
+ (аудио) — прежнее правило по `scene_hash` сцены.
42
+ - **Готовность сцены без склейки** (`input.scene_parts = [{unit_key, part_hash}]`): приём
43
+ части, закрывающий набор, ставит строке сцены `ready` + `sha256` (манифест
44
+ «unit_key:sha256» по порядку) + `job_id` + `path` (файл первой части) + `format`
45
+ (`png`); незакрытый набор → `pending`, `sha256`/`job_id` = NULL. Параллельный приём
46
+ двух частей одной сцены сериализуется блокировкой строки.
47
+ - `cancel({commandId})` дополнительно возвращает `layers` остановленной команды.
48
+ - `src/gen` может использовать встроенный `zlib` (граница зависимостей).
49
+ - **legacy** (`src/legacy/runtime/scene-window`): `initSceneWindow`, `slideWindow`,
50
+ `trySlideWindowOnComplete`, `reconcileWindowStatuses`, `restoreChunkStatusForScene` для
51
+ v2-книги ничего не делают (тот же предикат `isV2Book`, fail-closed) — read-repair
52
+ chunk-статусов по файлам и сдвиг окна больше не пишут legacy-ключи v2-книги
53
+ (`POST /book/:id/generate-next`).
54
+
3
55
  ## 1.0.0 (2026-11-06) — первая публикация: оркестрация v2, ядро `gen` (этапы 1a–1c)
4
56
 
5
57
  Опубликованный пакет: `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,20 @@ 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
+
34
+ **1.2.0 (observability).** Pass `logger` (`{ info | log, error }`) to
35
+ `createOrchestration`: the core writes one line per step —
36
+ `[gen-v2] command-created | claim | accept | error | requeue | command-finished`
37
+ with `book_id`, `command_id`, `job_id`, `kind`, `unit_key`, `attempt`,
38
+ `worker_id`, `sha256`, sizes and durations (allowlisted fields only: no upload
39
+ tokens, paths or task params). Image acceptance records `width`/`height`;
40
+ accepted files are `0644`.
41
+
28
42
  `gen` requires only node builtins and its own files: no `src/legacy`, Redis,
29
43
  Express or ComfyUI. Tests: `npm run test:gen` (env `PG_*` of the animastor-test
30
44
  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.2.0",
4
+ "description": "Animastor Orchestration 1.2.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
@@ -22,9 +22,27 @@ const {
22
22
  EXECUTOR_OF_KIND, LAYER_OF_KIND, LIVE,
23
23
  } = require('./util');
24
24
  const { checkLane } = require('./ports');
25
+ const { msBetween } = require('./log');
26
+
27
+ const NOOP_LOG = Object.freeze({ event() {} });
28
+ /** Mode of an accepted artifact: world-readable like the legacy outputs (О3; the tmp file is 0640). */
29
+ const ARTIFACT_MODE = 0o644;
30
+ const dim = (v) => (Number.isInteger(v) && v > 0 ? v : null);
25
31
 
26
32
  const PART_KINDS = new Set(['audio_chunk', 'iu_image', 'video_group']);
27
33
  const FINAL_FORMAT = { audio_merge: 'mp3', video_merge: 'mp4' };
34
+ const PART_FORMAT = { iu_image: 'png' };
35
+
36
+ /** input.scene_parts → [{unit_key, part_hash}] (non-empty, string fields) or null. */
37
+ function partsManifest(v) {
38
+ if (!Array.isArray(v) || v.length === 0) return null;
39
+ const out = [];
40
+ for (const p of v) {
41
+ if (!p || typeof p.unit_key !== 'string' || !p.unit_key || typeof p.part_hash !== 'string' || !p.part_hash) return null;
42
+ out.push({ unit_key: p.unit_key, part_hash: p.part_hash });
43
+ }
44
+ return out;
45
+ }
28
46
  const DEFAULT_MAX_UPLOAD_BYTES = 2 * 1024 * 1024 * 1024;
29
47
 
30
48
  function epochS() { return Math.floor(Date.now() / 1000); }
@@ -39,7 +57,7 @@ async function drain(stream) {
39
57
  try { stream.resume(); } catch (_) { /* ignore */ }
40
58
  }
41
59
 
42
- function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_UPLOAD_BYTES }) {
60
+ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_UPLOAD_BYTES, genLog = NOOP_LOG }) {
43
61
  const sceneLockKey = (j) => `animastor:gen-v2:scene:${JSON.stringify([j.book_id, j.chapter_id, j.scene_id])}`;
44
62
 
45
63
  // ── shared: a failed attempt → retry with backoff or failed (§7 «Ошибка», §9 пп.1–2)
@@ -63,7 +81,7 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
63
81
  [job.worker_id, job.job_id]);
64
82
  }
65
83
  await notifyProgress(client, job.book_id, job.command_id);
66
- return { status: r.rows[0].status, not_before: r.rows[0].not_before, retry };
84
+ return { status: r.rows[0].status, not_before: r.rows[0].not_before, retry, delay_ms: retry ? delay : undefined };
67
85
  }
68
86
 
69
87
  /**
@@ -73,13 +91,30 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
73
91
  async function failAttempt(jobId, attempt, errorClass, reason) {
74
92
  const cls = typeof errorClass === 'string' && errorClass ? errorClass.slice(0, 64) : 'unknown';
75
93
  const why = reason == null ? null : String(reason).slice(0, 2000);
76
- return withTx(pool, async (client) => {
77
- const job = (await client.query('SELECT * FROM gen_jobs WHERE job_id = $1 FOR UPDATE', [jobId])).rows[0];
94
+ let job = null;
95
+ let out = null;
96
+ const r = await withTx(pool, async (client) => {
97
+ job = (await client.query('SELECT * FROM gen_jobs WHERE job_id = $1 FOR UPDATE', [jobId])).rows[0];
78
98
  if (!job) return { status: 404, code: 'not_found' };
79
99
  if (job.status !== 'running' || job.attempt !== attempt) return { status: 409, code: 'stale_attempt' };
80
- const out = await failAttemptTx(client, job, cls, why);
100
+ out = await failAttemptTx(client, job, cls, why);
81
101
  return { status: 200, job_status: out.status, retry: out.retry };
82
102
  });
103
+ // О3, after commit: `error` for every failed attempt, `requeue` when it goes back to the queue
104
+ const ids = job ? {
105
+ book_id: job.book_id, command_id: job.command_id, job_id: job.job_id, kind: job.kind, unit_key: job.unit_key,
106
+ worker_id: job.worker_id,
107
+ } : { job_id: jobId };
108
+ if (r.status !== 200) {
109
+ genLog.event('error', { ...ids, attempt, error_class: cls, code: r.code });
110
+ } else {
111
+ genLog.event('error', {
112
+ ...ids, attempt, max_attempts: job.max_attempts, error_class: cls, job_status: out.status, retry: out.retry,
113
+ run_ms: msBetween(job.claimed_at),
114
+ });
115
+ if (out.retry) genLog.event('requeue', { ...ids, attempt, max_attempts: job.max_attempts, error_class: cls, delay_ms: out.delay_ms });
116
+ }
117
+ return r;
83
118
  }
84
119
 
85
120
  // ── scene_assets (§4.3: written only by acceptance) ──────────────────────
@@ -89,7 +124,54 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
89
124
  const sceneHash = job.input.scene_hash || null;
90
125
  if (PART_KINDS.has(job.kind)) {
91
126
  // 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 } };
127
+ const entry = { kind: job.kind, path: finalPath, sha256: sha, bytes, job_id: job.job_id, attempt: job.attempt };
128
+ // О3: the PNG validator knows the size — keep it with the part (scene_assets.width/height below)
129
+ if (validation && dim(validation.width) && dim(validation.height)) { entry.width = validation.width; entry.height = validation.height; }
130
+ if (typeof job.input.part_hash === 'string' && job.input.part_hash) entry.part_hash = job.input.part_hash;
131
+ const part = { [job.unit_key]: entry };
132
+ const sceneParts = partsManifest(job.input.scene_parts);
133
+ if (sceneParts) {
134
+ // 1.1.0 — a part kind WITHOUT a merge stage (iu_image): the scene asset is
135
+ // `ready` exactly when every part the planner listed for the scene
136
+ // (input.scene_parts = [{unit_key, part_hash}] in scene order) has an
137
+ // accepted entry with that part_hash; the acceptance that completes the
138
+ // set writes ready + sha256 (of the parts manifest «unit_key:sha256» per
139
+ // line, scene order) + job_id + path (the first part's file). Not complete
140
+ // → 'pending' (a half-regenerated scene is not ready for the new content).
141
+ // The row lock taken by the upsert serialises two IUs of one scene accepted
142
+ // in parallel; the second one sees the first one's part (READ COMMITTED
143
+ // re-reads the committed row on conflict).
144
+ const up = (await client.query(
145
+ `INSERT INTO scene_assets (book_id, chapter_id, scene_id, asset_type, build_id, scene_hash, status, metadata, updated_at)
146
+ VALUES ($1, $2, $3, $4, $5, $6, 'pending', jsonb_build_object('gen_parts', $7::jsonb), $8)
147
+ ON CONFLICT (book_id, chapter_id, scene_id, asset_type, build_id) DO UPDATE SET
148
+ metadata = jsonb_set(
149
+ CASE WHEN jsonb_typeof(scene_assets.metadata) = 'object' THEN scene_assets.metadata ELSE '{}'::jsonb END,
150
+ '{gen_parts}',
151
+ COALESCE(CASE WHEN jsonb_typeof(scene_assets.metadata->'gen_parts') = 'object'
152
+ THEN scene_assets.metadata->'gen_parts' END, '{}'::jsonb) || $7::jsonb),
153
+ updated_at = EXCLUDED.updated_at
154
+ RETURNING id, metadata->'gen_parts' AS parts`,
155
+ [job.book_id, job.chapter_id, job.scene_id, assetType, build, sceneHash, JSON.stringify(part), epochS()])).rows[0];
156
+ const parts = up.parts && typeof up.parts === 'object' ? up.parts : {};
157
+ const complete = sceneParts.every((p) => parts[p.unit_key] && parts[p.unit_key].part_hash === p.part_hash);
158
+ if (complete) {
159
+ const manifest = sceneParts.map((p) => `${p.unit_key}:${parts[p.unit_key].sha256 || ''}`).join('\n');
160
+ const first = parts[sceneParts[0].unit_key];
161
+ // width/height = those of the file `path` points at (the first part)
162
+ await client.query(
163
+ `UPDATE scene_assets SET scene_hash = $2, status = 'ready', error = NULL, sha256 = $3, job_id = $4,
164
+ path = $5, format = $6, width = $7, height = $8
165
+ WHERE id = $1`,
166
+ [up.id, sceneHash, crypto.createHash('sha256').update(manifest).digest('hex'), job.job_id,
167
+ first.path || finalPath, PART_FORMAT[job.kind] || null, dim(first.width), dim(first.height)]);
168
+ } else {
169
+ await client.query(
170
+ `UPDATE scene_assets SET scene_hash = $2, status = 'pending', sha256 = NULL, job_id = NULL WHERE id = $1`,
171
+ [up.id, sceneHash]);
172
+ }
173
+ return;
174
+ }
93
175
  await client.query(
94
176
  `INSERT INTO scene_assets (book_id, chapter_id, scene_id, asset_type, build_id, scene_hash, status, metadata, updated_at)
95
177
  VALUES ($1, $2, $3, $4, $5, $6, 'pending', jsonb_build_object('gen_parts', $7::jsonb), $8)
@@ -104,17 +186,21 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
104
186
  return;
105
187
  }
106
188
  const duration = validation && Number.isFinite(validation.durationSec) ? validation.durationSec : null;
189
+ const width = validation ? dim(validation.width) : null;
190
+ const height = validation ? dim(validation.height) : null;
107
191
  await client.query(
108
192
  `INSERT INTO scene_assets (book_id, chapter_id, scene_id, asset_type, path, build_id, scene_hash, status,
109
- job_id, sha256, duration_sec, format, updated_at)
110
- VALUES ($1, $2, $3, $4, $5, $6, $7, 'ready', $8, $9, $10, $11, $12)
193
+ job_id, sha256, duration_sec, format, updated_at, width, height)
194
+ VALUES ($1, $2, $3, $4, $5, $6, $7, 'ready', $8, $9, $10, $11, $12, $13, $14)
111
195
  ON CONFLICT (book_id, chapter_id, scene_id, asset_type, build_id) DO UPDATE SET
112
196
  path = EXCLUDED.path, scene_hash = EXCLUDED.scene_hash, status = 'ready', error = NULL,
113
197
  job_id = EXCLUDED.job_id, sha256 = EXCLUDED.sha256,
114
198
  duration_sec = COALESCE(EXCLUDED.duration_sec, scene_assets.duration_sec),
199
+ width = COALESCE(EXCLUDED.width, scene_assets.width),
200
+ height = COALESCE(EXCLUDED.height, scene_assets.height),
115
201
  format = EXCLUDED.format, updated_at = EXCLUDED.updated_at`,
116
202
  [job.book_id, job.chapter_id, job.scene_id, assetType, finalPath, build, sceneHash,
117
- job.job_id, sha, duration, FINAL_FORMAT[job.kind], epochS()]);
203
+ job.job_id, sha, duration, FINAL_FORMAT[job.kind], epochS(), width, height]);
118
204
  }
119
205
 
120
206
  // ── stage transitions (§6.3) — same transaction as the finished job ─────
@@ -231,7 +317,27 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
231
317
  * Steps 1(validate)–5 of §7 for a file already on disk at tmpPath.
232
318
  * @returns {Promise<{status:number, code?:string, reason?:string, idempotent?:boolean, sha256?:string, job_status?:string, stage_jobs_created?:number}>}
233
319
  */
234
- async function finishAccept(pre, attempt, tmpPath, sha, bytes) {
320
+ async function finishAccept(pre, attempt, tmpPath, sha, bytes, t0 = Date.now()) {
321
+ const r = await finishAcceptInner(pre, attempt, tmpPath, sha, bytes, t0);
322
+ // О3: `accept` for a committed result (or its idempotent replay); a stale
323
+ // attempt is an `error` line (code stale_attempt); invalid_result is logged by failAttempt.
324
+ const ids = {
325
+ book_id: pre.book_id, command_id: pre.command_id, job_id: pre.job_id, kind: pre.kind, unit_key: pre.unit_key,
326
+ attempt, worker_id: pre.worker_id,
327
+ };
328
+ if (r && r.status === 200) {
329
+ genLog.event('accept', {
330
+ ...ids, sha256: sha, bytes, width: r.width, height: r.height, idempotent: r.idempotent === true ? true : undefined,
331
+ stage_jobs_created: r.stage_jobs_created, ms: Date.now() - t0, run_ms: msBetween(pre.claimed_at),
332
+ });
333
+ } else if (r && r.code === 'stale_attempt') {
334
+ genLog.event('error', { ...ids, code: 'stale_attempt', sha256: sha, bytes });
335
+ }
336
+ if (r) { delete r.width; delete r.height; }
337
+ return r;
338
+ }
339
+
340
+ async function finishAcceptInner(pre, attempt, tmpPath, sha, bytes) {
235
341
  const finalPath = ports.artifactPath(pre);
236
342
  if (typeof finalPath !== 'string' || !path.isAbsolute(finalPath)) {
237
343
  await unlinkQuiet(tmpPath);
@@ -269,6 +375,7 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
269
375
  await fs.promises.mkdir(path.dirname(finalPath), { recursive: true });
270
376
  await fs.promises.rename(tmpPath, finalPath); // §7 п.3 (atomic, same partition)
271
377
  renamed = true;
378
+ await fs.promises.chmod(finalPath, ARTIFACT_MODE).catch(() => {}); // О3: 0644 like legacy outputs
272
379
  if (ports.onArtifactPlaced) await ports.onArtifactPlaced(job, finalPath); // e.g. drop the placeholder sidecar
273
380
  await client.query(
274
381
  `UPDATE gen_jobs SET status = 'done', result_path = $2, result_sha256 = $3, result_bytes = $4,
@@ -282,7 +389,10 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
282
389
  await upsertSceneAsset(client, job, finalPath, sha, bytes, validation);
283
390
  const stage = await transitions(client, cmds, job);
284
391
  await notifyProgress(client, job.book_id, job.command_id);
285
- return { status: 200, sha256: sha, job_status: 'done', stage_jobs_created: stage };
392
+ return {
393
+ status: 200, sha256: sha, job_status: 'done', stage_jobs_created: stage,
394
+ width: validation ? dim(validation.width) : null, height: validation ? dim(validation.height) : null,
395
+ };
286
396
  });
287
397
  } finally {
288
398
  if (!renamed) await unlinkQuiet(tmpPath); // rejected / failed before rename → discard
@@ -306,6 +416,7 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
306
416
  * @param {AsyncIterable<Buffer>} stream raw file body
307
417
  */
308
418
  async function acceptResult(jobId, attempt, token, stream) {
419
+ const t0 = Date.now();
309
420
  checkIds(jobId, attempt);
310
421
  if (!verifyUploadToken(uploadSecret, token, jobId, attempt)) {
311
422
  await drain(stream);
@@ -314,7 +425,11 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
314
425
  const pre = await readJob(jobId);
315
426
  if (!pre) { await drain(stream); throw new GenError('not_found', 404, 'unknown job'); }
316
427
  const current = (pre.status === 'running' || pre.status === 'done') && pre.attempt === attempt;
317
- if (!current) { await drain(stream); return { status: 409, code: 'stale_attempt' }; }
428
+ if (!current) {
429
+ await drain(stream);
430
+ genLog.event('error', { book_id: pre.book_id, command_id: pre.command_id, job_id: jobId, kind: pre.kind, unit_key: pre.unit_key, attempt, code: 'stale_attempt' });
431
+ return { status: 409, code: 'stale_attempt' };
432
+ }
318
433
 
319
434
  const finalPath = ports.artifactPath(pre);
320
435
  if (typeof finalPath !== 'string' || !path.isAbsolute(finalPath)) {
@@ -343,7 +458,7 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
343
458
  throw err;
344
459
  }
345
460
  await fh.close();
346
- return finishAccept(pre, attempt, tmpPath, hash.digest('hex'), bytes);
461
+ return finishAccept(pre, attempt, tmpPath, hash.digest('hex'), bytes, t0);
347
462
  }
348
463
 
349
464
  /**
package/src/gen/claim.js CHANGED
@@ -17,7 +17,9 @@ const {
17
17
 
18
18
  const MODES = Object.freeze(['private', 'share', 'system']);
19
19
 
20
- function createClaim({ pool, ports, uploadSecret, accept, sharedLimit = null, tokenGraceMs = 15 * 60_000 }) {
20
+ const NOOP_LOG = Object.freeze({ event() {} });
21
+
22
+ function createClaim({ pool, ports, uploadSecret, accept, sharedLimit = null, tokenGraceMs = 15 * 60_000, genLog = NOOP_LOG }) {
21
23
  const timeoutsJson = JSON.stringify(Object.fromEntries(KINDS.map((k) => [k, ports.timeoutFor(k)])));
22
24
 
23
25
  /**
@@ -32,6 +34,7 @@ function createClaim({ pool, ports, uploadSecret, accept, sharedLimit = null, to
32
34
  * @returns {Promise<{task:null}|{task:object}>}
33
35
  */
34
36
  async function claim(p = {}) {
37
+ const t0 = Date.now();
35
38
  const workerId = requireUuid(p.workerId, 'workerId');
36
39
  if (!WORKER_TYPES.includes(p.workerType)) throw new GenError('bad_request', 400, 'workerType must be audio|image|video');
37
40
  if (!MODES.includes(p.mode)) throw new GenError('bad_request', 400, 'mode must be private|share|system');
@@ -108,6 +111,10 @@ function createClaim({ pool, ports, uploadSecret, accept, sharedLimit = null, to
108
111
  }
109
112
  const deadlineMs = new Date(job.deadline).getTime();
110
113
  const exp = deadlineMs + tokenGraceMs;
114
+ genLog.event('claim', {
115
+ book_id: job.book_id, command_id: job.command_id, job_id: job.job_id, kind: job.kind, unit_key: job.unit_key,
116
+ attempt: job.attempt, max_attempts: job.max_attempts, worker_id: workerId, ms: Date.now() - t0,
117
+ });
111
118
  return {
112
119
  task: {
113
120
  job_id: job.job_id,
@@ -10,6 +10,8 @@
10
10
 
11
11
  'use strict';
12
12
 
13
+ const NOOP_LOG = Object.freeze({ event() {} });
14
+
13
15
  const {
14
16
  GenError, withTx, requireUuid, requireText, isUuid, notifyProgress, linkJobs,
15
17
  EXECUTOR_OF_KIND, LAYER_OF_KIND, FIRST_STAGE_KINDS, LAYERS,
@@ -88,13 +90,13 @@ async function purgeBookRows(pool, bookId) {
88
90
  });
89
91
  }
90
92
 
91
- function createCommands({ pool, ports }) {
93
+ function createCommands({ pool, ports, genLog = NOOP_LOG }) {
92
94
  /**
93
95
  * ADR §6.1 — one transaction.
94
96
  * @returns {Promise<{command_id:string, created:boolean, existing:boolean, status:string, layers:string[],
95
97
  * summary:{jobs_created:number, joined:number, skipped_ready:number}}>}
96
98
  */
97
- async function createCommand(params = {}) {
99
+ async function createCommandTx(params = {}) {
98
100
  const workspaceId = requireUuid(params.workspaceId, 'workspaceId');
99
101
  const userId = requireUuid(params.userId, 'userId');
100
102
  const bookId = requireText(params.bookId, 'bookId');
@@ -196,6 +198,32 @@ function createCommands({ pool, ports }) {
196
198
  if (readyKeys.has(gkey(u))) { skipped += 1; return false; }
197
199
  return true;
198
200
  });
201
+ // 1.1.0 — part-level readiness (opt-in: the unit carries input.part_hash).
202
+ // A part (e.g. one IU picture) whose accepted snapshot hash is recorded in
203
+ // scene_assets.metadata.gen_parts[unit_key].part_hash for the same build is
204
+ // already done for the current content — skip it even if its scene is not
205
+ // complete («сгенерировать недостающее» = only the missing / changed parts).
206
+ // A row the host marked 'stale' proves nothing. Units without part_hash
207
+ // (audio) keep the scene-level rule above unchanged.
208
+ const parted = todo.filter((u) => typeof u.input.part_hash === 'string' && u.input.part_hash);
209
+ if (parted.length) {
210
+ const r = await client.query(
211
+ `SELECT t.ord FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])
212
+ WITH ORDINALITY AS t(chapter_id, scene_id, asset_type, build_id, unit_key, part_hash, ord)
213
+ WHERE EXISTS (SELECT 1 FROM scene_assets a
214
+ WHERE a.book_id = $1 AND a.chapter_id = t.chapter_id AND a.scene_id = t.scene_id
215
+ AND a.asset_type = t.asset_type AND a.build_id = t.build_id
216
+ AND a.status IN ('pending', 'ready')
217
+ AND jsonb_typeof(a.metadata->'gen_parts') = 'object'
218
+ AND a.metadata->'gen_parts'->t.unit_key->>'part_hash' = t.part_hash)`,
219
+ [bookId, parted.map((u) => u.chapter_id), parted.map((u) => u.scene_id), parted.map((u) => LAYER_OF_KIND[u.kind]),
220
+ parted.map((u) => u.build_id), parted.map((u) => u.unit_key), parted.map((u) => u.input.part_hash)]);
221
+ const done = new Set(r.rows.map((row) => parted[Number(row.ord) - 1]));
222
+ if (done.size) {
223
+ skipped += done.size;
224
+ todo = todo.filter((u) => !done.has(u));
225
+ }
226
+ }
199
227
  }
200
228
 
201
229
  // lanes, one lookup per worker type (§4.2: computed at creation)
@@ -271,7 +299,8 @@ function createCommands({ pool, ports }) {
271
299
  * command waits for them (gen_command_jobs) — shared jobs keep running
272
300
  * @param {object} target
273
301
  * @param {{cancelledBy?:string}} [opts]
274
- * @returns {Promise<{commands_cancelled:number, jobs_cancelled:number, job_ids:string[], kept_shared:number}>}
302
+ * @returns {Promise<{commands_cancelled:number, jobs_cancelled:number, job_ids:string[], kept_shared:number, layers?:string[]}>}
303
+ * layers (1.1.0, {commandId} only): the layers of the command that was stopped
275
304
  */
276
305
  async function cancel(target = {}, opts = {}) {
277
306
  const by = opts.cancelledBy == null ? null : String(opts.cancelledBy).slice(0, 200);
@@ -294,7 +323,7 @@ function createCommands({ pool, ports }) {
294
323
  if (commandId !== undefined) {
295
324
  commands = (await client.query(
296
325
  `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;
326
+ WHERE command_id = $1 AND status = 'active' RETURNING command_id, book_id, layers`, [commandId, by])).rows;
298
327
  jobs = await client.query(
299
328
  `UPDATE gen_jobs j SET status = 'cancelled', finished_at = now()
300
329
  FROM gen_command_jobs l
@@ -321,17 +350,32 @@ function createCommands({ pool, ports }) {
321
350
  }
322
351
  const books = new Set([...commands.map((c) => c.book_id), ...jobs.rows.map((j) => j.book_id)]);
323
352
  for (const b of books) await notifyProgress(client, b, commandId || null);
324
- return {
353
+ const out = {
325
354
  commands_cancelled: commands.length,
326
355
  jobs_cancelled: jobs.rowCount,
327
356
  job_ids: jobs.rows.map((j) => j.job_id),
328
357
  kept_shared: keptShared,
329
358
  };
359
+ if (commandId !== undefined) out.layers = commands.length ? commands[0].layers : []; // 1.1.0
360
+ return out;
330
361
  });
331
362
  }
332
363
 
333
364
  const purgeBook = (bookId) => purgeBookRows(pool, bookId);
334
365
 
366
+ /** createCommandTx + the О3 `command-created` info line (also for a repeated click: existing=true). */
367
+ async function createCommand(params = {}) {
368
+ const t0 = Date.now();
369
+ const r = await createCommandTx(params);
370
+ genLog.event('command-created', {
371
+ book_id: params.bookId, command_id: r.command_id, layers: r.layers, status: r.status,
372
+ scope: params.scope && params.scope.level, existing: r.existing === true ? true : undefined,
373
+ jobs_created: r.summary && r.summary.jobs_created, joined: r.summary && r.summary.joined,
374
+ skipped_ready: r.summary && r.summary.skipped_ready, ms: Date.now() - t0,
375
+ });
376
+ return r;
377
+ }
378
+
335
379
  return { createCommand, cancel, purgeBook };
336
380
  }
337
381
 
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.2.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
@@ -25,6 +25,7 @@ const { createAccept } = require('./accept');
25
25
  const { createSweeper } = require('./sweeper');
26
26
  const { createProgress } = require('./progress');
27
27
  const { createLocalRunner } = require('./local-runner');
28
+ const { createGenLog, formatGenEvent } = require('./log');
28
29
 
29
30
  /**
30
31
  * @param {object} o
@@ -37,7 +38,7 @@ const { createLocalRunner } = require('./local-runner');
37
38
  * @param {number} [o.incomingMaxAgeMs=3600000] §9 п.4
38
39
  * @param {number} [o.tokenGraceMs=900000] upload token validity after the deadline
39
40
  * @param {number} [o.maxUploadBytes]
40
- * @param {object} [o.logger=console]
41
+ * @param {object} [o.logger=console] host logger port: info/log ([gen-v2] events, О3), error
41
42
  */
42
43
  function createOrchestration(o = {}) {
43
44
  const { pool } = o;
@@ -54,10 +55,12 @@ function createOrchestration(o = {}) {
54
55
  const ports = portsMod.validatePorts(o.ports);
55
56
  const logger = o.logger || console;
56
57
 
57
- const accept = createAccept({ pool, ports, uploadSecret: secret, maxUploadBytes: o.maxUploadBytes });
58
- const commands = createCommands({ pool, ports });
59
- const claim = createClaim({ pool, ports, uploadSecret: secret, accept, sharedLimit: o.sharedLimit ?? null, tokenGraceMs: o.tokenGraceMs });
60
- const sweeper = createSweeper({ pool, accept, outputDir: o.outputDir || null, offlineAfterMs: o.offlineAfterMs, incomingMaxAgeMs: o.incomingMaxAgeMs, logger });
58
+ // О3: one-line [gen-v2] info events through the host logger port (gen/log.js)
59
+ const genLog = createGenLog(logger);
60
+ const accept = createAccept({ pool, ports, uploadSecret: secret, maxUploadBytes: o.maxUploadBytes, genLog });
61
+ const commands = createCommands({ pool, ports, genLog });
62
+ const claim = createClaim({ pool, ports, uploadSecret: secret, accept, sharedLimit: o.sharedLimit ?? null, tokenGraceMs: o.tokenGraceMs, genLog });
63
+ const sweeper = createSweeper({ pool, accept, outputDir: o.outputDir || null, offlineAfterMs: o.offlineAfterMs, incomingMaxAgeMs: o.incomingMaxAgeMs, logger, genLog });
61
64
  const progress = createProgress({ pool });
62
65
  const local = createLocalRunner({ pool, ports, accept, logger });
63
66
 
@@ -95,13 +98,18 @@ module.exports = Object.freeze({
95
98
  ...portsMod.defaults,
96
99
  createDefaultValidateResult: media.createDefaultValidateResult,
97
100
  createAudioValidator: media.createAudioValidator,
101
+ createPngValidator: media.createPngValidator,
98
102
  }),
99
103
  media: Object.freeze({
100
104
  inspectMp3: media.inspectMp3,
101
105
  rmsDbfs: media.rmsDbfs,
102
106
  ffmpegDecodePcm: media.ffmpegDecodePcm,
103
107
  DEFAULT_RMS_THRESHOLD_DBFS: media.DEFAULT_RMS_THRESHOLD_DBFS,
108
+ inspectPng: media.inspectPng,
109
+ DEFAULT_MIN_LUMA_STDDEV: media.DEFAULT_MIN_LUMA_STDDEV,
104
110
  }),
105
111
  GenError: util.GenError,
112
+ /** pure formatter of the [gen-v2] info lines (О3) — for host tests / log parsers */
113
+ formatGenEvent,
106
114
  PROGRESS_CHANNEL: util.PROGRESS_CHANNEL,
107
115
  });
@@ -11,7 +11,7 @@
11
11
 
12
12
  const { withTx, notifyProgress } = require('./util');
13
13
 
14
- function createLocalRunner({ pool, ports, accept, logger = console }) {
14
+ function createLocalRunner({ pool, ports, accept, logger = null }) {
15
15
  const timeoutsJson = JSON.stringify({
16
16
  audio_merge: ports.timeoutFor('audio_merge'),
17
17
  video_merge: ports.timeoutFor('video_merge'),
@@ -60,7 +60,7 @@ function createLocalRunner({ pool, ports, accept, logger = console }) {
60
60
  try {
61
61
  while (!stopped && await runLocalOnce()) { /* drain */ }
62
62
  } catch (err) {
63
- logger.error && logger.error(`[gen-v2] local runner: ${err && err.message}`);
63
+ logger && logger.error && logger.error(`[gen-v2] local runner: ${err && err.message}`);
64
64
  } finally { running = false; }
65
65
  }
66
66
  if (!stopped) { timer = setTimeout(tick, intervalMs); if (timer.unref) timer.unref(); }
package/src/gen/log.js ADDED
@@ -0,0 +1,63 @@
1
+ // ======================================================
2
+ // gen/log — one-line info events of the v2 core (О3)
3
+ // ======================================================
4
+ // reports/2026-11-07/orch-v2-image-scene-run.md О3: claim, acceptance and the
5
+ // end of a command left no trace in the backend log; the run had to be
6
+ // reconstructed from HTTP lines, PG and the worker's own log.
7
+ //
8
+ // [gen-v2] <event> key=value key=value ...
9
+ //
10
+ // Events: command-created | claim | accept | error | requeue | command-finished.
11
+ // The logger is the host's port (createOrchestration({ logger })); the core
12
+ // never calls console itself. Only ALLOWLISTED fields are printed — never an
13
+ // upload token, a path or a payload (those may carry secrets or user text).
14
+
15
+ 'use strict';
16
+
17
+ const FIELDS = Object.freeze([
18
+ 'book_id', 'command_id', 'job_id', 'kind', 'unit_key', 'attempt', 'max_attempts', 'worker_id', 'executor', 'source',
19
+ 'status', 'job_status', 'code', 'error_class', 'retry', 'delay_ms',
20
+ 'sha256', 'bytes', 'width', 'height', 'idempotent', 'stage_jobs_created',
21
+ 'layers', 'scope', 'existing', 'jobs_created', 'joined', 'skipped_ready', 'done', 'failed', 'cancelled',
22
+ 'ms', 'run_ms',
23
+ ]);
24
+ const ALLOWED = new Set(FIELDS);
25
+
26
+ function fmt(v) {
27
+ if (v === null || v === undefined) return null;
28
+ if (Array.isArray(v)) return v.map(String).join(',');
29
+ if (typeof v === 'object') return JSON.stringify(v);
30
+ const s = String(v);
31
+ return /[\s"=]/.test(s) ? JSON.stringify(s) : s;
32
+ }
33
+
34
+ /** Pure: event name + fields → the log line (allowlisted keys, stable order). */
35
+ function formatGenEvent(event, fields = {}) {
36
+ const parts = [`[gen-v2] ${event}`];
37
+ for (const k of FIELDS) {
38
+ if (!Object.prototype.hasOwnProperty.call(fields, k)) continue;
39
+ const v = fmt(fields[k]);
40
+ if (v !== null) parts.push(`${k}=${v}`);
41
+ }
42
+ return parts.join(' ');
43
+ }
44
+
45
+ /** @param {object|null|undefined} logger host logger port ({info?, log?, warn?, error?}) */
46
+ function createGenLog(logger) {
47
+ const sink = logger && (typeof logger.info === 'function' ? logger.info.bind(logger)
48
+ : typeof logger.log === 'function' ? logger.log.bind(logger) : null);
49
+ function event(name, fields) {
50
+ if (!sink) return;
51
+ try { sink(formatGenEvent(name, fields)); } catch (_) { /* logging never breaks the core */ }
52
+ }
53
+ return { event };
54
+ }
55
+
56
+ /** Milliseconds between two timestamps (Date | string | number); null when unknown. */
57
+ function msBetween(from, to = Date.now()) {
58
+ const a = from instanceof Date ? from.getTime() : (from == null ? NaN : new Date(from).getTime());
59
+ const b = to instanceof Date ? to.getTime() : new Date(to).getTime();
60
+ return Number.isFinite(a) && Number.isFinite(b) ? Math.max(0, Math.round(b - a)) : null;
61
+ }
62
+
63
+ module.exports = { createGenLog, formatGenEvent, msBetween, FIELDS, ALLOWED };
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)
@@ -14,10 +14,13 @@
14
14
  const fs = require('fs');
15
15
  const path = require('path');
16
16
  const { withTx, notifyProgress } = require('./util');
17
+ const { msBetween } = require('./log');
17
18
 
18
19
  const BATCH = 200;
19
20
 
20
- function createSweeper({ pool, accept, outputDir = null, offlineAfterMs = 60_000, incomingMaxAgeMs = 60 * 60_000, logger = console }) {
21
+ const NOOP_LOG = Object.freeze({ event() {} });
22
+
23
+ function createSweeper({ pool, accept, outputDir = null, offlineAfterMs = 60_000, incomingMaxAgeMs = 60 * 60_000, logger = null, genLog = NOOP_LOG }) {
21
24
  const offlineAfterS = Math.max(1, Math.round(offlineAfterMs / 1000));
22
25
 
23
26
  async function failMany(rows, cls, reason) {
@@ -59,9 +62,15 @@ function createSweeper({ pool, accept, outputDir = null, offlineAfterMs = 60_000
59
62
  `UPDATE gen_commands SET status = $2, finished_at = now(), error = $3 WHERE command_id = $1`,
60
63
  [id, status, err]);
61
64
  await notifyProgress(client, c.book_id, id);
62
- return true;
65
+ return { book_id: c.book_id, status, k, run_ms: msBetween(c.created_at) };
63
66
  });
64
- if (done) n += 1;
67
+ if (done) {
68
+ n += 1;
69
+ genLog.event('command-finished', {
70
+ book_id: done.book_id, command_id: id, status: done.status,
71
+ done: done.k.done, failed: done.k.failed, cancelled: done.k.cancelled, run_ms: done.run_ms,
72
+ });
73
+ }
65
74
  }
66
75
  return n;
67
76
  }
@@ -121,7 +130,7 @@ function createSweeper({ pool, accept, outputDir = null, offlineAfterMs = 60_000
121
130
  if (!busy) {
122
131
  busy = true;
123
132
  try { await sweepOnce(); } catch (err) {
124
- logger.error && logger.error(`[gen-v2] sweeper: ${err && err.message}`);
133
+ logger && logger.error && logger.error(`[gen-v2] sweeper: ${err && err.message}`);
125
134
  } finally { busy = false; }
126
135
  }
127
136
  if (!stopped) { timer = setTimeout(tick, intervalMs); if (timer.unref) timer.unref(); }
@@ -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;