@things-factory/headless-twin 10.0.8 → 10.0.10

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 (381) hide show
  1. package/dist-server/engine/attention-digest.d.ts +52 -0
  2. package/dist-server/engine/attention-digest.js +76 -0
  3. package/dist-server/engine/attention-digest.js.map +1 -0
  4. package/dist-server/engine/canonical-ingest.d.ts +2 -2
  5. package/dist-server/engine/canonical-ingest.js +24 -2
  6. package/dist-server/engine/canonical-ingest.js.map +1 -1
  7. package/dist-server/engine/command-routing.d.ts +33 -0
  8. package/dist-server/engine/command-routing.js +53 -0
  9. package/dist-server/engine/command-routing.js.map +1 -0
  10. package/dist-server/engine/energy-topology.d.ts +86 -0
  11. package/dist-server/engine/energy-topology.js +144 -0
  12. package/dist-server/engine/energy-topology.js.map +1 -0
  13. package/dist-server/engine/index.d.ts +11 -0
  14. package/dist-server/engine/index.js +17 -0
  15. package/dist-server/engine/index.js.map +1 -1
  16. package/dist-server/engine/kpi-baseline.d.ts +78 -0
  17. package/dist-server/engine/kpi-baseline.js +123 -0
  18. package/dist-server/engine/kpi-baseline.js.map +1 -0
  19. package/dist-server/engine/kpi-fold.d.ts +137 -1
  20. package/dist-server/engine/kpi-fold.js +225 -0
  21. package/dist-server/engine/kpi-fold.js.map +1 -1
  22. package/dist-server/engine/kpi-query.d.ts +32 -1
  23. package/dist-server/engine/kpi-query.js +262 -20
  24. package/dist-server/engine/kpi-query.js.map +1 -1
  25. package/dist-server/engine/kpi-target.d.ts +17 -0
  26. package/dist-server/engine/kpi-target.js +24 -2
  27. package/dist-server/engine/kpi-target.js.map +1 -1
  28. package/dist-server/engine/live-attentions.d.ts +1 -0
  29. package/dist-server/engine/live-attentions.js +7 -1
  30. package/dist-server/engine/live-attentions.js.map +1 -1
  31. package/dist-server/engine/live-feed-registry.d.ts +25 -0
  32. package/dist-server/engine/live-feed-registry.js +51 -0
  33. package/dist-server/engine/live-feed-registry.js.map +1 -0
  34. package/dist-server/engine/load-meter.d.ts +181 -0
  35. package/dist-server/engine/load-meter.js +267 -0
  36. package/dist-server/engine/load-meter.js.map +1 -0
  37. package/dist-server/engine/local-declarations.d.ts +262 -0
  38. package/dist-server/engine/local-declarations.js +528 -0
  39. package/dist-server/engine/local-declarations.js.map +1 -0
  40. package/dist-server/engine/model-basis.d.ts +39 -6
  41. package/dist-server/engine/model-basis.js +69 -9
  42. package/dist-server/engine/model-basis.js.map +1 -1
  43. package/dist-server/engine/model-vocabulary.d.ts +17 -0
  44. package/dist-server/engine/model-vocabulary.js +81 -0
  45. package/dist-server/engine/model-vocabulary.js.map +1 -0
  46. package/dist-server/engine/oee-accumulator.d.ts +28 -0
  47. package/dist-server/engine/oee-accumulator.js +26 -1
  48. package/dist-server/engine/oee-accumulator.js.map +1 -1
  49. package/dist-server/engine/operation-basis.d.ts +32 -0
  50. package/dist-server/engine/operation-basis.js +87 -0
  51. package/dist-server/engine/operation-basis.js.map +1 -0
  52. package/dist-server/engine/property-effects.d.ts +30 -0
  53. package/dist-server/engine/property-effects.js +192 -0
  54. package/dist-server/engine/property-effects.js.map +1 -0
  55. package/dist-server/engine/runtime-key.d.ts +15 -0
  56. package/dist-server/engine/runtime-key.js +64 -0
  57. package/dist-server/engine/runtime-key.js.map +1 -0
  58. package/dist-server/engine/spec-coverage.js +3 -3
  59. package/dist-server/engine/spec-coverage.js.map +1 -1
  60. package/dist-server/engine/state-axes.d.ts +21 -0
  61. package/dist-server/engine/state-axes.js +59 -0
  62. package/dist-server/engine/state-axes.js.map +1 -0
  63. package/dist-server/engine/structure-diff.js +1 -1
  64. package/dist-server/engine/structure-diff.js.map +1 -1
  65. package/dist-server/engine/travel-estimator.d.ts +9 -2
  66. package/dist-server/engine/travel-estimator.js +11 -6
  67. package/dist-server/engine/travel-estimator.js.map +1 -1
  68. package/dist-server/engine/twin-engine.d.ts +418 -57
  69. package/dist-server/engine/twin-engine.js +1599 -306
  70. package/dist-server/engine/twin-engine.js.map +1 -1
  71. package/dist-server/engine/warm-start.d.ts +93 -13
  72. package/dist-server/engine/warm-start.js +114 -14
  73. package/dist-server/engine/warm-start.js.map +1 -1
  74. package/dist-server/index.d.ts +1 -0
  75. package/dist-server/index.js +17 -11
  76. package/dist-server/index.js.map +1 -1
  77. package/dist-server/migrations/1786000000000-RenameTwinInstanceBoardToModel.d.ts +5 -0
  78. package/dist-server/migrations/1786000000000-RenameTwinInstanceBoardToModel.js +48 -0
  79. package/dist-server/migrations/1786000000000-RenameTwinInstanceBoardToModel.js.map +1 -0
  80. package/dist-server/migrations/index.d.ts +2 -0
  81. package/dist-server/migrations/index.js +10 -0
  82. package/dist-server/migrations/index.js.map +1 -0
  83. package/dist-server/service/index.d.ts +3 -2
  84. package/dist-server/service/index.js +25 -17
  85. package/dist-server/service/index.js.map +1 -1
  86. package/dist-server/service/reference/discovery-result.d.ts +34 -0
  87. package/dist-server/service/reference/discovery-result.js +84 -0
  88. package/dist-server/service/reference/discovery-result.js.map +1 -0
  89. package/dist-server/service/reference/ingest-space.d.ts +53 -0
  90. package/dist-server/service/reference/ingest-space.js +79 -0
  91. package/dist-server/service/reference/ingest-space.js.map +1 -0
  92. package/dist-server/service/reference/knob-defaults.d.ts +20 -0
  93. package/dist-server/service/reference/knob-defaults.js +59 -0
  94. package/dist-server/service/reference/knob-defaults.js.map +1 -0
  95. package/dist-server/service/reference/reference-live.d.ts +23 -0
  96. package/dist-server/service/reference/reference-live.js +123 -6
  97. package/dist-server/service/reference/reference-live.js.map +1 -1
  98. package/dist-server/service/reference/reference-master.d.ts +227 -11
  99. package/dist-server/service/reference/reference-master.js +206 -25
  100. package/dist-server/service/reference/reference-master.js.map +1 -1
  101. package/dist-server/service/reference/reference-resolver.d.ts +33 -3
  102. package/dist-server/service/reference/reference-resolver.js +290 -23
  103. package/dist-server/service/reference/reference-resolver.js.map +1 -1
  104. package/dist-server/service/reference/template-registry.d.ts +19 -3
  105. package/dist-server/service/reference/template-registry.js.map +1 -1
  106. package/dist-server/service/twin-attention/twin-attention-query.d.ts +8 -1
  107. package/dist-server/service/twin-attention/twin-attention-query.js +39 -8
  108. package/dist-server/service/twin-attention/twin-attention-query.js.map +1 -1
  109. package/dist-server/service/twin-audit/command-audit.d.ts +37 -0
  110. package/dist-server/service/twin-audit/command-audit.js +53 -0
  111. package/dist-server/service/twin-audit/command-audit.js.map +1 -0
  112. package/dist-server/service/twin-audit/index.d.ts +4 -0
  113. package/dist-server/service/twin-audit/index.js +8 -0
  114. package/dist-server/service/twin-audit/index.js.map +1 -0
  115. package/dist-server/service/twin-audit/twin-audit-event.d.ts +24 -0
  116. package/dist-server/service/twin-audit/twin-audit-event.js +125 -0
  117. package/dist-server/service/twin-audit/twin-audit-event.js.map +1 -0
  118. package/dist-server/service/twin-audit/twin-audit-query.d.ts +4 -0
  119. package/dist-server/service/twin-audit/twin-audit-query.js +76 -0
  120. package/dist-server/service/twin-audit/twin-audit-query.js.map +1 -0
  121. package/dist-server/service/twin-control/twin-control-mutation.d.ts +2 -0
  122. package/dist-server/service/twin-control/twin-control-mutation.js +50 -11
  123. package/dist-server/service/twin-control/twin-control-mutation.js.map +1 -1
  124. package/dist-server/service/twin-event/twin-event-keys.d.ts +1 -1
  125. package/dist-server/service/twin-event/twin-event-keys.js +1 -1
  126. package/dist-server/service/twin-event/twin-event-keys.js.map +1 -1
  127. package/dist-server/service/twin-event/twin-event.d.ts +14 -5
  128. package/dist-server/service/twin-event/twin-event.js +46 -14
  129. package/dist-server/service/twin-event/twin-event.js.map +1 -1
  130. package/dist-server/service/twin-forecast/forecast-metrics.d.ts +13 -0
  131. package/dist-server/service/twin-forecast/forecast-metrics.js +57 -0
  132. package/dist-server/service/twin-forecast/forecast-metrics.js.map +1 -0
  133. package/dist-server/service/twin-forecast/forecast-tuning.d.ts +12 -0
  134. package/dist-server/service/twin-forecast/forecast-tuning.js +44 -0
  135. package/dist-server/service/twin-forecast/forecast-tuning.js.map +1 -0
  136. package/dist-server/service/twin-forecast/gap-analytics.d.ts +28 -2
  137. package/dist-server/service/twin-forecast/gap-analytics.js +43 -17
  138. package/dist-server/service/twin-forecast/gap-analytics.js.map +1 -1
  139. package/dist-server/service/twin-forecast/twin-forecast-query.js +219 -39
  140. package/dist-server/service/twin-forecast/twin-forecast-query.js.map +1 -1
  141. package/dist-server/service/twin-instance/twin-instance.d.ts +38 -5
  142. package/dist-server/service/twin-instance/twin-instance.js +66 -18
  143. package/dist-server/service/twin-instance/twin-instance.js.map +1 -1
  144. package/dist-server/service/twin-journal/twin-journal-query.d.ts +11 -4
  145. package/dist-server/service/twin-journal/twin-journal-query.js +95 -15
  146. package/dist-server/service/twin-journal/twin-journal-query.js.map +1 -1
  147. package/dist-server/service/twin-lifecycle/twin-lifecycle-mutation.d.ts +11 -5
  148. package/dist-server/service/twin-lifecycle/twin-lifecycle-mutation.js +46 -27
  149. package/dist-server/service/twin-lifecycle/twin-lifecycle-mutation.js.map +1 -1
  150. package/dist-server/service/twin-metrics/twin-metrics-query.d.ts +1 -0
  151. package/dist-server/service/twin-metrics/twin-metrics-query.js +63 -1
  152. package/dist-server/service/twin-metrics/twin-metrics-query.js.map +1 -1
  153. package/dist-server/service/twin-model/epcis-coverage.d.ts +14 -0
  154. package/dist-server/service/twin-model/epcis-coverage.js +174 -0
  155. package/dist-server/service/twin-model/epcis-coverage.js.map +1 -0
  156. package/dist-server/service/twin-model/iec61850-coverage.d.ts +14 -0
  157. package/dist-server/service/twin-model/iec61850-coverage.js +98 -0
  158. package/dist-server/service/twin-model/iec61850-coverage.js.map +1 -0
  159. package/dist-server/service/twin-model/index.d.ts +13 -0
  160. package/dist-server/service/twin-model/index.js +29 -0
  161. package/dist-server/service/twin-model/index.js.map +1 -0
  162. package/dist-server/service/twin-model/isa95-coverage.d.ts +48 -0
  163. package/dist-server/service/twin-model/isa95-coverage.js +155 -0
  164. package/dist-server/service/twin-model/isa95-coverage.js.map +1 -0
  165. package/dist-server/service/twin-model/project-structure.d.ts +16 -0
  166. package/dist-server/service/twin-model/project-structure.js +173 -0
  167. package/dist-server/service/twin-model/project-structure.js.map +1 -0
  168. package/dist-server/service/twin-model/standard-coverage.d.ts +9 -0
  169. package/dist-server/service/twin-model/standard-coverage.js +37 -0
  170. package/dist-server/service/twin-model/standard-coverage.js.map +1 -0
  171. package/dist-server/service/twin-model/twin-equipment.d.ts +64 -0
  172. package/dist-server/service/twin-model/twin-equipment.js +134 -0
  173. package/dist-server/service/twin-model/twin-equipment.js.map +1 -0
  174. package/dist-server/service/twin-model/twin-lineage-query.d.ts +3 -0
  175. package/dist-server/service/twin-model/twin-lineage-query.js +206 -0
  176. package/dist-server/service/twin-model/twin-lineage-query.js.map +1 -0
  177. package/dist-server/service/twin-model/twin-location.d.ts +58 -0
  178. package/dist-server/service/twin-model/twin-location.js +130 -0
  179. package/dist-server/service/twin-model/twin-location.js.map +1 -0
  180. package/dist-server/service/twin-model/twin-model-item-query.d.ts +141 -0
  181. package/dist-server/service/twin-model/twin-model-item-query.js +852 -0
  182. package/dist-server/service/twin-model/twin-model-item-query.js.map +1 -0
  183. package/dist-server/service/twin-model/twin-model-mutation.d.ts +57 -0
  184. package/dist-server/service/twin-model/twin-model-mutation.js +490 -0
  185. package/dist-server/service/twin-model/twin-model-mutation.js.map +1 -0
  186. package/dist-server/service/twin-model/twin-model-query.d.ts +43 -0
  187. package/dist-server/service/twin-model/twin-model-query.js +551 -0
  188. package/dist-server/service/twin-model/twin-model-query.js.map +1 -0
  189. package/dist-server/service/twin-model/twin-model-tree-query.d.ts +3 -0
  190. package/dist-server/service/twin-model/twin-model-tree-query.js +158 -0
  191. package/dist-server/service/twin-model/twin-model-tree-query.js.map +1 -0
  192. package/dist-server/service/twin-model/twin-operation.d.ts +61 -0
  193. package/dist-server/service/twin-model/twin-operation.js +137 -0
  194. package/dist-server/service/twin-model/twin-operation.js.map +1 -0
  195. package/dist-server/service/twin-space/move-space.d.ts +65 -0
  196. package/dist-server/service/twin-space/move-space.js +166 -0
  197. package/dist-server/service/twin-space/move-space.js.map +1 -0
  198. package/dist-server/service/twin-space/space-integrity.d.ts +97 -0
  199. package/dist-server/service/twin-space/space-integrity.js +182 -0
  200. package/dist-server/service/twin-space/space-integrity.js.map +1 -0
  201. package/dist-server/service/twin-space/twin-space-area.js +4 -4
  202. package/dist-server/service/twin-space/twin-space-area.js.map +1 -1
  203. package/dist-server/service/twin-space/twin-space-representation.js +6 -6
  204. package/dist-server/service/twin-space/twin-space-representation.js.map +1 -1
  205. package/dist-server/service/twin-space/twin-space-resolver.d.ts +63 -1
  206. package/dist-server/service/twin-space/twin-space-resolver.js +365 -18
  207. package/dist-server/service/twin-space/twin-space-resolver.js.map +1 -1
  208. package/dist-server/service/twin-space/twin-space.d.ts +17 -1
  209. package/dist-server/service/twin-space/twin-space.js +15 -5
  210. package/dist-server/service/twin-space/twin-space.js.map +1 -1
  211. package/dist-server/service/twin-state/twin-state-subscription.js +1 -1
  212. package/dist-server/service/twin-state/twin-state-subscription.js.map +1 -1
  213. package/dist-server/service/twin-structure/twin-structure.d.ts +1 -1
  214. package/dist-server/service/twin-structure/twin-structure.js +8 -7
  215. package/dist-server/service/twin-structure/twin-structure.js.map +1 -1
  216. package/dist-server/service/twin-target/twin-target-resolver.js +21 -4
  217. package/dist-server/service/twin-target/twin-target-resolver.js.map +1 -1
  218. package/dist-shared/axis-read.d.ts +12 -0
  219. package/dist-shared/axis-read.js +32 -0
  220. package/dist-shared/axis-read.js.map +1 -0
  221. package/dist-shared/entity-delta.d.ts +29 -0
  222. package/dist-shared/entity-delta.js +287 -0
  223. package/dist-shared/entity-delta.js.map +1 -0
  224. package/dist-shared/kpi-broadcast.d.ts +4 -0
  225. package/dist-shared/kpi-broadcast.js +16 -0
  226. package/dist-shared/kpi-broadcast.js.map +1 -0
  227. package/dist-shared/twin-level.d.ts +23 -0
  228. package/dist-shared/twin-level.js +52 -0
  229. package/dist-shared/twin-level.js.map +1 -0
  230. package/package.json +14 -12
  231. package/server/engine/attention-digest.ts +102 -0
  232. package/server/engine/canonical-ingest.ts +36 -4
  233. package/server/engine/command-routing.ts +67 -0
  234. package/server/engine/energy-topology.ts +189 -0
  235. package/server/engine/index.ts +17 -0
  236. package/server/engine/kpi-baseline.ts +202 -0
  237. package/server/engine/kpi-fold.ts +389 -1
  238. package/server/engine/kpi-query.ts +295 -22
  239. package/server/engine/kpi-target.ts +24 -2
  240. package/server/engine/live-attentions.ts +7 -2
  241. package/server/engine/live-feed-registry.ts +58 -0
  242. package/server/engine/load-meter.ts +384 -0
  243. package/server/engine/local-declarations.ts +700 -0
  244. package/server/engine/model-basis.ts +78 -10
  245. package/server/engine/model-vocabulary.ts +82 -0
  246. package/server/engine/oee-accumulator.ts +34 -1
  247. package/server/engine/operation-basis.ts +100 -0
  248. package/server/engine/property-effects.ts +199 -0
  249. package/server/engine/runtime-key.ts +58 -0
  250. package/server/engine/spec-coverage.ts +3 -3
  251. package/server/engine/state-axes.ts +60 -0
  252. package/server/engine/structure-diff.ts +1 -1
  253. package/server/engine/travel-estimator.ts +11 -6
  254. package/server/engine/twin-engine.ts +1710 -297
  255. package/server/engine/warm-start.ts +207 -22
  256. package/server/index.ts +13 -10
  257. package/server/migrations/1786000000000-RenameTwinInstanceBoardToModel.ts +43 -0
  258. package/server/migrations/index.ts +7 -0
  259. package/server/service/index.ts +9 -1
  260. package/server/service/reference/discovery-result.ts +95 -0
  261. package/server/service/reference/ingest-space.ts +104 -0
  262. package/server/service/reference/knob-defaults.ts +59 -0
  263. package/server/service/reference/reference-live.ts +121 -6
  264. package/server/service/reference/reference-master.ts +362 -35
  265. package/server/service/reference/reference-resolver.ts +307 -23
  266. package/server/service/reference/template-registry.ts +20 -5
  267. package/server/service/twin-attention/twin-attention-query.ts +43 -6
  268. package/server/service/twin-audit/command-audit.ts +81 -0
  269. package/server/service/twin-audit/index.ts +5 -0
  270. package/server/service/twin-audit/twin-audit-event.ts +112 -0
  271. package/server/service/twin-audit/twin-audit-query.ts +72 -0
  272. package/server/service/twin-control/twin-control-mutation.ts +53 -13
  273. package/server/service/twin-event/twin-event-keys.ts +1 -1
  274. package/server/service/twin-event/twin-event.ts +52 -15
  275. package/server/service/twin-forecast/forecast-metrics.ts +60 -0
  276. package/server/service/twin-forecast/forecast-tuning.ts +40 -0
  277. package/server/service/twin-forecast/gap-analytics.ts +48 -9
  278. package/server/service/twin-forecast/twin-forecast-query.ts +211 -38
  279. package/server/service/twin-instance/twin-instance.ts +127 -22
  280. package/server/service/twin-journal/twin-journal-query.ts +108 -14
  281. package/server/service/twin-lifecycle/twin-lifecycle-mutation.ts +40 -23
  282. package/server/service/twin-metrics/twin-metrics-query.ts +60 -3
  283. package/server/service/twin-model/epcis-coverage.ts +195 -0
  284. package/server/service/twin-model/iec61850-coverage.ts +117 -0
  285. package/server/service/twin-model/index.ts +25 -0
  286. package/server/service/twin-model/isa95-coverage.ts +190 -0
  287. package/server/service/twin-model/project-structure.ts +199 -0
  288. package/server/service/twin-model/standard-coverage.ts +35 -0
  289. package/server/service/twin-model/twin-equipment.ts +150 -0
  290. package/server/service/twin-model/twin-lineage-query.ts +193 -0
  291. package/server/service/twin-model/twin-location.ts +140 -0
  292. package/server/service/twin-model/twin-model-item-query.ts +848 -0
  293. package/server/service/twin-model/twin-model-mutation.ts +503 -0
  294. package/server/service/twin-model/twin-model-query.ts +537 -0
  295. package/server/service/twin-model/twin-model-tree-query.ts +180 -0
  296. package/server/service/twin-model/twin-operation.ts +150 -0
  297. package/server/service/twin-space/move-space.ts +262 -0
  298. package/server/service/twin-space/space-integrity.ts +293 -0
  299. package/server/service/twin-space/twin-space-area.ts +4 -4
  300. package/server/service/twin-space/twin-space-representation.ts +6 -6
  301. package/server/service/twin-space/twin-space-resolver.ts +365 -22
  302. package/server/service/twin-space/twin-space.ts +40 -6
  303. package/server/service/twin-state/twin-state-subscription.ts +1 -1
  304. package/server/service/twin-structure/twin-structure.ts +10 -7
  305. package/server/service/twin-target/twin-target-resolver.ts +22 -4
  306. package/shared/axis-read.ts +28 -0
  307. package/shared/entity-delta.ts +286 -0
  308. package/shared/kpi-broadcast.ts +13 -0
  309. package/shared/twin-level.ts +48 -0
  310. package/test/adopt-structure-live.test.ts +133 -0
  311. package/test/attention-digest.test.ts +135 -0
  312. package/test/axis-read.test.ts +87 -0
  313. package/test/boot-resume.test.ts +205 -0
  314. package/test/canonical-ingest-vocabularies.test.ts +118 -0
  315. package/test/capability-mapping.test.ts +5 -5
  316. package/test/command-routing.test.ts +61 -0
  317. package/test/declaration-reaches-model.test.ts +178 -0
  318. package/test/discovery-result.test.ts +75 -0
  319. package/test/energy-topology.test.ts +113 -0
  320. package/test/entity-delta.test.ts +195 -25
  321. package/test/event-time-column.test.ts +67 -0
  322. package/test/forecast-metrics.test.ts +71 -0
  323. package/test/forecast-tuning.test.ts +42 -0
  324. package/test/gap-analytics.test.ts +34 -7
  325. package/test/ingest-bench.test.ts +9 -9
  326. package/test/ingest-running-guard.test.ts +136 -0
  327. package/test/ingest-space.test.ts +78 -0
  328. package/test/instance-cache-lifecycle.test.ts +110 -0
  329. package/test/kernel-kind-guard.test.ts +96 -0
  330. package/test/knob-defaults.test.ts +72 -0
  331. package/test/kpi-baseline-db.test.ts +216 -0
  332. package/test/kpi-baseline.test.ts +196 -0
  333. package/test/kpi-fold.test.ts +393 -2
  334. package/test/kpi-query-bench.test.ts +130 -0
  335. package/test/lineage-survives-restart.test.ts +203 -0
  336. package/test/live-feed-registry.test.ts +67 -0
  337. package/test/live-kernel-facts.test.ts +161 -0
  338. package/test/live-mirror-parity.test.ts +54 -14
  339. package/test/load-meter.test.ts +314 -0
  340. package/test/local-declarations.test.ts +554 -0
  341. package/test/master-to-twin.test.ts +128 -36
  342. package/test/model-basis.test.ts +56 -1
  343. package/test/model-vocabulary.test.ts +114 -0
  344. package/test/move-space.test.ts +149 -0
  345. package/test/mutation-gate.test.ts +122 -0
  346. package/test/oee-accumulator.test.ts +90 -7
  347. package/test/operation-basis.test.ts +100 -0
  348. package/test/operations-capability-db.test.ts +165 -0
  349. package/test/project-structure-db.test.ts +226 -0
  350. package/test/projection-reaches-screen.test.ts +272 -0
  351. package/test/property-effects.test.ts +96 -0
  352. package/test/registry-key-guard.test.ts +80 -0
  353. package/test/resync-origin-site.test.ts +77 -0
  354. package/test/runtime-key.test.ts +66 -0
  355. package/test/scale-twin-bench.test.ts +7 -7
  356. package/test/snapshot-freshness.test.ts +60 -0
  357. package/test/space-integrity.test.ts +223 -0
  358. package/test/standard-coverage.test.ts +94 -0
  359. package/test/state-axes.test.ts +74 -0
  360. package/test/streamline-e2e.test.ts +16 -16
  361. package/test/structure-revision-db.test.ts +16 -15
  362. package/test/tenant-registry-db.test.ts +149 -0
  363. package/test/twin-audit.test.ts +83 -0
  364. package/test/twin-model-item-db.test.ts +275 -0
  365. package/test/twin-model-tree-db.test.ts +176 -0
  366. package/test/twin-origin-resync.test.ts +114 -0
  367. package/test/warm-start-seam.test.ts +140 -0
  368. package/test/warm-start.test.ts +223 -4
  369. package/tsconfig.json +6 -1
  370. package/tsconfig.shared.json +23 -0
  371. package/tsconfig.shared.tsbuildinfo +1 -0
  372. package/tsconfig.tsbuildinfo +1 -0
  373. package/dist-server/engine/entity-delta.d.ts +0 -19
  374. package/dist-server/engine/entity-delta.js +0 -161
  375. package/dist-server/engine/entity-delta.js.map +0 -1
  376. package/dist-server/service/twin-event/backfill-keys.d.ts +0 -11
  377. package/dist-server/service/twin-event/backfill-keys.js +0 -63
  378. package/dist-server/service/twin-event/backfill-keys.js.map +0 -1
  379. package/dist-server/tsconfig.tsbuildinfo +0 -1
  380. package/server/engine/entity-delta.ts +0 -169
  381. package/server/service/twin-event/backfill-keys.ts +0 -72
@@ -10,10 +10,15 @@
10
10
  Object.defineProperty(exports, "__esModule", { value: true });
11
11
  exports.TwinEngine = exports.DEFAULT_REALITY_MODE = void 0;
12
12
  const shell_1 = require("@things-factory/shell");
13
+ /* 저널을 자를 조건은 SQL 이 안다 — 관용구만 쓴다(원시 SQL 은 5개 드라이버에서 갈라진다). */
14
+ const typeorm_1 = require("typeorm");
13
15
  const cache_service_1 = require("@things-factory/cache-service");
14
16
  const twin_event_js_1 = require("../service/twin-event/twin-event.js");
15
17
  const twin_event_keys_js_1 = require("../service/twin-event/twin-event-keys.js");
16
18
  const warm_start_js_1 = require("./warm-start.js");
19
+ const local_declarations_js_1 = require("./local-declarations.js");
20
+ const runtime_key_js_1 = require("./runtime-key.js");
21
+ const command_routing_js_1 = require("./command-routing.js");
17
22
  const twin_instance_js_1 = require("../service/twin-instance/twin-instance.js");
18
23
  const twin_structure_js_1 = require("../service/twin-structure/twin-structure.js");
19
24
  const twin_space_js_1 = require("../service/twin-space/twin-space.js");
@@ -22,50 +27,220 @@ const twin_space_representation_js_1 = require("../service/twin-space/twin-space
22
27
  const twin_space_area_js_1 = require("../service/twin-space/twin-space-area.js");
23
28
  const twin_area_js_1 = require("../service/twin-space/twin-area.js");
24
29
  const reference_master_js_2 = require("../service/reference/reference-master.js");
30
+ const ingest_space_js_1 = require("../service/reference/ingest-space.js");
31
+ const reference_master_js_3 = require("../service/reference/reference-master.js");
32
+ const project_structure_js_1 = require("../service/twin-model/project-structure.js");
25
33
  const travel_estimator_js_1 = require("./travel-estimator.js");
26
34
  const measured_estimator_js_1 = require("./measured-estimator.js");
27
35
  const kpi_query_js_1 = require("./kpi-query.js");
28
36
  const node_crypto_1 = require("node:crypto");
29
- const entity_delta_js_1 = require("./entity-delta.js");
37
+ const entity_delta_js_1 = require("@things-factory/headless-twin/dist-shared/entity-delta.js");
38
+ const load_meter_js_1 = require("./load-meter.js");
30
39
  const structure_diff_js_1 = require("./structure-diff.js");
31
40
  const oee_accumulator_js_1 = require("./oee-accumulator.js");
41
+ const live_attentions_js_1 = require("./live-attentions.js");
42
+ const attention_digest_js_1 = require("./attention-digest.js");
43
+ const live_feed_registry_js_1 = require("./live-feed-registry.js");
44
+ const twin_kernel_1 = require("@operato/twin-kernel");
32
45
  /* 커널 런타임 로드 — CJS 번들(dist-cjs). 타입은 위 import type 로. replay = 이벤트열→상태 재구성(복구·시간여행). */
33
- const { WmsKernel, YmsKernel, MesKernel, TwinRuntime, StateProjector, replay, replaySegments, DOMAIN_CATALOG, OP_EVENT } = require('@operato/twin-kernel');
34
- const KERNELS = { wms: WmsKernel, yms: YmsKernel, mes: MesKernel };
46
+ const { WmsKernel, YmsKernel, MesKernel, EmsKernel, TwinRuntime, StateProjector, replay, replayFrom, replayWithCheckpoint, replaySegments, readBoardLocations, readBoardEquipment, DOMAIN_CATALOG, OP_EVENT } = require('@operato/twin-kernel');
47
+ const KERNELS = { wms: WmsKernel, yms: YmsKernel, mes: MesKernel, ems: EmsKernel };
48
+ /**
49
+ * 종류 문자열 → 커널. **모르는 값이면 던진다.**
50
+ *
51
+ * 예전에는 표를 찾고 없으면 WmsKernel 로 떨어졌다. `kind` 는 검증 없는 자유 문자열(`@Arg('kind') kind: string`)
52
+ * 이라 오타 하나·대소문자 하나로 야드/생산 트윈이 **조용히 창고 커널로 돌았다.** 오류가 없으니 화면에는
53
+ * 트윈이 정상으로 보이고, 안에서 도는 규칙만 다른 도메인의 것이다. 예측 경로가 가장 나쁘다 —
54
+ * 야드의 미래를 창고 규칙으로 실행해 놓고 숫자만 뜬다.
55
+ *
56
+ * 틀린 공장을 조용히 띄우는 것보다 뜨지 않는 편이 낫다.
57
+ */
58
+ function kernelFor(kind) {
59
+ const K = KERNELS[kind];
60
+ if (!K)
61
+ throw new Error(`unknown twin kind "${kind}" — expected one of ${Object.keys(KERNELS).join(' | ')}`);
62
+ return K;
63
+ }
35
64
  exports.DEFAULT_REALITY_MODE = 'sim-experiment';
36
65
  class TwinEngine {
66
+ /*
67
+ * 기동 중인 런타임 — **키는 `runtimeKey(domainId, instanceId)`** 다(`runtime-key.ts` 에 이유).
68
+ *
69
+ * 예전엔 `instanceId` 하나로 키를 잡았다. 그런데 정체성은 `(domain, instanceId)` 이고 DB 유일성도
70
+ * 그쪽이라, 두 테넌트가 같은 id 를 쓰면(레퍼런스 경로가 소스 이름을 id 로 쓴다) 한 자리를 다퉜다.
71
+ * **엔진 밖에서 이 맵을 직접 색인하지 않는다** — `owns`·`runtime`·`kernel` 같은 접근자를 쓴다.
72
+ */
37
73
  static { this.instances = {}; }
38
74
  /** 라이브 런타임이 없을 때(복구 후 미기동) 저널에서 재구성한 상태 캐시. */
75
+ /** 웜스타트 씨앗 — `instances` 와 **같은 키**(겹치면 남의 스냅샷으로 재고가 섞인다). */
39
76
  static { this.recovered = {}; }
40
77
  static { this.TICK_MS = 1000; }
78
+ /*
79
+ * ── 굶김 안전망 (2026-08-14) ──────────────────────────────────────────────
80
+ * 시뮬 틱은 **메인 이벤트 루프**에서 돈다. 그래서 한 트윈의 틱이 길어지면 그 시간만큼 호스트 전체가
81
+ * 멈춘다 — HTTP·구독·다른 트윈의 틱까지. 실측으로 `order-check` 의 틱 하나가 34.9초였고, 그 사이
82
+ * 구독자가 아무것도 빼내지 못해 pubsub 이 넘쳐 프로세스가 죽었다.
83
+ *
84
+ * 방송 반복은 걷어냈지만(`flushLiveBroadcasts` 로 병합) **커널 틱 자체는 여전히 메인 루프에 있다.**
85
+ * 근본 해결은 분산이고 그것은 이연됐다 — 그때까지의 안전망이 이 셋이다.
86
+ *
87
+ * 판정을 예산(500ms)이 아니라 **굶김 문턱**으로 따로 둔다: 조금 느린 트윈은 계기판이 말하게 두고
88
+ * (경고), 호스트를 굶기는 트윈만 멈춘다. 한 번으로 멈추지 않는다 — 웜스타트 직후의 첫 틱은 원래
89
+ * 무겁다(복구한 상태를 처음 접는다). **연속**으로 이어질 때가 구조적으로 느린 것이다.
90
+ */
91
+ /** 굶김 문턱 — 틱 간격의 배수(1초 간격이면 5초). 이 시간만큼 호스트가 멈춘다. */
92
+ static { this.STARVE_FACTOR = 5; }
93
+ /** 연속 몇 번이면 멈추나 — 3번이면 15초를 굶긴 셈이고, 그건 우연이 아니다. */
94
+ static { this.STARVE_STREAK = 3; }
95
+ static { this.starveStreak = new Map(); }
96
+ /**
97
+ * 왜 멈췄나 — **화면이 그대로 말할 수 있게.** 스스로 멈춘 트윈이 이유 없이 「정지」로만 보이면
98
+ * 사람은 자기가 멈춘 줄 안다. 메모리에만 둔다(재기동하면 사라진다 — 그때는 「모른다」가 사실이다).
99
+ */
100
+ static { this.stopNotes = new Map(); }
41
101
  /* 최신 스냅샷 영속(warm-start) — 재기동 시 저널 fold-from-0 replay 대신 마지막 라이브 스냅샷으로 복원.
42
102
  * 프레임워크 공통 cache-service(@things-factory/cache-service) 재사용(재발명 금지, framework-leverage §4).
43
103
  * 저널은 그대로 진실(시간여행/history replay 무변경) — 캐시는 display-only 웜스타트 최적화. */
44
104
  static { this.SNAPSHOT_CACHE_ID = 'twin-snapshot'; }
105
+ /*
106
+ * ── 재개점 **사슬** — 과거를 물었을 때 목표 직전에서 접기 위해 (2026-08-18) ──
107
+ *
108
+ * 최신 재개점 하나로는 시간여행을 도울 수 없다: 그것은 언제나 목표보다 **뒤**에 있다. 그래서 지점을
109
+ * 여러 개 남긴다. 다만 그것들은 각각 상태 전체를 들고 있어 무겁다 — 한 행에 몰아 넣으면 거대한
110
+ * JSON 이 되므로 **지점마다 따로 두고 색인을 둔다**(cache-service 는 해시 키 조회라 열거가 안 된다).
111
+ *
112
+ * 간격은 리비전 눈금으로 잡는다(`CHAIN_STRIDE`): 눈금을 넘을 때만 한 지점을 남기므로, 저널이 빠르게
113
+ * 자라는 트윈에서도 지점 수가 폭발하지 않는다. 오래된 것부터 버리고 최근 `CHAIN_KEEP` 개만 든다 —
114
+ * 과거로 깊이 갈수록 지점이 없어 0부터 접는 것은 **알려진 한계**다(무한 보관보다 정직하다).
115
+ */
116
+ static { this.CHAIN_CACHE_ID = 'twin-fold-chain'; }
117
+ static { this.CHAIN_INDEX_CACHE_ID = 'twin-fold-chain-index'; }
118
+ static { this.CHAIN_STRIDE = 5000; } // 리비전 눈금 — 이 간격을 넘을 때만 한 지점을 남긴다
119
+ static { this.CHAIN_KEEP = 5; } // 최근 몇 지점을 들고 있나(그보다 과거는 0부터 접는다)
45
120
  static { this.SNAPSHOT_TTL_S = 7 * 24 * 3600; } // 7일 — 정상 다운타임 생존, 만료 시 저널 replay 폴백
46
121
  static { this.CHECKPOINT_MS = 20000; } // 체크포인트 주기(핫 브로드캐스트 경로와 분리, O(state) 스로틀)
47
122
  /** 최신 스냅샷을 cache-service 에 체크포인트(도메인+instanceId 키). display-only·비차단·오류흡수. */
48
123
  static async persistSnapshot(domainId, instanceId) {
49
- const inst = this.instances[instanceId];
124
+ const inst = this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, instanceId)];
50
125
  if (!inst)
51
126
  return;
52
- const state = this.snapshot(instanceId);
127
+ /*
128
+ * **봉투가 아니라 상태를 저장한다.** `snapshot()` 은 시뮬에서 `runtime.resync()` 봉투를 주는데,
129
+ * 그것을 다시 `{revision, state}` 로 감싸 넣어 왔다 → 꺼낸 값에 축이 하나도 없어 웜스타트가
130
+ * 조용히 넘어갔다(저널에 수천 건이 있어도 트윈이 빈 채로 떴다).
131
+ */
132
+ const state = (0, warm_start_js_1.unwrapState)(this.snapshot(domainId, instanceId));
53
133
  if (!state)
54
134
  return;
55
135
  const revision = inst.revision ?? state.revision ?? 0;
56
- await cache_service_1.cacheService.setInCache(this.SNAPSHOT_CACHE_ID, { domainId, instanceId }, { revision, state }, this.SNAPSHOT_TTL_S);
136
+ /* 구조 리비전도 함께 — 읽는 쪽이 "이 상태가 지금의 공장인가" 를 가릴 수 있어야 한다. */
137
+ const { structureRev } = await this.tipOf(domainId, instanceId).catch(() => ({ structureRev: null }));
138
+ await cache_service_1.cacheService.setInCache(this.SNAPSHOT_CACHE_ID, { domainId, instanceId }, { revision, state, structureRev }, this.SNAPSHOT_TTL_S);
57
139
  }
140
+ /**
141
+ * 접기의 **재개점** — 리듀서 내부 상태 전부 + 가동 누적기.
142
+ *
143
+ * 스냅샷(`state`)은 소비처가 보는 값이라 이어 접기의 씨앗이 되지 못한다(보류된 담김·집합·반영 못 한
144
+ * 사건 집계가 없다 — 그 상태로 뒤를 접으면 0부터 접은 결과와 조용히 달라진다). 그래서 씨앗은 따로 든다.
145
+ */
146
+ static { this.FOLD_NOTE = 'reducer + oee checkpoint — the seed for folding only the tail'; }
58
147
  /** 체크포인트된 최신 스냅샷 로드(없으면 null). getFromCache 는 CacheStore 엔티티를 반환 → 페이로드는 .value. */
59
148
  static async loadSnapshot(domainId, instanceId) {
60
149
  const entry = await cache_service_1.cacheService.getFromCache(this.SNAPSHOT_CACHE_ID, { domainId, instanceId });
61
150
  return entry?.value ?? null;
62
151
  }
152
+ /**
153
+ * 접은 상태를 스냅샷으로 남긴다 — **라이브가 아니어도.**
154
+ *
155
+ * `persistSnapshot` 은 기동 중인 인스턴스에서만 뜬다(메모리가 진실이므로 옳다). 그런데 **멈춘**
156
+ * 트윈을 조회할 때마다 저널을 전량 다시 접고 있었다(23,731건짜리 트윈에서 4.6초). 그 폴드의 결과를
157
+ * 남겨 두면 **처음 한 번만 느리다.**
158
+ *
159
+ * `structureRev` 를 함께 적는다: 이벤트가 하나도 안 늘어도 구조를 갈아치우면(재프로비저닝) 그
160
+ * 상태는 낡은 것이다. 리비전만 보면 새 설비가 없는 옛 상태를 "지금" 으로 내게 된다.
161
+ */
162
+ static async saveFoldedSnapshot(domainId, instanceId, value) {
163
+ if (!value?.state)
164
+ return;
165
+ await cache_service_1.cacheService
166
+ .setInCache(this.SNAPSHOT_CACHE_ID, { domainId, instanceId }, value, this.SNAPSHOT_TTL_S)
167
+ .catch((err) => console.error(`[twin-engine] snapshot save fail "${instanceId}"`, err?.message ?? err));
168
+ }
169
+ /** 사슬 색인 — 어떤 리비전 지점을 들고 있나(최신순 아님, 오름차순). */
170
+ static async chainIndex(domainId, instanceId) {
171
+ const entry = await cache_service_1.cacheService.getFromCache(this.CHAIN_INDEX_CACHE_ID, { domainId, instanceId }).catch(() => null);
172
+ const revs = entry?.value?.revisions;
173
+ return Array.isArray(revs) ? revs.filter((r) => Number.isFinite(r)).sort((a, b) => a - b) : [];
174
+ }
175
+ /**
176
+ * 목표 이전의 **가장 가까운 지점**을 고른다 — 없으면 `null`(0부터 접는다).
177
+ *
178
+ * 시각으로 물었으면 그 지점의 마지막 사실 시각이 목표 이내여야 한다(리비전만 보면 목표보다 뒤의
179
+ * 사실이 씨앗에 섞인다). 구조가 바뀐 트윈에서는 쓰지 않는다 — 마디를 건너뛴 씨앗은 그 경계의
180
+ * 판정을 잃는다(그 경우는 0부터 접는 것이 옳다).
181
+ */
182
+ static async chainSeedFor(domainId, instanceId, target) {
183
+ const revs = await this.chainIndex(domainId, instanceId);
184
+ if (!revs.length)
185
+ return null;
186
+ for (const revision of [...revs].reverse()) {
187
+ if (target.revision != null && revision > target.revision)
188
+ continue;
189
+ const entry = await cache_service_1.cacheService.getFromCache(this.CHAIN_CACHE_ID, { domainId, instanceId, revision }).catch(() => null);
190
+ const value = entry?.value;
191
+ if (!value?.fold?.reducer)
192
+ continue;
193
+ if (target.timeMs != null) {
194
+ const t = value.eventTime ? Date.parse(String(value.eventTime)) : NaN;
195
+ /* 시각을 모르는 지점은 쓰지 않는다 — 목표 이내인지 가릴 수 없다(짐작하지 않는다). */
196
+ if (!Number.isFinite(t) || t > target.timeMs)
197
+ continue;
198
+ }
199
+ return value;
200
+ }
201
+ return null;
202
+ }
203
+ /** 눈금을 넘었으면 한 지점을 남긴다 — 오래된 것은 버린다(색인도 함께 줄인다). */
204
+ static async keepChainPoint(domainId, instanceId,
205
+ /*
206
+ * **보기(state)는 담지 않는다** (2026-08-18 실측으로 고침).
207
+ *
208
+ * 처음에는 상태까지 담았더니 지점 하나가 **11.4 MB** 였다(27만 건 트윈). 사슬이 필요한 것은 씨앗
209
+ * (재개점)뿐이고, 소비처가 보는 값은 그 씨앗에서 다시 만들어진다 — 같은 사실을 두 번 저장하지 않는다.
210
+ */
211
+ value) {
212
+ const revs = await this.chainIndex(domainId, instanceId);
213
+ const newest = revs.length ? revs[revs.length - 1] : -Infinity;
214
+ if (value.revision - newest < this.CHAIN_STRIDE)
215
+ return; // 아직 눈금을 넘지 않았다
216
+ const next = [...revs, value.revision].slice(-this.CHAIN_KEEP);
217
+ const dropped = revs.filter(r => !next.includes(r));
218
+ await cache_service_1.cacheService.setInCache(this.CHAIN_CACHE_ID, { domainId, instanceId, revision: value.revision }, value, this.SNAPSHOT_TTL_S);
219
+ await cache_service_1.cacheService.setInCache(this.CHAIN_INDEX_CACHE_ID, { domainId, instanceId }, { revisions: next }, this.SNAPSHOT_TTL_S);
220
+ /*
221
+ * 버린 지점은 **색인에서만** 빠진다 — 공용 캐시에 삭제 API 가 없다(`ICacheService` 는 get·set·
222
+ * clearStaleCache 뿐이다). 그래서 값은 TTL(7일)까지 남는다: 아무도 닿지 못하지만 자리는 차지한다.
223
+ * 지금 규모에서 감당할 수 있는 낭비이고, 공용 모듈에 삭제를 여는 것은 다른 소비처까지 함께 볼
224
+ * 일이라 여기서 몰래 하지 않는다 — **알려진 한계로 적어 둔다.**
225
+ */
226
+ if (dropped.length)
227
+ console.info(`[twin-engine] "${instanceId}" fold chain dropped ${dropped.join(', ')} from the index (values expire with the cache TTL).`);
228
+ }
229
+ /** 이 트윈 저널의 끝 리비전 · 최신 구조 리비전 — 스냅샷이 지금의 사실인지 가리는 두 값. */
230
+ static async tipOf(domainId, instanceId) {
231
+ const [tip, newest] = await Promise.all([
232
+ (0, shell_1.getRepository)(twin_event_js_1.TwinEvent).findOne({ where: { domain: { id: domainId }, instanceId }, order: { revision: 'DESC' } }),
233
+ (0, shell_1.getRepository)(twin_structure_js_1.TwinStructure).findOne({ where: { domain: { id: domainId }, instanceId }, order: { rev: 'DESC' } })
234
+ ]);
235
+ return { revision: tip?.revision ?? 0, structureRev: newest?.rev ?? null };
236
+ }
63
237
  /** 체크포인트 루프 기동(1회) — 라이브 인스턴스들의 최신 스냅샷을 주기 영속. */
64
238
  static startCheckpointLoop() {
65
239
  if (this.checkpointTimer)
66
240
  return;
67
241
  this.checkpointTimer = setInterval(() => {
68
- for (const [instanceId, inst] of Object.entries(this.instances)) {
242
+ for (const [key, inst] of Object.entries(this.instances)) {
243
+ const { instanceId } = (0, runtime_key_js_1.parseRuntimeKey)(key);
69
244
  this.persistSnapshot(inst.domainId, instanceId).catch(err => console.error(`[twin-engine] snapshot checkpoint fail "${instanceId}"`, err?.message ?? err));
70
245
  }
71
246
  }, this.CHECKPOINT_MS);
@@ -78,34 +253,7 @@ class TwinEngine {
78
253
  */
79
254
  static async bootstrap() {
80
255
  try {
81
- // 백필(space #3) — spaceId 컬럼 없는 기존 인스턴스를 board.spaceId 로 채움(1회, 마이그레이션 안전).
82
256
  const repo = (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance);
83
- const missing = (await repo.find()).filter(r => !r.spaceId && r.board?.spaceId);
84
- for (const r of missing) {
85
- r.spaceId = r.board.spaceId;
86
- r.areaId = r.board.areaId ?? r.areaId;
87
- await repo.save(r);
88
- }
89
- if (missing.length)
90
- console.log(`[twin-engine] backfilled spaceId for ${missing.length} instance(s).`);
91
- // 백필(area 단일화 P3) — deprecated content.areas → TwinArea 이관(폴백 제거 전 완전성 보장, 1회).
92
- const spaceRepo = (0, shell_1.getRepository)(twin_space_js_1.TwinSpace);
93
- const twinAreaRepo = (0, shell_1.getRepository)(twin_area_js_1.TwinArea);
94
- for (const sp of await spaceRepo.find()) {
95
- const cAreas = (sp.content?.areas ?? []);
96
- for (const a of cAreas) {
97
- if (!a?.id)
98
- continue;
99
- const ex = await twinAreaRepo.findOne({ where: { domain: { id: sp.domainId }, space: { id: sp.id }, areaId: a.id } });
100
- if (ex)
101
- continue;
102
- await twinAreaRepo.save(twinAreaRepo.create({
103
- domain: { id: sp.domainId }, space: { id: sp.id }, areaId: a.id,
104
- name: a.name ?? a.id, type: a.type, parentId: a.parentId ?? null,
105
- layout: a.x != null ? { x: a.x, y: a.y, w: a.w, h: a.h } : null
106
- }));
107
- }
108
- }
109
257
  const rows = await repo.find({ where: { status: 'running' } });
110
258
  for (const row of rows) {
111
259
  if (!row.domainId || !row.instanceId)
@@ -114,16 +262,28 @@ class TwinEngine {
114
262
  // 없으면 저널 fold-from-0 replay(진실 폴백 — replay 는 라이브 파생상태를 못 담으므로 캐시가 더 충실).
115
263
  const cached = await this.loadSnapshot(row.domainId, row.instanceId).catch(() => null);
116
264
  if (cached?.state) {
117
- this.recovered[row.instanceId] = { revision: cached.revision, state: cached.state };
118
- console.log(`[twin-engine] warm-started "${row.instanceId}" from snapshot cache → revision ${cached.revision}.`);
265
+ /* 예전에 겹포장으로 저장된 값이 남아 있을 수 있다 — 읽는 쪽에서도 벗긴다(한 번은 반드시 만난다). */
266
+ this.recovered[(0, runtime_key_js_1.runtimeKey)(row.domainId, row.instanceId)] = { revision: cached.revision, state: (0, warm_start_js_1.unwrapState)(cached.state) };
267
+ /*
268
+ * **「웜스타트했다」고 말하지 않는다** — 여기서는 상태를 **찾아 둔 것**뿐이다.
269
+ *
270
+ * 실제 주입은 기동 때 일어나고(`warmStart` 가 그때 무엇을 심었는지 말한다), 미러(live) 트윈은
271
+ * 그 씨앗을 아예 쓰지 않는다(`startLive` 가 버린다). 그런데 이 줄이 「warm-started」라고 말해
272
+ * 로그만 읽으면 심긴 줄 알게 된다 — 실제로 그렇게 읽고 재기동 뒤 지속시간이 사라진 것을
273
+ * 데이터 문제로 오진할 뻔했다.
274
+ */
275
+ console.log(`[twin-engine] found cached state for "${row.instanceId}" → revision ${cached.revision} (seeded at start).`);
119
276
  continue;
120
277
  }
121
278
  const state = await this.recover(row.domainId, row.instanceId).catch(() => null);
122
279
  if (state) {
123
- this.recovered[row.instanceId] = { revision: state.revision, state };
280
+ this.recovered[(0, runtime_key_js_1.runtimeKey)(row.domainId, row.instanceId)] = { revision: state.revision, state };
124
281
  console.log(`[twin-engine] recovered "${row.instanceId}" from journal → revision ${state.revision}.`);
125
282
  }
126
283
  }
284
+ /* 상태만 되찾는 것으로는 **도는 트윈이 되지 않는다** — 런타임까지 되살린다(아래). */
285
+ for (const row of rows)
286
+ await this.resumeRow(row);
127
287
  this.startCheckpointLoop(); // 이후 기동되는 라이브 인스턴스의 최신 스냅샷을 주기 영속
128
288
  }
129
289
  catch (err) {
@@ -131,28 +291,97 @@ class TwinEngine {
131
291
  }
132
292
  }
133
293
  /**
134
- * 웜스타트 — 기동하는 커널에 **직전 관측 상태**를 심는다.
294
+ * 부팅 때 **도는 트윈을 실제로 되살린다** — 「도는 중」이 사실이 되게.
295
+ *
296
+ * ── 무엇이 거짓말이었나 (2026-08-14) ────────────────────────────────────────
297
+ * `bootstrap()` 은 상태만 되찾아 `recovered` 에 담았고, 커널을 세우는 것은 **명시 mutation 뿐**이었다
298
+ * (이 파일 위쪽 주석이 「향후」라고 적어 둔 그 자리다). 그래서 서버를 한 번 재기동하면 등록부는
299
+ * `running` 이라 말하는데 **아무 커널도 돌지 않았다** — 화면은 도는 트윈을, 실제로는 멈춘 트윈을.
300
+ * 미러 트윈에서는 더 나쁘다: 계측이 조용히 끊기고, 사람은 「값이 안 변하네」로 알게 된다.
301
+ *
302
+ * ── 모드를 지어내지 않는다 ──────────────────────────────────────────────────
303
+ * 미러였던 트윈을 시뮬로 되살리면 **없던 움직임을 만들어 낸다**(관측 트윈이 스스로 물건을 옮긴다).
304
+ * 그래서 선언된 `realityMode` 그대로 되살린다 — 미러는 관측 구동으로, 시뮬은 시뮬로.
305
+ *
306
+ * ── 되살릴 수 없으면 그렇게 적는다 ──────────────────────────────────────────
307
+ * 실패를 삼키면 등록부가 계속 `running` 이라 말한다 — 우리가 고치려던 그 거짓말이다. 그래서 실패한
308
+ * 행은 `stopped` 로 적고 이유를 남긴다. 「멈췄다」는 사실이고, 「도는 중」은 사실이 아니었다.
309
+ */
310
+ static async resumeRow(row) {
311
+ const { domainId, instanceId } = row;
312
+ if (!domainId || !instanceId)
313
+ return;
314
+ if (this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, instanceId)])
315
+ return; // 이미 세워졌다(데모 시드 등)
316
+ /*
317
+ * 벤치 사본은 되살리지 않는다 — 그것은 **누군가 지켜보던 실험**이고, 무인으로 되살아나면 호스트를
318
+ * 그대로 두들긴다(격리 사본의 뜻은 「운영과 섞이지 않는다」이지 「영원히 돈다」가 아니다).
319
+ * 실험은 재기동을 넘기지 못했으므로 등록부도 그렇게 적는다.
320
+ */
321
+ if (row.purpose === 'bench') {
322
+ await this.markStopped(row, 'bench copy — an experiment does not survive a restart unattended');
323
+ return;
324
+ }
325
+ try {
326
+ if (row.realityMode === 'mirror') {
327
+ if (!row.model)
328
+ throw new Error('no model');
329
+ /* 시각 기준은 **공간**이 갖는다 — 교대의 HH:MM 을 어느 기준으로 읽나(라이브 기동과 같은 규칙). */
330
+ this.startLive(instanceId, domainId, row.kind, await this.withSpaceTimeBase(row.model, domainId));
331
+ /* 계측을 나르는 피드는 커넥터의 것이다 — 레퍼런스 계층이 부팅 훅에서 다시 붙인다
332
+ (`resumeReferenceLiveFeeds`). 여기서 어댑터를 아는 것은 계층을 거꾸로 잇는 것이다. */
333
+ console.log(`[twin-engine] resumed mirror "${instanceId}" — feed reattach is the reference layer's job.`);
334
+ }
335
+ else {
336
+ await this.startFromRegistry(domainId, instanceId);
337
+ console.log(`[twin-engine] resumed ${row.realityMode} "${instanceId}".`);
338
+ }
339
+ }
340
+ catch (err) {
341
+ await this.markStopped(row, err?.message ?? 'resume failed');
342
+ }
343
+ }
344
+ /** 되살리지 못한 행을 정직하게 적는다 — 「도는 중」이라 말하는 채로 두지 않는다. */
345
+ static async markStopped(row, why) {
346
+ console.warn(`[twin-engine] "${row.instanceId}" not resumed (${why}) — registry says stopped now.`);
347
+ try {
348
+ await (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance).update({ id: row.id }, { status: 'stopped' });
349
+ }
350
+ catch (e) {
351
+ console.error(`[twin-engine] could not mark "${row.instanceId}" stopped — registry now lies about it.`, e?.message);
352
+ }
353
+ }
354
+ /**
355
+ * 웜스타트 — 기동하는 커널에 **직전 관측 상태**를 주입한다.
135
356
  *
136
357
  * ── 왜 필요한가 ─────────────────────────────────────────────────────────────
137
- * `loadBoard` 는 **구조만** 싣는다(노드·무버). 상태(무엇이 어디에 얼마나)는 없다. 그래서 재기동한
358
+ * `loadTwinModel` 는 **구조만** 싣는다(자리·설비). 상태(무엇이 어디에 얼마나)는 없다. 그래서 재기동한
138
359
  * 트윈은 저널에 입고 540건이 남아 있어도 재고가 0 이었고, 화면은 "보유 중인 것이 없습니다" 라고
139
360
  * 말했다 — 있는 재고를 없다고 하는 셈이다(2026-07-31 hatiolab-wms 실측으로 확인).
140
361
  * `bootstrap()` 이 이미 체크포인트 캐시(없으면 저널 replay)로 상태를 복구해 `recovered` 에 담아 두는데,
141
362
  * 기동 순간 그걸 **버리고** 있었다. 반만 연결돼 있던 장치를 잇는다.
142
363
  *
143
- * ── 정직한 한계 ─────────────────────────────────────────────────────────────
144
- * · **오더는 복원하지 않는다.** `hydrateObserved` 의 오더 인자는 requested/fulfilled/lines 를 요구하는데
145
- * 스냅샷의 `OrderState` 에는 `progress` 밖에 없다. progress 에서 역산하면 없는 숫자를 지어내는 것이라
146
- * 넘기지 않는다 — 재고·노드·무버만 복원되고 진행 중 오더는 비어서 시작한다.
147
- * · 진행 중 개별 task 의 내부 상태도 관측만으로는 복원되지 않는다(커널이 명시한 한계, 재계획에 맡김).
148
- * · 근본 해법(상태 영속 계약·revision 이어붙임)은 별도 과제.
364
+ * ── 반쪽이던 복구를 마무리한다 (2026-08-05) ─────────────────────────────────
365
+ * 재고는 살아났는데 **진행 중 주문이 통째로 사라진** 화면이 남아 있었다. 씨앗이 자리·물품·설비
366
+ * 셋만 넘겼기 때문이다. 그 근거는 "스냅샷 오더에 progress 밖에 없다" 였고, 그때는 맞았다 —
367
+ * 그러나 커널 `OrderState` 가 원값(`requested`·`fulfilled`·`lines`)을 되찾은 뒤에도 이 자리만
368
+ * 그대로 남았다. 오류를 내지 않는 종류라 오래 버텼다.
369
+ *
370
+ * 지금은 **관측 스냅샷 전체**를 넘긴다(오더·작업·사람·자산 포함). 시뮬은 커널 `snapshot()`,
371
+ * 라이브는 `StateProjector` 가 그 일곱 축을 모두 담는다. 무엇을 심을 수 있는지 판정하는 규칙
372
+ * (이행 완료 오더 제외·고아 작업 제외)은 커널에 있고, 호스트가 미리 골라내지 않는다.
373
+ *
374
+ * ── 남은 한계는 숨기지 않고 센다 ────────────────────────────────────────────
375
+ * · 원값이 없는 오더(progress 만 있는 것)는 남은 수량을 알 수 없어 주입하지 않는다. **지어내지 않는
376
+ * 대신 몇 건인지 말한다** — 세지 않으면 "주문이 없다" 와 "주문을 못 심었다" 가 화면에서 같아진다.
377
+ * · 진행 중 개별 작업의 내부 상태는 관측만으로 완전히 복원되지 않는다(커널이 명시한 한계, 재계획에 맡김).
149
378
  *
150
379
  * ── 벤치는 시드하지 않는다 ──────────────────────────────────────────────────
151
- * 부하 벤치는 **새 시작에서 용량을 재는 것**이 목적이라 현재 상태를 심으면 측정이 오염된다.
380
+ * 부하 벤치는 **새 시작에서 용량을 재는 것**이 목적이라 현재 상태를 주입하면 측정이 오염된다.
152
381
  */
153
- static warmStart(id, kernel, purpose) {
382
+ static warmStart(domainId, id, kernel, purpose) {
154
383
  const hydrate = kernel.hydrateObserved;
155
- const plan = (0, warm_start_js_1.planWarmStart)(this.recovered[id]?.state, purpose, typeof hydrate === 'function');
384
+ const plan = (0, warm_start_js_1.planWarmStart)(this.recovered[(0, runtime_key_js_1.runtimeKey)(domainId, id)]?.state, purpose, typeof hydrate === 'function');
156
385
  if (plan.action === 'skip') {
157
386
  if (plan.reason === 'bench') {
158
387
  console.log(`[twin-engine] "${id}" is a bench twin — starting empty on purpose (seeding would skew the measurement).`);
@@ -163,25 +392,64 @@ class TwinEngine {
163
392
  return;
164
393
  }
165
394
  hydrate.call(kernel, plan.seed);
166
- console.log(`[twin-engine] warm-started "${id}" — ${plan.itemCount} item(s), ${plan.equipmentCount} equipment restored. ` +
167
- 'Open orders are not restored (the snapshot carries no requested/fulfilled counts).');
395
+ const restored = [
396
+ `${plan.itemCount} item(s)`,
397
+ `${plan.equipmentCount} equipment`,
398
+ `${plan.orderCount} open order(s)`,
399
+ `${plan.taskCount} task(s)`,
400
+ ...(plan.personCount ? [`${plan.personCount} person(s)`] : []),
401
+ ...(plan.assetCount ? [`${plan.assetCount} asset(s)`] : []),
402
+ /* 확인해 둔 신호를 이어받았다는 사실도 말한다 — 잃으면 확인 처리가 다시 빨개지는 것으로 보인다. */
403
+ ...(plan.ackedCount ? [`${plan.ackedCount} acknowledged attention(s)`] : []),
404
+ /* 「언제부터인가」도 말한다 — 잃으면 지속된 조건이 모두 「방금」으로 보인다. */
405
+ ...(plan.attentionSinceCount ? [`${plan.attentionSinceCount} attention start time(s)`] : [])
406
+ ].join(', ');
407
+ console.log(`[twin-engine] warm-started "${id}" — restored ${restored}.`);
408
+ /* 뺀 것은 조용히 넘기지 않는다 — 지어내지 않았다는 사실 자체를 말해야 화면의 빈칸이 읽힌다. */
409
+ if (plan.ordersWithoutDemand > 0) {
410
+ console.warn(`[twin-engine] "${id}": ${plan.ordersWithoutDemand} order(s) could not be restored — they carry progress only, ` +
411
+ 'with no requested/fulfilled counts, so the remaining demand is unknown. They are left out rather than guessed.');
412
+ }
168
413
  }
169
- /** 트윈 인스턴스 시작 — 커널 생성 + 보드 로드 + 직전 상태 웜스타트 + State 스트림 브리지 + 워커 tick + 레지스트리 영속. */
414
+ /** 트윈 인스턴스 시작 — 커널 생성 + 모델 로드 + 직전 상태 웜스타트 + State 스트림 브리지 + 워커 tick + 레지스트리 영속. */
170
415
  /**
171
416
  * 공정 명세를 커널에 싣는다 — **시뮬레이션의 시간을 데이터가 말하게 하는 마지막 한 칸.**
172
417
  *
173
- * `board.operations`(마스터 인제스트가 통과시킨 ISA-95 OperationsSegment 명세)를 커널이 소비한다.
418
+ * `model.operations`(마스터 인제스트가 통과시킨 ISA-95 OperationsSegment 명세)를 커널이 소비한다.
174
419
  * 없으면 커널 기본 상수로 굴러가고, 커널 `specCoverage()` 가 무엇을 기본값으로 썼는지 보고한다.
175
420
  *
176
421
  * 커널이 아직 이 API 를 갖지 않은 버전이면(발행 이전) **조용히 넘어가지 않고 경고한다** — 명세를
177
422
  * 선언했는데 반영되지 않는 상태를 모르고 지나가면, 예측이 상수로 돌아간 것을 아무도 알 수 없다.
178
423
  */
179
- static applyOperations(kernel, board, id) {
180
- const ops = board?.operations;
424
+ static applyOperations(kernel, model, id) {
425
+ /*
426
+ * 현장이 정한 공정 시간 — 명세 행과 **따로** 싣는다(`declareDurations`).
427
+ *
428
+ * 행이 없는 종류에도 시간을 줄 수 있어야 한다: 실측으로 창고·야드 트윈에는 공정 명세 행이 0개였고,
429
+ * 그 트윈들의 시간은 전부 커널 상수에서 왔다. 행을 지어 만드는 길은 막았다(`label`·`intent` 를
430
+ * 지어내면 능력 계산까지 오염된다) — 그래서 시간만 받는 창구가 커널에 있다.
431
+ */
432
+ const declared = model?.localDurations;
433
+ if (declared && Object.keys(declared).length) {
434
+ if (typeof kernel?.declareDurations !== 'function') {
435
+ console.warn(`[twin-engine] "${id}": this facility declared ${Object.keys(declared).length} operation duration(s) but the kernel cannot consume them ` +
436
+ '(declareDurations missing — kernel needs publishing). The simulation keeps running on built-in constants, and specCoverage() will keep reporting "default".');
437
+ }
438
+ else {
439
+ try {
440
+ kernel.declareDurations(declared);
441
+ }
442
+ catch (err) {
443
+ /* 커널이 거절한 값은 조용히 넘기지 않는다 — 화면은 「넣었습니다」라고 말한 값이다. */
444
+ console.warn(`[twin-engine] "${id}": declared operation duration rejected by the kernel — ${err?.message ?? err}`);
445
+ }
446
+ }
447
+ }
448
+ const ops = model?.operations;
181
449
  if (!ops?.length)
182
450
  return;
183
451
  if (typeof kernel?.loadOperations !== 'function') {
184
- console.warn(`[twin-engine] "${id}": board declares ${ops.length} operation spec(s) but the kernel cannot consume them (loadOperations missing — kernel needs publishing). Simulation will use built-in default durations.`);
452
+ console.warn(`[twin-engine] "${id}": model declares ${ops.length} operation spec(s) but the kernel cannot consume them (loadOperations missing — kernel needs publishing). Simulation will use built-in default durations.`);
185
453
  return;
186
454
  }
187
455
  kernel.loadOperations(ops);
@@ -191,17 +459,17 @@ class TwinEngine {
191
459
  *
192
460
  * 커널 `durationOf` 의 우선순위는 추정기 > 명세 > 상수다. 그 추정기 자리에 두 가지를 사슬로 넣는다:
193
461
  * ① **실측**(저널의 작업 종류별 작업시간 p50) — 그 현장에서 실제로 얼마 걸렸나. 가장 강한 근거.
194
- * ② **거리 × 속도**(board.layout + 설비 속도 속성) — 이동은 거리에 비례한다. 커널은 좌표를 모르므로
462
+ * ② **거리 × 속도**(model.layout + 설비 속도 속성) — 이동은 거리에 비례한다. 커널은 좌표를 모르므로
195
463
  * 호스트가 계산해 넣는다.
196
464
  * 둘 다 못 만들면 주입하지 않는다 — 커널이 명세·상수로 굴러가고 `specCoverage()` 가 그 사실을 남긴다.
197
465
  *
198
466
  * 실측은 DB 조회라 비동기다. 그래서 이 함수는 **await 하지 않는 쪽에서도 안전**하도록 실패를 삼키되,
199
467
  * 무엇을 왜 못 넣었는지는 로그로 남긴다(조용한 무효화 금지).
200
468
  */
201
- static async installEstimators(kernel, domainId, instanceId, board) {
469
+ static async installEstimators(kernel, domainId, instanceId, model) {
202
470
  if (!kernel || typeof kernel !== 'object')
203
471
  return;
204
- const travel = (0, travel_estimator_js_1.buildTravelEstimator)({ layout: board?.layout, equipment: board?.equipment, unit: board?.unit });
472
+ const travel = (0, travel_estimator_js_1.buildTravelEstimator)({ layout: model?.layout, equipment: model?.equipment, unit: model?.unit });
205
473
  const measured = await this.measuredEstimator(domainId, instanceId);
206
474
  const chained = (0, travel_estimator_js_1.chainEstimators)([measured?.estimator, travel.estimator]);
207
475
  if (!chained) {
@@ -226,8 +494,23 @@ class TwinEngine {
226
494
  */
227
495
  static { this.measuredCache = new Map(); }
228
496
  static { this.MEASURED_TTL_MS = 60_000; }
497
+ /**
498
+ * 캐시 항목 상한 — **라이프사이클이 놓친 것까지 막는 두 번째 방어.**
499
+ *
500
+ * 지움은 `forgetInstance` 가 한다(그것이 첫 번째 방어이고 정확한 쪽이다). 그런데 트윈이 우리 API 를
501
+ * 지나지 않고 사라지는 길이 있다: 도메인(테넌트)째로 지워지거나 DB 를 직접 손대는 경우다. 그때
502
+ * 남은 항목을 지울 주인이 없으므로 상한이 필요하다.
503
+ *
504
+ * 넘치면 **가장 오래 손대지 않은 것**부터 버린다(Map 의 삽입 순서가 곧 그 순서다 — 값을 쓸 때마다
505
+ * 다시 넣으므로). 버리는 것이 손해가 아닌 이유: 이 값은 캐시이고, 없으면 다시 계산한다.
506
+ *
507
+ * 수를 크게 잡는다 — 트윈 규모는 늘 크고, 항목 하나는 작업 종류별 소요 몇 줄이다. 상한이 작으면
508
+ * 정상 규모에서 서로 밀어내며 캐시가 무의미해진다(그게 더 나쁘다: 조용히 느려진다).
509
+ */
510
+ static { this.MEASURED_MAX = 5_000; }
229
511
  static async measuredEstimator(domainId, instanceId) {
230
- const key = `${domainId}:${instanceId}`;
512
+ /* 키는 `runtimeKey` 하나로 — 손으로 조립하면 지우는 쪽과 어긋나 못 지우는 항목이 생긴다. */
513
+ const key = (0, runtime_key_js_1.runtimeKey)(domainId, instanceId);
231
514
  const hit = this.measuredCache.get(key);
232
515
  if (hit && Date.now() - hit.at < this.MEASURED_TTL_MS)
233
516
  return hit.value;
@@ -240,9 +523,31 @@ class TwinEngine {
240
523
  catch (err) {
241
524
  console.warn(`[twin-engine] "${instanceId}": measured duration lookup failed — falling back to declared/default durations.`, err?.message);
242
525
  }
526
+ /* 다시 넣어 **최근 쓴 것**으로 만든다 — 삽입 순서가 곧 버릴 순서이므로 이 한 줄이 LRU 를 만든다. */
527
+ this.measuredCache.delete(key);
243
528
  this.measuredCache.set(key, { at: Date.now(), value });
529
+ if (this.measuredCache.size > this.MEASURED_MAX) {
530
+ const oldest = this.measuredCache.keys().next();
531
+ if (!oldest.done)
532
+ this.measuredCache.delete(oldest.value);
533
+ }
244
534
  return value;
245
535
  }
536
+ /**
537
+ * 이 트윈이 **이력에서 시간을 배운 작업 종류들** — 재기동에도 남는 근거.
538
+ *
539
+ * ── 왜 필요한가 (2026-08-18 실측) ────────────────────────────────────────
540
+ * 커널의 자기보고(`specCoverage()`)는 **작업이 새로 생길 때** 채워진다. 그래서 재기동 직후에는 이력이
541
+ * 풍부한 트윈에서도 목록이 비고, 「이 트윈이 무슨 공정을 돌리나」 화면이 빈칸이 된다 — 값을 채울 곳을
542
+ * 보여야 하는 화면이 정작 그때 아무 말도 못 한다.
543
+ *
544
+ * 그 빈칸을 이력로 메운다: 저널에서 배운 종류는 **추정기가 이미 답할 수 있는 종류**이므로, 지어내는
545
+ * 것이 아니라 있는 사실을 꺼내는 것이다. 같은 캐시(60초)를 쓰므로 조회마다 저널을 다시 접지 않는다.
546
+ */
547
+ static async measuredOperationKinds(domainId, instanceId) {
548
+ const measured = await this.measuredEstimator(domainId, instanceId);
549
+ return Object.keys(measured?.learned ?? {});
550
+ }
246
551
  /**
247
552
  * 지금 이 트윈이 어떤 모델로 굴러가는가 — 예측 출력 보정이 **자기가 배운 모델**에만 적용되도록
248
553
  * 비교하는 지문. 재료는 호스트가 아는 것(실측·속도·선언 명세)이라 커널 발행 상태와 무관하다.
@@ -251,27 +556,27 @@ class TwinEngine {
251
556
  static async modelBasis(domainId, instanceId) {
252
557
  try {
253
558
  const reg = await (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance).findOne({ where: { domain: { id: domainId }, instanceId } });
254
- const board = reg?.board;
559
+ const model = reg?.model;
255
560
  const measured = await this.measuredEstimator(domainId, instanceId);
256
- const travel = (0, travel_estimator_js_1.buildTravelEstimator)({ layout: board?.layout, equipment: board?.equipment, unit: board?.unit });
257
- return { measured: measured?.learned, speeds: travel.speedsByKind, declared: board?.operations };
561
+ const travel = (0, travel_estimator_js_1.buildTravelEstimator)({ layout: model?.layout, equipment: model?.equipment, unit: model?.unit });
562
+ return { measured: measured?.learned, speeds: travel.speedsByKind, declared: model?.operations };
258
563
  }
259
564
  catch {
260
565
  return undefined;
261
566
  }
262
567
  }
263
568
  /**
264
- * **이 트윈이 하루 몇 대를 낼 수 있는가** — 굴려 보지 않고 답한다.
569
+ * **이 트윈이 하루 몇 대를 낼 수 있는가** — 실행해 보지 않고 답한다.
265
570
  *
266
571
  * 계산은 커널이 자기 상태에서 한다(`kernel.capacity`). 여기서 하는 일은 **기준 주를 정해 주는
267
572
  * 것**뿐이다: 공휴일이 없는 평상주여야 한다 — 공휴일은 연간 가용량을 따로 깎지, 이 공장의 평상시
268
- * 천장을 정하지 않는다. 커널이 임의로 고르게 두면 그 주에 공휴일이 끼었을 때 천장이 조용히 낮아진다.
573
+ * 상한을 정하지 않는다. 커널이 임의로 고르게 두면 그 주에 공휴일이 끼었을 때 상한이 조용히 낮아진다.
269
574
  *
270
- * 트윈이 안 떠 있으면 `undefined` 다 — 0 이 아니다. 안 뜬 트윈의 천장을 0 이라고 답하면 화면은
575
+ * 트윈이 기동 중이 아니면 `undefined` 다 — 0 이 아니다. 기동하지 않은 트윈의 상한을 0 이라고 답하면 화면은
271
576
  * "이 공장은 아무것도 못 만든다" 고 말한다.
272
577
  */
273
578
  static async capacity(domainId, target, unitsPerDay, sampleWeekStartMs) {
274
- /* 대상은 **등록부**가 정한다 — 떠 있는 런타임만 훑으면 "안 떠 있어서 안 보이는 것" 과 "없는 것" 이
579
+ /* 대상은 **등록부**가 정한다 — 기동 중인 런타임만 훑으면 "안 떠 있어서 안 보이는 것" 과 "없는 것" 이
275
580
  구별되지 않는다. 화면은 그 둘을 다르게 말해야 한다. */
276
581
  const where = { domain: { id: domainId } };
277
582
  if (target.instanceId)
@@ -280,8 +585,8 @@ class TwinEngine {
280
585
  where.spaceId = target.spaceId;
281
586
  const registered = await (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance).find({ where });
282
587
  return registered.map(reg => {
283
- const rt = this.instances[reg.instanceId];
284
- const kernel = rt?.domainId === domainId ? rt.kernel : undefined;
588
+ const rt = this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, reg.instanceId)];
589
+ const kernel = rt?.kernel; // 키에 도메인이 있으므로 남의 런타임을 집을 수 없다
285
590
  if (typeof kernel?.capacity !== 'function')
286
591
  return { instanceId: reg.instanceId, kind: reg.kind, reason: 'not-running' };
287
592
  const analysis = kernel.capacity({ unitsPerDay, sampleWeekStartMs });
@@ -292,16 +597,76 @@ class TwinEngine {
292
597
  return { instanceId: reg.instanceId, kind: reg.kind, analysis };
293
598
  });
294
599
  }
295
- static start(id, domainId, kind, board, realityMode, purpose, resumeFrom) {
296
- if (this.instances[id])
297
- return this.instances[id];
298
- const Kernel = KERNELS[kind] ?? WmsKernel;
299
- const kernel = new Kernel(domainId, undefined, this.mesSpecOf(board));
300
- kernel.loadBoard(board); // 구조만. 상태는 아래 웜스타트가 심는다.
301
- this.applyOperations(kernel, board, id); // 시간·수율 명세(있으면) — 없으면 커널 기본값
600
+ /**
601
+ * **생산 능력 보고서** — ISA-95 Part 4 `OperationsCapability`. 구간의 양을 종류로 구분한다
602
+ * (약정·가용·달성불가). 용량(`capacity`)은 비율을 내고 이것은 **구간의 양**을 낸다.
603
+ *
604
+ * 대상 선정·거절 사유는 `capacity` 와 **같은 규율**이다: 등록부가 대상을 정하고(안 기동 중인 것과
605
+ * 없는 것을 구별한다), 공정을 선언하지 않은 트윈은 판정 대상이 아니라고 말한다(0 으로 채우면
606
+ * "야드가 병목" 이라는 없는 사실이 생긴다).
607
+ */
608
+ static async operationsCapability(domainId, target, unitsPerDay, sampleWeekStartMs, window) {
609
+ const where = { domain: { id: domainId } };
610
+ if (target.instanceId)
611
+ where.instanceId = target.instanceId;
612
+ else
613
+ where.spaceId = target.spaceId;
614
+ const registered = await (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance).find({ where });
615
+ return registered.map(reg => {
616
+ const rt = this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, reg.instanceId)];
617
+ const kernel = rt?.kernel;
618
+ if (typeof kernel?.operationsCapability !== 'function') {
619
+ return { instanceId: reg.instanceId, kind: reg.kind, reason: 'not-running' };
620
+ }
621
+ const report = kernel.operationsCapability({ unitsPerDay, sampleWeekStartMs, window });
622
+ if (!report?.perOperation?.length)
623
+ return { instanceId: reg.instanceId, kind: reg.kind, reason: 'no-operations' };
624
+ return { instanceId: reg.instanceId, kind: reg.kind, report };
625
+ });
626
+ }
627
+ /**
628
+ * 미러 기동의 연속성 씨앗 — 이어받은 것은 **말한다**(조용히 잇지 않는다).
629
+ *
630
+ * 커널이 그 문을 열어 두지 않았으면 그 사실도 말한다: 그 트윈은 재기동마다 열린 구간을 잃는다.
631
+ */
632
+ static seedLiveContinuity(domainId, id, kernel) {
633
+ const cached = this.recovered[(0, runtime_key_js_1.runtimeKey)(domainId, id)]?.state;
634
+ if (!cached)
635
+ return;
636
+ const plan = (0, warm_start_js_1.planLiveContinuity)(cached);
637
+ if (!plan.ackedCount && !plan.attentionSinceCount && !plan.energy)
638
+ return;
639
+ if (typeof kernel.hydrateContinuity !== 'function') {
640
+ console.warn(`[twin-engine] kernel for "${id}" cannot carry continuity (no hydrateContinuity) — the open demand window, ` +
641
+ 'its peak and the attention start times are lost on every restart.');
642
+ return;
643
+ }
644
+ try {
645
+ kernel.hydrateContinuity(plan.seed);
646
+ }
647
+ catch (err) {
648
+ /* 이어받기가 실패해도 미러는 돌아야 한다 — 다만 무엇을 잃었는지 말한다. */
649
+ console.warn(`[twin-engine] continuity seed failed for "${id}" — starting without it: ${err?.message ?? err}`);
650
+ return;
651
+ }
652
+ const carried = [
653
+ ...(plan.energy ? ['energy accumulation (open window, totalizer baselines, peak)'] : []),
654
+ ...(plan.ackedCount ? [`${plan.ackedCount} acknowledged attention(s)`] : []),
655
+ ...(plan.attentionSinceCount ? [`${plan.attentionSinceCount} attention start time(s)`] : [])
656
+ ].join(', ');
657
+ console.log(`[twin-engine] mirror "${id}" carried over ${carried} — observation axes come from the source.`);
658
+ }
659
+ static start(id, domainId, kind, model, realityMode, purpose, resumeFrom) {
660
+ const key = (0, runtime_key_js_1.runtimeKey)(domainId, id);
661
+ if (this.instances[key])
662
+ return this.instances[key];
663
+ const Kernel = kernelFor(kind);
664
+ const kernel = new Kernel(domainId, undefined, this.productionSpecOf(model));
665
+ kernel.loadTwinModel(model); // 구조만. 상태는 아래 웜스타트가 주입한다.
666
+ this.applyOperations(kernel, model, id); // 시간·수율 명세(있으면) — 없으면 커널 기본값
302
667
  /* 추정기는 DB 조회를 포함해 비동기 — 기동을 막지 않고 붙는다(붙기 전 작업은 명세·상수로 산출). */
303
- this.installEstimators(kernel, domainId, id, board).catch(err => console.warn('[twin-engine] estimator install failed', err?.message));
304
- this.warmStart(id, kernel, purpose);
668
+ this.installEstimators(kernel, domainId, id, model).catch(err => console.warn('[twin-engine] estimator install failed', err?.message));
669
+ this.warmStart(domainId, id, kernel, purpose);
305
670
  /*
306
671
  * **번호를 이어 센다** — 저널에 이미 있는 번호와 겹치지 않게.
307
672
  *
@@ -310,29 +675,60 @@ class TwinEngine {
310
675
  */
311
676
  if (resumeFrom && typeof kernel.resumeRevision === 'function')
312
677
  kernel.resumeRevision(resumeFrom);
678
+ /*
679
+ * ── 이 트윈의 시계를 **지금**에 맞춘다 (2026-08-15) ────────────────────────
680
+ * 커널의 기본 기준점은 상수(2026-01-01)다. 그대로 두면 시뮬 트윈의 저널 시각이 **재기동마다
681
+ * 되감겨** 며칠 치 사건이 전부 같은 분에 몰린다 — 「언제 있었던 일인가」를 되짚을 수 없고,
682
+ * 실 시각으로 창을 자르는 성과·이력 질의에는 그 트윈이 아예 보이지 않는다.
683
+ *
684
+ * 재기동하면 그만큼 시계가 앞으로 뛰는데, 그것이 사실이다: 그 사이 이 트윈은 돌지 않았고
685
+ * 저널의 빈 구간이 그 사실을 말한다.
686
+ */
687
+ kernel.setClockOrigin?.(Date.now());
313
688
  const runtime = new TwinRuntime(kernel);
314
689
  /* subscribe 는 RuntimeSubscription({ unsubscribe() }) 반환 → () => void 로 감쌈. */
315
- const inst = { id, domainId, runtime, kernel, realityMode: realityMode ?? exports.DEFAULT_REALITY_MODE, unsub: () => { } };
316
- this.instances[id] = inst;
317
- delete this.recovered[id]; // 웜스타트로 커널에 옮겨 심었다 — 이제 라이브가 진실이다.
690
+ /*
691
+ * **모드를 적어 둔다** (2026-08-18 실측으로 고침).
692
+ *
693
+ * 시뮬 경로는 `mode` 를 비워 두었고(「미지정=sim」이라는 규약에 기대), 라이브만 적었다. 그래서
694
+ * `modeOf()` 가 **도는 시뮬레이션에 undefined** 를 답했고, 선언·철회의 답이 「저장했다」로 나갔다 —
695
+ * 실제로는 도는 커널이 옛 수를 그대로 쓰고 재기동 때 받는데, 그 사실이 답에서 사라진 것이다.
696
+ * 규약에 기대는 대신 사실을 적는다: 「돌고 있나」를 묻는 쪽이 그 답을 받아야 한다.
697
+ */
698
+ const inst = { id, domainId, mode: 'sim', runtime, kernel, realityMode: realityMode ?? exports.DEFAULT_REALITY_MODE, spaceId: model?.spaceId, unsub: () => { } };
699
+ this.instances[key] = inst;
700
+ /* 다시 세웠으므로 지난 정지 이유는 사실이 아니다 — 남겨 두면 도는 트윈이 「굶겨서 멈췄다」고 말한다. */
701
+ this.stopNotes.delete(key);
702
+ delete this.recovered[key]; // 웜스타트로 커널에 옮겨 심었다 — 이제 라이브가 진실이다.
318
703
  /* 라이브 바인딩(P3): data 채널 필터가 subdomain 을 보므로 Domain 객체를 1회 해석해 둔다. */
319
704
  (0, shell_1.getRepository)(shell_1.Domain).findOne({ where: { id: domainId } }).then(d => (inst.domain = d)).catch(() => { });
320
705
  /* State 채널: runtime.subscribe(snapshot→delta→clock) → pubsub 방송(구독 리졸버가 instanceId 필터). */
321
706
  const sub = runtime.subscribe((msg) => {
322
- shell_1.pubsub.publish('twin-state', {
323
- twinState: { instanceId: id, kind: msg.kind, revision: msg.revision, payload: msg }
324
- });
707
+ this.publishGuarded('twin-state', { twinState: { instanceId: id, kind: msg.kind, revision: msg.revision, payload: msg } }, `twin-state:${id}`);
325
708
  /* 영속 + 라이브 바인딩 브리지: delta 마다 저널 저장 + 엔티티별 data(tag:) publish → 보드 컴포넌트 라이브. */
326
709
  if (msg.kind === 'delta') {
327
710
  this.persist(domainId, id, msg).catch(err => console.error('twin persist fail', err));
328
- this.publishEntityData(inst);
711
+ /*
712
+ * ── 방송은 **모아서** 한 번 (2026-08-14 실측으로 잡음) ────────────────────
713
+ * 여기서 곧바로 방송하고 있었다. 그런데 커널은 한 번의 tick 에서 사실을 **여러 개** 낸다
714
+ * (예약·배치·완료…). 그래서 tick 하나가 전 상태 투영을 수백 번 반복했다 — `order-check`
715
+ * 트윈에서 **틱 하나가 35초**를 먹고(단계 합은 32ms 였다: 시간은 반복 횟수에 있었다) 그
716
+ * 35초 동안 이벤트 루프가 막혀 구독자가 아무것도 빼내지 못했다. 밀린 push 가 1024를 넘는
717
+ * 순간 pubsub 이 던지고, 그 예외가 타이머 콜백을 타고 올라와 **호스트가 죽었다.**
718
+ *
719
+ * 라이브는 이미 dirty 표시 + 주기 flush 로 이 문제를 풀어 두었다(BROADCAST_COALESCE_MS).
720
+ * 시뮬만 그 규율 밖에 있었다 — 같은 규율로 들인다(최신-상태 채널이라 중간 상태를 모두
721
+ * 보낼 이유가 없다: 200ms 마다 마지막 것 하나면 화면은 같다).
722
+ */
723
+ inst.dirty = true;
724
+ this.ensureBroadcastCoalescer();
329
725
  }
330
726
  });
331
727
  inst.unsub = () => sub.unsubscribe();
332
- /* 복구 앵커: 레지스트리에 board/kind/status/realityMode 영속(재부팅 시 이게 있어야 replay·선언 거동 가능). */
333
- this.register(domainId, id, kind, board, 'running', inst.realityMode).catch(err => console.error('twin register fail', err));
728
+ /* 복구 앵커: 레지스트리에 model/kind/status/realityMode 영속(재부팅 시 이게 있어야 replay·선언 거동 가능). */
729
+ this.register(domainId, id, kind, model, 'running', inst.realityMode).catch(err => console.error('twin register fail', err));
334
730
  /* 워커 tick — 스켈레톤은 setInterval(메인 루프). 긴 시뮬 오프-루프(worker thread)는 스케일 하드닝(향후, §host 경계). */
335
- inst.timer = setInterval(() => runtime.tick(this.TICK_MS), this.TICK_MS);
731
+ inst.timer = setInterval(() => this.tickGuarded(domainId, id, runtime), this.TICK_MS);
336
732
  return inst;
337
733
  }
338
734
  /**
@@ -348,58 +744,114 @@ class TwinEngine {
348
744
  * 실 이벤트원 = reference 어댑터 openLiveFeed → face2-adapter.ingest → CanonicalEnvelope → ingestLive().
349
745
  */
350
746
  /**
351
- * 보드가 실은 **생산 정의**(레시피·라우트·바인딩)를 꺼낸다 — 커널의 정의-구동 모드 입구.
747
+ * 모델이 실은 **생산 정의**(레시피·라우트·바인딩)를 꺼낸다 — 커널의 정의-구동 모드 입구.
352
748
  *
353
749
  * ── 없을 때 무엇이 일어났나 ──────────────────────────────────────────────
354
750
  * 커널에는 정의-구동 MES 경로가 있는데 **호스트가 그것을 한 번도 넘기지 않았다.** 그래서 모든 MES
355
751
  * 트윈이 **하드코딩된 레거시 흐름**으로 돌았다 — 현장 레시피를 아무리 정성껏 적어도 커널은 그것을
356
752
  * 보지 못하고 토이 부품으로 토이 제품을 만들었다. 선언과 실행이 갈라져 있던 자리다.
357
753
  *
358
- * 보드에 없으면 `undefined` — 레거시 경로 그대로다(기존 트윈의 거동을 바꾸지 않는다).
754
+ * 모델에 없으면 `undefined` — 레거시 경로 그대로다(기존 트윈의 거동을 바꾸지 않는다).
359
755
  */
360
- static mesSpecOf(board) {
361
- return board?.mesSpec;
756
+ /**
757
+ * 생산 선언을 꺼낸다 — 커널 생성자에 넘긴다.
758
+ *
759
+ * **옛 이름(`mesSpec`)은 읽지 않는다.** 그것은 계약에 선언조차 없던 필드였고(MES 커널 생성자 인자
760
+ * 이름이 그대로 굳은 것), 일반 기제에 한 시스템 이름이 붙어 있었기 때문에 창고 트윈이 이 자리를
761
+ * 쓰지 못했다. 별명으로 남겨 두면 그 혼동이 계속되므로 하나로 통일했다.
762
+ *
763
+ * 옛 이름만 가진 모델이 있으면 **조용히 생산 선언을 잃는 대신 분명히 멈춘다** — 그 트윈은 공정이
764
+ * 없는 채로 돌게 되고(라인이 서 있는 창고), 원인을 찾기 어렵다.
765
+ */
766
+ static productionSpecOf(model) {
767
+ const legacy = model?.mesSpec;
768
+ if (legacy && !model?.productionSpec) {
769
+ throw new Error('the twin model carries the retired `mesSpec` field — rename it to `productionSpec` ' +
770
+ '(same shape; the name was tied to one kernel while the declaration is ISA-95 operations + BOM)');
771
+ }
772
+ return model?.productionSpec;
362
773
  }
363
774
  /**
364
- * 현장(공간)의 **시각 기준**을 보드에 얹는다 — 커널이 교대의 `HH:MM` 을 읽을 기준.
775
+ * 현장(공간)의 **시각 기준**을 모델에 얹는다 — 커널이 교대의 `HH:MM` 을 읽을 기준.
365
776
  *
366
777
  * **테넌트가 아니라 공간이 권위다.** 한 테넌트가 Rosarito(태평양)와 한국 공장을 함께 가질 수 있고,
367
- * 테넌트 단위(`Domain.timezone`)로 두면 둘 중 하나는 반드시 틀린다. 그래서 인스턴스가 묶인 공간의
778
+ * 테넌트 단위(`Domain.timezone`)로 두면 둘 중 하나는 반드시 틀린다. 그래서 인스턴스가 연결된 공간의
368
779
  * `timezone` 을 읽는다. 공간이 말하지 않으면 **테넌트로 내려가지 않는다** — 잘못된 입자로 답하는 것이
369
780
  * 모르는 것보다 나쁘다(그때는 커널이 UTC 로 읽고, 그 기본값은 계약에 밝혀져 있다).
370
781
  *
371
782
  * 커널은 zero-dep 이라 시간대 데이터베이스를 갖지 않으므로 **분 오프셋**으로 풀어 넘긴다. 그 값은
372
783
  * 지금 계절의 것이다(일광절약시간) — 계절을 넘는 긴 예측은 한 시간 어긋난다(계약에 명시).
373
784
  */
374
- static async withSpaceTimeBase(board, domainId, spaceId) {
375
- const sid = spaceId ?? board?.spaceId;
785
+ static async withSpaceTimeBase(model, domainId, spaceId) {
786
+ const sid = spaceId ?? model?.spaceId;
376
787
  if (!sid)
377
- return board;
788
+ return model;
378
789
  const space = await (0, shell_1.getRepository)(twin_space_js_1.TwinSpace).findOne({ where: { domain: { id: domainId }, spaceId: sid } }).catch(() => null);
379
790
  const offset = (0, reference_master_js_1.utcOffsetOf)(space?.timezone);
380
791
  if (offset === undefined) {
381
792
  if (space?.timezone)
382
793
  console.warn(`[twin-engine] space "${sid}" declares time zone "${space.timezone}" but it is not a known IANA zone — times will be read as UTC.`);
383
- return board;
794
+ return model;
384
795
  }
385
- return { ...board, utcOffsetMinutes: offset };
796
+ return { ...model, utcOffsetMinutes: offset };
386
797
  }
387
- static startLive(id, domainId, kind, board) {
388
- if (this.instances[id])
389
- return this.instances[id];
390
- const Kernel = KERNELS[kind] ?? WmsKernel;
391
- const kernel = new Kernel(domainId, undefined, this.mesSpecOf(board));
392
- kernel.loadBoard(board);
393
- this.applyOperations(kernel, board, id); // 명세는 라이브에도 실린다(예측 자격이 sim 과 같아진다)
798
+ static startLive(id, domainId, kind, model) {
799
+ const key = (0, runtime_key_js_1.runtimeKey)(domainId, id);
800
+ if (this.instances[key])
801
+ return this.instances[key];
802
+ const Kernel = kernelFor(kind);
803
+ const kernel = new Kernel(domainId, undefined, this.productionSpecOf(model));
804
+ kernel.loadTwinModel(model);
805
+ /* **세우는 쪽이 아는 사실은 세울 때 말한다.** 예전에는 첫 이벤트가 도착해야 커널이 스스로를
806
+ 관측 구동으로 여겼고, 그래서 아직 아무것도 못 받은 미러는 시뮬레이션 취급을 받았다. */
807
+ kernel.observe?.();
808
+ this.applyOperations(kernel, model, id); // 명세는 라이브에도 실린다(예측 자격이 sim 과 같아진다)
394
809
  /* `projector` 필드는 옛 이름으로 남긴다 — 소비처가 `snapshot()` 을 부르므로 얇은 어댑터로 잇는다.
395
810
  * (P3 에서 소비처를 커널 어휘로 바꾸면 사라진다.) */
396
811
  const projector = { apply: (e) => kernel.apply(e), snapshot: () => kernel.getSnapshot() };
397
- const inst = { id, domainId, mode: 'live', realityMode: 'mirror', kernel, projector, oee: new oee_accumulator_js_1.OeeAccumulator(), unsub: () => { } };
398
- /* 추정기(실측·거리)도 라이브에 붙인다 — 예측이 상수로 돌지 않게. 기동을 막지 않는다. */
399
- this.installEstimators(kernel, domainId, id, board).catch(err => console.warn('[twin-engine] estimator install failed', err?.message));
812
+ const inst = { id, domainId, mode: 'live', realityMode: 'mirror', kernel, projector, oee: new oee_accumulator_js_1.OeeAccumulator(), spaceId: model?.spaceId, unsub: () => { } };
813
+ /*
814
+ * ── 커널이 **판정으로 낸 사실**도 저널에 남는다 (2026-08-14 실측으로 잡음) ────
815
+ *
816
+ * 라이브는 인입 봉투만 저널에 적고 있었다(`ingestLive`). 그런데 커널은 관측을 접다가 **자기 사실**을
817
+ * 낸다 — 에너지의 수요 구간 마감·피크 경신·감축 제안이 그렇다(`emitOp`). 그것을 구독하는 곳이
818
+ * 없어서 그 사실들이 **커널 안에서 사라졌다**: 표본 48건이 저널에 쌓였는데 구간 마감은 0건이었고,
819
+ * 저널을 읽는 성과 화면의 전력 타일은 영원히 나오지 않았다.
820
+ *
821
+ * sim 은 `runtime.subscribe` 로 같은 일을 한다 — 라이브에만 그 배선이 없었다.
822
+ *
823
+ * **인입의 재방출은 걸러낸다**: `apply()` 는 받은 봉투를 구독자에게 그대로 흘린다(호스트가 두 모드에서
824
+ * 같은 배선을 쓰게 하려고). 그것까지 적으면 인입이 저널에 두 번 들어간다 — 그래서 방금 넣은 것과
825
+ * **같은 객체**인지 보고 건너뛴다(id 비교는 어댑터가 id 를 어떻게 만드는지에 기대게 되어 약하다).
826
+ */
827
+ const applying = new WeakSet();
828
+ inst.applying = applying;
829
+ inst.unsub = kernel.onEvent?.((e) => {
830
+ if (e && typeof e === 'object' && applying.has(e))
831
+ return // 인입의 재방출 — 저널은 인입에서 한 번만
832
+ ;
833
+ (inst.pendingJournal ?? (inst.pendingJournal = [])).push(e);
834
+ /* 커널이 낸 사실도 상태를 바꾼다(피크·마감) — 다음 방송 주기에 실린다. */
835
+ inst.dirty = true;
836
+ this.ensureBroadcastCoalescer();
837
+ }) ?? (() => { });
838
+ /* 추정기(실측·거리)도 라이브에 붙인다 — 예측이 상수로 계산되지 않게. 기동을 막지 않는다. */
839
+ this.installEstimators(kernel, domainId, id, model).catch(err => console.warn('[twin-engine] estimator install failed', err?.message));
400
840
  inst.metrics = { ingestedTotal: 0, broadcastTotal: 0, journaledTotal: 0, ingestRate: 0, broadcastRate: 0, journalRate: 0, backlog: 0, _accIngest: 0, _accBroadcast: 0, _accJournal: 0, _windowStartMs: Date.now() };
401
- this.instances[id] = inst;
402
- delete this.recovered[id];
841
+ this.instances[key] = inst;
842
+ /*
843
+ * **원천이 되풀어 주지 않는 것만 잇는다** (2026-08-18 실측으로 붙임).
844
+ *
845
+ * 미러는 오랫동안 아무것도 이어받지 않았다 — 진실이 원천에 있으니 옳은 판단이었지만, 원천이 **애초에
846
+ * 다시 말해 주지 않는 축**까지 함께 버렸다: 열린 15분 구간의 누적·적산 기준점·관측 이후 최대, 그리고
847
+ * 확인해 둔 신호와 조건이 언제부터인지. 그래서 재기동하면 오류 없이 값이 작아졌다(그 구간의 전력량과
848
+ * 피크가 부팅 이후로만 잡히고, 세 시간째 지속된 경보가 「0초째」가 됐다 — 요금이 걸린 수다).
849
+ *
850
+ * 관측 축(재고·위치·설비)은 **여전히 심지 않는다** — 다음 계측이 정정하고, 심으면 떠난 물건이
851
+ * 되살아난다. 무엇을 넘길지는 `planLiveContinuity` 가 고르고, 어떻게 흡수할지는 커널이 정한다.
852
+ */
853
+ this.seedLiveContinuity(domainId, id, kernel);
854
+ delete this.recovered[key];
403
855
  /* 라이브 바인딩(data 채널) subdomain 필터용 Domain 1회 해석(sim 과 동일). */
404
856
  (0, shell_1.getRepository)(shell_1.Domain).findOne({ where: { id: domainId } }).then(d => (inst.domain = d)).catch(() => { });
405
857
  /* 저널 revision 카운터 시드 — 기존 저널 최대치에서 이어붙임(재기동 시 revision 충돌 방지). 이후 인메모리 증가. */
@@ -407,7 +859,7 @@ class TwinEngine {
407
859
  .findOne({ where: { domain: { id: domainId }, instanceId: id }, order: { revision: 'DESC' } })
408
860
  .then(top => (inst.revision = top?.revision ?? 0))
409
861
  .catch(() => (inst.revision = 0));
410
- this.register(domainId, id, kind, board, 'running', 'mirror').catch(err => console.error('twin register fail', err));
862
+ this.register(domainId, id, kind, model, 'running', 'mirror').catch(err => console.error('twin register fail', err));
411
863
  return inst;
412
864
  }
413
865
  /**
@@ -415,17 +867,19 @@ class TwinEngine {
415
867
  * reference 어댑터가 낸 records → 커널 face2-adapter.ingest → CanonicalEnvelope 를 여기로 밀어넣는다.
416
868
  * (State 채널 델타/저널 결선은 후속 — 스켈레톤은 data(tag) 미러 중심.)
417
869
  */
418
- static ingestLive(id, envelopes) {
419
- const inst = this.instances[id];
870
+ static ingestLive(domainId, id, envelopes) {
871
+ const inst = this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, id)];
420
872
  if (inst?.mode !== 'live' || !inst.projector)
421
873
  return;
874
+ const tIngest = performance.now();
875
+ /* 인입 봉투를 표시해 두고 넣는다 — 커널이 그것을 재방출해도 저널에 두 번 적히지 않게(위 구독 주석). */
422
876
  for (const e of envelopes) {
877
+ if (e && typeof e === 'object')
878
+ inst.applying?.add(e);
423
879
  inst.projector.apply(e);
424
- inst.oee?.apply(e);
425
- } // 관측(projector) + 계산(OEE 누적)
426
- // 저널 결선(라이브도 sim 처럼 이벤트 영속) — 단 이벤트마다 DB write 하면 부하폭발이라 모아뒀다가
427
- // coalescer tick 에서 배치 기록(방송과 동일 주기). 히스토리 노브·타임라인·비즈니스 원장이 이 저널을 읽는다.
428
- ;
880
+ inst.oee?.apply(e); // 관측(projector) + 계산(OEE 누적)
881
+ }
882
+ (0, load_meter_js_1.recordPhase)(inst.load ?? (inst.load = (0, load_meter_js_1.newLoadMeter)()), 'ingest', performance.now() - tIngest);
429
883
  (inst.pendingJournal ?? (inst.pendingJournal = [])).push(...envelopes);
430
884
  if (inst.metrics) {
431
885
  inst.metrics.ingestedTotal += envelopes.length;
@@ -436,6 +890,18 @@ class TwinEngine {
436
890
  inst.dirty = true;
437
891
  this.ensureBroadcastCoalescer();
438
892
  }
893
+ /**
894
+ * 구간 성과 방송은 **없앴다**(2026-08-06). 카드가 `twinKpi` 를 직접 묻는다.
895
+ *
896
+ * 왜: 카드를 여러 단계(공간·트윈·구역·자리·설비)에 붙이려면 방송으로는 태그가 트윈당 1,200개가 되고,
897
+ * **모델에 카드를 하나도 안 놓아도** 30초마다 트윈마다 저널을 접었다. 질의로 바꾸니 보고 있는 카드
898
+ * 수만큼만 들고, 같은 (대상·창·축) 은 클라이언트가 하나로 합친다.
899
+ *
900
+ * 덤으로 질의만 할 수 있는 것이 둘 생겼다 — **과거 시각**(`toTime`)과 **공간 단위 합산**(여러 트윈을
901
+ * 한 번에 접기). 방송 루프는 트윈별이라 둘 다 못 했다.
902
+ *
903
+ * 축을 나눠도 폴드 비용이 같다는 실측이 근거다(`test/kpi-query-bench.test.ts`).
904
+ */
439
905
  /** 방송 병합 주기(ms) — 방송률 상한. 인제스트가 아무리 빨라도 이 주기로만 방송. */
440
906
  static { this.BROADCAST_COALESCE_MS = 200; }
441
907
  /** live 방송 coalescer — dirty 인 live 인스턴스만 주기적으로 1회 방송(entitySigs 로 변경 엔티티만). */
@@ -446,16 +912,19 @@ class TwinEngine {
446
912
  if (typeof this.broadcastTimer.unref === 'function')
447
913
  this.broadcastTimer.unref(); // 종료 비차단
448
914
  }
449
- /** dirty live 인스턴스 방송 flush(주기 tick 또는 명시 호출). 테스트/즉시 방송용으로 public. */
915
+ /**
916
+ * dirty 인스턴스 방송 flush(주기 tick 또는 명시 호출) — **시뮬과 라이브 둘 다.**
917
+ *
918
+ * 예전에는 라이브만 봤다(`mode !== 'live'` 면 건너뜀). 시뮬은 delta 마다 곧바로 방송했고, 그것이
919
+ * 한 tick 에서 수백 번 반복되며 이벤트 루프를 막았다(위 `start()` 주석의 35초 틱). 방송을 모으는
920
+ * 규율은 모드의 성질이 아니라 **채널의 성질**이다 — 최신-상태 채널이면 중간 상태는 보낼 값이 없다.
921
+ */
450
922
  static flushLiveBroadcasts() {
451
- let anyLive = false;
452
923
  const now = Date.now();
453
924
  for (const inst of Object.values(this.instances)) {
454
- if (inst.mode !== 'live')
455
- continue;
456
- anyLive = true;
925
+ const isLive = inst.mode === 'live';
457
926
  // 처리량 계측(④-1) — 창(≥1s)마다 유입/방송/저널률 갱신. dirty 무관(유휴면 0으로 수렴). 부하를 읽는 신호.
458
- const m = inst.metrics;
927
+ const m = isLive ? inst.metrics : undefined;
459
928
  if (m) {
460
929
  const dt = (now - m._windowStartMs) / 1000;
461
930
  if (dt >= 1) {
@@ -477,6 +946,10 @@ class TwinEngine {
477
946
  m.broadcastTotal++;
478
947
  m._accBroadcast++;
479
948
  }
949
+ /* 시뮬의 저널·state 채널은 자기 콜백이 delta 마다 처리한다(사실은 하나도 빠뜨리지 않는다).
950
+ 여기서 모으는 것은 **엔티티 방송**뿐이다 — 화면이 읽는 최신-상태 채널. */
951
+ if (!isLive)
952
+ continue;
480
953
  // ③ 저널 배치 기록 — 모아둔 이벤트에 revision 부여해 벌크 저장(이벤트마다 write 아님).
481
954
  // revision 카운터는 인메모리(startLive 에서 저널 high-water 로 1회 시드) → tick 마다 DB 질의 없음.
482
955
  const batch = inst.pendingJournal;
@@ -489,36 +962,49 @@ class TwinEngine {
489
962
  m._accJournal += batch.length;
490
963
  m.backlog = batch.length;
491
964
  }
492
- this.persistBatch(inst.domainId, inst.id, batch, start).catch(err => console.error('twin live journal fail', err));
965
+ const tJournal = performance.now();
966
+ this.persistBatch(inst.domainId, inst.id, batch, start)
967
+ .then(() => (0, load_meter_js_1.recordPhase)(inst.load ?? (inst.load = (0, load_meter_js_1.newLoadMeter)()), 'journal', performance.now() - tJournal))
968
+ .catch(err => console.error('twin live journal fail', err));
493
969
  }
494
970
  // ② State 채널 방송 — "바뀌었다"는 가벼운 신호만(kind+revision). 맵 구독(subscribeTwinState)은 이 신호에
495
971
  // scheduleRefresh(250ms 디바운스)→pollLive 로 되물어봄. 스냅샷(O(state))은 보는 사람이 물을 때만 1회 계산.
496
972
  // (여기서 payload 로 스냅샷을 실으면 아무도 안 읽는데 tick 마다 통째로 떠서 순수 낭비 — 신호만 보낸다.)
497
- shell_1.pubsub.publish('twin-state', {
498
- twinState: { instanceId: inst.id, kind: 'delta', revision: inst.revision ?? 0 }
499
- });
973
+ this.publishGuarded('twin-state', { twinState: { instanceId: inst.id, kind: 'delta', revision: inst.revision ?? 0 } }, `twin-state:${inst.id}`);
500
974
  }
501
- if (!anyLive && this.broadcastTimer) {
975
+ /* 돌고 있는 인스턴스가 하나도 없으면 tick 을 멈춘다(예전엔 「라이브가 없으면」이었는데, 이제
976
+ 시뮬도 이 flush 에 기대므로 그 조건이면 시뮬 방송이 멈춘 채 남는다). */
977
+ if (!Object.keys(this.instances).length && this.broadcastTimer) {
502
978
  clearInterval(this.broadcastTimer);
503
979
  this.broadcastTimer = undefined;
504
- } // live 없으면 tick 정지
980
+ }
505
981
  }
506
982
  /**
507
983
  * 저널 행 한 줄 — **기록 경로가 둘이라(라이브 벌크·심 단건) 행 모양은 반드시 한 곳에서 만든다.**
508
984
  * 두 곳에 각자 적으면 승격 검색 키가 한쪽에만 채워지고, 반쯤 빈 색인은 "저널에는 있는데
509
985
  * 검색으로는 안 나오는 이벤트" 를 만든다 — 저널에서 가장 나쁜 종류의 결함이다.
510
986
  */
987
+ /** 저널의 시각 축은 날짜다 — 못 읽는 값은 비운다(0 이나 지금으로 위장하지 않는다). */
988
+ static toEventTimeValue(v) {
989
+ if (v instanceof Date)
990
+ return v;
991
+ const t = typeof v === 'string' ? Date.parse(v) : NaN;
992
+ return Number.isNaN(t) ? undefined : new Date(t);
993
+ }
511
994
  static journalRow(repo, domainId, instanceId, e, revision, structureRev) {
512
995
  return repo.create({
513
996
  domain: { id: domainId },
514
997
  instanceId,
515
- tenantId: e?.tenantId,
516
998
  eventType: e?.eventType,
999
+ /* 커널이 커맨드에서 이어 준 값 — 이것이 감사 기록과 저널을 잇는 다리다. */
1000
+ correlationId: e?.correlationId,
517
1001
  revision,
518
1002
  /* **이 사실이 일어난 공장**을 함께 찍는다 — 이것이 없으면 나중에 구조가 바뀌었을 때 이 행을
519
1003
  새 공장에 대고 접게 되고, 그때 없던 설비에서 일이 있었던 것처럼 보인다. */
520
1004
  ...(structureRev === undefined ? {} : { structureRev }),
521
- eventTime: e?.eventTime,
1005
+ /* 커널은 ISO 문자열을 준다. 컬럼은 날짜다 — **여기서 옮긴다.** 문자열을 그대로 넣으면
1006
+ 드라이버가 제 형식으로 정규화하지 않아, 나중에 날짜로 거는 질의에 안 걸린다. */
1007
+ eventTime: this.toEventTimeValue(e?.eventTime),
522
1008
  ...(0, twin_event_keys_js_1.twinEventKeys)(e),
523
1009
  payload: e
524
1010
  });
@@ -531,7 +1017,7 @@ class TwinEngine {
531
1017
  */
532
1018
  static { this.structureRevCache = {}; }
533
1019
  static async structureRevOf(domainId, instanceId) {
534
- const key = `${domainId}:${instanceId}`;
1020
+ const key = (0, runtime_key_js_1.runtimeKey)(domainId, instanceId);
535
1021
  const cached = this.structureRevCache[key];
536
1022
  if (cached !== undefined)
537
1023
  return cached;
@@ -548,7 +1034,13 @@ class TwinEngine {
548
1034
  await repo.save(rows, { chunk: 500 });
549
1035
  }
550
1036
  /** 레지스트리 upsert(도메인+instanceId 유니크). status 인자로 provision(stopped)/start(running) 공용. */
551
- static async register(domainId, instanceId, kind, board, status = 'running', realityMode) {
1037
+ static async register(domainId, instanceId, kind, model, status = 'running', realityMode, origin,
1038
+ /*
1039
+ * 사람이 부르는 이름과 **누가 했나** — 업무키를 나눠 둔 대가로 이름을 함께 실어야 한다.
1040
+ * 사람 없는 경로(부팅 자동 프로비저닝·복구)는 `actor` 를 주지 않는다 — 아무 사용자를 적으면
1041
+ * 감사 기록이 거짓이 된다.
1042
+ */
1043
+ meta) {
552
1044
  const repo = (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance);
553
1045
  const existing = await repo.findOne({ where: { domain: { id: domainId }, instanceId } });
554
1046
  await repo.save(repo.create({
@@ -556,50 +1048,151 @@ class TwinEngine {
556
1048
  domain: { id: domainId },
557
1049
  instanceId,
558
1050
  kind,
559
- board,
560
- // 인스턴스↔공간 1급 링크(space #3) — board.spaceId/areaId 를 컬럼으로 승격(dual-write). board JSON 도 유지(커널·복구용).
561
- spaceId: board?.spaceId ?? existing?.spaceId,
562
- areaId: board?.areaId ?? existing?.areaId,
563
- // 현실 출처 선언(§0 ①) — 명시값 우선, 없으면 기존값 보존(재프로비전이 선언을 지우지 않게).
564
- realityMode: realityMode ?? existing?.realityMode ?? undefined,
1051
+ model,
1052
+ // 인스턴스↔공간 1급 링크(space #3) — model.spaceId/areaId 를 컬럼으로 승격(dual-write). model JSON 도 유지(커널·복구용).
1053
+ spaceId: model?.spaceId ?? existing?.spaceId,
1054
+ areaId: model?.areaId ?? existing?.areaId,
1055
+ /* 현실 출처 선언(§0 ①) — 명시값 우선, 없으면 기존값 보존(재프로비전이 선언을 지우지 않게).
1056
+ 둘 다 없으면 여기서 **각인한다**. 컬럼을 비워 두면 읽는 자리마다 기본값을 고르게 되고,
1057
+ 그러면 같은 트윈이 부르는 곳에 따라 다르게 재기동한다. 선언은 저장소에서 항상 명시적이다. */
1058
+ realityMode: realityMode ?? existing?.realityMode ?? exports.DEFAULT_REALITY_MODE,
1059
+ /* 용도도 각인한다. 벤치로 뒤집는 것은 `setPurpose` 하나뿐이므로 기존값을 반드시 보존한다
1060
+ — 여기서 덮으면 재프로비전이 벤치 사본을 운영 트윈으로 되돌린다. */
1061
+ purpose: existing?.purpose ?? 'operational',
1062
+ /* **다시 읽는 방법**을 각인한다. 명시값 우선, 없으면 기존값 보존 — 원천을 모르는 호출이
1063
+ 한 번 지나가면서 이미 알던 것을 지워 버리면, 그 트윈은 다시 읽을 수 없는 트윈이 된다. */
1064
+ origin: origin ?? existing?.origin ?? null,
1065
+ /* 이름은 **덮지 않고 채운다** — 사용자가 고친 이름을 재프로비전이 되돌리면 안 된다. */
1066
+ name: existing?.name ?? meta?.name ?? null,
1067
+ description: existing?.description ?? meta?.description ?? null,
1068
+ /* 만든 사람은 처음 한 번만. 고친 사람은 사람이 한 경우에만 갱신한다. */
1069
+ ...(existing ? {} : meta?.actor ? { creator: { id: meta.actor.id } } : {}),
1070
+ ...(meta?.actor ? { updater: { id: meta.actor.id } } : {}),
565
1071
  status
566
1072
  }));
567
1073
  }
568
1074
  /**
569
- * 라이브 구조 변이(resource.add 등)를 저장된 board 에 반영 — 런타임 커널의 무버를 registry board.equipment 에 동기.
570
- * 이게 없으면 런타임엔 추가돼도(상태·저널엔 반영) 저장 board 는 원본이라 프로비저닝 편집기·재기동(loadBoard)이
571
- * 추가분을 잃는다. 기존 board.equipment 항목은 보존(homeLocation 유지)하고 새 id 만 append(추가 시점 location=homeLocation).
1075
+ * 라이브 구조 변이(resource.add 등)를 저장된 model 에 반영 — 런타임 커널의 무버를 registry model.equipment 에 동기.
1076
+ * 이게 없으면 런타임엔 추가돼도(상태·저널엔 반영) 저장 model 는 원본이라 프로비저닝 편집기·재기동(loadTwinModel)이
1077
+ * 추가분을 잃는다. 기존 model.equipment 항목은 보존(homeLocation 유지)하고 새 id 만 append(추가 시점 location=homeLocation).
572
1078
  * 좌표(layout)만 다루는 register 와 달리 equipment 집합을 갱신하나, 재프로비전(purge)이 아니라 in-place 갱신이라
573
1079
  * 저널은 보존된다(추가는 이미 equipment 델타로 저널됨 → replay 는 id-keyed upsert 라 이중계산 없음).
574
1080
  */
575
1081
  static async syncBoardEquipment(domainId, instanceId) {
576
- const inst = this.instances[instanceId];
1082
+ const inst = this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, instanceId)];
577
1083
  const snap = inst?.kernel?.getSnapshot?.();
578
1084
  if (!snap?.equipment)
579
1085
  return;
580
1086
  const repo = (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance);
581
1087
  const reg = await repo.findOne({ where: { domain: { id: domainId }, instanceId } });
582
- if (!reg?.board)
1088
+ if (!reg?.model)
583
1089
  return;
584
- const board = reg.board;
585
- const known = new Set((board.equipment ?? []).map(m => m.id));
1090
+ const model = reg.model;
1091
+ const known = new Set((model.equipment ?? []).map(m => m.id));
586
1092
  const added = snap.equipment
587
1093
  .filter((m) => !known.has(m.id))
588
1094
  .map((m) => ({ id: m.id, kind: m.kind, homeLocation: m.location }));
589
1095
  if (!added.length)
590
1096
  return;
591
- board.equipment = [...(board.equipment ?? []), ...added];
592
- reg.board = board;
1097
+ model.equipment = [...(model.equipment ?? []), ...added];
1098
+ reg.model = model;
593
1099
  await repo.save(reg);
594
1100
  }
595
1101
  /**
596
- * 프로비저닝 — 레지스트리에 구조(board)를 등록만 하고 기동하지 않음(status='stopped').
1102
+ * 프로비저닝 — 레지스트리에 구조(model)를 등록만 하고 기동하지 않음(status='stopped').
597
1103
  * 재프로비전 시 구조 시그니처가 바뀌면(노드·무버 집합/속성 변경) 기존 저널을 purge 한다(ADR-0015):
598
- * board 는 replay 의 마스터라 구조가 바뀌면 과거 이벤트의 전제가 깨진다. 좌표(layout)만 바뀌면 저널 보존.
1104
+ * model 는 replay 의 마스터라 구조가 바뀌면 과거 이벤트의 전제가 깨진다. 좌표(layout)만 바뀌면 저널 보존.
1105
+ */
1106
+ /**
1107
+ * 실행 중이면 구조를 교체하지 않는다 — **판정 문장을 한 곳에 둔다.**
1108
+ *
1109
+ * 인제스트는 전량 교체라, 이벤트를 접고 있는 커널 밑에서 바닥을 바꾸는 셈이 된다. 지금은 거절이
1110
+ * 유일한 답이지만 최종형은 아니다(`adoptStructure` 배선). 두 곳에서 같은 문장으로 거절해야
1111
+ * 나중에 이 규칙을 걷어낼 때 걷어낼 것이 하나로 보인다.
599
1112
  */
600
- static async provision(domainId, instanceId, kind, board, comment) {
601
- if (this.instances[instanceId])
602
- throw new Error(`instance "${instanceId}" is running — stop before re-provisioning`);
1113
+ static assertNotRunning(domainId, instanceId) {
1114
+ if (!this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, instanceId)])
1115
+ return;
1116
+ /*
1117
+ * **거절도 번역돼야 한다.** 이 문장은 던져져서 리졸버의 `catch` 를 지나 화면 토스트에 그대로
1118
+ * 떴다 — 다섯 언어 제품에서 영어 한 줄이 사용자에게 보였다(2026-08-14 실측).
1119
+ *
1120
+ * 그래서 코드와 파라미터를 예외에 실어 보낸다(`ImportSpaceRefusal` 과 같은 규약: 영어 문장은
1121
+ * canonical 이고 로그·폴백으로만 쓰인다). 이유가 코드로 오면 화면이 옮길 수 있다.
1122
+ */
1123
+ const err = new Error(`instance "${instanceId}" is running — stop before re-provisioning`);
1124
+ err.code = 'twin-running';
1125
+ err.params = { instanceId };
1126
+ throw err;
1127
+ }
1128
+ /**
1129
+ * 돌면서 공장을 전환한다 — **미러 전용.**
1130
+ *
1131
+ * 미러가 비추는 현실은 안 멈춘다. 설비 한 대가 늘었다고 트윈을 멈췄다 세우면 그 사이의 사실을
1132
+ * 잃고, 라이브에서 유실은 곧 거짓이다. 그래서 미러는 **동작 중에** 새 구조를 받는다.
1133
+ *
1134
+ * 시뮬레이션은 여기 오지 않는다. 조건이 바뀐 실험은 다른 실험이므로 멈추고 다시 세우는 것이
1135
+ * 옳다 — 커널이 그렇게 거절한다(`FlowEngine.adoptStructure`).
1136
+ *
1137
+ * 세 가지가 **함께** 일어나야 한다. 하나라도 빠지면 층이 어긋난다:
1138
+ * ① 리비전 — 이 시점 이후의 이벤트가 새 번호를 달고 다닌다(재생이 마디를 나눌 수 있게)
1139
+ * ② 저장 model·구조 행 — 조회가 새 구조를 본다
1140
+ * ③ 커널 — 지금 접히는 이벤트가 새 구조 위에서 접힌다
1141
+ */
1142
+ static async adoptStructure(domainId, instanceId, model, comment, origin) {
1143
+ const inst = this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, instanceId)];
1144
+ if (!inst)
1145
+ throw new Error(`instance "${instanceId}" is not running — provision it instead of adopting`);
1146
+ if (inst.mode !== 'live')
1147
+ throw new Error(`instance "${instanceId}" is a simulation — stop it and re-provision (a changed experiment is a different experiment)`);
1148
+ const reg = await (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance).findOne({ where: { domain: { id: domainId }, instanceId } });
1149
+ if (!reg)
1150
+ throw new Error(`instance "${instanceId}" is running but not registered — refusing to adopt into an unknown twin`);
1151
+ const rev = await this.recordStructure(domainId, instanceId, model, comment);
1152
+ await this.register(domainId, instanceId, reg.kind, model, 'running', undefined, origin);
1153
+ /* 커널을 **마지막에** 전환한다 — 저장이 실패하면 메모리만 새 구조가 되어, 재기동하면 조용히
1154
+ 옛 구조로 돌아간다(고치기 어려운 어긋남이다). */
1155
+ const shift = inst.kernel.adoptStructure(model);
1156
+ /*
1157
+ * **공정 명세·현장이 정한 시간도 함께 싣는다** — 커널의 구조 전환은 자리·설비를 갈지만, 공정 시간은
1158
+ * 호스트가 실어 주는 것이므로(`model.localDurations`) 여기서 다시 부르지 않으면 돌고 있는 미러는
1159
+ * 재기동할 때까지 옛 시간으로 돈다(화면은 「넣었습니다」라고 말한 값이다).
1160
+ */
1161
+ this.applyOperations(inst.kernel, model, instanceId);
1162
+ /*
1163
+ * **투영 행도 새 구조를 따른다** (2026-08-18 실측으로 붙임).
1164
+ *
1165
+ * 행(`twin_locations`·`twin_equipment`)은 구조의 캐시다. 그런데 이 경로는 커널만 갈고 행은 그대로
1166
+ * 두었다 — 돌고 있는 미러에 값을 선언하면 커널은 새 값으로 계산하는데 **항목 패널은 옛 행을 보여
1167
+ * 준다**(넣은 값이 화면에서 보이지 않는다). 구조가 바뀐 순간이 곧 캐시를 다시 그릴 순간이다.
1168
+ *
1169
+ * 실패는 흡수한다: 투영이 막혀도(예: 모델에 중복 id) 커널은 이미 새 구조로 돌고 있으므로 그 사실을
1170
+ * 되돌리지 않는다 — 다만 조용히 넘기지 않고 말한다.
1171
+ */
1172
+ await (0, project_structure_js_1.projectStructure)(domainId, instanceId, model, instanceId).catch((err) => console.warn(`[twin-engine] "${instanceId}" adopted a new structure but its projected rows were not refreshed — ${err?.message ?? err}`));
1173
+ /*
1174
+ * **구조가 바뀐 순간이 상태가 바뀐 순간이다** — 그러니 방송한다.
1175
+ *
1176
+ * ── 무엇이 났나 (2026-08-18) ────────────────────────────────────────────
1177
+ * 구조 전환은 커널만 갈고 조용히 끝났다. 그런데 화면이 보는 것 상당수가 구조에서 파생된다 —
1178
+ * 계약 대비 판정, 주목 신호, 자리 색. 현장이 계약을 고쳐 선언한 순간 조건이 성립하는데도, 상태
1179
+ * 방송이 없어서 지도 레일은 **다음 계측 표본이 올 때까지** 옛 화면을 들고 있었다(그 사이 헤더
1180
+ * 배지는 4초 폴링으로 먼저 알아, 「배지엔 있고 목록엔 없는」 어긋난 화면이 실제로 보였다).
1181
+ *
1182
+ * 새 방송 경로를 만들지 않는다: dirty 를 세워 **이미 있는 병합 규율**(200ms)에 얹는다. 구조 전환은
1183
+ * 드물지만, 여러 트윈에 잇달아 들어올 수 있고(현장 일괄 선언) 그때도 방송률 상한은 지켜야 한다.
1184
+ */
1185
+ inst.dirty = true;
1186
+ this.ensureBroadcastCoalescer();
1187
+ return { rev, ...shift };
1188
+ }
1189
+ static async provision(domainId, instanceId, kind, model, comment, origin,
1190
+ /** 이름·저자 — 업무키를 나눠 둔 대가로 이름을 함께 남긴다(`register` 의 `meta` 그대로). */
1191
+ meta) {
1192
+ this.assertNotRunning(domainId, instanceId);
1193
+ /* 종류를 **저장하기 전에** 검증한다. 나중에 기동할 때 걸리면 원인이 프로비저닝에서 멀어지고,
1194
+ 그 사이 레지스트리에는 돌릴 수 없는 트윈이 앉아 있다. */
1195
+ kernelFor(kind);
603
1196
  const repo = (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance);
604
1197
  const existing = await repo.findOne({ where: { domain: { id: domainId }, instanceId } });
605
1198
  /*
@@ -611,10 +1204,10 @@ class TwinEngine {
611
1204
  * 하거나** 둘뿐이었고, 그래서 공장을 고칠 때마다 이력을 버려야 했다.
612
1205
  *
613
1206
  * 이제 셋째 길로 간다: 바뀐 구조를 **새 리비전**으로 남기고, 앞으로 쓰이는 이벤트가 그 번호를
614
- * 달고 다닌다. 재생은 구조가 바뀌는 지점에서 갈아탄 뒤 이어 접는다(`replaySegments`).
1207
+ * 달고 다닌다. 재생은 구조가 바뀌는 지점에서 전환한 뒤 이어 접는다(`replaySegments`).
615
1208
  */
616
- await this.recordStructure(domainId, instanceId, board, comment);
617
- await this.register(domainId, instanceId, kind, board, existing?.status === 'running' ? 'stopped' : existing?.status ?? 'stopped');
1209
+ await this.recordStructure(domainId, instanceId, model, comment);
1210
+ await this.register(domainId, instanceId, kind, model, existing?.status === 'running' ? 'stopped' : existing?.status ?? 'stopped', undefined, origin, meta);
618
1211
  }
619
1212
  /**
620
1213
  * 이 구조를 리비전으로 남기고 그 번호를 돌려준다 — **바뀌었을 때만** 새 번호가 생긴다.
@@ -622,9 +1215,9 @@ class TwinEngine {
622
1215
  * 프로비저닝은 부팅마다 다시 도는데, 그때마다 리비전이 늘면 이력이 뜻 없는 마디로 잘게 쪼개진다.
623
1216
  * 그래서 **구조 서명이 같으면 있던 리비전을 그대로 쓴다.**
624
1217
  */
625
- static async recordStructure(domainId, instanceId, board, comment) {
1218
+ static async recordStructure(domainId, instanceId, model, comment) {
626
1219
  const repo = (0, shell_1.getRepository)(twin_structure_js_1.TwinStructure);
627
- const signature = this.structureFingerprint(board);
1220
+ const signature = this.structureFingerprint(model);
628
1221
  const latest = await repo.findOne({ where: { domain: { id: domainId }, instanceId }, order: { rev: 'DESC' } });
629
1222
  /*
630
1223
  * **저장된 지문이 아니라 저장된 공장과 비교한다.**
@@ -633,22 +1226,22 @@ class TwinEngine {
633
1226
  * 것이라 무엇과도 안 맞는다. 그러면 **아무것도 안 바뀐 트윈들이 전부 "구조가 바뀌었다"** 로
634
1227
  * 기록된다 — 실제로 그렇게 됐고, 재기동 한 번에 리비전이 통째로 하나씩 늘었다.
635
1228
  *
636
- * 그래서 안 맞을 때 한 번 더 묻는다: 저장된 **보드**로 지문을 다시 계산하면 같은가? 같다면
1229
+ * 그래서 안 맞을 때 한 번 더 묻는다: 저장된 **모델**로 지문을 다시 계산하면 같은가? 같다면
637
1230
  * 공장은 그대로이고 지문 표기만 낡은 것이니, 리비전을 만들지 않고 표기만 고친다.
638
1231
  */
639
- if (latest && latest.signature !== signature && this.structureFingerprint(latest.board) === signature) {
1232
+ if (latest && latest.signature !== signature && this.structureFingerprint(latest.model) === signature) {
640
1233
  latest.signature = signature;
641
1234
  await repo.save(latest);
642
1235
  }
643
1236
  if (latest?.signature === signature) {
644
- this.structureRevCache[`${domainId}:${instanceId}`] = latest.rev;
1237
+ this.structureRevCache[(0, runtime_key_js_1.runtimeKey)(domainId, instanceId)] = latest.rev;
645
1238
  return latest.rev;
646
1239
  }
647
1240
  const rev = (latest?.rev ?? 0) + 1;
648
- await repo.save(repo.create({ domain: { id: domainId }, instanceId, rev, signature, board: board, ...(comment ? { comment } : {}) }));
649
- this.structureRevCache[`${domainId}:${instanceId}`] = rev;
1241
+ await repo.save(repo.create({ domain: { id: domainId }, instanceId, rev, signature, model: model, ...(comment ? { comment } : {}) }));
1242
+ this.structureRevCache[(0, runtime_key_js_1.runtimeKey)(domainId, instanceId)] = rev;
650
1243
  /* 구조가 바뀌면 재구성 캐시는 옛 공장의 것이다 — 버린다(지우는 건 캐시뿐, 사실은 남는다). */
651
- delete this.recovered[instanceId];
1244
+ delete this.recovered[(0, runtime_key_js_1.runtimeKey)(domainId, instanceId)];
652
1245
  if (latest)
653
1246
  console.info(`[twin-engine] "${instanceId}" structure changed → revision ${rev} (history kept; older events stay under revision ${latest.rev}).`);
654
1247
  return rev;
@@ -657,7 +1250,7 @@ class TwinEngine {
657
1250
  * 이 트윈이 거쳐 온 구조들 — **무엇이 언제 달라졌나.**
658
1251
  *
659
1252
  * 리비전은 그 시절 공장을 통째로 담지만(재생에 필요하다), 사람이 보고 싶은 것은 통째가 아니라
660
- * 차이다. 보드는 빼고 **차이 요약만** 내보낸다 — 62KB 짜리 보드를 화면에 실어 보낼 이유가 없다.
1253
+ * 차이다. 모델은 빼고 **차이 요약만** 내보낸다 — 62KB 짜리 보드를 화면에 실어 보낼 이유가 없다.
661
1254
  */
662
1255
  static async structureHistory(domainId, instanceId) {
663
1256
  const revs = await (0, shell_1.getRepository)(twin_structure_js_1.TwinStructure).find({ where: { domain: { id: domainId }, instanceId }, order: { rev: 'ASC' } });
@@ -682,15 +1275,15 @@ class TwinEngine {
682
1275
  createdAt: r.createdAt,
683
1276
  ...(r.comment ? { comment: r.comment } : {}),
684
1277
  events: (counts.get(r.rev) ?? 0) + (r.rev === oldest ? legacy : 0),
685
- diff: (0, structure_diff_js_1.diffStructures)(i === 0 ? undefined : revs[i - 1].board, r.board)
1278
+ diff: (0, structure_diff_js_1.diffStructures)(i === 0 ? undefined : revs[i - 1].model, r.model)
686
1279
  }));
687
1280
  }
688
1281
  /** 지금 쓰이는 구조 리비전 — 이벤트에 찍을 번호. 아직 없으면 기록하며 만든다. */
689
- static async currentStructureRev(domainId, instanceId, board) {
1282
+ static async currentStructureRev(domainId, instanceId, model) {
690
1283
  const latest = await (0, shell_1.getRepository)(twin_structure_js_1.TwinStructure).findOne({ where: { domain: { id: domainId }, instanceId }, order: { rev: 'DESC' } });
691
1284
  if (latest)
692
1285
  return latest.rev;
693
- return board ? this.recordStructure(domainId, instanceId, board) : undefined;
1286
+ return model ? this.recordStructure(domainId, instanceId, model) : undefined;
694
1287
  }
695
1288
  /** 구조 동일성 지문 — 좌표(layout) 등 뷰 관심사는 제외하고 커널이 보는 위상·용량·무버만. */
696
1289
  /**
@@ -700,27 +1293,28 @@ class TwinEngine {
700
1293
  * 길이를 강제하지 않아 그냥 들어가지만 **Postgres 는 거기서 터진다** — 개발에서는 멀쩡하고
701
1294
  * 운영에서만 죽는 종류의 실패다. 비교에만 쓰는 값이므로 해시로 충분하다.
702
1295
  */
703
- static structureFingerprint(board) {
704
- return (0, node_crypto_1.createHash)('sha256').update(this.structureSignature(board)).digest('hex');
1296
+ static structureFingerprint(model) {
1297
+ return (0, node_crypto_1.createHash)('sha256').update(this.structureSignature(model)).digest('hex');
705
1298
  }
706
- static structureSignature(board) {
707
- const locations = [...(board.locations ?? [])]
1299
+ static structureSignature(model) {
1300
+ const locations = [...(model.locations ?? [])]
708
1301
  .map(n => `${n.id}:${n.type}:${n.capacity}`)
709
1302
  .sort()
710
1303
  .join('|');
711
- const equipment = [...(board.equipment ?? [])]
1304
+ const equipment = [...(model.equipment ?? [])]
712
1305
  .map(m => `${m.id}:${m.kind}:${m.homeLocation}`)
713
1306
  .sort()
714
1307
  .join('|');
715
1308
  return `N[${locations}]M[${equipment}]`;
716
1309
  }
717
- /** 레지스트리 board 로 기동(프로비전된 인스턴스 start). board 인자 없이 저장된 구조로 재기동. */
1310
+ /** 레지스트리 model 로 기동(프로비전된 인스턴스 start). model 인자 없이 저장된 구조로 재기동. */
718
1311
  static async startFromRegistry(domainId, instanceId, realityMode) {
719
- if (this.instances[instanceId])
720
- return this.instances[instanceId];
1312
+ const key = (0, runtime_key_js_1.runtimeKey)(domainId, instanceId);
1313
+ if (this.instances[key])
1314
+ return this.instances[key];
721
1315
  const reg = await (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance).findOne({ where: { domain: { id: domainId }, instanceId } });
722
- if (!reg?.board)
723
- throw new Error(`instance "${instanceId}" not provisioned (no board)`);
1316
+ if (!reg?.model)
1317
+ throw new Error(`instance "${instanceId}" not provisioned (no model)`);
724
1318
  /*
725
1319
  * 웜스타트 재료를 **여기서 확실히 확보한다.**
726
1320
  * `start()` 는 동기라 스스로 캐시를 읽을 수 없어서 `recovered` 에 미리 담겨 있기를 기대하는데,
@@ -728,22 +1322,22 @@ class TwinEngine {
728
1322
  * 어떤 날은 조용히 빈 채로 뜬다 — 재현되지 않는 결함이 가장 나쁘다.
729
1323
  * 체크포인트 캐시 우선(O(1) + 라이브 파생상태 보존), 없으면 저널 replay 폴백(부팅과 같은 순서).
730
1324
  */
731
- if (!this.recovered[instanceId] && reg.purpose !== 'bench') {
1325
+ if (!this.recovered[key] && reg.purpose !== 'bench') {
732
1326
  const cached = await this.loadSnapshot(domainId, instanceId).catch(() => null);
733
1327
  if (cached?.state) {
734
- this.recovered[instanceId] = { revision: cached.revision, state: cached.state };
1328
+ this.recovered[key] = { revision: cached.revision, state: cached.state };
735
1329
  }
736
1330
  else {
737
1331
  const state = await this.recover(domainId, instanceId).catch(() => null);
738
1332
  if (state)
739
- this.recovered[instanceId] = { revision: state.revision, state };
1333
+ this.recovered[key] = { revision: state.revision, state };
740
1334
  }
741
1335
  }
742
1336
  /*
743
1337
  * 저널에 남아 있는 마지막 번호 — **모드와 무관하게** 이것을 이어 센다.
744
1338
  *
745
1339
  * 저널을 초기화하고 기동하는 모드(sim-experiment)라면 이 값이 0이라 아무 영향이 없다. 규칙을
746
- * 모드별로 가르지 않는 이유: "저널이 비어 있지 않으면 그 뒤부터" 하나면 어느 모드에서도
1340
+ * 모드별로 구분하지 않는 이유: "저널이 비어 있지 않으면 그 뒤부터" 하나면 어느 모드에서도
747
1341
  * 겹칠 수 없고, 모드가 늘어도 이 자리를 다시 손볼 일이 없다.
748
1342
  */
749
1343
  const last = await (0, shell_1.getRepository)(twin_event_js_1.TwinEvent)
@@ -752,10 +1346,13 @@ class TwinEngine {
752
1346
  .where('e.domain = :domainId', { domainId })
753
1347
  .andWhere('e.instanceId = :instanceId', { instanceId })
754
1348
  .getRawOne();
755
- return this.start(instanceId, domainId, reg.kind ?? 'wms', reg.board, realityMode ?? reg.realityMode ?? undefined, reg.purpose ?? undefined, Number(last?.max ?? 0) || 0);
1349
+ return this.start(instanceId, domainId,
1350
+ /* 커널 종류·현실 선언은 레지스트리에 반드시 있다(둘 다 NOT NULL). 예전에는 `?? 'wms'` 로
1351
+ 메웠는데, 그건 YMS/MES 트윈을 **조용히 WMS 로 부팅**시키는 길이었다 — 오류 없이 다른 공장이 뜬다. */
1352
+ reg.kind, reg.model, realityMode ?? reg.realityMode, reg.purpose, Number(last?.max ?? 0) || 0);
756
1353
  }
757
1354
  /**
758
- * 선언 기반 부팅(§0 프레임 ① → 부팅 거동 매핑) — 트윈이 선언한 realityMode 에 따라 재기동 방식을 가른다.
1355
+ * 선언 기반 부팅(§0 프레임 ① → 부팅 거동 매핑) — 트윈이 선언한 realityMode 에 따라 재기동 방식을 구분한다.
759
1356
  * 부팅 경로를 한 곳에 모아 "런타임 ≠ 현실" 범주오류를 코드로 강제한다.
760
1357
  * - 'mirror' : 현실=외부 실물 → startLive(재동기). 이벤트는 어댑터 ingest 로 유입, 커널 tick 없음.
761
1358
  * - 'sim-world' : 생성 타임라인 지속 → 저널 보존 + resume(현실 이어감).
@@ -767,9 +1364,9 @@ class TwinEngine {
767
1364
  static async bootDeclared(domainId, instanceId, mode = exports.DEFAULT_REALITY_MODE) {
768
1365
  if (mode === 'mirror') {
769
1366
  const reg = await (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance).findOne({ where: { domain: { id: domainId }, instanceId } });
770
- if (!reg?.board)
771
- throw new Error(`instance "${instanceId}" not provisioned (no board)`);
772
- return this.startLive(instanceId, domainId, reg.kind ?? 'wms', reg.board);
1367
+ if (!reg?.model)
1368
+ throw new Error(`instance "${instanceId}" not provisioned (no model)`);
1369
+ return this.startLive(instanceId, domainId, reg.kind, reg.model);
773
1370
  }
774
1371
  if (mode === 'sim-world') {
775
1372
  /*
@@ -797,58 +1394,131 @@ class TwinEngine {
797
1394
  */
798
1395
  static async resetJournal(domainId, instanceId) {
799
1396
  await (0, shell_1.getRepository)(twin_event_js_1.TwinEvent).delete({ domain: { id: domainId }, instanceId });
800
- delete this.recovered[instanceId];
1397
+ delete this.recovered[(0, runtime_key_js_1.runtimeKey)(domainId, instanceId)];
801
1398
  }
802
1399
  /** 삭제 — 정지 + 레지스트리 삭제 + 저널 purge(domain 스코프). */
803
1400
  static async remove(domainId, instanceId) {
804
- await this.stop(instanceId);
805
- delete this.recovered[instanceId];
1401
+ await this.stop(domainId, instanceId);
1402
+ this.forgetInstance(domainId, instanceId);
806
1403
  await (0, shell_1.getRepository)(twin_event_js_1.TwinEvent).delete({ domain: { id: domainId }, instanceId });
807
1404
  await (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance).delete({ domain: { id: domainId }, instanceId });
808
1405
  }
1406
+ /**
1407
+ * 이 트윈에 대해 **메모리에 남은 것을 전부 잊는다** — 지움의 한 자리.
1408
+ *
1409
+ * 캐시가 라이프사이클과 어긋나 있었다: 저널·등록부는 지우면서 인스턴스별 캐시는 남겨, 삭제된 트윈의
1410
+ * 항목이 **서버 재기동까지 살아 있었다.** 항목 하나가 하루치 KPI 그룹을 물고 있으므로 잊지 않으면
1411
+ * 지운 트윈이 계속 메모리를 차지한다. TTL 은 값이 낡는 것을 막을 뿐 **없어진 주인을 지우지 않는다.**
1412
+ *
1413
+ * 잊을 것을 여기 모아 두는 이유: 캐시를 새로 만드는 사람이 지우는 자리를 찾아 헤매지 않게 한다.
1414
+ * 새 인스턴스별 캐시를 만들면 **이 함수에 한 줄을 더한다** — 그러지 않으면 같은 누수가 다시 생긴다.
1415
+ */
1416
+ static forgetInstance(domainId, instanceId) {
1417
+ const key = (0, runtime_key_js_1.runtimeKey)(domainId, instanceId);
1418
+ delete this.recovered[key];
1419
+ this.measuredCache.delete(key);
1420
+ delete this.structureRevCache[key];
1421
+ }
809
1422
  /** 관리 목록 — domain 의 등록 인스턴스 전체(라이브 여부·최신 저널 revision·노드/무버 수 포함). */
810
1423
  static async list(domainId) {
811
1424
  const rows = await (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance).find({ where: { domain: { id: domainId } } });
1425
+ /*
1426
+ * **현장 이름을 함께 낸다** — 목록이 `spaceId` 만 내보내서 화면이 이름을 따로 조회하고 있었다.
1427
+ * 그 조회(`twinSpaces`)는 공간마다 카운트 쿼리를 도는 N+1 이라 느리고, 그 사이 화면은 **id 를
1428
+ * 이름처럼** 보여 준다(2026-08-13 관측: 「현장 crew-probe-site」). 한 번에 읽어 map 으로 붙이면
1429
+ * 왕복도 줄고 그 깜빡임도 사라진다. 이름이 없으면 **비운다** — id 를 이름으로 베끼지 않는다.
1430
+ */
1431
+ const spaceNameOf = new Map((await (0, shell_1.getRepository)(twin_space_js_1.TwinSpace).find({ where: { domain: { id: domainId } } })).map(s => [s.spaceId, s.name]));
1432
+ /*
1433
+ * **최신 리비전은 한 번에 묻는다.**
1434
+ *
1435
+ * 트윈마다 `findOne(order revision DESC)` 을 돌고 있었다 — 13개면 질의 13번이고, 트윈이 늘면
1436
+ * 그대로 자란다. 이 목록은 트윈 관리·현장 구성·엔티티 패널이 모두 읽는 자리다.
1437
+ * 한 번의 그룹 질의로 바꾼다(같은 모양의 선례가 이 파일에 이미 있다: structureRev 집계).
1438
+ */
1439
+ const tipOfInstance = new Map();
1440
+ try {
1441
+ const tips = await (0, shell_1.getRepository)(twin_event_js_1.TwinEvent)
1442
+ .createQueryBuilder('e')
1443
+ .select('e.instanceId', 'instanceId')
1444
+ .addSelect('MAX(e.revision)', 'revision')
1445
+ .where('e.domain = :domainId', { domainId })
1446
+ .groupBy('e.instanceId')
1447
+ .getRawMany();
1448
+ for (const t of tips)
1449
+ if (t?.instanceId != null)
1450
+ tipOfInstance.set(String(t.instanceId), Number(t.revision) || 0);
1451
+ }
1452
+ catch (err) {
1453
+ /* 집계가 실패하면 **0 으로 메우지 않는다** — 리비전 0 은 "아직 아무 일도 없었다" 는 사실 주장이다.
1454
+ 비워 두면 아래에서 `?? 0` 이 아니라 undefined 로 남고, 화면은 그것을 "모름" 으로 그린다. */
1455
+ console.error('[twin-engine] latest revision aggregate failed', err?.message ?? err);
1456
+ }
812
1457
  const out = [];
813
1458
  for (const r of rows) {
814
- const board = r.board ?? { locations: [], equipment: [] };
815
- const last = await (0, shell_1.getRepository)(twin_event_js_1.TwinEvent).findOne({
816
- where: { domain: { id: domainId }, instanceId: r.instanceId },
817
- order: { revision: 'DESC' }
818
- });
1459
+ const model = r.model ?? { locations: [], equipment: [] };
819
1460
  out.push({
820
1461
  instanceId: r.instanceId,
1462
+ /*
1463
+ * **이름을 함께 낸다.** 업무키(`instanceId`)만 내보내고 있어서 목록이 `crew-two` 만 보였다 —
1464
+ * 업무키를 나눠 둔 설계에서는 이름을 같이 실어야 그 나눔이 값을 한다.
1465
+ * 없으면 `undefined` 다(id 를 베끼지 않는다 — 화면이 이름 없음을 알아볼 수 있어야 한다).
1466
+ */
1467
+ name: r.name ?? undefined,
1468
+ description: r.description ?? undefined,
821
1469
  kind: r.kind,
822
1470
  status: r.status,
823
- spaceId: r.spaceId, // co-location: 같은 spaceId 인스턴스들이 한 공간(공장) 공유 — 공간뷰 집약 키(G7)
824
- realityMode: r.realityMode ?? exports.DEFAULT_REALITY_MODE, // 현실 출처 선언(§0 ①) — mirror/sim-world/sim-experiment
825
- purpose: r.purpose ?? 'operational', // 운영 vs 벤치 사본(1급 구별 — 이름 접두사 아님)
1471
+ spaceId: r.spaceId, // co-location: 같은 spaceId 인스턴스들이 한 현장 공유 — 현장뷰 집약 키(G7)
1472
+ /* 사람이 읽는 현장 이름 — 없으면 `undefined`(화면이 "이름 없음" 을 알아볼 수 있어야 한다). */
1473
+ spaceName: (r.spaceId ? spaceNameOf.get(r.spaceId) : undefined) || undefined,
1474
+ realityMode: r.realityMode, // 현실 출처 선언(§0 ①) — mirror/sim-world/sim-experiment. 저장 시 각인되므로 비지 않는다.
1475
+ purpose: r.purpose, // 운영 vs 벤치 사본(1급 구별 — 이름 접두사 아님). 저장 시 각인되므로 비지 않는다.
826
1476
  copyOf: r.copyOf ?? undefined,
827
- running: !!this.instances[r.instanceId],
828
- revision: last?.revision ?? 0,
829
- locationCount: board.locations?.length ?? 0,
830
- equipmentCount: board.equipment?.length ?? 0
1477
+ running: !!this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, r.instanceId)],
1478
+ /*
1479
+ * **계측이 들어오고 있나** — 「도는 중」과 다른 사실이다.
1480
+ *
1481
+ * 미러 트윈은 피드가 떨어져도 커널이 돌기만 하면 「도는 중」이었다. 그래서 아무것도 받지 않는
1482
+ * 트윈과 흐르는 트윈이 화면에서 똑같이 보였다(재기동 뒤 실제로 그랬다). 시뮬·정지 트윈에는
1483
+ * 「해당 없음」이다 — 없어야 하는 것을 끊겼다고 부르지 않는다.
1484
+ */
1485
+ /* 스스로 멈춘 이유 — 있으면 낸다. 재기동 뒤에는 없다(그때는 「모른다」가 사실이다). */
1486
+ stopNote: this.stopNotes.get((0, runtime_key_js_1.runtimeKey)(domainId, r.instanceId)) || undefined,
1487
+ liveFeed: (0, live_feed_registry_js_1.liveFeedStateOf)({
1488
+ realityMode: r.realityMode,
1489
+ running: !!this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, r.instanceId)],
1490
+ instanceId: r.instanceId
1491
+ }),
1492
+ revision: tipOfInstance.get(r.instanceId) ?? 0,
1493
+ /*
1494
+ * **리더를 거쳐 센다** — 보드 키를 직접 읽으면 옛 세대 모델이 0 으로 보인다.
1495
+ *
1496
+ * 커널은 자리·설비 배열의 **옛 세대 키까지 흡수해** 읽어 주는데, 이 목록은 새 이름만 직접
1497
+ * 세고 있었다. 그래서 옛 모델 12개가 화면에 **자리 0 · 설비 0**
1498
+ * 으로 떴다 — 오류 없이, 그냥 빈 공장처럼. 세는 규칙이 두 벌이면 이런 식으로 어긋난다.
1499
+ */
1500
+ locationCount: readBoardLocations(model).length,
1501
+ equipmentCount: readBoardEquipment(model).length
831
1502
  });
832
1503
  }
833
1504
  return out;
834
1505
  }
835
- /** 레거시 벤치 잔재 가드 — purpose 도입 전 만들어진 벤치/부하 공간(이름 규약)까지 걸러낸다. */
836
- static isBenchSpace(spaceId) {
837
- return !!spaceId && (/^bench-/.test(spaceId) || spaceId === 'rosarito-load' || /^loadtest/.test(spaceId));
838
- }
839
- /** 운영 공간 목록(벤치 소스 선택기) — 이름·규모 포함, 벤치 사본·잔재 제외. */
1506
+ /** 운영 공간 목록(벤치 소스 선택기) — 이름·규모 포함, 벤치 사본 제외. */
840
1507
  static async listSpaces(domainId) {
841
1508
  const nameOf = new Map((await (0, shell_1.getRepository)(twin_space_js_1.TwinSpace).find({ where: { domain: { id: domainId } } })).map(s => [s.spaceId, s.name]));
842
1509
  const insts = await (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance).find({ where: { domain: { id: domainId } } });
843
1510
  const agg = new Map();
844
1511
  for (const r of insts) {
845
- if (!r.spaceId || r.purpose === 'bench' || this.isBenchSpace(r.spaceId))
846
- continue; // 벤치·잔재 제외
847
- const board = r.board ?? {};
1512
+ /* 벤치 제외는 **선언으로만** 판단한다. 예전에는 spaceId 이름(`bench-`·`loadtest*`)으로도 추측했는데,
1513
+ 그러면 그렇게 이름 지은 진짜 운영 공간이 목록에서 조용히 사라진다. purpose 가 정본이다. */
1514
+ if (!r.spaceId || r.purpose === 'bench')
1515
+ continue;
1516
+ const model = r.model ?? {};
848
1517
  const a = agg.get(r.spaceId) ?? { spaceId: r.spaceId, name: nameOf.get(r.spaceId) ?? r.spaceId, instances: 0, locations: 0, equipment: 0 };
849
1518
  a.instances++;
850
- a.locations += board.locations?.length ?? 0;
851
- a.equipment += board.equipment?.length ?? 0;
1519
+ /* 목록과 **같은 규칙**으로 센다 — 여기만 직접 세면 공간 요약과 인스턴스 목록이 다른 수를 말한다. */
1520
+ a.locations += readBoardLocations(model).length;
1521
+ a.equipment += readBoardEquipment(model).length;
852
1522
  agg.set(r.spaceId, a);
853
1523
  }
854
1524
  return [...agg.values()];
@@ -858,7 +1528,7 @@ class TwinEngine {
858
1528
  await (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance).update({ domain: { id: domainId }, instanceId }, { purpose, copyOf: copyOf ?? null });
859
1529
  }
860
1530
  /**
861
- * 공간 구조 판독 — 완전복제(벤치 사본)의 소스. 저장물이 board(위상)·TwinSpace.content(치수·geo·표현)·TwinArea(영역)로
1531
+ * 공간 구조 판독 — 완전복제(벤치 사본)의 소스. 저장물이 model(위상)·TwinSpace.content(치수·geo·표현)·TwinArea(영역)로
862
1532
  * 분산돼 있으므로 셋을 모아 돌려준다. 호출측이 ReferenceMaster 로 재구성 → 재식별 → ingestMaster.
863
1533
  */
864
1534
  static async spaceStructure(domainId, spaceId) {
@@ -869,7 +1539,12 @@ class TwinEngine {
869
1539
  const insts = await (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance).find({ where: { domain: { id: domainId }, spaceId } });
870
1540
  if (!insts.length)
871
1541
  return null;
872
- return { name: sp?.name, content: sp?.content ?? {}, areas, instances: insts.map(i => ({ instanceId: i.instanceId, kind: i.kind, board: i.board })) };
1542
+ return {
1543
+ name: sp?.name,
1544
+ frame: { extentX: sp?.extentX, extentY: sp?.extentY, geo: sp?.geo, primaryRepresentationId: sp?.primaryRepresentationId },
1545
+ areas,
1546
+ instances: insts.map(i => ({ instanceId: i.instanceId, kind: i.kind, model: i.model }))
1547
+ };
873
1548
  }
874
1549
  /** 공간(+표현·영역) 삭제 — 벤치 정리 등. 호출측이 바인딩 인스턴스를 먼저 제거하는 전제(가드 없음). deleteTwinSpace 리졸버와 동형. */
875
1550
  static async deleteSpace(domainId, spaceId) {
@@ -887,46 +1562,115 @@ class TwinEngine {
887
1562
  * Face2 마스터 인제스트(ADR-0018) — 레퍼런스 시스템(실 또는 가상)의 마스터를 읽어 트윈을 생성.
888
1563
  * 엔티티를 손배선/발명하지 않고 마스터에서 반영: 공간(Space) upsert + 인스턴스 provision(미기동).
889
1564
  * 노드타입은 커널 카탈로그로 검증(warning). start 는 호출측(bootstrap/mutation)이 결정.
1565
+ *
1566
+ * `into.spaceId` — **이 현장에 더한다.** 한 현실을 여러 렌즈(WMS·MES·YMS)가 비추므로 새 트윈이
1567
+ * 기존 공간으로 들어갈 수 있다. 아래 병합은 원래 그 경우를 위해 있었는데(N:1) 만드는 흐름에서
1568
+ * 공간을 고를 방법이 없었다 — 마스터가 파생한 id 만 쓰였다. 판정은 `resolveIngestSpace`(순수).
890
1569
  */
891
- static async ingestMaster(domainId, master) {
892
- const { board, spaceContent, warnings } = (0, reference_master_js_2.masterToTwin)(master, DOMAIN_CATALOG);
893
- const spaceId = board.spaceId;
894
- const repo = (0, shell_1.getRepository)(twin_space_js_1.TwinSpace);
895
- const existing = await repo.findOne({ where: { domain: { id: domainId }, spaceId } });
1570
+ static async ingestMaster(domainId, master, into,
1571
+ /** 누가 인제스트했나 — 사람이 없는 경로(부팅)는 주지 않는다(감사 기록을 지어내지 않는다). */
1572
+ actor) {
896
1573
  /*
897
- * 공유 공간(여러 트윈이 한 spaceId, N:1) content 병합 — 마지막 인제스트가 통째로 덮어써 area(그룹)·표현이
898
- * 유실되던 문제 보정. area·landmark 는 id 합집합, representations 는 비어있지 않은 쪽 보존, 나머지는 first-wins.
1574
+ * **거절할 것이면 아무것도 쓰기 전에 거절한다.**
1575
+ *
1576
+ * 가동 중 재프로비저닝은 `provision` 이 막는다. 그런데 그 호출은 이 함수의 **맨 끝**이라,
1577
+ * 그때까지 공간·표현·구역(TwinArea)은 이미 저장된 뒤였다. 사용자에게는 "인제스트 실패" 로
1578
+ * 보이는데 실제로는 절반이 적용된 상태 — 실패라고 말하면서 데이터를 바꾸는 것이 가장 나쁘다.
1579
+ *
1580
+ * 그래서 판정을 앞으로 옮긴다. 아래 `provision` 의 같은 판정은 그대로 둔다 — 이건 편의를 위한
1581
+ * 앞선 거절이고, 저기가 진짜 방벽이다(다른 경로가 생겨도 지켜져야 한다).
1582
+ *
1583
+ * **미러는 여기서 거절하지 않는다.** 미러가 비추는 현실은 안 멈추므로 동작 중에 전환한다
1584
+ * (아래 `adoptStructure`). 거절은 시뮬레이션에만 남는다 — 조건이 바뀐 실험은 다른 실험이다.
899
1585
  */
900
- const prev = existing?.content ?? {};
901
- const cur = spaceContent;
902
- const unionById = (a = [], b = []) => {
903
- const m = new Map();
904
- for (const x of [...a, ...b])
905
- if (x?.id)
906
- m.set(x.id, x);
907
- return [...m.values()];
908
- };
909
- const mergedContent = {
910
- width: prev.width ?? cur.width,
911
- depth: prev.depth ?? cur.depth,
912
- unit: prev.unit ?? cur.unit,
913
- geo: prev.geo ?? cur.geo,
914
- primaryId: prev.primaryId ?? cur.primaryId,
915
- representations: (cur.representations?.length ? cur.representations : prev.representations) ?? [],
916
- // areas 는 content 에 더 이상 쓰지 않는다(area 단일화 P3) — 권위=TwinArea. 아래 TwinArea 로만 기록.
917
- landmarks: unionById(prev.landmarks, cur.landmarks)
918
- };
1586
+ const running = this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, master.source)];
1587
+ if (running && running.mode !== 'live')
1588
+ this.assertNotRunning(domainId, master.source);
1589
+ const { model, spaceContent, warnings } = (0, reference_master_js_2.masterToTwin)(master, DOMAIN_CATALOG);
919
1590
  /*
920
- * **현장의 시각 기준을 공간에 남긴다** — 그러지 않으면 공간이 권위인데 그 값을 영원히 모른다.
1591
+ * ── 현장 선언을 다시 얹는다 (2026-08-18) ──────────────────────────────────
921
1592
  *
922
- * 마스터가 보드에 오프셋을 실어 주므로 갓 프로비저닝한 트윈은 맞게 돌지만, `withSpaceTimeBase` 가
923
- * 읽는 곳은 **공간**이다. 여기서 옮기지 않으면 공간의 시간대가 계속 비어 있고, 사용자가 화면에서
924
- * 그것을 보거나 고칠 수도 없다(만들고 잇지 않으면 없는 것이다).
1593
+ * 여기가 「원천에서 다시 그리는」 자리다. 요금 단가·계약 정보처럼 **현장이 정한 수**는 원천이 모르므로
1594
+ * 다시 그리면 그대로 사라진다 — 금액이 사라지고, 사용자는 자기가 넣은 값이 어디로 갔는지 알 수 없다.
1595
+ * 그래서 겹으로 보관한 선언을 매번 다시 얹는다(`engine/local-declarations`).
925
1596
  *
926
- * **사용자가 고친 값을 마스터가 덮지 않는다** — 이미 있으면 그대로 둔다(현장이 정본을 이긴다).
1597
+ * 대상이 사라졌으면(구조가 바뀌었다) 그 사실을 경고로 낸다 — 갈 곳 없는 선언을 조용히 버리지 않는다.
1598
+ */
1599
+ const prior = await (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance).findOne({ where: { domain: { id: domainId }, instanceId: master.source } });
1600
+ /*
1601
+ * 겹이 **둘**이다 — 현장(공간)의 것과 이 트윈의 것. 순서가 규율이다: 현장 먼저, 트윈이 나중.
1602
+ * 요금처럼 현장이 정한 수는 그 현장의 트윈 전부가 같이 읽어야 하고, 한 트윈만 다르게 두는 실험은
1603
+ * 좁은 겹이 이겨야 한다(넓은 값을 고치면 나머지 트윈이 함께 흔들린다).
927
1604
  */
1605
+ const priorSpaceId = prior?.spaceId ?? model?.spaceId;
1606
+ const spaceRow = priorSpaceId
1607
+ ? await (0, shell_1.getRepository)(twin_space_js_1.TwinSpace).findOne({ where: { domain: { id: domainId }, spaceId: priorSpaceId } })
1608
+ : null;
1609
+ if (prior?.localDeclarations || spaceRow?.localDeclarations) {
1610
+ const layered = (0, local_declarations_js_1.applyDeclarationLayers)(model, spaceRow?.localDeclarations, prior?.localDeclarations);
1611
+ Object.assign(model, layered.model);
1612
+ /*
1613
+ * 겹을 **다시 저장한다** — 여기서 얹은 것은 원천에서 새로 그린 모델이므로, 그때 우리가 덮은 값이
1614
+ * 곧 지금의 원천 값이다(`replaced`). 저장하지 않으면 그 기억이 낡아, 철회가 옛 원천 값으로
1615
+ * 되돌린다 — 원천이 그동안 값을 고쳤어도 알 수 없다.
1616
+ */
1617
+ if (prior) {
1618
+ prior.localDeclarations = layered.instanceLayerApplied;
1619
+ await (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance).save(prior);
1620
+ }
1621
+ if (spaceRow) {
1622
+ spaceRow.localDeclarations = layered.spaceLayerApplied;
1623
+ await (0, shell_1.getRepository)(twin_space_js_1.TwinSpace).save(spaceRow);
1624
+ }
1625
+ /*
1626
+ * 갈 곳 없는 선언은 경고로 낸다 — 다만 **현장 겹의 것은 뺀다**: 한 현장에는 여러 종류의 트윈이
1627
+ * 살고(창고·야드·에너지), 요금 자리가 없는 트윈에 요금이 얹히지 않는 것은 정상이다.
1628
+ */
1629
+ for (const t of layered.missingTargets.filter(x => x.scope === 'instance')) {
1630
+ warnings.push((0, reference_master_js_3.unresolvedReference)('localDeclaration.target', `${t.target}:${t.id}`));
1631
+ }
1632
+ }
1633
+ const repo = (0, shell_1.getRepository)(twin_space_js_1.TwinSpace);
1634
+ /* 합칠 공간을 골랐으면 **있는지 먼저 확인한다** — 없는 곳에 조용히 새 공간을 만들면 사용자는
1635
+ 합쳤다고 믿고 화면은 따로 논다. 판정 함수가 그 경우 거절한다. */
1636
+ const wanted = (into?.spaceId ?? '').trim();
1637
+ const wantedExists = wanted
1638
+ ? (await repo.count({ where: { domain: { id: domainId }, spaceId: wanted } })) > 0
1639
+ : false;
1640
+ const choice = (0, ingest_space_js_1.resolveIngestSpace)(model.spaceId, wanted, wantedExists);
1641
+ const spaceId = choice.spaceId;
1642
+ model.spaceId = spaceId; // 보드(커널 소비)도 같은 공간을 가리켜야 한다
1643
+ const existing = await repo.findOne({ where: { domain: { id: domainId }, spaceId } });
1644
+ if (choice.joined) {
1645
+ /* 같은 id 의 구역·랜드마크는 합집합으로 접힌다 — 구분할 수 없는 것을 고르지 않고 무엇이
1646
+ 합쳐졌는지 말한다(정당한 경우가 많으므로 막지 않는다). */
1647
+ }
1648
+ /*
1649
+ * 공유 공간(여러 트윈이 한 spaceId, N:1) — **먼저 쓴 값이 이긴다.**
1650
+ *
1651
+ * 마지막 인제스트가 통째로 덮어써 표현·구역이 유실되던 문제 보정. 설계 좌표계 범위와
1652
+ * 지오레퍼런스는 공간의 성질이라 트윈마다 다를 수 없다 — 두 번째 트윈이 들어오면서 바꾸면
1653
+ * 먼저 놓인 구역들이 통째로 어긋난다. 그래서 이미 있으면 그대로 둔다.
1654
+ */
1655
+ const cur = spaceContent;
928
1656
  const timezone = existing?.timezone || master.space.timezone;
929
- const savedSpace = await repo.save(repo.create({ ...(existing ?? {}), domain: { id: domainId }, spaceId, name: existing?.name || master.siteName, ...(timezone ? { timezone } : {}), content: mergedContent }));
1657
+ const savedSpace = await repo.save(repo.create({
1658
+ ...(existing ?? {}),
1659
+ domain: { id: domainId },
1660
+ spaceId,
1661
+ name: existing?.name || master.siteName,
1662
+ ...(timezone ? { timezone } : {}),
1663
+ extentX: existing?.extentX ?? cur.width,
1664
+ extentY: existing?.extentY ?? cur.depth,
1665
+ geo: existing?.geo ?? cur.geo,
1666
+ /*
1667
+ * 대표 표현 포인터는 **표현을 저장한 뒤** 실제 행 id 로 채운다(아래). 여기서 마스터의 논리
1668
+ * id(`r-map` 따위)를 넣으면 표현 행은 생성 uuid 를 받으므로 포인터가 **처음부터 허공을
1669
+ * 가리킨다** — 실제로 13개 현장이 그 상태였고 정합성 점검이 잡았다(2026-08-13). 화면은
1670
+ * 행의 `isPrimary` 로 ★를 그려서 증상이 보이지 않았다(사실이 두 벌이면 이렇게 조용하다).
1671
+ */
1672
+ primaryRepresentationId: existing?.primaryRepresentationId ?? null
1673
+ }));
930
1674
  /*
931
1675
  * 표현을 twin_space_representations 테이블에 저장한다 — 뷰(twin-map-page 등)는 content 가 아니라 테이블 표현을 소싱하므로,
932
1676
  * 저장하지 않으면 인제스트 사이트에 "대표 표현" 이 없어 지도로 시작하지 못한다. rep.areas 가 있으면 TwinSpaceArea 도 함께 저장.
@@ -947,6 +1691,19 @@ class TwinEngine {
947
1691
  await areaRepo.save(areaRepo.create({ domain: { id: domainId }, representation: { id: savedRep.id }, name: area.name, type: area.type, geometry: area.geometry, drillTo: area.drillTo ?? null, binding: area.binding ?? null, style: area.style ?? null }));
948
1692
  }
949
1693
  }
1694
+ /*
1695
+ * 대표를 **저장된 행 id** 로 가리킨다 — 마스터의 논리 id 는 저장 키가 아니다. 고른 순서:
1696
+ * ① 마스터가 primary 로 표시한 표현 ② 없으면 첫 표현 ③ 표현이 없으면 비운다(지어내지 않는다).
1697
+ */
1698
+ const saved = await repRepo.find({ where: { domain: { id: domainId }, space: { id: savedSpace.id } }, order: { seq: 'ASC' } });
1699
+ const primary = saved.find(r => r.isPrimary) ?? saved[0];
1700
+ if (primary && savedSpace.primaryRepresentationId !== primary.id) {
1701
+ await repo.save(repo.create({ ...savedSpace, primaryRepresentationId: primary.id }));
1702
+ /* 하나만 대표다 — 행 플래그도 그 하나로 맞춘다(둘이 켜져 있으면 화면이 ★를 두 번 그린다). */
1703
+ for (const r of saved)
1704
+ if (!!r.isPrimary !== (r.id === primary.id))
1705
+ await repRepo.save(repRepo.create({ ...r, isPrimary: r.id === primary.id }));
1706
+ }
950
1707
  }
951
1708
  /*
952
1709
  * area 단일화(space #2, P1) — 논리 구역을 TwinArea(정규·표현무관·공유)에 dual-write(upsert by areaId).
@@ -969,12 +1726,54 @@ class TwinEngine {
969
1726
  layout: a.x != null || a.w != null ? { x: a.x, y: a.y, w: a.w, h: a.h } : null
970
1727
  }));
971
1728
  }
972
- await this.provision(domainId, master.source, master.system, board);
1729
+ if (running) {
1730
+ /* 실행 중인 미러 — 멈추지 않고 전환한다. 무엇이 사라졌는지는 **경고로 말한다**
1731
+ (멈췄다 세우는 마디가 없으므로, 말하지 않으면 자리 하나가 조용히 없어진다). */
1732
+ const shift = await this.adoptStructure(domainId, master.source, model, undefined, master.origin);
1733
+ warnings.push((0, reference_master_js_3.structureAdopted)(shift.rev, shift));
1734
+ }
1735
+ else {
1736
+ /* 사이트 이름이 곧 트윈의 이름이다 — 마스터가 이미 말했으므로 지어내지 않고 그대로 싣는다. */
1737
+ await this.provision(domainId, master.source, master.system, model, undefined, master.origin, {
1738
+ name: master.siteName,
1739
+ description: master.description,
1740
+ actor
1741
+ });
1742
+ }
1743
+ /*
1744
+ * 구조 투영 — model(커널 입력 문서)를 **표준 엔티티 행**으로 푼다(ADR-0032).
1745
+ *
1746
+ * 인제스트가 유일한 쓰기 경로다. 여기서 실패해도 인제스트 자체는 성공으로 둔다 —
1747
+ * 행은 **원본에서 언제든 다시 그릴 수 있는 캐시**이고, 트윈 자체는 model 로 이미 동작한다.
1748
+ * 다만 **조용히 넘기지 않는다**: 못 이은 참조는 인제스트 경고로 올라간다.
1749
+ */
1750
+ try {
1751
+ const projected = await (0, project_structure_js_1.projectStructure)(domainId, master.source, model, master.source);
1752
+ for (const ref of projected.unresolvedHome)
1753
+ warnings.push((0, reference_master_js_3.unresolvedReference)('equipment.homeLocation', ref));
1754
+ for (const ref of projected.unresolvedArea)
1755
+ warnings.push((0, reference_master_js_3.unresolvedReference)('location.area', ref));
1756
+ /*
1757
+ * 발전 형상은 **시각**을 읽는다 — 시간대를 모르면 UTC 로 읽히고, 현장 정오가 아닌 시각에 피크가 선다.
1758
+ * 시간대를 지어내지 않고 그 조합을 말한다(공간에 선언하면 사라진다).
1759
+ */
1760
+ if (model?.utcOffsetMinutes === undefined) {
1761
+ for (const e of (model?.equipment ?? [])) {
1762
+ const hasProfile = (e?.properties ?? []).some(p => String(p?.id) === twin_kernel_1.EMS_PROPERTY.genDailyProfile && String(p?.value ?? '').trim());
1763
+ if (hasProfile)
1764
+ warnings.push((0, reference_master_js_3.generationWithoutTimeZone)(String(model?.spaceId ?? ''), String(e.id)));
1765
+ }
1766
+ }
1767
+ }
1768
+ catch (err) {
1769
+ console.error(`[twin-engine] structure projection failed for "${master.source}":`, err?.message);
1770
+ warnings.push((0, reference_master_js_3.projectionFailed)(err?.message ?? 'unknown'));
1771
+ }
973
1772
  if (warnings.length)
974
- console.warn(`[twin-engine] ingest "${master.source}" warnings:`, warnings);
1773
+ console.warn(`[twin-engine] ingest "${master.source}" warnings: ${(0, reference_master_js_3.describeWarnings)(warnings)}`);
975
1774
  return { instanceId: master.source, spaceId, warnings };
976
1775
  }
977
- /** 단건 상세 — 프로비저닝 에디터가 편집할 board(구조+layout) 포함. */
1776
+ /** 단건 상세 — 프로비저닝 에디터가 편집할 model(구조+layout) 포함. */
978
1777
  static async detail(domainId, instanceId) {
979
1778
  const r = await (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance).findOne({ where: { domain: { id: domainId }, instanceId } });
980
1779
  if (!r)
@@ -983,9 +1782,9 @@ class TwinEngine {
983
1782
  instanceId: r.instanceId,
984
1783
  kind: r.kind,
985
1784
  status: r.status,
986
- running: !!this.instances[r.instanceId],
1785
+ running: !!this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, r.instanceId)],
987
1786
  realityMode: r.realityMode, // 현실 선언 — what-if 적용 가드용(mirror=예측 전용, 자극 주입 불가)
988
- board: r.board
1787
+ model: r.model
989
1788
  };
990
1789
  }
991
1790
  /**
@@ -993,16 +1792,51 @@ class TwinEngine {
993
1792
  * 보드 컴포넌트가 tag 로 구독(board-ui provider)해 `component.data` 로 라이브 갱신. delta 시에만(희소).
994
1793
  * tag=엔티티 id(데모=단일 인스턴스). 멀티 인스턴스/보드 재사용 시 tag 네임스페이스는 후속.
995
1794
  */
1795
+ /** 방송 실패 로그 조절 — 창마다 한 줄(막힌 구독자는 초당 수십 번 실패한다). */
1796
+ static { this.publishDrops = new Map(); }
1797
+ static { this.PUBLISH_DROP_LOG_MS = 10_000; }
1798
+ /**
1799
+ * 한 번의 방송 — **구독자 하나가 호스트를 죽이지 못하게.**
1800
+ *
1801
+ * ── 무엇이 죽였나 (2026-08-14) ─────────────────────────────────────────────
1802
+ * 밀린 push 가 1024를 넘으면 pubsub 이 던진다(`RepeaterOverflowError`). 그 방송은 타이머 콜백
1803
+ * 안에서 일어나므로 예외가 잡히는 곳 없이 올라가 **프로세스가 끝났다** — 트윈 14개가 도는 호스트가
1804
+ * 소비를 멈춘 구독자 하나 때문에 통째로.
1805
+ *
1806
+ * 못 보낸 것은 **사실로 남긴다**(횟수를 세고 창마다 한 줄 남긴다). 삼키면 「보냈는데 화면이 낡았다」가
1807
+ * 되고, 그건 가장 찾기 어려운 부류다.
1808
+ */
1809
+ static publishGuarded(channel, payload, what) {
1810
+ try {
1811
+ shell_1.pubsub.publish(channel, payload);
1812
+ return true;
1813
+ }
1814
+ catch (err) {
1815
+ const d = this.publishDrops.get(what) ?? { count: 0, lastLogMs: 0 };
1816
+ d.count++;
1817
+ const now = Date.now();
1818
+ if (now - d.lastLogMs >= this.PUBLISH_DROP_LOG_MS) {
1819
+ d.lastLogMs = now;
1820
+ console.warn(`[twin-engine] broadcast dropped on "${what}" (${d.count} so far) — ${err?.message ?? err}`);
1821
+ }
1822
+ this.publishDrops.set(what, d);
1823
+ return false;
1824
+ }
1825
+ }
996
1826
  static publishEntityData(inst) {
997
1827
  const domain = inst.domain;
998
1828
  if (!domain)
999
1829
  return;
1000
1830
  /* 상태 출처 스왑 — sim: 커널 runtime, live: projector 미러(+OEE 계산 층 보강). 계약·payload 동일, 드라이버만 다름. */
1831
+ const load = inst.load ?? (inst.load = (0, load_meter_js_1.newLoadMeter)());
1832
+ /* ① 상태 투영 — 상태 크기에 비례한다(대규모에서 가장 무거운 축). */
1833
+ const tSnap = performance.now();
1001
1834
  const st = inst.mode === 'live'
1002
1835
  ? inst.oee
1003
1836
  ? (0, oee_accumulator_js_1.withLiveOee)(inst.projector?.snapshot?.(), inst.oee) // 관측 커널 + 계산(OEE) → equipment payload 에 oee 포함(sim 동형)
1004
1837
  : inst.projector?.snapshot?.()
1005
1838
  : inst.runtime?.resync?.()?.state;
1839
+ (0, load_meter_js_1.recordPhase)(load, 'snapshot', performance.now() - tSnap);
1006
1840
  if (!st)
1007
1841
  return;
1008
1842
  /*
@@ -1014,14 +1848,25 @@ class TwinEngine {
1014
1848
  const seen = new Set();
1015
1849
  /* payload 매핑은 순수 함수(buildEntityDeltas)로 분리 — 여기선 시그니처 dedup + 발행만.
1016
1850
  * 변화한 엔티티만 발행(최신-상태 채널이라 무변화 재방송 무의미). */
1017
- for (const { tag, data } of (0, entity_delta_js_1.buildEntityDeltas)(st)) {
1851
+ /* ② payload 만들기 — 엔티티 수에 비례. ③ 시그니처 비교 + 발행 — 바뀐 것 수에 비례. */
1852
+ const tDelta = performance.now();
1853
+ const deltas = (0, entity_delta_js_1.buildEntityDeltas)(st, inst.id);
1854
+ (0, load_meter_js_1.recordPhase)(load, 'deltas', performance.now() - tDelta);
1855
+ const tPub = performance.now();
1856
+ for (const { tag, data } of deltas) {
1018
1857
  seen.add(tag);
1019
1858
  const sig = JSON.stringify(data);
1020
1859
  if (sigs.get(tag) === sig)
1021
1860
  continue; // 무변화 → 발행 생략
1022
1861
  sigs.set(tag, sig);
1023
- shell_1.pubsub.publish('data', { data: { domain, tag, data } });
1862
+ /*
1863
+ * **못 보냈으면 보낸 것으로 적지 않는다.** 시그니처를 남겨 두면 다음 주기에 「무변화」로 건너뛰고,
1864
+ * 그 태그는 영원히 낡은 값을 보여 준다(오류 없이). 되돌려 두면 다음 주기가 다시 시도한다.
1865
+ */
1866
+ if (!this.publishGuarded('data', { data: { domain, tag, data } }, `data:${inst.id}`))
1867
+ sigs.delete(tag);
1024
1868
  }
1869
+ (0, load_meter_js_1.recordPhase)(load, 'publish', performance.now() - tPub);
1025
1870
  /* 사라진 엔티티의 시그니처 정리(맵 무한 성장 방지). */
1026
1871
  if (sigs.size > seen.size)
1027
1872
  for (const tag of sigs.keys())
@@ -1034,7 +1879,7 @@ class TwinEngine {
1034
1879
  }
1035
1880
  /**
1036
1881
  * 재부팅 복구 / 시간여행 — DB 저널을 replay 해 상태 재구성.
1037
- * board 는 레지스트리(TwinInstance)에서, 이벤트는 TwinEvent(revision ASC)에서.
1882
+ * model 는 레지스트리(TwinInstance)에서, 이벤트는 TwinEvent(revision ASC)에서.
1038
1883
  * 커서 두 축(runtime-state-model §4): **시각(untilTime, 사용자 모국어·공간 공통축)** 우선, 없으면 리비전(untilRevision, 렌즈 내부).
1039
1884
  * - untilTime 주면 `eventTime ≤ T` 인 이벤트만(그 시점 watermark) — 공동배치 여러 트윈을 하나의 시각 T로 통일 해소.
1040
1885
  * - 둘 다 없으면 최신(라이브 인메모리 진실).
@@ -1044,29 +1889,104 @@ class TwinEngine {
1044
1889
  // 라이브 최신(시간여행 아님) + 인메모리 인스턴스 → 라이브 커널 스냅샷을 직접 사용.
1045
1890
  // replay(StateProjector)는 attentions·ack 등 라이브 전용 파생 상태를 담지 못하므로, 최신은 커널 진실을 쓴다.
1046
1891
  if (untilRevision == null && untilTime == null) {
1047
- const live = this.instances[instanceId];
1892
+ const live = this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, instanceId)];
1048
1893
  if (live?.kernel?.getSnapshot)
1049
1894
  return live.kernel.getSnapshot();
1050
1895
  // live 모드는 kernel 이 없고 projector 미러 → 인메모리 최신 스냅샷(projector+OEE+attentions) 직접 사용.
1051
1896
  // (저널이 있어도 최신은 인메모리가 진실 — replay 는 시간여행/복구 전용.)
1052
1897
  if (live?.mode === 'live' && live.projector)
1053
- return this.snapshot(instanceId);
1898
+ return this.snapshot(domainId, instanceId);
1899
+ }
1900
+ /*
1901
+ * **끝에 있는 스냅샷이면 접지 않는다.**
1902
+ *
1903
+ * 멈춘 트윈을 조회할 때마다 저널을 전량 접고 있었다 — 트윈을 하나도 안 돌려도 모델 조회가
1904
+ * 4.6~7.7초였던 이유다(crew-probe 23,731건). 스냅샷은 같은 폴드의 결과이므로, 그 뒤로 이벤트도
1905
+ * 구조 변경도 없다면 **다시 접어 봐야 같은 값**이다.
1906
+ *
1907
+ * 쓰지 않는 조건을 좁게 잡는다: 지금을 물었을 때만(시간여행은 그 시점까지 접어야 한다), 리비전이
1908
+ * 끝과 같을 때만, 구조 리비전까지 같을 때만. 하나라도 어긋나면 접는다 — 캐시가 사실을 이기지 않는다.
1909
+ */
1910
+ const asOfNowRead = untilRevision == null && untilTime == null;
1911
+ const tip = asOfNowRead ? await this.tipOf(domainId, instanceId).catch(() => null) : null;
1912
+ /* 한 번만 읽는다 — 끝에 있으면 그대로 쓰고, 아니면 아래에서 **이어 접는 씨앗**으로 쓴다. */
1913
+ const cachedForResume = asOfNowRead && tip ? await this.loadSnapshot(domainId, instanceId).catch(() => null) : null;
1914
+ if (cachedForResume) {
1915
+ const state = (0, warm_start_js_1.unwrapState)(cachedForResume.state);
1916
+ if (state && (cachedForResume.revision ?? 0) === tip.revision && (cachedForResume.structureRev ?? null) === tip.structureRev)
1917
+ return state;
1054
1918
  }
1055
1919
  const reg = await (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance).findOne({ where: { domain: { id: domainId }, instanceId } });
1056
- if (!reg?.board)
1057
- throw new Error(`twin instance "${instanceId}" not registered (no board to replay)`);
1920
+ if (!reg?.model)
1921
+ throw new Error(`twin instance "${instanceId}" not registered (no model to replay)`);
1922
+ /*
1923
+ * ── 재개점에서 **이어 접는다** (2026-08-18) ────────────────────────────
1924
+ *
1925
+ * 우리는 이미 접은 결과를 남기고 있다(`saveFoldedSnapshot`). 그 지점의 **재개점**(리듀서 내부 상태
1926
+ * 전부 + 가동 누적기)이 함께 있으면, 그 뒤에 일어난 것만 접어도 같은 답이 나온다 — 그 동치는
1927
+ * 커널 시험이 증명한다(0부터 접기 == 재개점 + 꼬리).
1928
+ *
1929
+ * 쓰는 조건을 좁게 잡는다: **지금을 물었을 때만**(시간여행은 목표 이전 재개점이 필요한데 지금은
1930
+ * 최신 하나만 남긴다 — 사슬은 다음 단계다), 구조가 그대로일 때만(구조가 바뀌면 그 경계에서 갈라
1931
+ * 접어야 한다), 재개점이 저널 끝보다 앞설 때만. 하나라도 어긋나면 0부터 접는다 — **캐시가 사실을
1932
+ * 이기지 않는다.**
1933
+ */
1934
+ /*
1935
+ * 씨앗은 둘 중 하나다: **지금**을 물으면 최신 재개점, **과거**를 물으면 사슬에서 목표 직전 지점.
1936
+ *
1937
+ * 과거 씨앗은 구조가 한 번도 바뀌지 않은 트윈에서만 쓴다 — 구조가 갈린 저널은 마디마다 갈아 접어야
1938
+ * 하고, 마디를 건너뛴 씨앗은 그 경계의 판정을 잃는다(그때는 0부터 접는 것이 옳다).
1939
+ */
1940
+ const structureCount = asOfNowRead
1941
+ ? 0
1942
+ : await (0, shell_1.getRepository)(twin_structure_js_1.TwinStructure).count({ where: { domain: { id: domainId }, instanceId } }).catch(() => 99);
1943
+ const pastSeed = !asOfNowRead && structureCount <= 1
1944
+ ? await this.chainSeedFor(domainId, instanceId, {
1945
+ ...(untilRevision != null ? { revision: untilRevision } : {}),
1946
+ ...(untilTime != null && !Number.isNaN(Date.parse(untilTime)) ? { timeMs: Date.parse(untilTime) } : {})
1947
+ }).catch(() => null)
1948
+ : null;
1949
+ const resume = asOfNowRead && tip && cachedForResume && cachedForResume.fold && (cachedForResume.structureRev ?? null) === tip.structureRev
1950
+ ? cachedForResume
1951
+ : pastSeed;
1952
+ /*
1953
+ * **자를 것을 알면서 다 읽어 오지 않는다** (2026-08-18 실측).
1954
+ *
1955
+ * 저널을 전량 읽어 온 뒤 JS 에서 걸렀다. 27만 건짜리 트윈(order-check)에서 한 시간 전 상태를 물으면
1956
+ * **7.4초**가 걸렸고, 그 대부분이 「필요 없는 행을 읽어 오는 시간」이었다. 시각·리비전 상한은 SQL 이
1957
+ * 아는 조건이므로 거기서 자른다(TypeORM 관용구만 — 원시 SQL 은 5개 드라이버에서 갈라진다).
1958
+ *
1959
+ * 시각 상한에는 **경계를 그대로** 쓴다(`<=`): 그 시각에 일어난 사실은 그 시각의 화면에 있어야 한다.
1960
+ * 시각이 없는 레거시 행은 보수적으로 포함해 왔는데, SQL 로 자르면 그 행들이 빠진다 — 그래서 시각
1961
+ * 조건일 때는 **시각이 비어 있는 행도 함께** 가져와 예전과 같은 결과를 낸다.
1962
+ */
1963
+ const cutoffMs = untilTime != null ? Date.parse(untilTime) : NaN;
1964
+ const useTime = untilTime != null && !Number.isNaN(cutoffMs);
1965
+ const baseWhere = { domain: { id: domainId }, instanceId };
1966
+ /* 이어 접을 때는 **그 뒤만** 읽는다 — 재개점까지의 사실은 이미 씨앗 안에 있다. */
1967
+ const from = resume ? (resume.revision ?? 0) : undefined;
1058
1968
  const rows = await (0, shell_1.getRepository)(twin_event_js_1.TwinEvent).find({
1059
- where: { domain: { id: domainId }, instanceId },
1969
+ where: useTime
1970
+ ? from
1971
+ ? /* 씨앗 뒤 · 목표 이내 — 시각이 빈 옛 행은 씨앗 뒤에 있는 것만 포함한다(보수적 포함을 유지). */
1972
+ [
1973
+ { ...baseWhere, revision: (0, typeorm_1.MoreThan)(from), eventTime: (0, typeorm_1.LessThanOrEqual)(new Date(cutoffMs)) },
1974
+ { ...baseWhere, revision: (0, typeorm_1.MoreThan)(from), eventTime: (0, typeorm_1.IsNull)() }
1975
+ ]
1976
+ : [
1977
+ { ...baseWhere, eventTime: (0, typeorm_1.LessThanOrEqual)(new Date(cutoffMs)) },
1978
+ { ...baseWhere, eventTime: (0, typeorm_1.IsNull)() }
1979
+ ]
1980
+ : untilRevision != null
1981
+ ? from
1982
+ ? { ...baseWhere, revision: (0, typeorm_1.And)((0, typeorm_1.MoreThan)(from), (0, typeorm_1.LessThanOrEqual)(untilRevision)) }
1983
+ : { ...baseWhere, revision: (0, typeorm_1.LessThanOrEqual)(untilRevision) }
1984
+ : from
1985
+ ? { ...baseWhere, revision: (0, typeorm_1.MoreThan)(from) }
1986
+ : baseWhere,
1060
1987
  order: { revision: 'ASC' }
1061
1988
  });
1062
- const cutoffMs = untilTime != null ? Date.parse(untilTime) : NaN;
1063
- const wanted = rows.filter(r => {
1064
- if (untilTime != null && !Number.isNaN(cutoffMs)) {
1065
- const t = r.eventTime != null ? Date.parse(String(r.eventTime)) : NaN;
1066
- return Number.isNaN(t) ? true : t <= cutoffMs; // eventTime 없는 레거시 행은 포함(보수적)
1067
- }
1068
- return untilRevision == null || (r.revision ?? 0) <= untilRevision;
1069
- });
1989
+ const wanted = rows;
1070
1990
  /*
1071
1991
  * **그때의 공장으로 접는다.**
1072
1992
  *
@@ -1081,7 +2001,7 @@ class TwinEngine {
1081
2001
  where: { domain: { id: domainId }, instanceId },
1082
2002
  order: { rev: 'ASC' }
1083
2003
  });
1084
- const boardOf = new Map(structures.map(x => [x.rev, x.board]));
2004
+ const boardOf = new Map(structures.map(x => [x.rev, x.model]));
1085
2005
  /* 컬럼이 생기기 전 행은 리비전이 비어 있다 — **가장 오래된 구조**에 속한다(0 으로 채우지 않는다). */
1086
2006
  const oldest = structures[0]?.rev;
1087
2007
  const revOf = (r) => r.structureRev ?? oldest;
@@ -1090,12 +2010,12 @@ class TwinEngine {
1090
2010
  if (!r.payload)
1091
2011
  continue;
1092
2012
  const rev = revOf(r);
1093
- const board = (rev !== undefined && boardOf.get(rev)) || reg.board;
2013
+ const model = (rev !== undefined && boardOf.get(rev)) || reg.model;
1094
2014
  const last = segments[segments.length - 1];
1095
- if (last && last.board === board)
2015
+ if (last && last.model === model)
1096
2016
  last.events.push(r.payload);
1097
2017
  else
1098
- segments.push({ board, events: [r.payload] });
2018
+ segments.push({ model, events: [r.payload] });
1099
2019
  }
1100
2020
  /*
1101
2021
  * **가장 새 구조가 지금의 공장이다** — 그 아래에서 아직 아무 일도 없었더라도.
@@ -1108,19 +2028,115 @@ class TwinEngine {
1108
2028
  * 설비가 화면에 서고 — 이 작업이 막으려던 바로 그 거짓말이 된다.
1109
2029
  */
1110
2030
  const asOfNow = untilRevision == null && untilTime == null;
1111
- const newest = structures[structures.length - 1]?.board;
1112
- if (asOfNow && newest && segments[segments.length - 1]?.board !== newest)
1113
- segments.push({ board: newest, events: [] });
1114
- if (!segments.length)
1115
- return replay(((asOfNow && newest) || reg.board), []);
1116
- if (segments.length === 1)
1117
- return replay(segments[0].board, segments[0].events);
2031
+ const newest = structures[structures.length - 1]?.model;
2032
+ if (asOfNow && newest && segments[segments.length - 1]?.model !== newest)
2033
+ segments.push({ model: newest, events: [] });
2034
+ /*
2035
+ * 접은 상태에 **주의 신호와 시각을 채운다.**
2036
+ *
2037
+ * 라이브·시뮬은 커널이 신호를 스스로 내지만, 저널을 접는 이 경로는 프로젝터 상태만 낸다 — 신호도
2038
+ * `nowTime` 도 없다. 그래서 **과거를 다시 계산하면 주의 레일이 텅 비었고**(지도는 `snap.attentions` 를
2039
+ * 읽는다), 기동돼 있지 않은 트윈을 보는 화면도 같았다. 신호는 상태에서 계산되는 것이므로
2040
+ * 여기서 같은 공식(`deriveAttentions`)으로 채우면 된다 — 두 벌을 두지 않는다.
2041
+ *
2042
+ * `nowTime` 이 먼저다: "늦었나" 판정이 그 값을 본다. 다시 계산한 시점의 정직한 "지금" 은 물어본 시각
2043
+ * (`untilTime`)이고, 없으면 마지막으로 적용한 이벤트의 시각이다. 둘 다 없으면 채우지 않는다 —
2044
+ * 벽시계를 끼워 넣으면 과거 화면이 "지금 기준으로 늦었다" 고 말하게 된다.
2045
+ */
2046
+ const lastEventTime = rows.length ? (rows[rows.length - 1]?.eventTime?.toISOString() ?? '') : '';
2047
+ /*
2048
+ * **가동 이력도 되살린다** — 다시 계산한 화면에 설비 계측이 비어 있던 것.
2049
+ *
2050
+ * OEE 는 원 시스템이 누적을 보내 주지 않아 호스트가 상태 전이를 적분해 만든다(그래서 커널이 아니라
2051
+ * 여기 있다). 그런데 그 누적기는 **라이브에서만** 돌았고, 저널을 접는 경로는 그 계산을 하지 않았다 —
2052
+ * 과거를 다시 계산하면 모든 설비가 "가동 이력이 전혀 없음" 으로 보였다.
2053
+ *
2054
+ * 없는 것은 데이터가 아니라 계산이다: 입력(`equipment.status` 전이·`quality.output`)은 저널에 다
2055
+ * 있다. 그래서 **같은 누적기에 같은 이벤트를 태운다** — 규칙을 두 벌 만들지 않는다.
2056
+ *
2057
+ * 시간여행에서도 맞다: 여기 태우는 것은 이미 잘라 낸(`wanted`) 이벤트뿐이므로, 그 시점까지의
2058
+ * 가동 이력이 나온다(그 뒤에 일어난 고장이 과거 화면에 섞이지 않는다).
2059
+ */
2060
+ const oee = new oee_accumulator_js_1.OeeAccumulator();
2061
+ /* 재개점이 있으면 그 위에 꼬리만 얹는다 — 없으면 꼬리분만 세어 가용률이 조용히 작아진다. */
2062
+ if (resume?.fold?.oee)
2063
+ oee.restore(resume.fold.oee);
2064
+ for (const r of wanted) {
2065
+ try {
2066
+ oee.apply(r.payload);
2067
+ }
2068
+ catch {
2069
+ /* 한 건이 이상해도 나머지 계측을 버리지 않는다 — 누적기는 모르는 이벤트를 무시하는 계약이다. */
2070
+ }
2071
+ }
2072
+ const withNow = (st) => {
2073
+ if (!st || typeof st !== 'object')
2074
+ return st;
2075
+ const nowTime = st.nowTime || untilTime || lastEventTime || undefined;
2076
+ const based = nowTime ? { ...st, nowTime } : st;
2077
+ /* 계측 시점은 그 화면의 "지금" 이다 — 벽시계로 재면 과거 화면의 가용률이 시간이 갈수록 떨어진다. */
2078
+ const nowMs = nowTime ? Date.parse(String(nowTime)) : Number.NaN;
2079
+ const withMetrics = (0, oee_accumulator_js_1.withLiveOee)(based, oee, Number.isFinite(nowMs) ? nowMs : undefined);
2080
+ return (0, live_attentions_js_1.withLiveAttentions)(withMetrics);
2081
+ };
2082
+ /* 접은 결과를 남긴다 — **지금을 물었을 때만**(시간여행 결과를 "지금" 으로 저장하면 거짓이 된다). */
2083
+ /*
2084
+ * 접은 지점의 리비전 — 사슬에 적을 이름이다. 꼬리를 접었으면 그 꼬리의 끝, 아무것도 안 읽었으면
2085
+ * 씨앗의 자리 그대로다(모르면 0).
2086
+ */
2087
+ const foldedTo = rows.length ? (rows[rows.length - 1]?.revision ?? 0) : (from ?? 0);
2088
+ const keep = (st, fold) => {
2089
+ /* 재개점을 함께 남긴다 — 상태만 남기면 다음 번에 또 0부터 접어야 한다(그것이 이 작업의 요점이다).
2090
+ **구조가 갈린 폴드에는 재개점을 붙이지 않는다**: 마디를 건너뛴 씨앗은 그 경계의 판정을 잃는다. */
2091
+ if (asOfNowRead && tip && st) {
2092
+ void this.saveFoldedSnapshot(domainId, instanceId, { revision: tip.revision, state: st, structureRev: tip.structureRev, fold });
2093
+ }
2094
+ /*
2095
+ * 사슬에는 **과거를 접었을 때도** 한 지점을 남긴다 (2026-08-18 실측으로 고침).
2096
+ *
2097
+ * 처음에는 「지금 읽기」에서만 남겼다. 그런데 도는 트윈의 지금 읽기는 커널 스냅샷으로 즉시 답하고
2098
+ * 폴드에 닿지 않는다 — 그래서 사슬이 **영원히 비어 있었다**(실측: 지점 0개, 시간여행 3.7s 그대로).
2099
+ *
2100
+ * 지점은 「지금」을 주장하지 않는다: 자기 리비전과 시각을 달고 있으므로 과거 폴드의 결과를 남겨도
2101
+ * 거짓이 아니다(그것이 스냅샷과 다른 점이다). 그래서 첫 과거 조회가 다음 과거 조회를 빠르게 한다.
2102
+ */
2103
+ if (fold && st) {
2104
+ const at = asOfNowRead && tip ? tip.revision : foldedTo;
2105
+ if (at > 0)
2106
+ void this.keepChainPoint(domainId, instanceId, {
2107
+ revision: at,
2108
+ ...(lastEventTime ? { eventTime: lastEventTime } : {}),
2109
+ structureRev: (asOfNowRead && tip ? tip.structureRev : null) ?? null,
2110
+ fold
2111
+ }).catch(() => { });
2112
+ }
2113
+ return st;
2114
+ };
2115
+ /*
2116
+ * 씨앗이 있으면 **이어 접는다** — 한 구조 안에서만(구조가 갈리면 아래 마디 경로가 맡는다).
2117
+ * 새 재개점도 함께 남긴다: 다음 번에 또 꼬리만 접을 수 있어야 이 지름길이 계속 산다.
2118
+ */
2119
+ if (resume?.fold?.reducer && segments.length <= 1) {
2120
+ const model = (segments[0]?.model ?? (asOfNow && newest) ?? reg.model);
2121
+ const out = replayFrom(model, resume.fold.reducer, segments[0]?.events ?? []);
2122
+ return keep(withNow(out.state), { reducer: out.checkpoint, oee: oee.serialize() });
2123
+ }
2124
+ if (!segments.length) {
2125
+ const model = ((asOfNow && newest) || reg.model);
2126
+ const out = replayWithCheckpoint(model, []);
2127
+ return keep(withNow(out.state), { reducer: out.checkpoint, oee: oee.serialize() });
2128
+ }
2129
+ if (segments.length === 1) {
2130
+ const out = replayWithCheckpoint(segments[0].model, segments[0].events);
2131
+ return keep(withNow(out.state), { reducer: out.checkpoint, oee: oee.serialize() });
2132
+ }
2133
+ /* 커널 계약도 `model` 이다(0.6.14) — 경계에서 어휘를 되돌려 담던 브릿지가 사라졌다. */
1118
2134
  const { state, shifts } = replaySegments(segments);
1119
2135
  /* 경계에서 사라진 것을 조용히 넘기지 않는다 — 수가 줄어든 이유를 어딘가에는 남겨야 한다. */
1120
2136
  for (const sh of shifts)
1121
2137
  if (sh.equipmentDropped || sh.locationsDropped || sh.personsDropped || sh.assetsDropped)
1122
2138
  console.info(`[twin-engine] "${instanceId}" replay crossed a structure change — dropped ${sh.equipmentDropped} equipment, ${sh.locationsDropped} locations, ${sh.personsDropped} persons, ${sh.assetsDropped} assets that no longer exist.`);
1123
- return state;
2139
+ return keep(withNow(state));
1124
2140
  }
1125
2141
  /**
1126
2142
  * 공간(공동배치) 시각 범위 — 스크러버 앵커(runtime-state-model §4·§6). 그 공간 전 인스턴스 저널의 min/max eventTime.
@@ -1154,12 +2170,19 @@ class TwinEngine {
1154
2170
  static onStop(fn) {
1155
2171
  this.stopHooks.push(fn);
1156
2172
  }
1157
- static async stop(id) {
1158
- const i = this.instances[id];
2173
+ static async stop(domainId, id) {
2174
+ const i = this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, id)];
1159
2175
  if (i) {
2176
+ /*
2177
+ * **끄기 전에 남긴다** — 지금이 메모리가 진실인 마지막 순간이다.
2178
+ *
2179
+ * 남기지 않으면 다음 조회가 저널을 전량 다시 접는다(그 값은 어차피 방금 메모리에 있던 것이다).
2180
+ * 체크포인트 루프가 20초마다 뜨지만 그 사이에 멈추면 그 구간이 통째로 다시 접힌다.
2181
+ */
2182
+ await this.persistSnapshot(domainId, id).catch(err => console.error(`[twin-engine] snapshot on stop fail "${id}"`, err?.message ?? err));
1160
2183
  clearInterval(i.timer);
1161
2184
  i.unsub();
1162
- delete this.instances[id];
2185
+ delete this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, id)];
1163
2186
  await (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance)
1164
2187
  .update({ domain: { id: i.domainId }, instanceId: id }, { status: 'stopped' })
1165
2188
  .catch(err => console.error('twin deregister fail', err));
@@ -1171,8 +2194,161 @@ class TwinEngine {
1171
2194
  catch { /* 훅 격리 */ }
1172
2195
  }
1173
2196
  }
1174
- static runtime(id) {
1175
- return this.instances[id]?.runtime;
2197
+ /*
2198
+ * tick 한 번 — **한 트윈의 예외가 서버를 내리지 못하게** 감싼다.
2199
+ *
2200
+ * 잘못된 시나리오가 실렸을 때 다음 tick 에서 `rate.meanPerHour` 를 읽다 터졌고, 타이머 콜백의
2201
+ * 예외는 아무도 받지 않아 **uncaught exception 으로 프로세스가 내려갔다.** 한 테넌트의 잘못된
2202
+ * 선언이 모든 테넌트를 멈춘 셈이다. 문 앞에서 막는 것이 1차 방벽이고(`validateScenario`),
2203
+ * 이것이 2차 방벽이다.
2204
+ *
2205
+ * **조용히 삼키지 않는다.** 실행을 멈추고 그 사실을 남긴다 — 예외를 무시하고 계속 tick 하면
2206
+ * 같은 오류가 매 주기 쏟아지고, 그 트윈은 "도는 것처럼 보이면서" 아무것도 진행하지 않는다.
2207
+ */
2208
+ /**
2209
+ * 같은 현장 트윈들의 **설비 상태**를 커널에 넘긴다 — 커널이 요청할 때만.
2210
+ *
2211
+ * ── 경계 (2026-08-14) ──────────────────────────────────────────────────────
2212
+ * 호스트가 아는 것은 **누가 같은 현장에 있는가** 하나다. 무엇을 읽고 그것을 어떻게 부하로 바꿀지는
2213
+ * 커널이 정한다(계수는 트윈의 모델이 선언한다). 호스트가 kW 를 계산해 주면 트윈마다 다른 규칙이
2214
+ * 생기고, 그 규칙은 어디에도 적혀 있지 않게 된다.
2215
+ *
2216
+ * 상태만 넘긴다. 스냅샷을 통째로 넘기면 상태 크기에 비례한 비용을 매 tick 치르게 된다 —
2217
+ * 설비 목록은 그 트윈의 커널이 이미 들고 있는 것이라 훑는 값이 싸다.
2218
+ */
2219
+ static feedPeerEquipment(inst) {
2220
+ const kernel = inst.kernel;
2221
+ if (typeof kernel?.observePeerEquipment !== 'function')
2222
+ return; // 이웃을 읽지 않는 커널
2223
+ if (!inst.spaceId) {
2224
+ kernel.observePeerEquipment([]); // 현장이 없으면 이웃도 없다(옛 상태가 남지 않게 비운다)
2225
+ return;
2226
+ }
2227
+ const peers = [];
2228
+ for (const other of Object.values(this.instances)) {
2229
+ if (other === inst || other.domainId !== inst.domainId || other.spaceId !== inst.spaceId)
2230
+ continue;
2231
+ const eq = other.kernel?.equipment;
2232
+ if (!eq || typeof eq.forEach !== 'function')
2233
+ continue;
2234
+ eq.forEach(e => peers.push({ id: String(e?.id ?? ''), status: String(e?.status ?? '') }));
2235
+ }
2236
+ kernel.observePeerEquipment(peers);
2237
+ }
2238
+ static tickGuarded(domainId, id, runtime) {
2239
+ const inst = this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, id)];
2240
+ const load = inst && (inst.load ?? (inst.load = (0, load_meter_js_1.newLoadMeter)()));
2241
+ const t0 = performance.now();
2242
+ try {
2243
+ /* 이웃의 설비 상태를 먼저 싣는다 — 커널이 이번 tick 에서 부하를 만들 때 읽는다. */
2244
+ if (inst)
2245
+ this.feedPeerEquipment(inst);
2246
+ runtime.tick(this.TICK_MS);
2247
+ /* 재고 말한다 — 시뮬 틱은 메인 이벤트 루프에서 수행된다. 예산(간격의 절반)을 넘기면 HTTP·구독이
2248
+ 함께 느려지는데, 예전에는 그것을 볼 계기판이 없어 "터지면 알고 느려지면 몰랐다". */
2249
+ if (load) {
2250
+ const took = performance.now() - t0;
2251
+ (0, load_meter_js_1.recordPhase)(load, 'tick', took);
2252
+ const j = (0, load_meter_js_1.judgeCycle)(load, took, this.TICK_MS, Date.now());
2253
+ if (j.warn)
2254
+ console.warn((0, load_meter_js_1.slowTickMessage)(id, took, j.budgetMs, load));
2255
+ this.guardStarvation(domainId, id, took);
2256
+ }
2257
+ }
2258
+ catch (err) {
2259
+ /*
2260
+ * 멈추는 길은 **하나**다(`stop`) — 예전에는 타이머만 껐다. 그러면 등록부는 계속 `running` 이라
2261
+ * 말하고(아무 틱도 없는 채로), 부팅 재개는 그 거짓을 근거로 다시 세운다. 스냅샷 보존·피드 정리·
2262
+ * 등록부 갱신이 모두 `stop` 안에 있다.
2263
+ */
2264
+ this.stopWithNote(domainId, id, { code: 'tick-failed', params: { reason: String(err?.message ?? err) } }, `[twin-engine] "${id}" tick failed — this twin is stopped (other twins keep running). ` +
2265
+ `Fix the declaration and start it again. Reason: ${err?.message ?? err}`);
2266
+ }
2267
+ }
2268
+ /**
2269
+ * 호스트를 굶기는 트윈을 멈춘다 — **도는 척하는 것보다 멈춘 것이 낫다.**
2270
+ *
2271
+ * 굶김 문턱을 넘는 틱이 연속 `STARVE_STREAK` 번이면 그 트윈은 구조적으로 무겁다(우연이 아니다).
2272
+ * 문턱 아래로 한 번만 내려와도 연속을 끊는다 — 무거운 순간 하나로 트윈을 내리지 않는다.
2273
+ */
2274
+ static guardStarvation(domainId, id, tookMs) {
2275
+ const key = (0, runtime_key_js_1.runtimeKey)(domainId, id);
2276
+ const starveMs = this.TICK_MS * this.STARVE_FACTOR;
2277
+ if (!(tookMs >= starveMs)) {
2278
+ this.starveStreak.delete(key);
2279
+ return;
2280
+ }
2281
+ const streak = (this.starveStreak.get(key) ?? 0) + 1;
2282
+ this.starveStreak.set(key, streak);
2283
+ if (streak < this.STARVE_STREAK)
2284
+ return;
2285
+ this.starveStreak.delete(key);
2286
+ const secs = Math.round(tookMs) / 1000;
2287
+ this.stopWithNote(domainId, id, { code: 'starved', params: { streak, thresholdSec: starveMs / 1000, lastSec: secs } }, `[twin-engine] "${id}" stopped — ${streak} consecutive ticks over ${starveMs / 1000}s (last ${secs}s). ` +
2288
+ `A simulation tick runs on the main loop, so this twin was stalling HTTP, subscriptions and every other twin. ` +
2289
+ `Its state is checkpointed; start it again after making it lighter (fewer orders/resources) or wait for off-loop ticking.`);
2290
+ }
2291
+ /** 멈추고 **이유를 남긴다** — 이유 없는 「정지」는 사람이 자기가 멈춘 것으로 읽는다. */
2292
+ static stopWithNote(domainId, id, note, log) {
2293
+ console.error(log);
2294
+ this.stopNotes.set((0, runtime_key_js_1.runtimeKey)(domainId, id), note);
2295
+ this.stop(domainId, id).catch(err => console.error(`[twin-engine] stop after guard failed "${id}"`, err?.message ?? err));
2296
+ }
2297
+ /** 이 트윈이 스스로 멈춘 이유(있으면) — 화면이 옮겨 말한다. */
2298
+ static stopNoteOf(domainId, id) {
2299
+ return this.stopNotes.get((0, runtime_key_js_1.runtimeKey)(domainId, id));
2300
+ }
2301
+ /**
2302
+ * 이 트윈이 **지금 실행 중인가** — 판정의 집 하나.
2303
+ *
2304
+ * "스냅샷이 있나" 로는 답이 되지 않는다: 웜스타트가 되살린 상태가 캐시에 남아 있으면 멈춘 트윈도
2305
+ * 스냅샷을 낸다. 그것을 관측 중으로 읽으면 화면이 **멈춘 트윈의 작업을 0 건이라고 단언**한다
2306
+ * (실제로 그렇게 나왔다 — 관측이 없는 것과 0 건은 다르다는 이 프로젝트의 규율을 화면이 어겼다).
2307
+ *
2308
+ * 목록이 쓰는 것과 **같은 술어**다(`list()` 의 `running`) — 두 벌이면 어긋난다.
2309
+ */
2310
+ static isRunning(domainId, id) {
2311
+ return !!this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, id)];
2312
+ }
2313
+ static runtime(domainId, id) {
2314
+ return this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, id)]?.runtime;
2315
+ }
2316
+ /*
2317
+ * 커맨드 실행 — **판정은 `routeCommand`(순수)가 하고 여기서는 실행만** 한다.
2318
+ * 판정을 코드 한가운데 두면 이 부류를 테스트로 못 잡는다(엔진은 DB 를 물고 있어 단위 테스트가
2319
+ * 불러올 수 없다). 예전에는 리졸버가 `inst.runtime.dispatch` 를 곧바로 불러 미러에서 터졌다.
2320
+ */
2321
+ static async dispatchCommand(domainId, instanceId, command) {
2322
+ const inst = this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, instanceId)];
2323
+ const type = String(command?.type ?? '');
2324
+ const route = (0, command_routing_js_1.routeCommand)(inst && { mode: inst.mode, hasRuntime: !!inst.runtime, hasKernelDispatch: typeof inst.kernel?.dispatch === 'function' }, !!inst && inst.domainId === domainId, type);
2325
+ if (route.target === 'reject') {
2326
+ return { accepted: false, errorCode: route.errorCode, errorParams: route.errorParams, error: route.errorCode };
2327
+ }
2328
+ const cmd = { ...command, tenantId: domainId }; // tenantId 는 호출자 도메인으로 각인(감사·무결성)
2329
+ if (route.target === 'runtime')
2330
+ return inst.runtime.dispatch(cmd);
2331
+ /*
2332
+ * 미러 — 관측 커널로 보내고, **커맨드가 낸 사실을 저널 큐에 실어** 코얼레서가 번호를 부여하게 한다.
2333
+ * 미러에는 State 구독 배관이 없어(시뮬은 그 경로로 저널링) 커널 방출이 아무 데도 닿지 않는다.
2334
+ * 여기서 DB 를 따로 읽어 번호를 매기면 인메모리 카운터와 어긋나 리비전이 겹친다(겹침은 오류를
2335
+ * 내지 않고 재생 순서만 조용히 뒤섞는다).
2336
+ */
2337
+ const kernel = inst.kernel;
2338
+ const emitted = [];
2339
+ const off = kernel.onEvent?.((e) => emitted.push(e));
2340
+ let ack;
2341
+ try {
2342
+ ack = kernel.dispatch(cmd);
2343
+ }
2344
+ finally {
2345
+ off?.();
2346
+ }
2347
+ if (ack?.accepted && emitted.length) {
2348
+ inst.pendingJournal = [...(inst.pendingJournal ?? []), ...emitted];
2349
+ inst.dirty = true; // 코얼레서가 이번 주기에 비우고 방송까지 하게 한다
2350
+ }
2351
+ return ack ?? { accepted: false, errorCode: 'unknown-command', error: 'unknown-command' };
1176
2352
  }
1177
2353
  /**
1178
2354
  * 도메인 소유 게이트 — 인스턴스가 이 도메인 소유일 때만 true(테넌트 격리).
@@ -1180,16 +2356,25 @@ class TwinEngine {
1180
2356
  * this.instances[id] 를 만지기 전에 반드시 이걸로 확인해야 한다. 인스턴스 id 는 추측 가능하므로
1181
2357
  * 검증 없이 접근하면 크로스테넌트 읽기/정지가 가능해진다.
1182
2358
  */
2359
+ /**
2360
+ * 이 런타임의 **관측 모드** — `'live'`(외부 실물을 미러) 또는 `'sim'`(커널이 실행한다). 기동 중이 아니면 없다.
2361
+ *
2362
+ * 소비처가 `instances[id].mode` 를 직접 읽던 자리를 대신한다. 레지스트리를 밖에 열면 도메인 확인이
2363
+ * 자리마다 제각각이 되고, 실제로 그렇게 됐다(테넌트 격리 전수 확인, 2026-08-06).
2364
+ */
2365
+ static modeOf(domainId, id) {
2366
+ return this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, id)]?.mode;
2367
+ }
1183
2368
  static owns(domainId, id) {
1184
- return this.instances[id]?.domainId === domainId;
2369
+ return !!this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, id)];
1185
2370
  }
1186
2371
  /**
1187
2372
  * 이 트윈이 이 테넌트 것인가 — **떠 있든 아니든.**
1188
2373
  *
1189
- * `owns()` 는 **떠 있는** 런타임만 안다. 그것을 이력 조회의 관문으로 쓰면, 꺼진 트윈의 저널을
2374
+ * `owns()` 는 **기동 중인** 런타임만 안다. 그것을 이력 조회의 관문으로 쓰면, 꺼진 트윈의 저널을
1190
2375
  * 읽으려 할 때 "이 테넌트에 없다" 는 답이 돌아온다 — 두 가지가 틀렸다. 첫째, 저널은 트윈이 꺼져
1191
2376
  * 있을 때 **가장 필요한 것**이다(그게 이력의 존재 이유다). 둘째, 그 문장은 남의 것이라는 뜻이라
1192
- * 사용자가 권한 문제로 오해한다. 실제로는 그냥 안 돌고 있을 뿐이다.
2377
+ * 사용자가 권한 문제로 오해한다. 실제로는 그냥 실행 중이 아닐 뿐이다.
1193
2378
  *
1194
2379
  * 소유는 **등록부**가 안다. 이력·집계처럼 런타임과 무관한 질문은 이쪽에 묻는다.
1195
2380
  */
@@ -1198,37 +2383,145 @@ class TwinEngine {
1198
2383
  return true;
1199
2384
  return !!(await (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance).findOne({ where: { domain: { id: domainId }, instanceId } }));
1200
2385
  }
2386
+ /**
2387
+ * **이 공간의 인스턴스들** — 한 현실을 여러 렌즈가 비추므로, 공간을 물으면 그 렌즈 전부를 답한다.
2388
+ *
2389
+ * 화면이 이 규칙을 손으로 짜지 않게 서버가 답한다. 예측 화면은 같은 확장을 **한 파일에서 두 번**
2390
+ * 복제하고 있었다(전체 목록을 받아 클라이언트에서 걸렀다) — 규칙이 흩어지면 한쪽만 고쳐진다.
2391
+ *
2392
+ * 떠 있지 않은 것도 포함한다: 공간에 무엇이 있는지는 기동 여부와 다른 사실이다.
2393
+ */
2394
+ static async instanceIdsOfSpace(domainId, spaceId) {
2395
+ if (!spaceId)
2396
+ return [];
2397
+ const rows = await (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance).find({ where: { domain: { id: domainId }, spaceId } });
2398
+ return rows.map(r => r.instanceId).filter((x) => !!x);
2399
+ }
2400
+ /**
2401
+ * **이 공간에서 봐야 할 것** — 공간의 모든 렌즈에서 신호를 모은다.
2402
+ *
2403
+ * 합집합이 그대로 뜻이 있는 유일한 렌즈다(예측은 합칠 수 없다 — P50 두 개를 더할 수 없다).
2404
+ * 정렬·잘라내기는 화면과 **같은 규칙**을 쓴다(`digestAttentions`) — 서버가 고른 상위 N 이 화면이
2405
+ * 고를 N 과 달라지면 그 어긋남은 아무 데서도 오류로 드러나지 않는다.
2406
+ *
2407
+ * 신호마다 어느 트윈에서 왔는지(`instanceId`)를 붙인다. 공간에서 보면 같은 자리 id 가 렌즈마다
2408
+ * 다른 것을 가리킬 수 있고, 조치는 결국 그 트윈에 보내야 한다.
2409
+ */
2410
+ static async attentionsOfSpace(domainId, spaceId, limit) {
2411
+ const ids = await this.instanceIdsOfSpace(domainId, spaceId);
2412
+ const lenses = ids
2413
+ /* 떠 있지 않은 트윈은 **지금** 신호가 없다(그 시절 신호는 시간여행이 답한다). */
2414
+ .filter(id => this.owns(domainId, id))
2415
+ .map(id => {
2416
+ const kernel = this.kernel(domainId, id);
2417
+ const snap = kernel?.getSnapshot?.() ?? this.snapshot(domainId, id);
2418
+ return { instanceId: id, attentions: snap?.attentions ?? [] };
2419
+ });
2420
+ /* 모으는 규칙(태깅·급한 순서·자리 색)은 순수 함수가 들고 있다 — 여기서 손으로 접지 않는다. */
2421
+ return (0, attention_digest_js_1.mergeLensAttentions)(lenses, limit);
2422
+ }
1201
2423
  /** 라이브 커널(ForecastTwin) — forecast/divergence 예측 연산용. */
1202
- static kernel(id) {
1203
- return this.instances[id]?.kernel;
2424
+ static kernel(domainId, id) {
2425
+ return this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, id)]?.kernel;
1204
2426
  }
1205
2427
  /** 라이브 처리량 계측 스냅샷(모니터, ④-1) — 내부 누적(_acc*) 제외한 공개 지표. live 아니면 null. */
1206
- static metrics(id) {
1207
- const m = this.instances[id]?.metrics;
2428
+ static metrics(domainId, id) {
2429
+ const m = this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, id)]?.metrics;
1208
2430
  if (!m)
1209
2431
  return null;
1210
2432
  return {
1211
2433
  instanceId: id,
1212
2434
  ingestedTotal: m.ingestedTotal, broadcastTotal: m.broadcastTotal, journaledTotal: m.journaledTotal,
1213
2435
  ingestRate: m.ingestRate, broadcastRate: m.broadcastRate, journalRate: m.journalRate,
1214
- backlog: m.backlog, broadcastCoalesceMs: this.BROADCAST_COALESCE_MS
2436
+ backlog: m.backlog, broadcastCoalesceMs: this.BROADCAST_COALESCE_MS,
2437
+ /* 작업별 부하 — 무거운 것부터. 잰 적이 없으면 null(0 으로 채우면 "빠르다" 로 읽힌다). */
2438
+ load: (0, load_meter_js_1.loadSummary)(this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, id)]?.load, this.TICK_MS)
1215
2439
  };
1216
2440
  }
2441
+ /**
2442
+ * 부하 계기판만 따로 — **시뮬 트윈도 포함한다.**
2443
+ *
2444
+ * `metrics()` 는 라이브 지표(`inst.metrics`)가 있어야 무언가를 돌려준다. 그런데 이벤트 루프를 점유하는
2445
+ * 것은 주로 **시뮬 틱**이고, 시뮬 인스턴스에는 그 지표가 없어 통째로 안 보였다.
2446
+ */
2447
+ static load(domainId, id) {
2448
+ const inst = this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, id)];
2449
+ if (!inst)
2450
+ return null;
2451
+ return {
2452
+ instanceId: id,
2453
+ mode: inst.mode ?? 'sim',
2454
+ domainId: inst.domainId,
2455
+ domainLabel: inst.domain?.subdomain,
2456
+ realityMode: inst.realityMode,
2457
+ tickMs: this.TICK_MS,
2458
+ running: !!inst.timer || inst.mode === 'live',
2459
+ ...((0, load_meter_js_1.loadSummary)(inst.load, this.TICK_MS) ?? { recent: null, total: null, forksCreated: 0, overBudget: 0, budgetMs: this.TICK_MS * 0.5, loadRatio: null })
2460
+ };
2461
+ }
2462
+ /**
2463
+ * **한 곳에서 보는 전체 부하** — 몇 개가 실행 중이고, 누가 루프를 점유하고 있나.
2464
+ *
2465
+ * 시뮬 트윈도 포함한다(`metrics()` 는 라이브 지표가 있어야 답해서 시뮬이 통째로 안 보였다).
2466
+ */
2467
+ static fleet(domainId) {
2468
+ const keys = Object.keys(this.instances).filter(key => !domainId || (0, runtime_key_js_1.isOfDomain)(key, domainId));
2469
+ const rows = keys.map(key => {
2470
+ const at = (0, runtime_key_js_1.parseRuntimeKey)(key);
2471
+ const inst = this.instances[key];
2472
+ /* 도메인을 함께 넘긴다 — 운영자가 먼저 묻는 것은 "어느 테넌트가 루프를 먹나" 다.
2473
+ 읽을 수 있는 이름(subdomain)은 라이브 인스턴스에만 붙어 있으므로, 없으면 리졸버가 채운다. */
2474
+ return {
2475
+ instanceId: at.instanceId,
2476
+ mode: inst.mode ?? 'sim',
2477
+ domainId: at.domainId,
2478
+ domainLabel: inst.domain?.subdomain,
2479
+ meter: inst.load
2480
+ };
2481
+ });
2482
+ return {
2483
+ tickMs: this.TICK_MS,
2484
+ broadcastCoalesceMs: this.BROADCAST_COALESCE_MS,
2485
+ ...(0, load_meter_js_1.fleetLoad)(rows, this.TICK_MS),
2486
+ /* 줄마다 상세 — 화면이 펼쳐 볼 수 있게. 최근 부하 순서는 fleetLoad 가 정한다. */
2487
+ details: keys.map(key => { const at = (0, runtime_key_js_1.parseRuntimeKey)(key); return this.load(at.domainId, at.instanceId); }).filter(Boolean)
2488
+ };
2489
+ }
2490
+ /** 이 트윈에서 fork 가 만들어졌다 — 예측 한 번이 수십 개를 만든다. */
2491
+ static countForks(domainId, id, count) {
2492
+ const inst = this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, id)];
2493
+ if (inst)
2494
+ (0, load_meter_js_1.recordFork)(inst.load ?? (inst.load = (0, load_meter_js_1.newLoadMeter)()), count);
2495
+ }
2496
+ /** 엔진 밖(예측 질의 등)에서 무거운 작업을 잰다 — 같은 계기판에 모인다. */
2497
+ static recordLoad(domainId, id, phase, tookMs) {
2498
+ const inst = this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, id)];
2499
+ if (inst)
2500
+ (0, load_meter_js_1.recordPhase)(inst.load ?? (inst.load = (0, load_meter_js_1.newLoadMeter)()), phase, tookMs);
2501
+ }
1217
2502
  /** 전체 라이브 인스턴스 계측(모니터 대시보드용). */
1218
2503
  static async allMetrics(domainId) {
2504
+ /* 도메인 없이 부르면 전 테넌트를 훑는다(내부 모니터용) — 키에서 도메인을 되돌려 각자에게 묻는다. */
1219
2505
  const rows = Object.keys(this.instances)
1220
- .filter(id => !domainId || this.instances[id].domainId === domainId)
1221
- .map(id => this.metrics(id))
2506
+ .filter(key => !domainId || (0, runtime_key_js_1.isOfDomain)(key, domainId))
2507
+ .map(key => {
2508
+ const at = (0, runtime_key_js_1.parseRuntimeKey)(key);
2509
+ return this.metrics(at.domainId, at.instanceId);
2510
+ })
1222
2511
  .filter(Boolean);
1223
2512
  if (!rows.length || !domainId)
1224
2513
  return rows;
1225
2514
  // 표시 이름 부여 — 실행중 카드가 id 만 보이지 않도록 공간명을 실어준다(공간 카드와 동일). name=공간명 폴백 spaceId 폴백 instanceId.
1226
2515
  const insts = await (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance).find({ where: { domain: { id: domainId } } });
1227
2516
  const spaceOf = new Map(insts.map(i => [i.instanceId, i.spaceId]));
2517
+ /* 용도 선언도 함께 실어 보낸다 — 화면이 공간 이름으로 벤치를 **추측하지 않게** 한다.
2518
+ 추측하면 `loadtest-` 로 이름 지은 운영 트윈에 벤치 딱지가 붙는다. */
2519
+ const purposeOf = new Map(insts.map(i => [i.instanceId, i.purpose]));
1228
2520
  const nameOf = new Map((await (0, shell_1.getRepository)(twin_space_js_1.TwinSpace).find({ where: { domain: { id: domainId } } })).map(s => [s.spaceId, s.name]));
1229
2521
  for (const r of rows) {
1230
2522
  const sp = spaceOf.get(r.instanceId);
1231
2523
  r.spaceId = sp;
2524
+ r.purpose = purposeOf.get(r.instanceId);
1232
2525
  r.name = (sp && nameOf.get(sp)) || sp || r.instanceId;
1233
2526
  }
1234
2527
  return rows;
@@ -1244,18 +2537,18 @@ class TwinEngine {
1244
2537
  */
1245
2538
  /**
1246
2539
  * 예측용 커널을 **임의 시각 T 기준**으로 재구성 — 과거-vantage 예측(백테스트)·"그때 서서 본 미래".
1247
- * recover(untilTime)로 T 시점 상태를, T 이하 오더 관측을 모아 hydrate → monteCarloForecast 가 T 에서 앞으로 굴린다.
2540
+ * recover(untilTime)로 T 시점 상태를, T 이하 오더 관측을 모아 hydrate → monteCarloForecast 가 T 에서 앞으로 실행한다.
1248
2541
  * sim/live 무관(저널 기반 재구성). untilTime 생략 시 최신. 도메인 스코프(reg·journal 조회가 domainId).
1249
2542
  */
1250
2543
  static async buildForecastKernelAt(domainId, instanceId, untilTime) {
1251
2544
  const reg = await (0, shell_1.getRepository)(twin_instance_js_1.TwinInstance).findOne({ where: { domain: { id: domainId }, instanceId } });
1252
- if (!reg?.board)
2545
+ if (!reg?.model)
1253
2546
  return null;
1254
- const Kernel = KERNELS[reg.kind ?? 'wms'] ?? WmsKernel;
1255
- const k = new Kernel(domainId, undefined, this.mesSpecOf(reg.board));
1256
- k.loadBoard(reg.board);
1257
- this.applyOperations(k, reg.board, instanceId); // 예측도 같은 명세로 굴러야 한다(화면과 다른 숫자 금지)
1258
- await this.installEstimators(k, domainId, instanceId, reg.board); // 예측은 기다린다 — 실측을 놓치면 예측이 상수로 돈다
2547
+ const Kernel = kernelFor(reg.kind);
2548
+ const k = new Kernel(domainId, undefined, this.productionSpecOf(reg.model));
2549
+ k.loadTwinModel(reg.model);
2550
+ this.applyOperations(k, reg.model, instanceId); // 예측도 같은 명세로 굴러야 한다(화면과 다른 숫자 금지)
2551
+ await this.installEstimators(k, domainId, instanceId, reg.model); // 예측은 기다린다 — 실측을 놓치면 예측이 상수로 계산된다
1259
2552
  const state = await this.recover(domainId, instanceId, undefined, untilTime).catch(() => null);
1260
2553
  if (!state)
1261
2554
  return null;
@@ -1263,7 +2556,7 @@ class TwinEngine {
1263
2556
  const rows = await (0, shell_1.getRepository)(twin_event_js_1.TwinEvent).find({ where: { domain: { id: domainId }, instanceId, eventType: OP_EVENT.order }, order: { revision: 'ASC' } });
1264
2557
  const latest = new Map();
1265
2558
  for (const r of rows) {
1266
- if (Number.isFinite(cutoff) && Date.parse(r.eventTime) > cutoff)
2559
+ if (Number.isFinite(cutoff) && (r.eventTime?.getTime() ?? NaN) > cutoff)
1267
2560
  continue;
1268
2561
  const d = r.payload?.data;
1269
2562
  if (d?.orderId)
@@ -1273,8 +2566,8 @@ class TwinEngine {
1273
2566
  return k;
1274
2567
  }
1275
2568
  /** 현재 전체 스냅샷 — 라이브 우선, 없으면 저널 복구 캐시. */
1276
- static snapshot(id) {
1277
- const inst = this.instances[id];
2569
+ static snapshot(domainId, id) {
2570
+ const inst = this.instances[(0, runtime_key_js_1.runtimeKey)(domainId, id)];
1278
2571
  if (inst?.mode === 'live' && inst.projector) {
1279
2572
  /* live: **커널이 주목 신호를 스스로 낸다**(관측 모드) — 호스트가 덧붙이던 withLiveAttentions 는
1280
2573
  * 필요 없다. OEE 만 호스트가 채운다: 원 시스템이 시간 누적을 보내 주지 않아 상태 전이를 적분해
@@ -1282,7 +2575,7 @@ class TwinEngine {
1282
2575
  const st = inst.projector.snapshot();
1283
2576
  return inst.oee ? (0, oee_accumulator_js_1.withLiveOee)(st, inst.oee) : st;
1284
2577
  }
1285
- return inst?.runtime?.resync() ?? this.recovered[id];
2578
+ return inst?.runtime?.resync() ?? this.recovered[(0, runtime_key_js_1.runtimeKey)(domainId, id)];
1286
2579
  }
1287
2580
  }
1288
2581
  exports.TwinEngine = TwinEngine;