@animastor/orchestration 0.3.5 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +101 -0
  2. package/README.md +37 -0
  3. package/package.json +11 -8
  4. package/src/gen/accept.js +425 -0
  5. package/src/gen/claim.js +155 -0
  6. package/src/gen/commands.js +367 -0
  7. package/src/gen/index.js +110 -0
  8. package/src/gen/local-runner.js +80 -0
  9. package/src/gen/ports.js +169 -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 +368 -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 +17 -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
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;
@@ -33,6 +33,7 @@ const { lazyHostBinding } = require('../host/host-bindings');
33
33
  const state = lazyHostBinding('state');
34
34
  const progressEventsOp = require('./progress-events-port').progressEventsOp;
35
35
  const persist = require('./persistence-port').persist;
36
+ const { isV2Book } = require('./persistence-port');
36
37
 
37
38
  const logPrefix = '[COMMAND-GATE]';
38
39
 
@@ -95,11 +96,12 @@ async function isBookCancelled(redis, bookId) {
95
96
 
96
97
  /** Per-pass memo (one scheduler tick / one reconcile pass). */
97
98
  function createGateCache() {
98
- return { layer: new Map(), cancelled: new Map() };
99
+ return { layer: new Map(), cancelled: new Map(), v2: new Map() };
99
100
  }
100
101
 
101
102
  async function memo(cache, bucket, bookId, fn) {
102
103
  if (!cache) return fn();
104
+ if (!cache[bucket]) cache[bucket] = new Map();
103
105
  if (cache[bucket].has(bookId)) return cache[bucket].get(bookId);
104
106
  const value = await fn();
105
107
  cache[bucket].set(bookId, value);
@@ -113,9 +115,16 @@ const EMPTY_TASK_STATE = Object.freeze({ managed: false, activeTypes: new Set()
113
115
  *
114
116
  * @returns {Promise<{stages:Set<string>, denied:Object<string,string>,
115
117
  * cancelled:boolean, layerCfg:object, taskState:{managed:boolean, activeTypes:Set<string>}}>}
116
- * `denied[stage]` ∈ 'cancelled' | 'no_active_task' | 'layer_disabled'.
118
+ * `denied[stage]` ∈ 'cancelled' | 'no_active_task' | 'layer_disabled' | 'orchestration_v2'.
117
119
  */
118
120
  async function getAuthorizedStages(redis, bookId, chapterId, sceneId, cache = null) {
121
+ // Orchestration v2 (1b/E): a v2 book is never authorized for a legacy stage —
122
+ // the gen core owns it (fail-closed inside isV2Book).
123
+ if (await memo(cache, 'v2', bookId, () => isV2Book(bookId))) {
124
+ const denied = {};
125
+ for (const stage of mediaRegistry.listMediaTypes()) denied[stage] = 'orchestration_v2';
126
+ return { stages: new Set(), denied, cancelled: false, layerCfg: null, taskState: EMPTY_TASK_STATE, v2: true };
127
+ }
119
128
  const cancelled = await memo(cache, 'cancelled', bookId, () => isBookCancelled(redis, bookId));
120
129
  const layerCfg = await memo(cache, 'layer', bookId, () => getLayerConfig(redis, bookId));
121
130
 
@@ -154,6 +154,26 @@ function persist(op) {
154
154
  return fn;
155
155
  }
156
156
 
157
+ // ── Orchestration v2 isolation (ADR ORCHESTRATION_V2 §12 этап 1; задача 1b/E) ──
158
+ // A book with books.orchestration = 'v2' belongs to the v2 core (gen_*): the
159
+ // legacy contour (command gate, reconcile, scheduler, retry policy, startup
160
+ // resume) must not touch it. The ONE predicate every legacy leg asks. The host
161
+ // adapter implements the OPTIONAL op orchestration.isV2Book(bookId) (not in
162
+ // OPS: adapters/mocks without it keep the pre-v2 behaviour = "not v2").
163
+ // Fail-closed: when the op exists but cannot answer, the book is treated as v2
164
+ // (legacy keeps its hands off).
165
+ async function isV2Book(bookId) {
166
+ if (!bookId || !impl) return false;
167
+ const fn = resolveOp(impl, 'orchestration.isV2Book');
168
+ if (typeof fn !== 'function') return false;
169
+ try {
170
+ return (await fn(bookId)) === true;
171
+ } catch (err) {
172
+ console.warn(`[PERSISTENCE-PORT] orchestration.isV2Book(${bookId}) failed: ${err && err.message} — treated as v2 (fail-closed)`);
173
+ return true;
174
+ }
175
+ }
176
+
157
177
  function isPersistencePortWired() {
158
178
  return impl !== null;
159
179
  }
@@ -164,6 +184,7 @@ function _resetPersistencePort() {
164
184
  }
165
185
 
166
186
  module.exports = {
187
+ isV2Book,
167
188
  OPS,
168
189
  setPersistencePort,
169
190
  persistence,
@@ -31,6 +31,8 @@ const mediaRegistry = require('@animastor/generation').mediaRegistry;
31
31
  // audio-path composition are consumed as persistence OPERATIONS through the
32
32
  // same port (their implementations stay host-side).
33
33
  const persist = require('./persistence-port').persist;
34
+ // Orchestration v2 (1b/E): every phase skips books with books.orchestration='v2'.
35
+ const { isV2Book } = require('./persistence-port');
34
36
  const config = lazyHostBinding('config');
35
37
  // S-5: the event journal is an append-only observability sink (zero requires,
36
38
  // no orchestration policy) — the ONLY runtime→Generation dependency allowed
@@ -549,6 +551,7 @@ async function checkStalledAudioScenes(redis, deps) {
549
551
  let stalled = 0;
550
552
  for (const entry of allStates) {
551
553
  const { bookId, chapterId, sceneId, state: orchState } = entry;
554
+ if (await isV2Book(bookId)) continue; // orchestration v2: not legacy's
552
555
  if (orchState.phase !== PHASES.WAITING_CHUNKS) continue;
553
556
 
554
557
  const buildId = orchState.build_id || 'default';
@@ -671,6 +674,7 @@ async function checkStalledVideoScenes(redis, deps) {
671
674
  let stalled = 0;
672
675
  for (const entry of allStates) {
673
676
  const { bookId, chapterId, sceneId, state: orchState } = entry;
677
+ if (await isV2Book(bookId)) continue; // orchestration v2: not legacy's
674
678
  if (orchState.phase !== PHASES.WAITING_CHUNKS) continue;
675
679
 
676
680
  // ── ПЕРЕСМОТР ПОРОГА ЗАСТОЯ ──
@@ -1031,6 +1035,7 @@ async function checkStaleDispatchLeases(redis, bookId, chapterId, sceneId) {
1031
1035
  */
1032
1036
  async function reconcileScene(redis, bookId, chapterId, sceneId) {
1033
1037
  const report = new ReconciliationReport();
1038
+ if (await isV2Book(bookId)) return report; // orchestration v2: not legacy's
1034
1039
 
1035
1040
  try {
1036
1041
  // Check orphan states
@@ -2055,6 +2060,10 @@ async function recoverResultKeys(redis, deps, scope) {
2055
2060
  // marker or one from an older dispatch of the same job_id
2056
2061
  // (audio/video regeneration within the TTL) is no proof — such
2057
2062
  // a result goes through the fenced handler exactly as before.
2063
+ {
2064
+ const pj = require('@animastor/contracts').jobProtocolV2.parseJobId(job_id);
2065
+ if (pj && await isV2Book(pj.bookId)) continue; // orchestration v2: key left untouched
2066
+ }
2058
2067
  const dedup = await readResultDedup(redis, job_id, buildId);
2059
2068
  if (dedup.state === 'settled' && dedup.dispatchId === String(dispatchId)) {
2060
2069
  await redis.del(key);
@@ -2116,6 +2125,7 @@ async function recoverResultKeys(redis, deps, scope) {
2116
2125
  // Parse job_id to get stage and scene info
2117
2126
  const jobSchema = require('@animastor/contracts').jobProtocolV2;
2118
2127
  const parsed = jobSchema.parseJobId(job_id);
2128
+ if (parsed && await isV2Book(parsed.bookId)) continue; // orchestration v2: key left untouched
2119
2129
  if (parsed) {
2120
2130
  const stageMap = { audio_chunk: 'audio', iu_image: 'image', scene_image: 'image', scene_video: 'video' };
2121
2131
  const stage = stageMap[parsed.kind];
@@ -2159,6 +2169,7 @@ async function recoverAudioOrchStates(redis, deps) {
2159
2169
 
2160
2170
  for (const entry of allStates) {
2161
2171
  const { bookId, chapterId, sceneId, state: orchState } = entry;
2172
+ if (await isV2Book(bookId)) continue; // orchestration v2: not legacy's
2162
2173
  const phase = orchState.phase;
2163
2174
  const buildId = orchState.build_id || 'default';
2164
2175
  const mergedPath = syncPath.join(OUTPUT_DIR, buildId, artifactNaming.sceneAudioName(bookId, chapterId, sceneId));
@@ -2260,6 +2271,7 @@ async function recoverVideoOrchStates(redis, deps) {
2260
2271
 
2261
2272
  for (const entry of allStates) {
2262
2273
  const { bookId, chapterId, sceneId, state: orchState } = entry;
2274
+ if (await isV2Book(bookId)) continue; // orchestration v2: not legacy's
2263
2275
  const phase = orchState.phase;
2264
2276
  const buildId = orchState.build_id || 'default';
2265
2277
  const suffixes = videoOrch.groupSuffixes(orchState);
@@ -2367,6 +2379,7 @@ async function checkVersionStaleness(redis, deps) {
2367
2379
 
2368
2380
  let outdated = 0;
2369
2381
  for (const entry of sceneMap.values()) {
2382
+ if (await isV2Book(entry.bookId)) continue; // orchestration v2
2370
2383
  if (entry.staleAssets.size === 0) continue;
2371
2384
 
2372
2385
  let assetStates;
@@ -2413,6 +2426,7 @@ async function reconcileMissingSceneState(redis, deps) {
2413
2426
  const bookResult = { rows: await persist('listBooks')() };
2414
2427
  let count = 0;
2415
2428
  for (const row of bookResult.rows) {
2429
+ if (await isV2Book(row.book_id)) continue; // orchestration v2
2416
2430
  const totalKey = `animastor:book-scenes:${row.book_id}:total`;
2417
2431
  const totalRaw = await redis.get(totalKey);
2418
2432
  if (!totalRaw || parseInt(totalRaw, 10) === 0) {
@@ -2490,6 +2504,7 @@ const state = lazyHostBinding('state');
2490
2504
 
2491
2505
  let scenesAdded = 0;
2492
2506
  for (const bookId of books) {
2507
+ if (await isV2Book(bookId)) { log(`[WORKLIST] ${bookId}: skipped (orchestration v2)`); continue; }
2493
2508
  if (cancelled.has(bookId)) {
2494
2509
  log(`[WORKLIST] ${bookId}: skipped (cancellation tombstone)`);
2495
2510
  continue;
@@ -386,7 +386,15 @@ async function tick(redis, loadedBooks = {}) {
386
386
  const parsed = parseSceneKey(sceneKey);
387
387
  if (parsed) activeBookIds.add(parsed.bookId);
388
388
  }
389
+ // Orchestration v2 (1b/E): a v2 book is skipped entirely — no read-modify-write
390
+ // of any legacy key (registry, asset-state, active index, leases).
391
+ const v2Books = new Set();
389
392
  for (const bookId of activeBookIds) {
393
+ if (await require('./persistence-port').isV2Book(bookId)) v2Books.add(bookId);
394
+ }
395
+ if (v2Books.size > 0) log(`V2_SKIP: ${[...v2Books].join(',')} (orchestration v2 — legacy scheduler keeps out)`);
396
+ for (const bookId of activeBookIds) {
397
+ if (v2Books.has(bookId)) continue;
390
398
  const completedTasks = await progressEventsOp('reconcileCompletedTasks')(
391
399
  redis,
392
400
  bookId,
@@ -417,6 +425,7 @@ async function tick(redis, loadedBooks = {}) {
417
425
  }
418
426
 
419
427
  const { bookId, chapterId, sceneId } = parsed;
428
+ if (v2Books.has(bookId)) { summary.skipped++; continue; }
420
429
 
421
430
  // Force applies only to the scene×stage pairs of the command.
422
431
  let bookForce = forceCache.get(bookId);
@@ -75,7 +75,19 @@ function error(msg) {
75
75
  console.error(`${logPrefix} ❌ ${msg}`);
76
76
  }
77
77
 
78
+ // Orchestration v2 (2a): the window / read-repair functions below rewrite legacy
79
+ // chunk statuses and asset-state from the files on disk («file exists → image
80
+ // ready»). A v2 book's files are written by the gen core, its readiness lives in
81
+ // PG scene_assets — legacy keeps its hands off ALL its layers (one predicate,
82
+ // fail-closed inside isV2Book).
83
+ async function isV2(bookId, what) {
84
+ if (!(await require('./persistence-port').isV2Book(bookId))) return false;
85
+ log(`${what} skipped: ${bookId} is on orchestration v2`);
86
+ return true;
87
+ }
88
+
78
89
  async function initSceneWindow(redis, scenes, loadedBook, buildId, bookId, scopeInfo) {
90
+ if (await isV2(bookId, 'initSceneWindow')) return 0;
79
91
  const scope = scopeInfo || (await genScope.getScope(redis, bookId));
80
92
  const bounds = genScope.scopeBounds(scope, scenes);
81
93
  const totalScenes = bounds.endIndex;
@@ -340,6 +352,7 @@ async function _checkAssetVersionStale(bookId, chapterId, sceneId, buildId) {
340
352
  * do NOT override the pending state — the scene stays pending for regeneration.
341
353
  */
342
354
  async function restoreChunkStatusForScene(redis, buildId, bookId, chapterId, sceneId) {
355
+ if (await isV2(bookId, 'restoreChunkStatusForScene')) return;
343
356
  const buildDir = path.join(OUTPUT_DIR, buildId);
344
357
  if (!fs.existsSync(buildDir)) return;
345
358
 
@@ -477,6 +490,7 @@ async function isWindowComplete(redis, bookId) {
477
490
  * Try to slide window forward if all current window scenes have audio + image complete.
478
491
  */
479
492
  async function trySlideWindowOnComplete(redis, bookId, loadedBook, buildId) {
493
+ if (await isV2(bookId, 'trySlideWindowOnComplete')) return { started: 0, remaining: 0, reason: 'orchestration_v2' };
480
494
  // Command-only generation: sliding the window forward after its scenes
481
495
  // complete is an automatic start of the next scenes. Behind the
482
496
  // WINDOW_AUTO_NEXT_ENABLED flag, default OFF (owner decision pending).
@@ -516,6 +530,7 @@ async function trySlideWindowOnComplete(redis, bookId, loadedBook, buildId) {
516
530
  }
517
531
 
518
532
  async function slideWindow(redis, bookId, loadedBook, buildId) {
533
+ if (await isV2(bookId, 'slideWindow')) return { started: 0, remaining: 0, reason: 'orchestration_v2' };
519
534
  if (await isCancelled(redis, bookId)) {
520
535
  log(`Slide skipped: generation cancelled for ${bookId}`);
521
536
  return { started: 0, remaining: 0, reason: 'cancelled' };
@@ -603,6 +618,7 @@ async function slideWindow(redis, bookId, loadedBook, buildId) {
603
618
  * were missed (e.g. after Cancel→Generate cycles).
604
619
  */
605
620
  async function reconcileWindowStatuses(redis, bookId, buildId) {
621
+ if (await isV2(bookId, 'reconcileWindowStatuses')) return { reconciled: 0, reason: 'orchestration_v2' };
606
622
  const buildDir = path.join(OUTPUT_DIR, buildId);
607
623
  if (!fs.existsSync(buildDir)) return { reconciled: 0 };
608
624
 
@@ -683,6 +699,7 @@ async function reconcileWindowStatuses(redis, bookId, buildId) {
683
699
  }
684
700
 
685
701
  async function startScene(redis, s, buildId, bookId) {
702
+ if (await isV2(bookId, 'startScene')) return false;
686
703
  if (await isCancelled(redis, bookId)) {
687
704
  log(`startScene skipped: generation cancelled for ${bookId}`);
688
705
  return false;
@@ -1,174 +0,0 @@
1
- // ======================================================
2
- // STAGE 96 — ARTIFACT ROOT BINDING (поведение закрытых литералов)
3
- // ======================================================
4
- // Четыре production-литерала '/data/output' в orchestration-пакете
5
- // (scene-callbacks.js:281,393 · reconciliation-engine.js:124,158)
6
- // переведены на существующий шов artifactRoot (host-bindings, §32.30).
7
- //
8
- // Тесты проверяют ПОВЕДЕНИЕ на свежих исходниках пакета (src/, а не
9
- // npm-копия в backend/node_modules):
10
- // — путь строится из привязанного корня, а не из литерала;
11
- // — при корне '/data/output' (контракт сохранённых данных PG/Redis)
12
- // результирующая строка байт-в-байт равна прежней.
13
- // ======================================================
14
-
15
- const { expect } = require('chai');
16
- const fs = require('fs');
17
- const os = require('os');
18
- const path = require('path');
19
- const { bindHostModules } = require('../src/host/host-bindings');
20
- const { createMockRedis } = require('./mocks/redis-mock');
21
-
22
- const engine = require('../src/runtime/reconciliation-engine');
23
- const callbacks = require('../src/orchestration/scene-callbacks');
24
-
25
- const BOOK = 'b1';
26
- const CHAPTER = 'ch1';
27
- const SCENE = 'sc1';
28
-
29
- let tmpRoot;
30
- let redis;
31
- let currentStates;
32
-
33
- const imageStub = {
34
- resolveCanonicalSceneImage: () => null,
35
- getImageMetadata: async () => null,
36
- };
37
- const videoStub = {
38
- validateVideoFile: () => ({ valid: false, duration: null, metadata: null }),
39
- };
40
-
41
- const stateStub = {
42
- AssetState: {
43
- NEW: 'new', DIRTY: 'dirty', PENDING: 'pending',
44
- GENERATING: 'generating', READY: 'ready',
45
- FAILED: 'failed', PLACEHOLDER: 'placeholder',
46
- },
47
- getAssetStates: async () => ({ audio: 'new', ...currentStates }),
48
- };
49
-
50
- const failFast = (name) => () => {
51
- throw new Error(`[ARTIFACT-ROOT-TEST] ${name} not wired`);
52
- };
53
-
54
- function wire(artifactRootValue) {
55
- bindHostModules({
56
- state: () => stateStub,
57
- media: () => ({ audio: {}, image: imageStub, video: videoStub }),
58
- journal: () => ({ appendSceneEvent: async () => {} }),
59
- artifactRoot: () => artifactRootValue,
60
- });
61
- }
62
-
63
- describe('Stage 96 — artifactRoot-шов вместо литералов', () => {
64
- before(() => {
65
- tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'stage96-artifact-root-'));
66
- fs.mkdirSync(path.join(tmpRoot, 'default'), { recursive: true });
67
- redis = createMockRedis();
68
- wire(tmpRoot);
69
- });
70
-
71
- after(() => {
72
- // Вернуть дефолтный fail-fast, как в test/test-bindings.js
73
- bindHostModules({
74
- state: failFast('state'),
75
- media: failFast('media'),
76
- journal: failFast('journal'),
77
- artifactRoot: failFast('artifactRoot'),
78
- });
79
- fs.rmSync(tmpRoot, { recursive: true, force: true });
80
- });
81
-
82
- describe('reconciliation-engine — checkOrphanVideoState', () => {
83
- it('missingFile строится из привязанного корня, а не из литерала', async () => {
84
- currentStates = { video: 'ready' };
85
- const res = await engine.checkOrphanVideoState(redis, BOOK, CHAPTER, SCENE);
86
- expect(res).to.be.an('object');
87
- expect(res.missingFile).to.equal(`${tmpRoot}/default/${BOOK}_${CHAPTER}_${SCENE}.mp4`);
88
- });
89
-
90
- it('null, когда файл существует ПОД ПРИВЯЗАННЫМ корнем', async () => {
91
- const file = path.join(tmpRoot, 'default', `${BOOK}_${CHAPTER}_${SCENE}.mp4`);
92
- fs.writeFileSync(file, 'x');
93
- try {
94
- currentStates = { video: 'ready' };
95
- expect(await engine.checkOrphanVideoState(redis, BOOK, CHAPTER, SCENE)).to.be.null;
96
- } finally {
97
- fs.rmSync(file, { force: true });
98
- }
99
- });
100
- });
101
-
102
- describe('reconciliation-engine — checkOrphanImageState', () => {
103
- it('resolveCanonicalSceneImage получает привязанный корень', async () => {
104
- let seenRoot = null;
105
- imageStub.resolveCanonicalSceneImage = (root) => { seenRoot = root; return null; };
106
- try {
107
- currentStates = { image: 'ready' };
108
- const res = await engine.checkOrphanImageState(redis, BOOK, CHAPTER, SCENE);
109
- expect(seenRoot).to.equal(tmpRoot);
110
- expect(res).to.be.an('object');
111
- expect(res.type).to.equal('orphan_image_state');
112
- } finally {
113
- imageStub.resolveCanonicalSceneImage = () => null;
114
- }
115
- });
116
- });
117
-
118
- describe('scene-callbacks — handleVideoCompleted', () => {
119
- it('validateVideoFile получает путь под привязанным корнем', async () => {
120
- let seenPath = null;
121
- videoStub.validateVideoFile = (p) => {
122
- seenPath = p;
123
- return { valid: false, duration: null, metadata: null };
124
- };
125
- try {
126
- currentStates = { video: 'generating' };
127
- const res = await callbacks.handleVideoCompleted(redis, BOOK, CHAPTER, SCENE, 'build1');
128
- expect(seenPath).to.equal(`${tmpRoot}/build1/${BOOK}_${CHAPTER}_${SCENE}.mp4`);
129
- expect(res).to.deep.include({ ok: false, retryable: true, reason: 'video_invalid' });
130
- } finally {
131
- videoStub.validateVideoFile = () => ({ valid: false, duration: null, metadata: null });
132
- }
133
- });
134
- });
135
-
136
- describe('scene-callbacks — handleImageCompleted', () => {
137
- it('resolveCanonicalSceneImage получает привязанный корень', async () => {
138
- let seenRoot = null;
139
- imageStub.resolveCanonicalSceneImage = (root) => { seenRoot = root; return null; };
140
- try {
141
- currentStates = { image: 'generating' };
142
- const res = await callbacks.handleImageCompleted(redis, BOOK, CHAPTER, SCENE, 'build1');
143
- expect(seenRoot).to.equal(tmpRoot);
144
- expect(res).to.deep.include({ ok: false, retryable: true, reason: 'image_not_found' });
145
- } finally {
146
- imageStub.resolveCanonicalSceneImage = () => null;
147
- }
148
- });
149
- });
150
-
151
- describe('обратная совместимость (контракт контейнерных путей)', () => {
152
- it('при корне /data/output строка байт-в-байт равна прежнему литералу', async () => {
153
- wire('/data/output');
154
- try {
155
- let seenPath = null;
156
- videoStub.validateVideoFile = (p) => {
157
- seenPath = p;
158
- return { valid: false, duration: null, metadata: null };
159
- };
160
- currentStates = { video: 'generating' };
161
- await callbacks.handleVideoCompleted(redis, BOOK, CHAPTER, SCENE, 'build1');
162
- // ровно то, что до Stage 96 формировал шаблон
163
- expect(seenPath).to.equal(`/data/output/build1/${BOOK}_${CHAPTER}_${SCENE}.mp4`);
164
-
165
- currentStates = { video: 'ready' };
166
- const orphan = await engine.checkOrphanVideoState(redis, BOOK, CHAPTER, SCENE);
167
- expect(orphan.missingFile).to.equal(`/data/output/default/${BOOK}_${CHAPTER}_${SCENE}.mp4`);
168
- } finally {
169
- videoStub.validateVideoFile = () => ({ valid: false, duration: null, metadata: null });
170
- wire(tmpRoot);
171
- }
172
- });
173
- });
174
- });