@animastor/orchestration 0.3.5 → 1.0.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.
Files changed (58) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/README.md +31 -0
  3. package/package.json +11 -8
  4. package/src/gen/accept.js +370 -0
  5. package/src/gen/claim.js +155 -0
  6. package/src/gen/commands.js +338 -0
  7. package/src/gen/index.js +107 -0
  8. package/src/gen/local-runner.js +80 -0
  9. package/src/gen/ports.js +163 -0
  10. package/src/gen/progress.js +99 -0
  11. package/src/gen/sql/001-gen-core.js +130 -0
  12. package/src/gen/sql/002-command-jobs.js +58 -0
  13. package/src/gen/sql/003-scope-scenes.js +38 -0
  14. package/src/gen/sql/index.js +35 -0
  15. package/src/gen/sweeper.js +141 -0
  16. package/src/gen/util.js +136 -0
  17. package/src/gen/validate-media.js +181 -0
  18. package/src/index.js +15 -91
  19. package/src/legacy/index.js +100 -0
  20. package/src/{runtime → legacy/runtime}/command-gate.js +11 -2
  21. package/src/{runtime → legacy/runtime}/persistence-port.js +21 -0
  22. package/src/{runtime → legacy/runtime}/reconciliation-engine.js +15 -0
  23. package/src/{runtime → legacy/runtime}/runtime-scheduler.js +9 -0
  24. package/src/{runtime → legacy/runtime}/scene-window.js +4 -0
  25. package/test/artifact-root-binding.test.js +0 -174
  26. package/test/capacity-deferral.test.js +0 -265
  27. package/test/counter-reconciliation.test.js +0 -164
  28. package/test/mocks/redis-mock.js +0 -231
  29. package/test/reconcile-quota-leak.test.js +0 -366
  30. package/test/stage146-d1-artifact-naming.test.js +0 -103
  31. package/test/stage147-a1-null-build-gate.test.js +0 -211
  32. package/test/test-bindings.js +0 -60
  33. /package/src/{host → legacy/host}/host-bindings.js +0 -0
  34. /package/src/{orchestration → legacy/orchestration}/index.js +0 -0
  35. /package/src/{orchestration → legacy/orchestration}/orchestrator.js +0 -0
  36. /package/src/{orchestration → legacy/orchestration}/runtime-result-consumer.js +0 -0
  37. /package/src/{orchestration → legacy/orchestration}/scene-callbacks.js +0 -0
  38. /package/src/{orchestration → legacy/orchestration}/scene-orchestrator.js +0 -0
  39. /package/src/{orchestration → legacy/orchestration}/scene-restoration.js +0 -0
  40. /package/src/{orchestration → legacy/orchestration}/scene-utils.js +0 -0
  41. /package/src/{runtime → legacy/runtime}/active-scenes-index.js +0 -0
  42. /package/src/{runtime → legacy/runtime}/audio-fsm-port.js +0 -0
  43. /package/src/{runtime → legacy/runtime}/circuit-breaker.js +0 -0
  44. /package/src/{runtime → legacy/runtime}/counter-reconciliation.js +0 -0
  45. /package/src/{runtime → legacy/runtime}/dispatch-engine.js +0 -0
  46. /package/src/{runtime → legacy/runtime}/dispatch-outcomes.js +0 -0
  47. /package/src/{runtime → legacy/runtime}/failure-taxonomy.js +0 -0
  48. /package/src/{runtime → legacy/runtime}/hub-cancel-port.js +0 -0
  49. /package/src/{runtime → legacy/runtime}/layer-config-port.js +0 -0
  50. /package/src/{runtime → legacy/runtime}/lease-manager.js +0 -0
  51. /package/src/{runtime → legacy/runtime}/placeholder-audio-port.js +0 -0
  52. /package/src/{runtime → legacy/runtime}/progress-events-port.js +0 -0
  53. /package/src/{runtime → legacy/runtime}/retry-budget-manager.js +0 -0
  54. /package/src/{runtime → legacy/runtime}/runtime-metrics.js +0 -0
  55. /package/src/{runtime → legacy/runtime}/runtime-result-emitter.js +0 -0
  56. /package/src/{runtime → legacy/runtime}/scene-data-port.js +0 -0
  57. /package/src/{runtime → legacy/runtime}/video-fsm-port.js +0 -0
  58. /package/src/{runtime → legacy/runtime}/worker-health.js +0 -0
@@ -0,0 +1,141 @@
1
+ // ======================================================
2
+ // gen/sweeper — the only background loop of v2 generation (ADR §9)
3
+ // ======================================================
4
+ // 1. running with deadline < now() → error 'timeout' (retry or failed)
5
+ // 2. running on a worker silent > offlineAfter → error 'worker_offline' (retry or failed)
6
+ // 3. active command with no live job in gen_command_jobs (created + joined + next stages)
7
+ // → done | partial | failed | cancelled
8
+ // 4. .incoming/*.tmp older than incomingMaxAge → deleted
9
+ // Idempotent. I1: it never INSERTs into gen_jobs — a retry re-queues the
10
+ // SAME row (attempt is kept, the next claim increments it).
11
+
12
+ 'use strict';
13
+
14
+ const fs = require('fs');
15
+ const path = require('path');
16
+ const { withTx, notifyProgress } = require('./util');
17
+
18
+ const BATCH = 200;
19
+
20
+ function createSweeper({ pool, accept, outputDir = null, offlineAfterMs = 60_000, incomingMaxAgeMs = 60 * 60_000, logger = console }) {
21
+ const offlineAfterS = Math.max(1, Math.round(offlineAfterMs / 1000));
22
+
23
+ async function failMany(rows, cls, reason) {
24
+ let n = 0;
25
+ for (const row of rows) {
26
+ const r = await accept.failAttempt(row.job_id, row.attempt, cls, reason);
27
+ if (r.status === 200) n += 1;
28
+ }
29
+ return n;
30
+ }
31
+
32
+ const NOTHING_LIVE_SQL = `
33
+ NOT EXISTS (SELECT 1 FROM gen_command_jobs l JOIN gen_jobs j ON j.job_id = l.job_id
34
+ WHERE l.command_id = c.command_id AND j.status IN ('queued','running'))`;
35
+
36
+ async function finishCommands() {
37
+ const cand = await pool.query(
38
+ `SELECT c.command_id FROM gen_commands c WHERE c.status = 'active' AND ${NOTHING_LIVE_SQL} LIMIT ${BATCH}`);
39
+ let n = 0;
40
+ for (const { command_id: id } of cand.rows) {
41
+ const done = await withTx(pool, async (client) => {
42
+ const c = (await client.query(
43
+ `SELECT c.* FROM gen_commands c WHERE c.command_id = $1 AND c.status = 'active' AND ${NOTHING_LIVE_SQL}
44
+ FOR UPDATE OF c SKIP LOCKED`, [id])).rows[0];
45
+ if (!c) return false;
46
+ const k = (await client.query(
47
+ `SELECT count(*) FILTER (WHERE status = 'done')::int AS done,
48
+ count(*) FILTER (WHERE status = 'failed')::int AS failed,
49
+ count(*) FILTER (WHERE status = 'cancelled')::int AS cancelled
50
+ FROM gen_command_jobs l JOIN gen_jobs j ON j.job_id = l.job_id
51
+ WHERE l.command_id = $1`, [id])).rows[0];
52
+ let status;
53
+ if (k.failed === 0 && k.cancelled === 0) status = 'done';
54
+ else if (k.done > 0) status = 'partial';
55
+ else if (k.failed > 0) status = 'failed';
56
+ else status = 'cancelled';
57
+ const err = k.failed || k.cancelled ? `failed=${k.failed} cancelled=${k.cancelled}` : null;
58
+ await client.query(
59
+ `UPDATE gen_commands SET status = $2, finished_at = now(), error = $3 WHERE command_id = $1`,
60
+ [id, status, err]);
61
+ await notifyProgress(client, c.book_id, id);
62
+ return true;
63
+ });
64
+ if (done) n += 1;
65
+ }
66
+ return n;
67
+ }
68
+
69
+ async function cleanIncoming() {
70
+ if (!outputDir) return 0;
71
+ let removed = 0;
72
+ let builds;
73
+ try { builds = await fs.promises.readdir(outputDir, { withFileTypes: true }); } catch (_) { return 0; }
74
+ const cutoff = Date.now() - incomingMaxAgeMs;
75
+ for (const d of builds) {
76
+ if (!d.isDirectory()) continue;
77
+ const dir = path.join(outputDir, d.name, '.incoming');
78
+ let files;
79
+ try { files = await fs.promises.readdir(dir); } catch (_) { continue; }
80
+ for (const f of files) {
81
+ if (!f.endsWith('.tmp')) continue;
82
+ const p = path.join(dir, f);
83
+ try {
84
+ const st = await fs.promises.stat(p);
85
+ if (st.isFile() && st.mtimeMs < cutoff) { await fs.promises.unlink(p); removed += 1; }
86
+ } catch (_) { /* raced with acceptance */ }
87
+ }
88
+ }
89
+ return removed;
90
+ }
91
+
92
+ /** One pass. @returns {Promise<{timeouts:number, offline:number, commands_finished:number, tmp_removed:number}>} */
93
+ async function sweepOnce() {
94
+ const expired = await pool.query(
95
+ `SELECT job_id, attempt FROM gen_jobs WHERE status = 'running' AND deadline < now()
96
+ ORDER BY deadline LIMIT ${BATCH}`);
97
+ const timeouts = await failMany(expired.rows, 'timeout', 'deadline exceeded');
98
+
99
+ const silent = await pool.query(
100
+ `SELECT j.job_id, j.attempt FROM gen_jobs j
101
+ LEFT JOIN workers w ON w.worker_id = j.worker_id
102
+ WHERE j.status = 'running' AND j.executor <> 'local'
103
+ AND (w.worker_id IS NULL OR w.last_seen IS NULL
104
+ OR w.last_seen < floor(extract(epoch from now()))::bigint - $1)
105
+ LIMIT ${BATCH}`, [offlineAfterS]);
106
+ const offline = await failMany(silent.rows, 'worker_offline', `worker silent > ${offlineAfterS}s`);
107
+
108
+ const commandsFinished = await finishCommands();
109
+ const tmpRemoved = await cleanIncoming();
110
+ return { timeouts, offline, commands_finished: commandsFinished, tmp_removed: tmpRemoved };
111
+ }
112
+
113
+ let timer = null;
114
+ let busy = false;
115
+ let stopped = true;
116
+ function startSweeper(intervalMs = 10_000) {
117
+ if (!stopped) return;
118
+ stopped = false;
119
+ const tick = async () => {
120
+ if (stopped) return;
121
+ if (!busy) {
122
+ busy = true;
123
+ try { await sweepOnce(); } catch (err) {
124
+ logger.error && logger.error(`[gen-v2] sweeper: ${err && err.message}`);
125
+ } finally { busy = false; }
126
+ }
127
+ if (!stopped) { timer = setTimeout(tick, intervalMs); if (timer.unref) timer.unref(); }
128
+ };
129
+ timer = setTimeout(tick, intervalMs);
130
+ if (timer.unref) timer.unref();
131
+ }
132
+ function stopSweeper() {
133
+ stopped = true;
134
+ if (timer) clearTimeout(timer);
135
+ timer = null;
136
+ }
137
+
138
+ return { sweepOnce, startSweeper, stopSweeper };
139
+ }
140
+
141
+ module.exports = { createSweeper };
@@ -0,0 +1,136 @@
1
+ // ======================================================
2
+ // gen/util — shared helpers of the v2 orchestration core
3
+ // ======================================================
4
+ // No I/O except through the pg pool handed in by the host. No requires of
5
+ // src/legacy, Redis, Express or ComfyUI (ADR ORCHESTRATION_V2 §5).
6
+
7
+ 'use strict';
8
+
9
+ const crypto = require('crypto');
10
+
11
+ /** Error with an HTTP-ish status and a stable machine code. */
12
+ class GenError extends Error {
13
+ constructor(code, status, message, extra) {
14
+ super(message || code);
15
+ this.name = 'GenError';
16
+ this.code = code;
17
+ this.status = status;
18
+ if (extra) Object.assign(this, extra);
19
+ }
20
+ }
21
+
22
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
23
+ function isUuid(v) { return typeof v === 'string' && UUID_RE.test(v); }
24
+
25
+ function requireUuid(v, name) {
26
+ if (!isUuid(v)) throw new GenError('bad_request', 400, `${name} must be a UUID`);
27
+ return v;
28
+ }
29
+
30
+ function requireText(v, name, max = 256) {
31
+ if (typeof v !== 'string' || v.length === 0 || v.length > max) {
32
+ throw new GenError('bad_request', 400, `${name} must be a non-empty string (<= ${max})`);
33
+ }
34
+ return v;
35
+ }
36
+
37
+ /**
38
+ * Run fn(client) inside BEGIN/COMMIT on a dedicated pooled client.
39
+ * Rolls back on throw. The client is always released.
40
+ */
41
+ async function withTx(pool, fn) {
42
+ const client = await pool.connect();
43
+ try {
44
+ await client.query('BEGIN');
45
+ const out = await fn(client);
46
+ await client.query('COMMIT');
47
+ return out;
48
+ } catch (err) {
49
+ try { await client.query('ROLLBACK'); } catch (_) { /* connection gone */ }
50
+ throw err;
51
+ } finally {
52
+ client.release();
53
+ }
54
+ }
55
+
56
+ // ── kinds / executors / layers ───────────────────────────────────────────
57
+ const KINDS = Object.freeze(['audio_chunk', 'iu_image', 'video_group', 'audio_merge', 'video_merge']);
58
+ const EXECUTOR_OF_KIND = Object.freeze({
59
+ audio_chunk: 'gpu:audio',
60
+ iu_image: 'gpu:image',
61
+ video_group: 'gpu:video',
62
+ audio_merge: 'local',
63
+ video_merge: 'local',
64
+ });
65
+ const LAYER_OF_KIND = Object.freeze({
66
+ audio_chunk: 'audio',
67
+ audio_merge: 'audio',
68
+ iu_image: 'image',
69
+ video_group: 'video',
70
+ video_merge: 'video',
71
+ });
72
+ /** 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']);
74
+ const LAYERS = Object.freeze(['audio', 'image', 'video']);
75
+ const WORKER_TYPES = LAYERS;
76
+ const LIVE = Object.freeze(['queued', 'running']);
77
+
78
+ // ── upload token (ADR §7: HMAC of job_id, attempt, exp) ──────────────────
79
+ function sign(secret, jobId, attempt, exp) {
80
+ return crypto.createHmac('sha256', secret)
81
+ .update(`gen-upload:v1:${jobId}:${attempt}:${exp}`)
82
+ .digest('base64url');
83
+ }
84
+
85
+ function issueUploadToken(secret, jobId, attempt, exp) {
86
+ return `v1.${exp}.${sign(secret, jobId, attempt, exp)}`;
87
+ }
88
+
89
+ /** @returns {boolean} true when the token is a valid, unexpired one for (jobId, attempt). */
90
+ function verifyUploadToken(secret, token, jobId, attempt, nowMs = Date.now()) {
91
+ if (typeof token !== 'string') return false;
92
+ const parts = token.split('.');
93
+ if (parts.length !== 3 || parts[0] !== 'v1') return false;
94
+ const exp = Number(parts[1]);
95
+ if (!Number.isSafeInteger(exp) || exp < nowMs) return false;
96
+ const expected = Buffer.from(sign(secret, jobId, attempt, exp));
97
+ const got = Buffer.from(parts[2]);
98
+ return expected.length === got.length && crypto.timingSafeEqual(expected, got);
99
+ }
100
+
101
+ // ── NOTIFY (ADR §9: payload book_id, command_id; delivered on COMMIT) ─────
102
+ const PROGRESS_CHANNEL = 'gen_progress';
103
+ async function notifyProgress(client, bookId, commandId) {
104
+ await client.query('SELECT pg_notify($1, $2)', [PROGRESS_CHANNEL,
105
+ JSON.stringify({ book_id: bookId, command_id: commandId || null })]);
106
+ }
107
+
108
+ /** Link jobs to commands (§4.2a). Idempotent. */
109
+ async function linkJobs(client, commandIds, jobIds) {
110
+ if (!commandIds.length || !jobIds.length) return 0;
111
+ const r = await client.query(
112
+ `INSERT INTO gen_command_jobs (command_id, job_id)
113
+ SELECT c, j FROM unnest($1::uuid[]) AS c CROSS JOIN unnest($2::uuid[]) AS j
114
+ ON CONFLICT DO NOTHING`, [commandIds, jobIds]);
115
+ return r.rowCount;
116
+ }
117
+
118
+ module.exports = {
119
+ PROGRESS_CHANNEL,
120
+ notifyProgress,
121
+ linkJobs,
122
+ GenError,
123
+ isUuid,
124
+ requireUuid,
125
+ requireText,
126
+ withTx,
127
+ KINDS,
128
+ EXECUTOR_OF_KIND,
129
+ LAYER_OF_KIND,
130
+ FIRST_STAGE_KINDS,
131
+ LAYERS,
132
+ WORKER_TYPES,
133
+ LIVE,
134
+ issueUploadToken,
135
+ verifyUploadToken,
136
+ };
@@ -0,0 +1,181 @@
1
+ // ======================================================
2
+ // gen/validate-media — default result validators (ADR §7 п.1, §13.4)
3
+ // ======================================================
4
+ // Audio: MP3 magic bytes (ID3v2 tag or MPEG Layer III frame sync), duration
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.
7
+ //
8
+ // PCM decoding is injected (`decodePcm(path) → Int16Array`); the default
9
+ // spawns the `ffmpeg` binary (node builtin child_process, no npm dependency).
10
+ // Fail-closed: no decoder → the result is NOT accepted (reason
11
+ // decoder_unavailable) — «тишина = ready» must never come back.
12
+
13
+ 'use strict';
14
+
15
+ const fs = require('fs');
16
+ const { spawn } = require('child_process');
17
+
18
+ const DEFAULT_RMS_THRESHOLD_DBFS = -50;
19
+ const MIN_AUDIO_BYTES = 256;
20
+
21
+ // MPEG audio tables (Layer III only)
22
+ const BITRATES_KBPS = {
23
+ 1: [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320],
24
+ 2: [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],
25
+ };
26
+ const SAMPLE_RATES = { 1: [44100, 48000, 32000], 2: [22050, 24000, 16000], 25: [11025, 12000, 8000] };
27
+
28
+ /** Parse one MPEG Layer III frame header at buf[off]. @returns {{len:number, samples:number, sr:number}|null} */
29
+ function parseFrameHeader(buf, off) {
30
+ if (off + 4 > buf.length) return null;
31
+ const b1 = buf[off + 1], b2 = buf[off + 2];
32
+ if (buf[off] !== 0xff || (b1 & 0xe0) !== 0xe0) return null;
33
+ const verBits = (b1 >> 3) & 0x03; // 00 = 2.5, 10 = 2, 11 = 1
34
+ const layerBits = (b1 >> 1) & 0x03; // 01 = Layer III
35
+ if (verBits === 0x01 || layerBits !== 0x01) return null;
36
+ const version = verBits === 0x03 ? 1 : verBits === 0x02 ? 2 : 25;
37
+ const brIdx = (b2 >> 4) & 0x0f;
38
+ const srIdx = (b2 >> 2) & 0x03;
39
+ if (brIdx === 0 || brIdx === 0x0f || srIdx === 0x03) return null;
40
+ const padding = (b2 >> 1) & 0x01;
41
+ const bitrate = BITRATES_KBPS[version === 1 ? 1 : 2][brIdx] * 1000;
42
+ const sr = SAMPLE_RATES[version][srIdx];
43
+ const coef = version === 1 ? 144 : 72;
44
+ const len = Math.floor((coef * bitrate) / sr) + padding;
45
+ return { len, samples: version === 1 ? 1152 : 576, sr };
46
+ }
47
+
48
+ /**
49
+ * Inspect an MP3 buffer: magic + frame walk.
50
+ * @returns {{ok:true, durationSec:number, frames:number}|{ok:false, reason:string}}
51
+ */
52
+ function inspectMp3(buf) {
53
+ if (!Buffer.isBuffer(buf) || buf.length < MIN_AUDIO_BYTES) return { ok: false, reason: 'too_small' };
54
+ let off = 0;
55
+ if (buf[0] === 0x49 && buf[1] === 0x44 && buf[2] === 0x33) { // "ID3"
56
+ if (buf.length < 10) return { ok: false, reason: 'not_mp3' };
57
+ const size = ((buf[6] & 0x7f) << 21) | ((buf[7] & 0x7f) << 14) | ((buf[8] & 0x7f) << 7) | (buf[9] & 0x7f);
58
+ off = 10 + size + ((buf[5] & 0x10) ? 10 : 0);
59
+ }
60
+ const first = parseFrameHeader(buf, off);
61
+ if (!first) return { ok: false, reason: 'not_mp3' };
62
+ let frames = 0;
63
+ let duration = 0;
64
+ while (off < buf.length) {
65
+ const h = parseFrameHeader(buf, off);
66
+ if (!h || h.len <= 4) break;
67
+ if (off + h.len > buf.length) break; // truncated tail frame — not counted
68
+ frames += 1;
69
+ duration += h.samples / h.sr;
70
+ off += h.len;
71
+ }
72
+ if (frames === 0 || !(duration > 0)) return { ok: false, reason: 'zero_duration' };
73
+ return { ok: true, durationSec: duration, frames };
74
+ }
75
+
76
+ /** RMS of 16-bit PCM in dBFS (-Infinity for digital silence). */
77
+ function rmsDbfs(samples) {
78
+ if (!samples || samples.length === 0) return -Infinity;
79
+ let acc = 0;
80
+ for (let i = 0; i < samples.length; i += 1) acc += samples[i] * samples[i];
81
+ const rms = Math.sqrt(acc / samples.length);
82
+ return rms === 0 ? -Infinity : 20 * Math.log10(rms / 32768);
83
+ }
84
+
85
+ /** Default decoder: ffmpeg → mono 16 kHz s16le. Rejects with code ENOENT if ffmpeg is absent. */
86
+ function ffmpegDecodePcm(filePath, { ffmpegPath = 'ffmpeg', timeoutMs = 60_000 } = {}) {
87
+ return new Promise((resolve, reject) => {
88
+ const p = spawn(ffmpegPath, ['-v', 'error', '-nostdin', '-i', filePath, '-f', 's16le', '-ac', '1', '-ar', '16000', '-'],
89
+ { stdio: ['ignore', 'pipe', 'pipe'] });
90
+ const chunks = [];
91
+ let stderr = '';
92
+ const timer = setTimeout(() => { p.kill('SIGKILL'); }, timeoutMs);
93
+ p.stdout.on('data', (d) => chunks.push(d));
94
+ p.stderr.on('data', (d) => { if (stderr.length < 2000) stderr += d.toString(); });
95
+ p.on('error', (err) => { clearTimeout(timer); reject(err); });
96
+ p.on('close', (code) => {
97
+ clearTimeout(timer);
98
+ if (code !== 0) return reject(Object.assign(new Error(`ffmpeg exit ${code}: ${stderr.trim()}`), { code: 'EDECODE' }));
99
+ const buf = Buffer.concat(chunks);
100
+ resolve(new Int16Array(buf.buffer, buf.byteOffset, Math.floor(buf.length / 2)));
101
+ });
102
+ });
103
+ }
104
+
105
+ /**
106
+ * @param {object} [opts]
107
+ * @param {number} [opts.rmsThresholdDbfs=-50] below → silence (rejected)
108
+ * @param {(path:string)=>Promise<Int16Array>} [opts.decodePcm] PCM decoder
109
+ * @returns {(tmpPath:string)=>Promise<{ok:boolean, reason?:string, durationSec?:number, rmsDbfs?:number}>}
110
+ */
111
+ function createAudioValidator(opts = {}) {
112
+ const threshold = Number.isFinite(opts.rmsThresholdDbfs) ? opts.rmsThresholdDbfs : DEFAULT_RMS_THRESHOLD_DBFS;
113
+ const decodePcm = typeof opts.decodePcm === 'function' ? opts.decodePcm : ffmpegDecodePcm;
114
+ return async function validateAudio(tmpPath) {
115
+ const buf = await fs.promises.readFile(tmpPath);
116
+ const mp3 = inspectMp3(buf);
117
+ if (!mp3.ok) return mp3;
118
+ let pcm;
119
+ try {
120
+ pcm = await decodePcm(tmpPath);
121
+ } catch (err) {
122
+ if (err && err.code === 'ENOENT') return { ok: false, reason: 'decoder_unavailable' };
123
+ return { ok: false, reason: 'decode_failed' };
124
+ }
125
+ const level = rmsDbfs(pcm);
126
+ if (!(level >= threshold)) {
127
+ return { ok: false, reason: 'silence', durationSec: mp3.durationSec, rmsDbfs: level };
128
+ }
129
+ return { ok: true, durationSec: mp3.durationSec, rmsDbfs: level };
130
+ };
131
+ }
132
+
133
+ const PNG_SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
134
+
135
+ async function readHead(filePath, n) {
136
+ const fh = await fs.promises.open(filePath, 'r');
137
+ try {
138
+ const buf = Buffer.alloc(n);
139
+ const { bytesRead } = await fh.read(buf, 0, n, 0);
140
+ return buf.subarray(0, bytesRead);
141
+ } finally { await fh.close(); }
142
+ }
143
+
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
+ }
148
+
149
+ async function validateMp4(tmpPath) {
150
+ const head = await readHead(tmpPath, 12);
151
+ return head.length >= 8 && head.toString('latin1', 4, 8) === 'ftyp' ? { ok: true } : { ok: false, reason: 'not_mp4' };
152
+ }
153
+
154
+ /**
155
+ * Default validateResult port: dispatches by job.kind.
156
+ * @param {object} [opts] forwarded to createAudioValidator
157
+ */
158
+ function createDefaultValidateResult(opts = {}) {
159
+ const audio = createAudioValidator(opts);
160
+ return async function validateResult(job, tmpPath) {
161
+ switch (job && job.kind) {
162
+ case 'audio_chunk':
163
+ case 'audio_merge': return audio(tmpPath);
164
+ case 'iu_image': return validatePng(tmpPath);
165
+ case 'video_group':
166
+ case 'video_merge': return validateMp4(tmpPath);
167
+ default: return { ok: false, reason: 'unknown_kind' };
168
+ }
169
+ };
170
+ }
171
+
172
+ module.exports = {
173
+ DEFAULT_RMS_THRESHOLD_DBFS,
174
+ inspectMp3,
175
+ rmsDbfs,
176
+ ffmpegDecodePcm,
177
+ createAudioValidator,
178
+ createDefaultValidateResult,
179
+ validatePng,
180
+ validateMp4,
181
+ };
package/src/index.js CHANGED
@@ -1,100 +1,24 @@
1
1
  // ======================================================
2
- // @animastor/orchestration — package root (public API)
2
+ // @animastor/orchestration 1.0.0 — package root
3
3
  // ======================================================
4
- // The orchestration/runtime contour physically extracted from the backend
5
- // host (§32.30; gate: §32.29 — READY FOR PHYSICAL MOVE). This root exports
6
- // EXACTLY the measured host consumption surface — nothing "just in case":
4
+ // 1.0.0 = orchestration v2 (ADR animastor-docs architecture/ORCHESTRATION_V2.md).
7
5
  //
8
- // 1. The orchestration facade (former backend/src/orchestration/index.js,
9
- // moved verbatim) — the stage executor + FSM-safe scene writers the
10
- // host and the S-5 seam registry consume.
11
- // 2. createRuntimeResultConsumer — the Phase-5 result-reporting consumer
12
- // the composition root registers via runtimeResultEmitter.setConsumer.
13
- // 3. The eight O-2..O-10 port CONTRACT modules (tier-owned, moved with
14
- // the contour) — the host storage adapters bind these at startup.
15
- // 4. bindHostModules / hostBinding — the composition-root binding surface
16
- // that wires the host-owned modules the moved files consume
17
- // (config/state/media/seams/artifact root/PW-2 resolver).
18
- //
19
- // §32.30: the facade exports are LAZY getters (the FSM-writer re-exports
20
- // resolve the stateOps host binding on access), so the root itself builds
21
- // its export object with defineProperties — a literal spread would fire
22
- // those getters at require time, before the composition root binds host
23
- // modules. The surface (names + facade-wins precedence) is unchanged.
24
- //
25
- // Everything else in the package (dispatch-engine, reconciliation-engine,
26
- // scene-window, scheduler, lease/circuit/retry managers, worker-health,
27
- // metrics) is INTERNAL: no host module and no host test may deep-import it.
28
- //
29
- // Dependency direction after the move (guarded by backend PM-G suite):
30
- // backend host → @animastor/orchestration → ports/host-bindings/contracts
31
- // The package requires @animastor/generation (root specifier only) and
32
- // @animastor/contracts; it never requires backend/src, storage, book,
33
- // routes, services, Redis or PG clients.
34
- //
35
- // Docs: docs/architecture/generation-module-extraction-reconnaissance.md
36
- // §32.29 (frozen API) · §32.30 (physical extraction landed)
6
+ // • Every export of 0.3.x is unchanged: the old orchestration lives verbatim
7
+ // in src/legacy/ during the migration (removed at ADR stage 4). Its root
8
+ // uses lazy getters (FSM writers resolve host bindings on access), so the
9
+ // property DESCRIPTORS are copied, never the values — nothing fires at
10
+ // require time, exactly as before.
11
+ // • `gen` — the new v2 core (src/gen/): PG-only, no legacy / Redis /
12
+ // Express / ComfyUI. Lazy too: requiring the package does not load it.
37
13
 
38
- const orchestrationFacade = require('./orchestration');
39
- const { createRuntimeResultConsumer } = require('./orchestration/runtime-result-consumer');
40
- const hostBindings = require('./host/host-bindings');
14
+ 'use strict';
41
15
 
42
- // 1 — orchestration facade (lazy accessors over the moved facade modules)
43
- const FACADE_KEYS = Object.keys(orchestrationFacade);
44
- const LAZY_FACADE_PROPS = Object.fromEntries(FACADE_KEYS.map((key) => [key, {
45
- enumerable: true,
46
- get() { return orchestrationFacade[key]; },
47
- }]));
48
-
49
- // 2 + 3 + 4 — eager values (no binding resolution at require time)
50
- const EAGER_EXPORTS = {
51
- createRuntimeResultConsumer,
52
- ports: {
53
- persistence: require('./runtime/persistence-port'),
54
- sceneData: require('./runtime/scene-data-port'),
55
- placeholderAudio: require('./runtime/placeholder-audio-port'),
56
- progressEvents: require('./runtime/progress-events-port'),
57
- audioFsm: require('./runtime/audio-fsm-port'),
58
- videoFsm: require('./runtime/video-fsm-port'),
59
- hubCancel: require('./runtime/hub-cancel-port'),
60
- layerConfig: require('./runtime/layer-config-port'),
61
- },
62
- bindHostModules: hostBindings.bindHostModules,
63
- clearHostBindings: hostBindings.clearHostBindings,
64
- hostBinding: hostBindings.hostBinding,
65
- isHostBindingWired: hostBindings.isHostBindingWired,
66
- lazyHostBinding: hostBindings.lazyHostBinding,
67
- requiredHostBindings: hostBindings.requiredHostBindings,
68
- BINDING_NAMES: hostBindings.BINDING_NAMES,
69
- };
16
+ const legacy = require('./legacy');
70
17
 
71
- // 5 — the host-facing runtime namespace: the measured routes/services/helpers
72
- // consumption surface (the former backend/src/runtime/index.js barrel minus
73
- // its host-stay members loop/gpuDispatcher/retentionManager). Lazy getters —
74
- // no eager module loads at require time.
75
- const RUNTIME_NS = {
76
- scheduler: './runtime/runtime-scheduler',
77
- activeScenes: './runtime/active-scenes-index',
78
- commandGate: './runtime/command-gate',
79
- reconciliation: './runtime/reconciliation-engine',
80
- dispatch: './runtime/dispatch-engine',
81
- leaseManager: './runtime/lease-manager',
82
- counterReconciliation: './runtime/counter-reconciliation',
83
- metrics: './runtime/runtime-metrics',
84
- workerHealth: './runtime/worker-health',
85
- sceneWindow: './runtime/scene-window',
86
- failureTaxonomy: './runtime/failure-taxonomy',
87
- runtimeResultEmitter: './runtime/runtime-result-emitter',
88
- };
89
- const LAZY_RUNTIME_PROPS = Object.fromEntries(Object.entries(RUNTIME_NS).map(([key, target]) => [key, {
18
+ const api = Object.defineProperties({}, Object.getOwnPropertyDescriptors(legacy));
19
+ Object.defineProperty(api, 'gen', {
90
20
  enumerable: true,
91
- get() { return require(target); },
92
- }]));
93
-
94
- const base = { ...EAGER_EXPORTS };
95
- Object.defineProperties(base, LAZY_FACADE_PROPS);
96
- Object.defineProperties(base, {
97
- runtime: { enumerable: true, value: Object.defineProperties({}, LAZY_RUNTIME_PROPS) },
21
+ get() { return require('./gen'); },
98
22
  });
99
23
 
100
- module.exports = base;
24
+ module.exports = api;
@@ -0,0 +1,100 @@
1
+ // ======================================================
2
+ // @animastor/orchestration — package root (public API)
3
+ // ======================================================
4
+ // The orchestration/runtime contour physically extracted from the backend
5
+ // host (§32.30; gate: §32.29 — READY FOR PHYSICAL MOVE). This root exports
6
+ // EXACTLY the measured host consumption surface — nothing "just in case":
7
+ //
8
+ // 1. The orchestration facade (former backend/src/orchestration/index.js,
9
+ // moved verbatim) — the stage executor + FSM-safe scene writers the
10
+ // host and the S-5 seam registry consume.
11
+ // 2. createRuntimeResultConsumer — the Phase-5 result-reporting consumer
12
+ // the composition root registers via runtimeResultEmitter.setConsumer.
13
+ // 3. The eight O-2..O-10 port CONTRACT modules (tier-owned, moved with
14
+ // the contour) — the host storage adapters bind these at startup.
15
+ // 4. bindHostModules / hostBinding — the composition-root binding surface
16
+ // that wires the host-owned modules the moved files consume
17
+ // (config/state/media/seams/artifact root/PW-2 resolver).
18
+ //
19
+ // §32.30: the facade exports are LAZY getters (the FSM-writer re-exports
20
+ // resolve the stateOps host binding on access), so the root itself builds
21
+ // its export object with defineProperties — a literal spread would fire
22
+ // those getters at require time, before the composition root binds host
23
+ // modules. The surface (names + facade-wins precedence) is unchanged.
24
+ //
25
+ // Everything else in the package (dispatch-engine, reconciliation-engine,
26
+ // scene-window, scheduler, lease/circuit/retry managers, worker-health,
27
+ // metrics) is INTERNAL: no host module and no host test may deep-import it.
28
+ //
29
+ // Dependency direction after the move (guarded by backend PM-G suite):
30
+ // backend host → @animastor/orchestration → ports/host-bindings/contracts
31
+ // The package requires @animastor/generation (root specifier only) and
32
+ // @animastor/contracts; it never requires backend/src, storage, book,
33
+ // routes, services, Redis or PG clients.
34
+ //
35
+ // Docs: docs/architecture/generation-module-extraction-reconnaissance.md
36
+ // §32.29 (frozen API) · §32.30 (physical extraction landed)
37
+
38
+ const orchestrationFacade = require('./orchestration');
39
+ const { createRuntimeResultConsumer } = require('./orchestration/runtime-result-consumer');
40
+ const hostBindings = require('./host/host-bindings');
41
+
42
+ // 1 — orchestration facade (lazy accessors over the moved facade modules)
43
+ const FACADE_KEYS = Object.keys(orchestrationFacade);
44
+ const LAZY_FACADE_PROPS = Object.fromEntries(FACADE_KEYS.map((key) => [key, {
45
+ enumerable: true,
46
+ get() { return orchestrationFacade[key]; },
47
+ }]));
48
+
49
+ // 2 + 3 + 4 — eager values (no binding resolution at require time)
50
+ const EAGER_EXPORTS = {
51
+ createRuntimeResultConsumer,
52
+ ports: {
53
+ persistence: require('./runtime/persistence-port'),
54
+ sceneData: require('./runtime/scene-data-port'),
55
+ placeholderAudio: require('./runtime/placeholder-audio-port'),
56
+ progressEvents: require('./runtime/progress-events-port'),
57
+ audioFsm: require('./runtime/audio-fsm-port'),
58
+ videoFsm: require('./runtime/video-fsm-port'),
59
+ hubCancel: require('./runtime/hub-cancel-port'),
60
+ layerConfig: require('./runtime/layer-config-port'),
61
+ },
62
+ bindHostModules: hostBindings.bindHostModules,
63
+ clearHostBindings: hostBindings.clearHostBindings,
64
+ hostBinding: hostBindings.hostBinding,
65
+ isHostBindingWired: hostBindings.isHostBindingWired,
66
+ lazyHostBinding: hostBindings.lazyHostBinding,
67
+ requiredHostBindings: hostBindings.requiredHostBindings,
68
+ BINDING_NAMES: hostBindings.BINDING_NAMES,
69
+ };
70
+
71
+ // 5 — the host-facing runtime namespace: the measured routes/services/helpers
72
+ // consumption surface (the former backend/src/runtime/index.js barrel minus
73
+ // its host-stay members loop/gpuDispatcher/retentionManager). Lazy getters —
74
+ // no eager module loads at require time.
75
+ const RUNTIME_NS = {
76
+ scheduler: './runtime/runtime-scheduler',
77
+ activeScenes: './runtime/active-scenes-index',
78
+ commandGate: './runtime/command-gate',
79
+ reconciliation: './runtime/reconciliation-engine',
80
+ dispatch: './runtime/dispatch-engine',
81
+ leaseManager: './runtime/lease-manager',
82
+ counterReconciliation: './runtime/counter-reconciliation',
83
+ metrics: './runtime/runtime-metrics',
84
+ workerHealth: './runtime/worker-health',
85
+ sceneWindow: './runtime/scene-window',
86
+ failureTaxonomy: './runtime/failure-taxonomy',
87
+ runtimeResultEmitter: './runtime/runtime-result-emitter',
88
+ };
89
+ const LAZY_RUNTIME_PROPS = Object.fromEntries(Object.entries(RUNTIME_NS).map(([key, target]) => [key, {
90
+ enumerable: true,
91
+ get() { return require(target); },
92
+ }]));
93
+
94
+ const base = { ...EAGER_EXPORTS };
95
+ Object.defineProperties(base, LAZY_FACADE_PROPS);
96
+ Object.defineProperties(base, {
97
+ runtime: { enumerable: true, value: Object.defineProperties({}, LAZY_RUNTIME_PROPS) },
98
+ });
99
+
100
+ module.exports = base;