@animastor/orchestration 1.3.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,28 @@
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
+
3
26
  ## 1.3.0 (2026-11-09) — этап 3a: видео (`video_group` + `video_merge`)
4
27
 
5
28
  Основание: ADR `ORCHESTRATION_V2.md` §6.3, §6.5, §8.1, §13 п.11. Minor: порты 1.0–1.2 не меняются,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@animastor/orchestration",
3
- "version": "1.3.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,7 +19,7 @@ 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');
@@ -122,6 +122,7 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
122
122
 
123
123
  // ── scene_assets (§4.3: written only by acceptance) ──────────────────────
124
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
125
126
  const assetType = job.layer;
126
127
  const build = job.build_id;
127
128
  const sceneHash = job.input.scene_hash || null;
@@ -21,12 +21,25 @@ const {
21
21
  normalisePlan, readyParts, mergePartsOf, mergeUnitFor, linkSceneLive, recordSkips, skipSummary,
22
22
  } = require('./stage');
23
23
 
24
- 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;
25
31
  const SCOPE_LEVELS = Object.freeze(['book', 'chapter', 'scenes', 'scene', 'unit']);
26
32
  const MAX_SCOPE_SCENES = 10_000;
27
33
 
28
- function normaliseScope(scope) {
34
+ function normaliseScope(scope, kind = 'regenerate') {
29
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
+ }
30
43
  if (!s || !SCOPE_LEVELS.includes(s.level)) throw new GenError('bad_request', 400, 'scope.level must be book|chapter|scenes|scene|unit');
31
44
  const out = { level: s.level };
32
45
  const opt = (k) => { if (s[k] !== undefined && s[k] !== null) out[k] = requireText(s[k], `scope.${k}`); };
@@ -54,8 +67,10 @@ function unitFitsLayer(kind, layer) {
54
67
  return layer === 'video' && kind === 'iu_image';
55
68
  }
56
69
 
57
- function checkUnit(u, layer) {
58
- 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
59
74
  && FIRST_STAGE_KINDS.includes(u.kind) && unitFitsLayer(u.kind, layer)
60
75
  && typeof u.chapter_id === 'string' && u.chapter_id
61
76
  && typeof u.scene_id === 'string' && u.scene_id
@@ -105,8 +120,11 @@ function createCommands({ pool, ports, genLog = NOOP_LOG }) {
105
120
  const bookId = requireText(params.bookId, 'bookId');
106
121
  const kind = params.kind || 'regenerate';
107
122
  if (!COMMAND_KINDS.includes(kind)) throw new GenError('bad_request', 400, `kind must be ${COMMAND_KINDS.join('|')}`);
108
- const scope = normaliseScope(params.scope);
123
+ const scope = normaliseScope(params.scope, kind);
109
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
+ }
110
128
  if (requested.length === 0 || requested.some((l) => !LAYERS.includes(l))) {
111
129
  throw new GenError('bad_request', 400, 'layers must be a non-empty subset of audio|image|video');
112
130
  }
@@ -115,7 +133,9 @@ function createCommands({ pool, ports, genLog = NOOP_LOG }) {
115
133
 
116
134
  // §6.1 п.2: requested ∩ enabled (host layer-config passed in, or the optional port)
117
135
  let effective;
118
- 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)) {
119
139
  effective = requested.filter((l) => params.enabledLayers.includes(l));
120
140
  } else {
121
141
  effective = [];
@@ -160,12 +180,12 @@ function createCommands({ pool, ports, genLog = NOOP_LOG }) {
160
180
  // planner (1.3.0) runs on THIS transaction and must see the image / audio jobs
161
181
  // this very command has just created (they are what a video scene waits for).
162
182
  const bookRef = { bookId, workspaceId, userId };
163
- const planCtx = { db: client };
183
+ const planCtx = { db: client, kind };
164
184
  const seen = new Set();
165
185
  const takeUnits = (list, layer) => {
166
186
  const out = [];
167
187
  for (const u of list) {
168
- checkUnit(u, layer);
188
+ checkUnit(u, layer, kind);
169
189
  if (seen.has(unitKey(u))) continue; // video+image may both plan the same IU
170
190
  seen.add(unitKey(u));
171
191
  out.push(u);
package/src/gen/index.js CHANGED
@@ -100,6 +100,7 @@ module.exports = Object.freeze({
100
100
  createDefaultValidateResult: media.createDefaultValidateResult,
101
101
  createAudioValidator: media.createAudioValidator,
102
102
  createPngValidator: media.createPngValidator,
103
+ createWavValidator: media.createWavValidator,
103
104
  }),
104
105
  media: Object.freeze({
105
106
  inspectMp3: media.inspectMp3,
@@ -107,10 +108,12 @@ module.exports = Object.freeze({
107
108
  ffmpegDecodePcm: media.ffmpegDecodePcm,
108
109
  DEFAULT_RMS_THRESHOLD_DBFS: media.DEFAULT_RMS_THRESHOLD_DBFS,
109
110
  inspectPng: media.inspectPng,
111
+ inspectWav: media.inspectWav,
110
112
  DEFAULT_MIN_LUMA_STDDEV: media.DEFAULT_MIN_LUMA_STDDEV,
111
113
  }),
112
114
  GenError: util.GenError,
113
115
  /** pure formatter of the [gen-v2] info lines (О3) — for host tests / log parsers */
114
116
  formatGenEvent,
115
117
  PROGRESS_CHANNEL: util.PROGRESS_CHANNEL,
118
+ KINDS: util.KINDS,
116
119
  });
package/src/gen/ports.js CHANGED
@@ -105,6 +105,7 @@ const TIMEOUT_MS = Object.freeze({
105
105
  video_group: 60 * 60_000,
106
106
  audio_merge: 10 * 60_000,
107
107
  video_merge: 20 * 60_000,
108
+ voice_reference: 15 * 60_000,
108
109
  });
109
110
  function defaultTimeoutFor(kind) { return TIMEOUT_MS[kind]; }
110
111
 
@@ -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 };
@@ -7,6 +7,7 @@ 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
9
  const { GEN_COMMAND_SKIPS_SQL } = require('./004-command-skips');
10
+ const { GEN_VOICE_REFERENCE_SQL } = require('./005-voice-reference');
10
11
  const { withTx } = require('../util');
11
12
 
12
13
  const MIGRATIONS = Object.freeze([
@@ -14,6 +15,7 @@ const MIGRATIONS = Object.freeze([
14
15
  Object.freeze({ id: '002-command-jobs', statements: GEN_COMMAND_JOBS_SQL }),
15
16
  Object.freeze({ id: '003-scope-scenes', statements: GEN_SCOPE_SCENES_SQL }),
16
17
  Object.freeze({ id: '004-command-skips', statements: GEN_COMMAND_SKIPS_SQL }),
18
+ Object.freeze({ id: '005-voice-reference', statements: GEN_VOICE_REFERENCE_SQL }),
17
19
  ]);
18
20
 
19
21
  /**
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,