@animastor/orchestration 1.2.0 → 1.4.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,54 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.4.1 (2026-11-17, unpublished)
4
+
5
+ Только зависимость: `@animastor/generation` ^0.3.0 (VBook 4, шаг 3 — реестр инвалидации на героях).
6
+ Кода оркестрации изменение не касается.
7
+
8
+ ## 1.4.0 (2026-11-12, unpublished) — kind `voice_reference`
9
+
10
+ Основание: animastor-docs `architecture/VOICE_REFERENCES.md`. Minor: прежние порты не меняются.
11
+
12
+ - **Kind `voice_reference`** — кандидат референса голоса героя (или нормализация загруженного файла)
13
+ на аудио-воркере: executor `gpu:audio`, слой `audio`, таймаут 15 мин. Не сценовый ассет: приём
14
+ не пишет `scene_assets`, переходов стадий нет (`NON_SCENE_KINDS`).
15
+ - **Команда `kind: 'voice_reference'`**: `layers: ['audio']`, `scope = {level:'book', voice:{…}}`
16
+ (`voice` — непрозрачные данные хоста, ≤ 16 КиБ); layer-config книги не применяется. Планировщик
17
+ получает `planCtx.kind`; команда `voice_reference` принимает только units `voice_reference`, другие
18
+ команды — только прочие kinds (`bad_plan`).
19
+ - **Миграция `005-voice-reference`** — новые определения `gen_jobs_kind_check`,
20
+ `gen_jobs_kind_executor_check`, `gen_jobs_layer_kind_check`, `gen_commands_kind_check` (имена прежние,
21
+ идемпотентно).
22
+ - **WAV-валидатор** `createWavValidator` / `media.inspectWav`: RIFF/WAVE, PCM s16, непустой `data`,
23
+ не тишина (RMS по PCM, без ffmpeg). `createDefaultValidateResult` диспатчит `voice_reference` → wav.
24
+ - Экспорт `KINDS`.
25
+
26
+ ## 1.3.0 (2026-11-09) — этап 3a: видео (`video_group` + `video_merge`)
27
+
28
+ Основание: ADR `ORCHESTRATION_V2.md` §6.3, §6.5, §8.1, §13 п.11. Minor: порты 1.0–1.2 не меняются,
29
+ новое — дополнительно (лишний аргумент `ctx`, объектная форма ответа планировщика video, порт `inputFiles`).
30
+
31
+ - **Планирование на транзакции.** `planUnits(book, scope, layer, ctx)`, `ctx.db` — клиент транзакции
32
+ команды или приёма. Слои audio / image планируются и вставляются первыми, video — последним, чтобы
33
+ планировщик видел только что созданные работы этой же команды.
34
+ - **Ответ video `{units, waits, skipped}`.** `waits` — сцена ждёт живые `iu_image` / `audio_chunk` /
35
+ `audio_merge`: команда присоединяется к ним (`gen_command_jobs`), группы появятся переходом.
36
+ `skipped` — `{chapter_id, scene_id, reason: 'skipped_*'}` → `summary[reason] = [scene_id…]` и таблица
37
+ **`gen_command_skips`** (миграция `004-command-skips`, insert-only — приём не обновляет `gen_commands`).
38
+ `progress().commands[].skipped`.
39
+ - **Переходы (§6.3).** `audio_chunk → audio_merge` также для видео-команд, ждущих это аудио;
40
+ `audio_merge → ступень video`; `iu_image → ступень video`; `video_group → video_merge` по
41
+ `input.merge_parts` (все части плана сцены `done` с тем же `part_hash`, ни одной живой), иначе прежнее
42
+ правило. Ступень video уважает `part_hash` готовых групп; все группы готовы, склейки для этого контента
43
+ нет → только `video_merge` (и при создании команды без `force`).
44
+ - **Хуки.** `onArtifactPlaced(job, finalPath, {db, meta})`: `db` — транзакция приёма, `meta` — то, что
45
+ `runLocal` вернул рядом с `{path}`.
46
+ - **Входные файлы (§8.1).** Необязательный порт `inputFiles(job)` → `[{name, path, sha256, bytes}]`;
47
+ задача выдачи несёт `input_files: [{name, sha256, bytes}]`; `orch.openInput(jobId, attempt, token, name)`
48
+ — тот же токен, только текущая `running`-попытка (`409 stale_attempt`), только имена из списка (`404`),
49
+ байты = sha256 снимка (`409 input_changed`).
50
+ - Тесты: `test/gen/video.test.js` (10).
51
+
3
52
  ## 1.2.0 (2026-11-07) — наблюдаемость v2 (О3)
4
53
 
5
54
  Основание: `reports/2026-11-07/orch-v2-image-scene-run.md` О3 и «мелочи». Minor: только
package/README.md CHANGED
@@ -39,6 +39,17 @@ with `book_id`, `command_id`, `job_id`, `kind`, `unit_key`, `attempt`,
39
39
  tokens, paths or task params). Image acceptance records `width`/`height`;
40
40
  accepted files are `0644`.
41
41
 
42
+ **1.3.0 (video, stage 3a).** `planUnits(book, scope, layer, ctx)` gets
43
+ `ctx.db` (the command / acceptance transaction); for `video` it may answer
44
+ `{units, waits, skipped}` — waits join the live images / audio of the scene,
45
+ skip reasons (`skipped_*`) land in the command summary and in
46
+ `gen_command_skips` (migration 004, `progress().commands[].skipped`). Stage
47
+ transitions: `audio_merge → video`, `iu_image → video`, `video_group →
48
+ video_merge` by `input.merge_parts`; all parts done, no merge → the merge alone.
49
+ `onArtifactPlaced(job, path, {db, meta})` (meta = what `runLocal` returned);
50
+ optional port `inputFiles(job)` → `task.input_files` + `orch.openInput(…)` for
51
+ `GET /internal/gen/jobs/:id/input/:name` (ADR §8.1).
52
+
42
53
  `gen` requires only node builtins and its own files: no `src/legacy`, Redis,
43
54
  Express or ComfyUI. Tests: `npm run test:gen` (env `PG_*` of the animastor-test
44
55
  stack; refuses a DB not ending in `_test` or port 5432).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@animastor/orchestration",
3
- "version": "1.2.0",
3
+ "version": "1.4.1",
4
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",
@@ -44,7 +44,7 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@animastor/contracts": "^0.1.0",
47
- "@animastor/generation": "^0.1.0",
47
+ "@animastor/generation": "^0.3.0",
48
48
  "music-metadata": "^11.12.3"
49
49
  },
50
50
  "devDependencies": {
package/src/gen/accept.js CHANGED
@@ -19,10 +19,13 @@ const crypto = require('crypto');
19
19
 
20
20
  const {
21
21
  GenError, withTx, isUuid, notifyProgress, verifyUploadToken, linkJobs,
22
- EXECUTOR_OF_KIND, LAYER_OF_KIND, LIVE,
22
+ EXECUTOR_OF_KIND, LAYER_OF_KIND, LIVE, NON_SCENE_KINDS,
23
23
  } = require('./util');
24
24
  const { checkLane } = require('./ports');
25
25
  const { msBetween } = require('./log');
26
+ const {
27
+ normalisePlan, readyParts, mergePartsOf, mergeUnitFor, linkSceneLive, recordSkips,
28
+ } = require('./stage');
26
29
 
27
30
  const NOOP_LOG = Object.freeze({ event() {} });
28
31
  /** Mode of an accepted artifact: world-readable like the legacy outputs (О3; the tmp file is 0640). */
@@ -119,6 +122,7 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
119
122
 
120
123
  // ── scene_assets (§4.3: written only by acceptance) ──────────────────────
121
124
  async function upsertSceneAsset(client, job, finalPath, sha, bytes, validation) {
125
+ if (NON_SCENE_KINDS.includes(job.kind)) return; // 1.4.0: voice_reference is not a scene asset
122
126
  const assetType = job.layer;
123
127
  const build = job.build_id;
124
128
  const sceneHash = job.input.scene_hash || null;
@@ -272,43 +276,106 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
272
276
  return r.rows.map((x) => ({ unit_key: x.unit_key, job_id: x.job_id, path: x.result_path, sha256: x.result_sha256, meta: x.meta || null }));
273
277
  }
274
278
 
279
+ /** Is the scene asset of this layer already ready for exactly this content? */
280
+ async function sceneReady(client, job, layer, sceneHash) {
281
+ if (!sceneHash) return false;
282
+ const r = await client.query(
283
+ `SELECT 1 FROM scene_assets WHERE book_id = $1 AND chapter_id = $2 AND scene_id = $3 AND asset_type = $4
284
+ AND build_id = $5 AND status = 'ready' AND scene_hash = $6 LIMIT 1`,
285
+ [job.book_id, job.chapter_id, job.scene_id, layer, job.build_id, sceneHash]);
286
+ return r.rowCount > 0;
287
+ }
288
+
289
+ /**
290
+ * 1.3.0 — the video stage of one scene (§6.3, §6.5, §13 п.11): asked after the last
291
+ * IU of the scene and after its audio merge. The host video planner, run on THIS
292
+ * transaction, decides: groups now / wait (join the live images or audio) / skip
293
+ * with a reason (recorded for the commands, insert-only).
294
+ */
295
+ async function videoStage(client, qualifying, job) {
296
+ const owner = qualifying[0];
297
+ const ids = qualifying.map((c) => c.command_id);
298
+ const force = qualifying.some((c) => c.force === true);
299
+ const plan = normalisePlan(await ports.planUnits(
300
+ { bookId: owner.book_id, workspaceId: owner.workspace_id, userId: owner.user_id },
301
+ { level: 'scene', chapter_id: job.chapter_id, scene_id: job.scene_id }, 'video', { db: client }), 'video');
302
+ let units = plan.units.filter((u) => u && u.kind === 'video_group'
303
+ && u.chapter_id === job.chapter_id && u.scene_id === job.scene_id
304
+ && typeof u.unit_key === 'string' && u.unit_key && typeof u.build_id === 'string' && u.build_id
305
+ && u.input && typeof u.input === 'object')
306
+ .map((u) => ({ ...u, input: { ...u.input, scene_hash: u.scene_hash ?? u.input.scene_hash ?? null } }));
307
+ let created = 0;
308
+ if (units.length && !force) {
309
+ const sceneHash = units[0].input.scene_hash;
310
+ if (await sceneReady(client, units[0], 'video', sceneHash)) {
311
+ units = []; // the scene video is current
312
+ } else {
313
+ const done = await readyParts(client, job.book_id, units);
314
+ if (done.size === units.length && mergePartsOf(units[0].input)) {
315
+ const merge = await mergeUnitFor(client, job.book_id, units[0]);
316
+ if (merge) { created += await insertStageJobs(client, qualifying, [merge]); units = []; }
317
+ } else if (done.size) {
318
+ units = units.filter((u) => !done.has(u));
319
+ }
320
+ }
321
+ }
322
+ created += await insertStageJobs(client, qualifying, units);
323
+ if (plan.waits.length) await linkSceneLive(client, ids, job.book_id, plan.waits);
324
+ if (plan.skipped.length) await recordSkips(client, ids, plan.skipped);
325
+ return created;
326
+ }
327
+
275
328
  /**
276
329
  * §6.3: a next stage is created only if at least one command linked to the finished job is
277
330
  * active, has the layer and the layer is enabled; the new job is linked to all such commands.
331
+ * audio_chunk (last of the scene) → audio_merge — commands with audio, and (1.3.0) video
332
+ * commands waiting for this audio (§13 п.11 п.3)
333
+ * iu_image (last of the scene) → video stage — commands with video
334
+ * audio_merge → video stage — commands with video (1.3.0)
335
+ * video_group (last of the plan) → video_merge — by input.merge_parts (1.3.0) or, without
336
+ * it, every linked group of the scene
278
337
  */
279
338
  async function transitions(client, cmds, job) {
280
- const nextLayer = job.kind === 'iu_image' ? 'video' : job.layer;
281
- const qualifying = [];
282
- for (const c of cmds) {
283
- if (c.status === 'active' && c.layers.includes(nextLayer) && await ports.isLayerEnabled(c.book_id, nextLayer)) qualifying.push(c);
284
- }
285
- if (!qualifying.length) return 0;
286
- const ids = qualifying.map((c) => c.command_id);
339
+ const active = cmds.filter((c) => c.status === 'active');
340
+ if (!active.length) return 0;
341
+ const pick = async (layers, enabledLayer) => {
342
+ const out = [];
343
+ for (const c of active) {
344
+ if (layers.some((l) => c.layers.includes(l)) && await ports.isLayerEnabled(c.book_id, enabledLayer)) out.push(c);
345
+ }
346
+ return out;
347
+ };
348
+ const lockScene = () => client.query('SELECT pg_advisory_xact_lock(hashtext($1))', [sceneLockKey(job)]);
287
349
  const mergeInput = async (kind) => ({
288
350
  scene_hash: job.input.scene_hash ?? null,
289
351
  parts: await doneParts(client, job, kind),
290
352
  });
291
353
  const sceneUnit = (kind, input) => ({ chapter_id: job.chapter_id, scene_id: job.scene_id, kind, unit_key: 'scene', build_id: job.build_id, input });
292
354
 
293
- if (job.kind === 'audio_chunk' || job.kind === 'video_group' || job.kind === 'iu_image') {
294
- await client.query('SELECT pg_advisory_xact_lock(hashtext($1))', [sceneLockKey(job)]);
295
- if (!(await sceneStageComplete(client, job, job.kind, ids))) return 0;
296
- }
297
355
  if (job.kind === 'audio_chunk') {
298
- return insertStageJobs(client, qualifying, [sceneUnit('audio_merge', await mergeInput('audio_chunk'))]);
356
+ const q = await pick(['audio', 'video'], 'audio');
357
+ if (!q.length) return 0;
358
+ await lockScene();
359
+ if (!(await sceneStageComplete(client, job, 'audio_chunk', q.map((c) => c.command_id)))) return 0;
360
+ return insertStageJobs(client, q, [sceneUnit('audio_merge', await mergeInput('audio_chunk'))]);
299
361
  }
300
362
  if (job.kind === 'video_group') {
301
- return insertStageJobs(client, qualifying, [sceneUnit('video_merge', await mergeInput('video_group'))]);
363
+ const q = await pick(['video'], 'video');
364
+ if (!q.length) return 0;
365
+ await lockScene();
366
+ if (mergePartsOf(job.input)) {
367
+ const merge = await mergeUnitFor(client, job.book_id, job);
368
+ return merge ? insertStageJobs(client, q, [merge]) : 0;
369
+ }
370
+ if (!(await sceneStageComplete(client, job, 'video_group', q.map((c) => c.command_id)))) return 0;
371
+ return insertStageJobs(client, q, [sceneUnit('video_merge', await mergeInput('video_group'))]);
302
372
  }
303
- if (job.kind === 'iu_image') {
304
- const owner = qualifying[0];
305
- const planned = await ports.planUnits(
306
- { bookId: owner.book_id, workspaceId: owner.workspace_id, userId: owner.user_id },
307
- { level: 'scene', chapter_id: job.chapter_id, scene_id: job.scene_id }, 'video');
308
- const groups = (Array.isArray(planned) ? planned : []).filter((u) => u && u.kind === 'video_group'
309
- && u.chapter_id === job.chapter_id && u.scene_id === job.scene_id
310
- && typeof u.unit_key === 'string' && typeof u.build_id === 'string' && u.input && typeof u.input === 'object');
311
- return insertStageJobs(client, qualifying, groups.map((u) => ({ ...u, input: { ...u.input, scene_hash: u.scene_hash ?? u.input.scene_hash ?? null } })));
373
+ if (job.kind === 'iu_image' || job.kind === 'audio_merge') {
374
+ const q = await pick(['video'], 'video');
375
+ if (!q.length) return 0;
376
+ await lockScene();
377
+ if (job.kind === 'iu_image' && !(await sceneStageComplete(client, job, 'iu_image', q.map((c) => c.command_id)))) return 0;
378
+ return videoStage(client, q, job);
312
379
  }
313
380
  return 0;
314
381
  }
@@ -317,8 +384,8 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
317
384
  * Steps 1(validate)–5 of §7 for a file already on disk at tmpPath.
318
385
  * @returns {Promise<{status:number, code?:string, reason?:string, idempotent?:boolean, sha256?:string, job_status?:string, stage_jobs_created?:number}>}
319
386
  */
320
- async function finishAccept(pre, attempt, tmpPath, sha, bytes, t0 = Date.now()) {
321
- const r = await finishAcceptInner(pre, attempt, tmpPath, sha, bytes, t0);
387
+ async function finishAccept(pre, attempt, tmpPath, sha, bytes, t0 = Date.now(), localMeta = null) {
388
+ const r = await finishAcceptInner(pre, attempt, tmpPath, sha, bytes, localMeta);
322
389
  // О3: `accept` for a committed result (or its idempotent replay); a stale
323
390
  // attempt is an `error` line (code stale_attempt); invalid_result is logged by failAttempt.
324
391
  const ids = {
@@ -337,7 +404,7 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
337
404
  return r;
338
405
  }
339
406
 
340
- async function finishAcceptInner(pre, attempt, tmpPath, sha, bytes) {
407
+ async function finishAcceptInner(pre, attempt, tmpPath, sha, bytes, localMeta = null) {
341
408
  const finalPath = ports.artifactPath(pre);
342
409
  if (typeof finalPath !== 'string' || !path.isAbsolute(finalPath)) {
343
410
  await unlinkQuiet(tmpPath);
@@ -376,7 +443,8 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
376
443
  await fs.promises.rename(tmpPath, finalPath); // §7 п.3 (atomic, same partition)
377
444
  renamed = true;
378
445
  await fs.promises.chmod(finalPath, ARTIFACT_MODE).catch(() => {}); // О3: 0644 like legacy outputs
379
- if (ports.onArtifactPlaced) await ports.onArtifactPlaced(job, finalPath); // e.g. drop the placeholder sidecar
446
+ // e.g. drop the placeholder sidecar; 1.3.0: ctx.db = this transaction, ctx.meta = what runLocal returned
447
+ if (ports.onArtifactPlaced) await ports.onArtifactPlaced(job, finalPath, { db: client, meta: localMeta });
380
448
  await client.query(
381
449
  `UPDATE gen_jobs SET status = 'done', result_path = $2, result_sha256 = $3, result_bytes = $4,
382
450
  finished_at = now(), deadline = NULL
@@ -472,11 +540,11 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
472
540
  }
473
541
 
474
542
  /** Accept a file produced by the backend itself (executor='local'); no token. */
475
- async function acceptLocalFile(job, filePath) {
543
+ async function acceptLocalFile(job, filePath, meta = null) {
476
544
  const hash = crypto.createHash('sha256');
477
545
  let bytes = 0;
478
546
  for await (const chunk of fs.createReadStream(filePath)) { hash.update(chunk); bytes += chunk.length; }
479
- return finishAccept(job, job.attempt, filePath, hash.digest('hex'), bytes);
547
+ return finishAccept(job, job.attempt, filePath, hash.digest('hex'), bytes, Date.now(), meta);
480
548
  }
481
549
 
482
550
  return { acceptResult, acceptError, failAttempt, acceptLocalFile };
package/src/gen/claim.js CHANGED
@@ -11,10 +11,32 @@
11
11
 
12
12
  'use strict';
13
13
 
14
+ const fs = require('fs');
15
+ const crypto = require('crypto');
16
+
14
17
  const {
15
- GenError, withTx, requireUuid, isUuid, issueUploadToken, notifyProgress, KINDS, WORKER_TYPES,
18
+ GenError, withTx, requireUuid, isUuid, issueUploadToken, verifyUploadToken, notifyProgress, KINDS, WORKER_TYPES,
16
19
  } = require('./util');
17
20
 
21
+ const SAFE_INPUT_NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,200}$/;
22
+ const MAX_INPUTS = 16;
23
+
24
+ /** Validate the host's inputFiles(job) answer: plain file names, absolute paths, sha256. */
25
+ function listInputs(list) {
26
+ if (list == null) return [];
27
+ if (!Array.isArray(list) || list.length > MAX_INPUTS) throw new GenError('bad_inputs', 500, 'inputFiles(job) must return an array (<= 16)');
28
+ const seen = new Set();
29
+ return list.map((f) => {
30
+ const ok = f && typeof f.name === 'string' && SAFE_INPUT_NAME.test(f.name) && !f.name.includes('..')
31
+ && typeof f.path === 'string' && f.path.startsWith('/')
32
+ && typeof f.sha256 === 'string' && /^[0-9a-f]{64}$/.test(f.sha256)
33
+ && Number.isInteger(f.bytes) && f.bytes > 0;
34
+ if (!ok || seen.has(f.name)) throw new GenError('bad_inputs', 500, `inputFiles(job): invalid entry ${f && f.name}`);
35
+ seen.add(f.name);
36
+ return { name: f.name, path: f.path, sha256: f.sha256, bytes: f.bytes };
37
+ });
38
+ }
39
+
18
40
  const MODES = Object.freeze(['private', 'share', 'system']);
19
41
 
20
42
  const NOOP_LOG = Object.freeze({ event() {} });
@@ -102,8 +124,11 @@ function createClaim({ pool, ports, uploadSecret, accept, sharedLimit = null, to
102
124
  if (!job) return { task: null };
103
125
 
104
126
  let payload;
127
+ let inputs = null;
105
128
  try {
106
129
  payload = await ports.buildPayload(job);
130
+ // 1.3.0 — input files (e.g. IU frames of a video group) travel by link, not base64 (§8.1)
131
+ if (ports.inputFiles) inputs = listInputs(await ports.inputFiles(job));
107
132
  } catch (err) {
108
133
  // the payload cannot be built → this attempt fails deterministically (no silent loss)
109
134
  await accept.failAttempt(job.job_id, job.attempt, 'deterministic', `build_payload: ${err && err.message}`);
@@ -128,10 +153,37 @@ function createClaim({ pool, ports, uploadSecret, accept, sharedLimit = null, to
128
153
  timeout_ms: ports.timeoutFor(job.kind),
129
154
  deadline: new Date(deadlineMs).toISOString(),
130
155
  upload_token: issueUploadToken(uploadSecret, job.job_id, job.attempt, exp),
156
+ ...(inputs && inputs.length ? { input_files: inputs.map((f) => ({ name: f.name, sha256: f.sha256, bytes: f.bytes })) } : {}),
131
157
  },
132
158
  };
133
159
  }
134
160
 
161
+ /**
162
+ * GET /internal/gen/jobs/:job_id/input/:name?attempt=N (ADR §8.1, 1.3.0): the same
163
+ * upload token as the result; only the CURRENT running attempt; only a name the job
164
+ * lists; the bytes must still be the snapshot taken at planning (sha256) — a frame
165
+ * replaced in between → 409 input_changed (the video would not match its hash).
166
+ * @returns {Promise<{status:number, code?:string, body?:Buffer, name?:string, sha256?:string}>}
167
+ */
168
+ async function openInput(jobId, attempt, token, name) {
169
+ if (!isUuid(jobId)) return { status: 404, code: 'not_found' };
170
+ if (!Number.isInteger(attempt) || attempt < 1) return { status: 400, code: 'bad_request' };
171
+ if (!verifyUploadToken(uploadSecret, token, jobId, attempt)) return { status: 401, code: 'unauthorized' };
172
+ if (!ports.inputFiles) return { status: 404, code: 'not_found' };
173
+ const job = (await pool.query('SELECT * FROM gen_jobs WHERE job_id = $1', [jobId])).rows[0];
174
+ if (!job) return { status: 404, code: 'not_found' };
175
+ if (job.status !== 'running' || job.attempt !== attempt) return { status: 409, code: 'stale_attempt' };
176
+ let list;
177
+ try { list = listInputs(await ports.inputFiles(job)); } catch (_) { return { status: 404, code: 'not_found' }; }
178
+ const f = list.find((x) => x.name === name);
179
+ if (!f) return { status: 404, code: 'not_found' };
180
+ let body;
181
+ try { body = await fs.promises.readFile(f.path); } catch (_) { return { status: 409, code: 'input_missing' }; }
182
+ const sha = crypto.createHash('sha256').update(body).digest('hex');
183
+ if (sha !== f.sha256) return { status: 409, code: 'input_changed' };
184
+ return { status: 200, body, name: f.name, sha256: sha };
185
+ }
186
+
135
187
  /**
136
188
  * Worker liveness (ADR §8.3): last_seen + current_job_id; answer = jobs to stop.
137
189
  * cancel = this worker's jobs cancelled in the last hour + the reported
@@ -156,7 +208,7 @@ function createClaim({ pool, ports, uploadSecret, accept, sharedLimit = null, to
156
208
  });
157
209
  }
158
210
 
159
- return { claim, beacon };
211
+ return { claim, beacon, openInput };
160
212
  }
161
213
 
162
214
  module.exports = { createClaim, MODES };
@@ -17,13 +17,29 @@ const {
17
17
  EXECUTOR_OF_KIND, LAYER_OF_KIND, FIRST_STAGE_KINDS, LAYERS,
18
18
  } = require('./util');
19
19
  const { checkLane } = require('./ports');
20
+ const {
21
+ normalisePlan, readyParts, mergePartsOf, mergeUnitFor, linkSceneLive, recordSkips, skipSummary,
22
+ } = require('./stage');
20
23
 
21
- const COMMAND_KINDS = Object.freeze(['regenerate', 'generate_all']);
24
+ const COMMAND_KINDS = Object.freeze(['regenerate', 'generate_all', 'voice_reference']);
25
+ // 1.4.0 — voice_reference (VOICE_REFERENCES.md): the command creates
26
+ // voice_reference jobs only; layers = ['audio'] (the worker type), the book
27
+ // layer-config does not apply (a voice reference is not a book layer);
28
+ // scope = {level:'book', voice:{…}} — `voice` is opaque host data (≤ 16 KiB
29
+ // JSON) handed to planUnits via planCtx.kind / scope.voice.
30
+ const VOICE_SCOPE_MAX_BYTES = 16 * 1024;
22
31
  const SCOPE_LEVELS = Object.freeze(['book', 'chapter', 'scenes', 'scene', 'unit']);
23
32
  const MAX_SCOPE_SCENES = 10_000;
24
33
 
25
- function normaliseScope(scope) {
34
+ function normaliseScope(scope, kind = 'regenerate') {
26
35
  const s = scope && typeof scope === 'object' ? scope : null;
36
+ if (kind === 'voice_reference') {
37
+ if (!s || s.level !== 'book') throw new GenError('bad_request', 400, 'voice_reference: scope.level must be book');
38
+ const v = s.voice;
39
+ if (!v || typeof v !== 'object' || Array.isArray(v)) throw new GenError('bad_request', 400, 'voice_reference: scope.voice object required');
40
+ if (Buffer.byteLength(JSON.stringify(v)) > VOICE_SCOPE_MAX_BYTES) throw new GenError('bad_request', 400, 'voice_reference: scope.voice too large');
41
+ return { level: 'book', voice: JSON.parse(JSON.stringify(v)) };
42
+ }
27
43
  if (!s || !SCOPE_LEVELS.includes(s.level)) throw new GenError('bad_request', 400, 'scope.level must be book|chapter|scenes|scene|unit');
28
44
  const out = { level: s.level };
29
45
  const opt = (k) => { if (s[k] !== undefined && s[k] !== null) out[k] = requireText(s[k], `scope.${k}`); };
@@ -51,8 +67,10 @@ function unitFitsLayer(kind, layer) {
51
67
  return layer === 'video' && kind === 'iu_image';
52
68
  }
53
69
 
54
- function checkUnit(u, layer) {
55
- const ok = u && typeof u === 'object'
70
+ function checkUnit(u, layer, commandKind = 'regenerate') {
71
+ // a voice_reference command plans voice_reference units only, and no other command does
72
+ const kindOk = u && ((commandKind === 'voice_reference') === (u.kind === 'voice_reference'));
73
+ const ok = u && typeof u === 'object' && kindOk
56
74
  && FIRST_STAGE_KINDS.includes(u.kind) && unitFitsLayer(u.kind, layer)
57
75
  && typeof u.chapter_id === 'string' && u.chapter_id
58
76
  && typeof u.scene_id === 'string' && u.scene_id
@@ -102,8 +120,11 @@ function createCommands({ pool, ports, genLog = NOOP_LOG }) {
102
120
  const bookId = requireText(params.bookId, 'bookId');
103
121
  const kind = params.kind || 'regenerate';
104
122
  if (!COMMAND_KINDS.includes(kind)) throw new GenError('bad_request', 400, `kind must be ${COMMAND_KINDS.join('|')}`);
105
- const scope = normaliseScope(params.scope);
123
+ const scope = normaliseScope(params.scope, kind);
106
124
  const requested = Array.isArray(params.layers) ? [...new Set(params.layers)] : [];
125
+ if (kind === 'voice_reference' && (requested.length !== 1 || requested[0] !== 'audio')) {
126
+ throw new GenError('bad_request', 400, "voice_reference: layers must be ['audio']");
127
+ }
107
128
  if (requested.length === 0 || requested.some((l) => !LAYERS.includes(l))) {
108
129
  throw new GenError('bad_request', 400, 'layers must be a non-empty subset of audio|image|video');
109
130
  }
@@ -112,7 +133,9 @@ function createCommands({ pool, ports, genLog = NOOP_LOG }) {
112
133
 
113
134
  // §6.1 п.2: requested ∩ enabled (host layer-config passed in, or the optional port)
114
135
  let effective;
115
- if (Array.isArray(params.enabledLayers)) {
136
+ if (kind === 'voice_reference') {
137
+ effective = ['audio']; // not a book layer — layer-config does not apply
138
+ } else if (Array.isArray(params.enabledLayers)) {
116
139
  effective = requested.filter((l) => params.enabledLayers.includes(l));
117
140
  } else {
118
141
  effective = [];
@@ -153,78 +176,22 @@ function createCommands({ pool, ports, genLog = NOOP_LOG }) {
153
176
  if (ins.rowCount === 0) return existingResponse(await existingOf()); // concurrent twin committed first
154
177
  const cmd = ins.rows[0];
155
178
 
156
- // §6.1 п.3: plan units per layer
179
+ // §6.1 п.3: plan units per layer. Audio / image first, video last: the video
180
+ // planner (1.3.0) runs on THIS transaction and must see the image / audio jobs
181
+ // this very command has just created (they are what a video scene waits for).
157
182
  const bookRef = { bookId, workspaceId, userId };
158
- const units = [];
183
+ const planCtx = { db: client, kind };
159
184
  const seen = new Set();
160
- for (const layer of effective) {
161
- const planned = await ports.planUnits(bookRef, scope, layer);
162
- if (!Array.isArray(planned)) throw new GenError('bad_plan', 500, `planUnits(${layer}) must return an array`);
163
- for (const u of planned) {
164
- checkUnit(u, layer);
185
+ const takeUnits = (list, layer) => {
186
+ const out = [];
187
+ for (const u of list) {
188
+ checkUnit(u, layer, kind);
165
189
  if (seen.has(unitKey(u))) continue; // video+image may both plan the same IU
166
190
  seen.add(unitKey(u));
167
- units.push(u);
168
- }
169
- }
170
-
171
- // §6.1 п.3: skip units whose scene asset is ready for the current content (PG scene_assets only)
172
- let skipped = 0;
173
- let todo = units;
174
- if (!force && units.length) {
175
- const k5 = (g) => `${g.chapter_id}\u0000${g.scene_id}\u0000${g.asset_type}\u0000${g.build_id}\u0000${g.scene_hash}`;
176
- const gkey = (u) => k5({ ...u, asset_type: LAYER_OF_KIND[u.kind] });
177
- const groups = new Map();
178
- for (const u of units) {
179
- if (typeof u.scene_hash !== 'string' || !u.scene_hash) continue; // readiness unprovable → do it
180
- if (!groups.has(gkey(u))) groups.set(gkey(u), { chapter_id: u.chapter_id, scene_id: u.scene_id, asset_type: LAYER_OF_KIND[u.kind], build_id: u.build_id, scene_hash: u.scene_hash });
191
+ out.push(u);
181
192
  }
182
- const readyKeys = new Set();
183
- if (groups.size) {
184
- const list = [...groups.values()];
185
- const r = await client.query(
186
- `SELECT g.ord FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[])
187
- WITH ORDINALITY AS g(chapter_id, scene_id, asset_type, build_id, scene_hash, ord)
188
- WHERE EXISTS (SELECT 1 FROM scene_assets a
189
- WHERE a.book_id = $1 AND a.chapter_id = g.chapter_id AND a.scene_id = g.scene_id
190
- AND a.asset_type = g.asset_type AND a.build_id = g.build_id
191
- AND a.status = 'ready' AND a.scene_hash = g.scene_hash)`,
192
- [bookId, list.map((x) => x.chapter_id), list.map((x) => x.scene_id), list.map((x) => x.asset_type),
193
- list.map((x) => x.build_id), list.map((x) => x.scene_hash)]);
194
- for (const row of r.rows) readyKeys.add(k5(list[Number(row.ord) - 1]));
195
- }
196
- todo = units.filter((u) => {
197
- if (typeof u.scene_hash !== 'string' || !u.scene_hash) return true;
198
- if (readyKeys.has(gkey(u))) { skipped += 1; return false; }
199
- return true;
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
- }
227
- }
193
+ return out;
194
+ };
228
195
 
229
196
  // lanes, one lookup per worker type (§4.2: computed at creation)
230
197
  const laneCache = new Map();
@@ -242,10 +209,73 @@ function createCommands({ pool, ports, genLog = NOOP_LOG }) {
242
209
  return laneCache.get(type);
243
210
  };
244
211
 
245
- // §6.1 п.4: insert; a unit live under another command → joined (link to the live job)
246
212
  let created = 0;
247
213
  let joined = 0;
248
- if (todo.length) {
214
+ let skipped = 0;
215
+
216
+ /** §6.1 пп.3–4 for one batch of planned units: skip ready, insert / join the rest. */
217
+ const place = async (units) => {
218
+ let todo = units;
219
+ if (!force && units.length) {
220
+ // scene level: the scene asset is ready for the current content (PG scene_assets only)
221
+ const k5 = (g) => `${g.chapter_id}\u0000${g.scene_id}\u0000${g.asset_type}\u0000${g.build_id}\u0000${g.scene_hash}`;
222
+ const gkey = (u) => k5({ ...u, asset_type: LAYER_OF_KIND[u.kind] });
223
+ const groups = new Map();
224
+ for (const u of units) {
225
+ if (typeof u.scene_hash !== 'string' || !u.scene_hash) continue; // readiness unprovable → do it
226
+ if (!groups.has(gkey(u))) groups.set(gkey(u), { chapter_id: u.chapter_id, scene_id: u.scene_id, asset_type: LAYER_OF_KIND[u.kind], build_id: u.build_id, scene_hash: u.scene_hash });
227
+ }
228
+ const readyKeys = new Set();
229
+ if (groups.size) {
230
+ const list = [...groups.values()];
231
+ const r = await client.query(
232
+ `SELECT g.ord FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[])
233
+ WITH ORDINALITY AS g(chapter_id, scene_id, asset_type, build_id, scene_hash, ord)
234
+ WHERE EXISTS (SELECT 1 FROM scene_assets a
235
+ WHERE a.book_id = $1 AND a.chapter_id = g.chapter_id AND a.scene_id = g.scene_id
236
+ AND a.asset_type = g.asset_type AND a.build_id = g.build_id
237
+ AND a.status = 'ready' AND a.scene_hash = g.scene_hash)`,
238
+ [bookId, list.map((x) => x.chapter_id), list.map((x) => x.scene_id), list.map((x) => x.asset_type),
239
+ list.map((x) => x.build_id), list.map((x) => x.scene_hash)]);
240
+ for (const row of r.rows) readyKeys.add(k5(list[Number(row.ord) - 1]));
241
+ }
242
+ todo = units.filter((u) => {
243
+ if (typeof u.scene_hash !== 'string' || !u.scene_hash) return true;
244
+ if (readyKeys.has(gkey(u))) { skipped += 1; return false; }
245
+ return true;
246
+ });
247
+ // 1.1.0 — part-level readiness (opt-in: the unit carries input.part_hash).
248
+ // A part (e.g. one IU picture, one video group) whose accepted snapshot hash
249
+ // is recorded in scene_assets.metadata.gen_parts[unit_key].part_hash for the
250
+ // same build is already done for the current content — skip it even if its
251
+ // scene is not complete («сгенерировать недостающее» = only the missing /
252
+ // changed parts). A row the host marked 'stale' proves nothing. Units without
253
+ // part_hash (audio) keep the scene-level rule above unchanged.
254
+ const done = await readyParts(client, bookId, todo);
255
+ if (done.size) {
256
+ // 1.3.0 — a part kind with a merge stage (input.merge_parts: video_group):
257
+ // every part of the scene is already done but the scene is not ready for
258
+ // this content → the merge alone is created (local, no GPU). Parts whose
259
+ // done job cannot be found go back to the plan.
260
+ const byScene = new Map();
261
+ for (const u of todo) {
262
+ if (!mergePartsOf(u.input)) continue;
263
+ const sk = `${u.chapter_id}\u0000${u.scene_id}`;
264
+ if (!byScene.has(sk)) byScene.set(sk, []);
265
+ byScene.get(sk).push(u);
266
+ }
267
+ const extra = [];
268
+ for (const list of byScene.values()) {
269
+ if (!list.every((u) => done.has(u))) continue; // some parts run → the transition merges
270
+ const merge = await mergeUnitFor(client, bookId, list[0]);
271
+ if (merge) extra.push(merge);
272
+ else for (const u of list) done.delete(u);
273
+ }
274
+ skipped += done.size;
275
+ todo = todo.filter((u) => !done.has(u)).concat(extra);
276
+ }
277
+ }
278
+ if (!todo.length) return;
249
279
  const cols = { ch: [], sc: [], uk: [], kind: [], ex: [], layer: [], build: [], lane: [], max: [], input: [] };
250
280
  for (const u of todo) {
251
281
  const ex = EXECUTOR_OF_KIND[u.kind];
@@ -256,6 +286,7 @@ function createCommands({ pool, ports, genLog = NOOP_LOG }) {
256
286
  cols.max.push(ports.maxAttemptsFor(u.kind));
257
287
  cols.input.push(JSON.stringify({ ...u.input, scene_hash: u.scene_hash ?? u.input.scene_hash ?? null }));
258
288
  }
289
+ // §6.1 п.4: insert; a unit live under another command → joined (link to the live job)
259
290
  const ins2 = await client.query(
260
291
  `INSERT INTO gen_jobs (command_id, workspace_id, user_id, book_id, chapter_id, scene_id, unit_key,
261
292
  kind, executor, layer, build_id, lane, max_attempts, input, created_at)
@@ -270,7 +301,7 @@ function createCommands({ pool, ports, genLog = NOOP_LOG }) {
270
301
  RETURNING job_id`,
271
302
  [cmd.command_id, workspaceId, userId, bookId, cols.ch, cols.sc, cols.uk, cols.kind, cols.ex,
272
303
  cols.layer, cols.build, cols.lane, cols.max, cols.input]);
273
- created = ins2.rowCount;
304
+ created += ins2.rowCount;
274
305
  // live jobs of the same units (ours just inserted + other commands' → joined)
275
306
  const live = await client.query(
276
307
  `SELECT j.job_id, j.command_id FROM gen_jobs j
@@ -278,10 +309,37 @@ function createCommands({ pool, ports, genLog = NOOP_LOG }) {
278
309
  ON j.chapter_id = t.ch AND j.scene_id = t.sc AND j.kind = t.kind AND j.unit_key = t.uk
279
310
  WHERE j.book_id = $1 AND j.status IN ('queued','running')`,
280
311
  [bookId, cols.ch, cols.sc, cols.kind, cols.uk]);
281
- joined = live.rows.filter((r) => r.command_id !== cmd.command_id).length;
312
+ joined += live.rows.filter((r) => r.command_id !== cmd.command_id).length;
282
313
  await linkJobs(client, [cmd.command_id], live.rows.map((r) => r.job_id));
314
+ };
315
+
316
+ const nonVideo = [];
317
+ for (const layer of effective.filter((l) => l !== 'video')) {
318
+ const plan = normalisePlan(await ports.planUnits(bookRef, scope, layer, planCtx), layer);
319
+ nonVideo.push(...takeUnits(plan.units, layer));
320
+ }
321
+ await place(nonVideo);
322
+
323
+ // 1.3.0 — video (§6.5, §13 п.11): the planner decides per scene: groups now /
324
+ // wait for live images or audio (the command joins those jobs; the groups come
325
+ // from the transition of their acceptance) / skip with a reason.
326
+ let skips = [];
327
+ if (effective.includes('video')) {
328
+ const plan = normalisePlan(await ports.planUnits(bookRef, scope, 'video', planCtx), 'video');
329
+ await place(takeUnits(plan.units, 'video'));
330
+ if (plan.waits.length) {
331
+ // joined = links to live jobs another command created (our own image / audio jobs are not «joined»)
332
+ const foreign = async () => (await client.query(
333
+ `SELECT count(*)::int AS n FROM gen_command_jobs l JOIN gen_jobs j ON j.job_id = l.job_id
334
+ WHERE l.command_id = $1 AND j.command_id <> $1`, [cmd.command_id])).rows[0].n;
335
+ const before = await foreign();
336
+ await linkSceneLive(client, [cmd.command_id], bookId, plan.waits);
337
+ joined += (await foreign()) - before;
338
+ }
339
+ skips = plan.skipped;
340
+ await recordSkips(client, [cmd.command_id], skips);
283
341
  }
284
- const summary = { jobs_created: created, joined, skipped_ready: skipped };
342
+ const summary = { jobs_created: created, joined, skipped_ready: skipped, ...skipSummary(skips) };
285
343
  await client.query('UPDATE gen_commands SET summary = $2::jsonb WHERE command_id = $1', [cmd.command_id, JSON.stringify(summary)]);
286
344
  await notifyProgress(client, bookId, cmd.command_id);
287
345
  return {
package/src/gen/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // ======================================================
2
- // @animastor/orchestration · gen — orchestration v2 core (1.2.0)
2
+ // @animastor/orchestration · gen — orchestration v2 core (1.3.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
@@ -10,7 +10,7 @@
10
10
  // await gen.migrate(pool);
11
11
  // const orch = gen.createOrchestration({ pool, ports, uploadSecret, outputDir });
12
12
  // orch.createCommand(...), orch.cancel(...), orch.purgeBook(bookId), orch.claim(...), orch.acceptResult(...),
13
- // orch.acceptError(...), orch.beacon(...), orch.sweepOnce(), orch.startSweeper(ms),
13
+ // orch.acceptError(...), orch.beacon(...), orch.openInput(...), orch.sweepOnce(), orch.startSweeper(ms),
14
14
  // orch.stop(), orch.progress(bookId), orch.listenProgress(fn), orch.runLocalOnce()
15
15
 
16
16
  'use strict';
@@ -70,6 +70,7 @@ function createOrchestration(o = {}) {
70
70
  purgeBook: commands.purgeBook,
71
71
  claim: claim.claim,
72
72
  beacon: claim.beacon,
73
+ openInput: claim.openInput,
73
74
  acceptResult: accept.acceptResult,
74
75
  acceptError: accept.acceptError,
75
76
  sweepOnce: sweeper.sweepOnce,
@@ -99,6 +100,7 @@ module.exports = Object.freeze({
99
100
  createDefaultValidateResult: media.createDefaultValidateResult,
100
101
  createAudioValidator: media.createAudioValidator,
101
102
  createPngValidator: media.createPngValidator,
103
+ createWavValidator: media.createWavValidator,
102
104
  }),
103
105
  media: Object.freeze({
104
106
  inspectMp3: media.inspectMp3,
@@ -106,10 +108,12 @@ module.exports = Object.freeze({
106
108
  ffmpegDecodePcm: media.ffmpegDecodePcm,
107
109
  DEFAULT_RMS_THRESHOLD_DBFS: media.DEFAULT_RMS_THRESHOLD_DBFS,
108
110
  inspectPng: media.inspectPng,
111
+ inspectWav: media.inspectWav,
109
112
  DEFAULT_MIN_LUMA_STDDEV: media.DEFAULT_MIN_LUMA_STDDEV,
110
113
  }),
111
114
  GenError: util.GenError,
112
115
  /** pure formatter of the [gen-v2] info lines (О3) — for host tests / log parsers */
113
116
  formatGenEvent,
114
117
  PROGRESS_CHANNEL: util.PROGRESS_CHANNEL,
118
+ KINDS: util.KINDS,
115
119
  });
@@ -42,7 +42,8 @@ function createLocalRunner({ pool, ports, accept, logger = null }) {
42
42
  const r = await accept.failAttempt(job.job_id, job.attempt, (err && err.error_class) || 'unknown', `run_local: ${err && err.message}`);
43
43
  return { job_id: job.job_id, attempt: job.attempt, ...r };
44
44
  }
45
- const r = await accept.acceptLocalFile(job, out.path);
45
+ // 1.3.0: out.meta (e.g. measured chunk durations) reaches onArtifactPlaced inside the acceptance tx
46
+ const r = await accept.acceptLocalFile(job, out.path, out.meta === undefined ? null : out.meta);
46
47
  return { job_id: job.job_id, attempt: job.attempt, ...r };
47
48
  }
48
49
 
package/src/gen/ports.js CHANGED
@@ -28,8 +28,22 @@
28
28
  // Optional:
29
29
  // maxAttemptsFor(kind) → int ≥ 1 (default: 1 + max retries of the policy)
30
30
  // isLayerEnabled(bookId, layer) → Promise<boolean> (§6.3 «только если слой включён»; default true)
31
- // onArtifactPlaced(job, finalPath) → called inside the acceptance transaction right after the
32
- // rename (§7 п.3), e.g. to drop a placeholder sidecar marker
31
+ // onArtifactPlaced(job, finalPath, ctx) → called inside the acceptance transaction right after the
32
+ // rename (§7 п.3), e.g. to drop a placeholder sidecar marker.
33
+ // 1.3.0: ctx = {db, meta} — db: the acceptance transaction client
34
+ // (writes commit or roll back with the result); meta: what runLocal
35
+ // returned next to {path} (local jobs), else null
36
+ // inputFiles(job) → [{name, path, sha256, bytes}] (1.3.0) input files of a GPU job,
37
+ // served by GET /internal/gen/jobs/:id/input/:name (§8.1); listed
38
+ // in the claimed task as input_files [{name, sha256, bytes}]
39
+ //
40
+ // 1.3.0 planUnits(book, scope, layer, ctx): ctx = {db} — the command / acceptance transaction
41
+ // client (read-only use). For layer 'video' the result may be {units, waits, skipped}:
42
+ // waits [{chapter_id, scene_id}] — the scene waits for live images / audio: the command
43
+ // joins those jobs, the video stage follows their acceptance (§6.3, §6.5)
44
+ // skipped [{chapter_id, scene_id, reason: 'skipped_*'}] — summary + gen_command_skips
45
+ // A part unit may carry input.merge_parts [{unit_key, part_hash}] (every part of the scene):
46
+ // its merge is created when all those parts are done (video_group → video_merge).
33
47
 
34
48
  'use strict';
35
49
 
@@ -39,7 +53,7 @@ const REQUIRED = Object.freeze([
39
53
  'planUnits', 'buildPayload', 'artifactPath', 'validateResult',
40
54
  'runLocal', 'laneFor', 'timeoutFor', 'retryPolicy',
41
55
  ]);
42
- const OPTIONAL = Object.freeze(['maxAttemptsFor', 'isLayerEnabled', 'onArtifactPlaced']);
56
+ const OPTIONAL = Object.freeze(['maxAttemptsFor', 'isLayerEnabled', 'onArtifactPlaced', 'inputFiles']);
43
57
 
44
58
  // ── default retry policy: gpu-retry-policy.cjs:50–53 ─────────────────────
45
59
  const RETRY_POLICY = Object.freeze({
@@ -91,6 +105,7 @@ const TIMEOUT_MS = Object.freeze({
91
105
  video_group: 60 * 60_000,
92
106
  audio_merge: 10 * 60_000,
93
107
  video_merge: 20 * 60_000,
108
+ voice_reference: 15 * 60_000,
94
109
  });
95
110
  function defaultTimeoutFor(kind) { return TIMEOUT_MS[kind]; }
96
111
 
@@ -40,10 +40,22 @@ function createProgress({ pool }) {
40
40
  WHERE l.command_id = ANY($1::uuid[])
41
41
  GROUP BY 1, 2, 3, 4, 5, 6`, [ids])).rows : [];
42
42
 
43
+ // 1.3.0 — why the command made no work for a scene (§6.5, §13 п.11 п.9): {reason: [scene_id…]}
44
+ const skipRows = ids.length ? (await pool.query(
45
+ `SELECT command_id, reason, scene_id FROM gen_command_skips WHERE command_id = ANY($1::uuid[])
46
+ ORDER BY created_at, chapter_id, scene_id`, [ids])).rows : [];
47
+ const skippedOf = new Map();
48
+ for (const r of skipRows) {
49
+ if (!skippedOf.has(r.command_id)) skippedOf.set(r.command_id, {});
50
+ const m = skippedOf.get(r.command_id);
51
+ if (!m[r.reason]) m[r.reason] = [];
52
+ if (!m[r.reason].includes(r.scene_id)) m[r.reason].push(r.scene_id);
53
+ }
54
+
43
55
  const byCmd = new Map(cmds.map((c) => [c.command_id, {
44
56
  command_id: c.command_id, kind: c.kind, scope: c.scope, layers: c.layers, force: c.force,
45
57
  status: c.status, user_id: c.user_id, created_at: c.created_at, finished_at: c.finished_at,
46
- error: c.error, summary: c.summary,
58
+ error: c.error, summary: c.summary, skipped: skippedOf.get(c.command_id) || {},
47
59
  totals: zero(), by_layer: {}, merges: {}, scenes: new Map(),
48
60
  }]));
49
61
  const add = (row, field) => {
@@ -0,0 +1,26 @@
1
+ // ======================================================
2
+ // gen/sql/004-command-skips — ADR ORCHESTRATION_V2 §6.5, §13 п.11 (stage 3, video)
3
+ // ======================================================
4
+ // gen_command_skips: why a command did NOT create work for a scene
5
+ // (skipped_needs_audio / skipped_image_dirty / skipped_needs_image, …).
6
+ // Written when the command is created (also mirrored into gen_commands.summary)
7
+ // and by stage transitions inside the acceptance transaction (a video command
8
+ // waited for images / audio and the scene turned out not ready). Insert-only:
9
+ // the acceptance transaction never updates gen_commands rows (it holds them
10
+ // FOR SHARE — an UPDATE there could deadlock two parallel acceptances).
11
+ // Progress reads it. Rows go with the command (ON DELETE CASCADE).
12
+
13
+ 'use strict';
14
+
15
+ const GEN_COMMAND_SKIPS_SQL = Object.freeze([
16
+ `CREATE TABLE IF NOT EXISTS gen_command_skips (
17
+ command_id UUID NOT NULL REFERENCES gen_commands(command_id) ON DELETE CASCADE,
18
+ chapter_id TEXT NOT NULL,
19
+ scene_id TEXT NOT NULL,
20
+ reason TEXT NOT NULL CHECK (reason ~ '^skipped_[a-z_]{1,48}$'),
21
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
22
+ PRIMARY KEY (command_id, chapter_id, scene_id, reason)
23
+ )`,
24
+ ]);
25
+
26
+ module.exports = { GEN_COMMAND_SKIPS_SQL };
@@ -0,0 +1,47 @@
1
+ // ======================================================
2
+ // gen/sql/005-voice-reference — kind voice_reference (1.4.0, VOICE_REFERENCES.md)
3
+ // ======================================================
4
+ // gen_jobs.kind gains 'voice_reference' (executor gpu:audio, layer audio);
5
+ // gen_commands.kind gains 'voice_reference'. The four constraints keep their
6
+ // NAMES and get new definitions (001/002 add them only when the name is
7
+ // missing, so the old definitions never come back). Idempotent: a constraint
8
+ // is replaced only while its definition does not mention voice_reference.
9
+
10
+ 'use strict';
11
+
12
+ const REPLACE_CHECK = (table, name, expr) => `
13
+ DO $$
14
+ BEGIN
15
+ IF EXISTS (
16
+ SELECT 1 FROM pg_constraint
17
+ WHERE conname = '${name}' AND conrelid = '${table}'::regclass
18
+ AND pg_get_constraintdef(oid) NOT LIKE '%voice_reference%'
19
+ ) THEN
20
+ ALTER TABLE ${table} DROP CONSTRAINT ${name};
21
+ END IF;
22
+ IF NOT EXISTS (
23
+ SELECT 1 FROM pg_constraint
24
+ WHERE conname = '${name}' AND conrelid = '${table}'::regclass
25
+ ) THEN
26
+ ALTER TABLE ${table} ADD CONSTRAINT ${name} CHECK (${expr});
27
+ END IF;
28
+ END $$`;
29
+
30
+ const LAYER_OF_KIND_SQL = `CASE kind
31
+ WHEN 'audio_chunk' THEN 'audio' WHEN 'audio_merge' THEN 'audio' WHEN 'voice_reference' THEN 'audio'
32
+ WHEN 'iu_image' THEN 'image'
33
+ WHEN 'video_group' THEN 'video' WHEN 'video_merge' THEN 'video' END`;
34
+
35
+ const GEN_VOICE_REFERENCE_SQL = Object.freeze([
36
+ REPLACE_CHECK('gen_jobs', 'gen_jobs_kind_check',
37
+ `kind IN ('audio_chunk','iu_image','video_group','audio_merge','video_merge','voice_reference')`),
38
+ REPLACE_CHECK('gen_jobs', 'gen_jobs_kind_executor_check',
39
+ `(kind IN ('audio_chunk','voice_reference') AND executor = 'gpu:audio')
40
+ OR (kind = 'iu_image' AND executor = 'gpu:image')
41
+ OR (kind = 'video_group' AND executor = 'gpu:video')
42
+ OR (kind IN ('audio_merge','video_merge') AND executor = 'local')`),
43
+ REPLACE_CHECK('gen_jobs', 'gen_jobs_layer_kind_check', `layer = (${LAYER_OF_KIND_SQL})`),
44
+ REPLACE_CHECK('gen_commands', 'gen_commands_kind_check', `kind IN ('regenerate','generate_all','voice_reference')`),
45
+ ]);
46
+
47
+ module.exports = { GEN_VOICE_REFERENCE_SQL, LAYER_OF_KIND_SQL };
@@ -6,12 +6,16 @@
6
6
  const { GEN_CORE_SQL } = require('./001-gen-core');
7
7
  const { GEN_COMMAND_JOBS_SQL } = require('./002-command-jobs');
8
8
  const { GEN_SCOPE_SCENES_SQL } = require('./003-scope-scenes');
9
+ const { GEN_COMMAND_SKIPS_SQL } = require('./004-command-skips');
10
+ const { GEN_VOICE_REFERENCE_SQL } = require('./005-voice-reference');
9
11
  const { withTx } = require('../util');
10
12
 
11
13
  const MIGRATIONS = Object.freeze([
12
14
  Object.freeze({ id: '001-gen-core', statements: GEN_CORE_SQL }),
13
15
  Object.freeze({ id: '002-command-jobs', statements: GEN_COMMAND_JOBS_SQL }),
14
16
  Object.freeze({ id: '003-scope-scenes', statements: GEN_SCOPE_SCENES_SQL }),
17
+ Object.freeze({ id: '004-command-skips', statements: GEN_COMMAND_SKIPS_SQL }),
18
+ Object.freeze({ id: '005-voice-reference', statements: GEN_VOICE_REFERENCE_SQL }),
15
19
  ]);
16
20
 
17
21
  /**
@@ -0,0 +1,185 @@
1
+ // ======================================================
2
+ // gen/stage — helpers shared by command creation and stage transitions
3
+ // (1.3.0: video, ADR §6.3, §6.5, §13 п.11)
4
+ // ======================================================
5
+ // Everything here runs on the caller's transaction client (command tx or
6
+ // acceptance tx) and never UPDATEs gen_commands (acceptance holds those rows
7
+ // FOR SHARE).
8
+
9
+ 'use strict';
10
+
11
+ const { GenError, LAYER_OF_KIND, LIVE } = require('./util');
12
+
13
+ /** part kind → its merge kind (a part kind with input.merge_parts ends in this local job) */
14
+ const MERGE_OF_PART = Object.freeze({ video_group: 'video_merge', audio_chunk: 'audio_merge' });
15
+ /** kinds a waiting video command joins in its scene (images + audio, §6.5, §13 п.11 п.3) */
16
+ const VIDEO_WAIT_KINDS = Object.freeze(['iu_image', 'audio_chunk', 'audio_merge']);
17
+ const SKIP_REASON_RE = /^skipped_[a-z_]{1,48}$/;
18
+
19
+ /** input.merge_parts → [{unit_key, part_hash}] (non-empty, string fields) or null. */
20
+ function mergePartsOf(input) {
21
+ const v = input && input.merge_parts;
22
+ if (!Array.isArray(v) || v.length === 0) return null;
23
+ const out = [];
24
+ for (const p of v) {
25
+ if (!p || typeof p.unit_key !== 'string' || !p.unit_key || typeof p.part_hash !== 'string' || !p.part_hash) return null;
26
+ out.push({ unit_key: p.unit_key, part_hash: p.part_hash });
27
+ }
28
+ return out;
29
+ }
30
+
31
+ /**
32
+ * planUnits result → {units, waits, skipped}. A plain array (every layer before
33
+ * 1.3.0, audio / image now) is {units: array}. Video may return the object form:
34
+ * units — first-stage units (video_group)
35
+ * waits — [{chapter_id, scene_id}] scenes waiting for live images / audio: the
36
+ * command joins those live jobs; the video stage follows their acceptance
37
+ * skipped — [{chapter_id, scene_id, reason: 'skipped_*'}]
38
+ */
39
+ function normalisePlan(planned, layer) {
40
+ if (Array.isArray(planned)) return { units: planned, waits: [], skipped: [] };
41
+ if (!planned || typeof planned !== 'object' || !Array.isArray(planned.units)) {
42
+ throw new GenError('bad_plan', 500, `planUnits(${layer}) must return an array or {units, waits?, skipped?}`);
43
+ }
44
+ const scene = (x) => x && typeof x.chapter_id === 'string' && x.chapter_id && typeof x.scene_id === 'string' && x.scene_id;
45
+ const waits = Array.isArray(planned.waits) ? planned.waits : [];
46
+ const skipped = Array.isArray(planned.skipped) ? planned.skipped : [];
47
+ if (!waits.every(scene)) throw new GenError('bad_plan', 500, `planUnits(${layer}): waits[] entries need chapter_id, scene_id`);
48
+ if (!skipped.every((s) => scene(s) && typeof s.reason === 'string' && SKIP_REASON_RE.test(s.reason))) {
49
+ throw new GenError('bad_plan', 500, `planUnits(${layer}): skipped[] entries need chapter_id, scene_id, reason skipped_*`);
50
+ }
51
+ return {
52
+ units: planned.units,
53
+ waits: waits.map((w) => ({ chapter_id: w.chapter_id, scene_id: w.scene_id })),
54
+ skipped: skipped.map((s) => ({ chapter_id: s.chapter_id, scene_id: s.scene_id, reason: s.reason })),
55
+ };
56
+ }
57
+
58
+ /**
59
+ * Units whose part is already accepted for the current content: the scene asset
60
+ * of the same build records gen_parts[unit_key].part_hash = input.part_hash
61
+ * (row pending / ready — a 'stale' row proves nothing). 1.1.0 rule, shared.
62
+ * @returns {Promise<Set<object>>} subset of `units` (by identity)
63
+ */
64
+ async function readyParts(client, bookId, units) {
65
+ const parted = units.filter((u) => u.input && typeof u.input.part_hash === 'string' && u.input.part_hash);
66
+ if (!parted.length) return new Set();
67
+ const r = await client.query(
68
+ `SELECT t.ord FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])
69
+ WITH ORDINALITY AS t(chapter_id, scene_id, asset_type, build_id, unit_key, part_hash, ord)
70
+ WHERE EXISTS (SELECT 1 FROM scene_assets a
71
+ WHERE a.book_id = $1 AND a.chapter_id = t.chapter_id AND a.scene_id = t.scene_id
72
+ AND a.asset_type = t.asset_type AND a.build_id = t.build_id
73
+ AND a.status IN ('pending', 'ready')
74
+ AND jsonb_typeof(a.metadata->'gen_parts') = 'object'
75
+ AND a.metadata->'gen_parts'->t.unit_key->>'part_hash' = t.part_hash)`,
76
+ [bookId, parted.map((u) => u.chapter_id), parted.map((u) => u.scene_id), parted.map((u) => LAYER_OF_KIND[u.kind]),
77
+ parted.map((u) => u.build_id), parted.map((u) => u.unit_key), parted.map((u) => u.input.part_hash)]);
78
+ return new Set(r.rows.map((row) => parted[Number(row.ord) - 1]));
79
+ }
80
+
81
+ /**
82
+ * For every listed part: the latest DONE job of that unit_key with that part_hash
83
+ * (same build). Returned in `parts` order; `missing` = parts without such a job.
84
+ */
85
+ async function donePartsFor(client, { bookId, chapterId, sceneId, buildId, kind }, parts) {
86
+ const r = await client.query(
87
+ `SELECT DISTINCT ON (j.unit_key) j.unit_key, j.job_id, j.result_path, j.result_sha256,
88
+ j.input->'part_meta' AS meta, j.input->>'part_hash' AS part_hash
89
+ FROM gen_jobs j
90
+ JOIN unnest($6::text[], $7::text[]) AS t(uk, ph) ON j.unit_key = t.uk AND j.input->>'part_hash' = t.ph
91
+ WHERE j.book_id = $1 AND j.chapter_id = $2 AND j.scene_id = $3 AND j.kind = $4 AND j.build_id = $5
92
+ AND j.status = 'done'
93
+ ORDER BY j.unit_key, j.finished_at DESC`,
94
+ [bookId, chapterId, sceneId, kind, buildId, parts.map((p) => p.unit_key), parts.map((p) => p.part_hash)]);
95
+ const by = new Map(r.rows.map((x) => [x.unit_key, x]));
96
+ const done = [];
97
+ const missing = [];
98
+ for (const p of parts) {
99
+ const x = by.get(p.unit_key);
100
+ if (!x) { missing.push(p); continue; }
101
+ done.push({ unit_key: x.unit_key, job_id: x.job_id, path: x.result_path, sha256: x.result_sha256, part_hash: x.part_hash, meta: x.meta || null });
102
+ }
103
+ return { done, missing };
104
+ }
105
+
106
+ /** Is any job of these unit_keys of the scene live (queued / running)? */
107
+ async function anyLive(client, { bookId, chapterId, sceneId, kind }, unitKeys) {
108
+ const r = await client.query(
109
+ `SELECT 1 FROM gen_jobs WHERE book_id = $1 AND chapter_id = $2 AND scene_id = $3 AND kind = $4
110
+ AND unit_key = ANY($5::text[]) AND status = ANY($6::text[]) LIMIT 1`,
111
+ [bookId, chapterId, sceneId, kind, unitKeys, LIVE]);
112
+ return r.rowCount > 0;
113
+ }
114
+
115
+ /**
116
+ * The merge unit of a scene whose parts (input.merge_parts of its part units) are
117
+ * all done: {kind: merge, unit_key: 'scene', input: {scene_hash, parts}} or null.
118
+ */
119
+ async function mergeUnitFor(client, bookId, partUnit) {
120
+ const parts = mergePartsOf(partUnit.input);
121
+ const mergeKind = MERGE_OF_PART[partUnit.kind];
122
+ if (!parts || !mergeKind) return null;
123
+ const where = { bookId, chapterId: partUnit.chapter_id, sceneId: partUnit.scene_id, buildId: partUnit.build_id, kind: partUnit.kind };
124
+ if (await anyLive(client, where, parts.map((p) => p.unit_key))) return null;
125
+ const { done, missing } = await donePartsFor(client, where, parts);
126
+ if (missing.length) return null;
127
+ const sceneHash = partUnit.scene_hash ?? partUnit.input.scene_hash ?? null;
128
+ return {
129
+ chapter_id: partUnit.chapter_id, scene_id: partUnit.scene_id, kind: mergeKind, unit_key: 'scene',
130
+ build_id: partUnit.build_id, scene_hash: sceneHash,
131
+ input: { scene_hash: sceneHash, parts: done, merge_parts: parts },
132
+ };
133
+ }
134
+
135
+ /** Link commands to every live job of `kinds` in the given scenes (a waiting command joins them). */
136
+ async function linkSceneLive(client, commandIds, bookId, scenes, kinds = VIDEO_WAIT_KINDS) {
137
+ if (!commandIds.length || !scenes.length) return 0;
138
+ const r = await client.query(
139
+ `INSERT INTO gen_command_jobs (command_id, job_id)
140
+ SELECT c, j.job_id
141
+ FROM gen_jobs j
142
+ JOIN unnest($2::text[], $3::text[]) AS s(ch, sc) ON j.chapter_id = s.ch AND j.scene_id = s.sc
143
+ CROSS JOIN unnest($4::uuid[]) AS c
144
+ WHERE j.book_id = $1 AND j.kind = ANY($5::text[]) AND j.status IN ('queued','running')
145
+ ON CONFLICT DO NOTHING`,
146
+ [bookId, scenes.map((s) => s.chapter_id), scenes.map((s) => s.scene_id), commandIds, kinds]);
147
+ return r.rowCount;
148
+ }
149
+
150
+ /** Record skip reasons for commands (insert-only, idempotent). */
151
+ async function recordSkips(client, commandIds, skipped) {
152
+ if (!commandIds.length || !skipped.length) return 0;
153
+ const rows = [];
154
+ for (const c of commandIds) for (const s of skipped) rows.push([c, s.chapter_id, s.scene_id, s.reason]);
155
+ const r = await client.query(
156
+ `INSERT INTO gen_command_skips (command_id, chapter_id, scene_id, reason)
157
+ SELECT * FROM unnest($1::uuid[], $2::text[], $3::text[], $4::text[])
158
+ ON CONFLICT DO NOTHING`,
159
+ [rows.map((x) => x[0]), rows.map((x) => x[1]), rows.map((x) => x[2]), rows.map((x) => x[3])]);
160
+ return r.rowCount;
161
+ }
162
+
163
+ /** skipped[] → {skipped_x: [scene_id…]} for the command summary. */
164
+ function skipSummary(skipped) {
165
+ const out = {};
166
+ for (const s of skipped) {
167
+ if (!out[s.reason]) out[s.reason] = [];
168
+ if (!out[s.reason].includes(s.scene_id)) out[s.reason].push(s.scene_id);
169
+ }
170
+ return out;
171
+ }
172
+
173
+ module.exports = {
174
+ MERGE_OF_PART,
175
+ VIDEO_WAIT_KINDS,
176
+ mergePartsOf,
177
+ normalisePlan,
178
+ readyParts,
179
+ donePartsFor,
180
+ anyLive,
181
+ mergeUnitFor,
182
+ linkSceneLive,
183
+ recordSkips,
184
+ skipSummary,
185
+ };
package/src/gen/util.js CHANGED
@@ -54,9 +54,14 @@ async function withTx(pool, fn) {
54
54
  }
55
55
 
56
56
  // ── kinds / executors / layers ───────────────────────────────────────────
57
- const KINDS = Object.freeze(['audio_chunk', 'iu_image', 'video_group', 'audio_merge', 'video_merge']);
57
+ // voice_reference (1.4.0, VOICE_REFERENCES.md): one candidate of a character's
58
+ // voice reference (or the normalisation of an uploaded file) on the audio worker.
59
+ // Layer 'audio' (the worker type), but NOT a scene asset — acceptance never
60
+ // writes scene_assets for it and it has no stage transition.
61
+ const KINDS = Object.freeze(['audio_chunk', 'iu_image', 'video_group', 'audio_merge', 'video_merge', 'voice_reference']);
58
62
  const EXECUTOR_OF_KIND = Object.freeze({
59
63
  audio_chunk: 'gpu:audio',
64
+ voice_reference: 'gpu:audio',
60
65
  iu_image: 'gpu:image',
61
66
  video_group: 'gpu:video',
62
67
  audio_merge: 'local',
@@ -65,12 +70,15 @@ const EXECUTOR_OF_KIND = Object.freeze({
65
70
  const LAYER_OF_KIND = Object.freeze({
66
71
  audio_chunk: 'audio',
67
72
  audio_merge: 'audio',
73
+ voice_reference: 'audio',
68
74
  iu_image: 'image',
69
75
  video_group: 'video',
70
76
  video_merge: 'video',
71
77
  });
72
78
  /** Kinds a command may create directly (first stage, ADR §6.1 п.5 / §6.3). */
73
- const FIRST_STAGE_KINDS = Object.freeze(['audio_chunk', 'iu_image', 'video_group']);
79
+ const FIRST_STAGE_KINDS = Object.freeze(['audio_chunk', 'iu_image', 'video_group', 'voice_reference']);
80
+ /** Kinds that are not scene assets (acceptance skips scene_assets). */
81
+ const NON_SCENE_KINDS = Object.freeze(['voice_reference']);
74
82
  const LAYERS = Object.freeze(['audio', 'image', 'video']);
75
83
  const WORKER_TYPES = LAYERS;
76
84
  const LIVE = Object.freeze(['queued', 'running']);
@@ -128,6 +136,7 @@ module.exports = {
128
136
  EXECUTOR_OF_KIND,
129
137
  LAYER_OF_KIND,
130
138
  FIRST_STAGE_KINDS,
139
+ NON_SCENE_KINDS,
131
140
  LAYERS,
132
141
  WORKER_TYPES,
133
142
  LIVE,
@@ -133,6 +133,56 @@ function createAudioValidator(opts = {}) {
133
133
  };
134
134
  }
135
135
 
136
+ // ── WAV (1.4.0, voice_reference): RIFF/WAVE, PCM s16le, data present, not silence ──
137
+ /**
138
+ * Parse the chunk list of a RIFF/WAVE buffer.
139
+ * @returns {{ok:true, chunks:Array<{id:string, offset:number, size:number}>, fmt:{format:number, channels:number,
140
+ * sampleRate:number, bitsPerSample:number}, data:{offset:number, size:number}, durationSec:number}
141
+ * | {ok:false, reason:string}}
142
+ */
143
+ function inspectWav(buf) {
144
+ if (!Buffer.isBuffer(buf) || buf.length < 12 || buf.toString('latin1', 0, 4) !== 'RIFF' || buf.toString('latin1', 8, 12) !== 'WAVE') {
145
+ return { ok: false, reason: 'not_wav' };
146
+ }
147
+ const chunks = [];
148
+ let pos = 12;
149
+ while (pos + 8 <= buf.length) {
150
+ const id = buf.toString('latin1', pos, pos + 4);
151
+ const size = buf.readUInt32LE(pos + 4);
152
+ if (pos + 8 + size > buf.length) return { ok: false, reason: 'truncated_chunk' };
153
+ chunks.push({ id, offset: pos + 8, size });
154
+ pos += 8 + size + (size & 1);
155
+ }
156
+ const fmtC = chunks.find((c) => c.id === 'fmt ');
157
+ const dataC = chunks.find((c) => c.id === 'data');
158
+ if (!fmtC || fmtC.size < 16) return { ok: false, reason: 'no_fmt' };
159
+ if (!dataC || dataC.size === 0) return { ok: false, reason: 'no_data' };
160
+ const fmt = {
161
+ format: buf.readUInt16LE(fmtC.offset),
162
+ channels: buf.readUInt16LE(fmtC.offset + 2),
163
+ sampleRate: buf.readUInt32LE(fmtC.offset + 4),
164
+ bitsPerSample: buf.readUInt16LE(fmtC.offset + 14),
165
+ };
166
+ if (fmt.format !== 1 || fmt.bitsPerSample !== 16 || fmt.channels < 1 || fmt.sampleRate <= 0) return { ok: false, reason: 'not_pcm_s16' };
167
+ const frames = Math.floor(dataC.size / (2 * fmt.channels));
168
+ return { ok: true, chunks, fmt, data: { offset: dataC.offset, size: dataC.size }, durationSec: frames / fmt.sampleRate };
169
+ }
170
+
171
+ function createWavValidator(opts = {}) {
172
+ const threshold = Number.isFinite(opts.rmsThresholdDbfs) ? opts.rmsThresholdDbfs : DEFAULT_RMS_THRESHOLD_DBFS;
173
+ return async function validateWav(tmpPath) {
174
+ const buf = await fs.promises.readFile(tmpPath);
175
+ const w = inspectWav(buf);
176
+ if (!w.ok) return w;
177
+ const n = Math.floor(w.data.size / 2);
178
+ const samples = new Int16Array(n);
179
+ for (let i = 0; i < n; i += 1) samples[i] = buf.readInt16LE(w.data.offset + i * 2);
180
+ const level = rmsDbfs(samples);
181
+ if (!(level >= threshold)) return { ok: false, reason: 'silence', durationSec: w.durationSec, rmsDbfs: level };
182
+ return { ok: true, durationSec: w.durationSec, rmsDbfs: level };
183
+ };
184
+ }
185
+
136
186
  const PNG_SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
137
187
 
138
188
  // ── PNG (1.1.0): structure + dimensions + «not a blank frame» ────────────
@@ -340,11 +390,13 @@ async function validateMp4(tmpPath) {
340
390
  */
341
391
  function createDefaultValidateResult(opts = {}) {
342
392
  const audio = createAudioValidator(opts);
393
+ const wav = createWavValidator(opts);
343
394
  const png = createPngValidator({ minLumaStddev: opts.minLumaStddev });
344
395
  return async function validateResult(job, tmpPath) {
345
396
  switch (job && job.kind) {
346
397
  case 'audio_chunk':
347
398
  case 'audio_merge': return audio(tmpPath);
399
+ case 'voice_reference': return wav(tmpPath);
348
400
  case 'iu_image': return png(tmpPath);
349
401
  case 'video_group':
350
402
  case 'video_merge': return validateMp4(tmpPath);
@@ -360,6 +412,8 @@ module.exports = {
360
412
  ffmpegDecodePcm,
361
413
  createAudioValidator,
362
414
  createDefaultValidateResult,
415
+ inspectWav,
416
+ createWavValidator,
363
417
  validatePng,
364
418
  validateMp4,
365
419
  inspectPng,