@senpi-ai/runtime 1.1.2 → 3.0.3

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 (481) hide show
  1. package/README.md +10 -9
  2. package/dist/actions/action-runtime-module.d.ts.map +1 -1
  3. package/dist/actions/action-runtime-module.js +1 -1
  4. package/dist/actions/action-runtime-module.js.map +1 -1
  5. package/dist/actions/close-position/close-position.action.d.ts.map +1 -1
  6. package/dist/actions/close-position/close-position.action.js +61 -14
  7. package/dist/actions/close-position/close-position.action.js.map +1 -1
  8. package/dist/actions/decision-engine.d.ts.map +1 -1
  9. package/dist/actions/decision-engine.js +3 -0
  10. package/dist/actions/decision-engine.js.map +1 -1
  11. package/dist/actions/open-position/open-position.action.d.ts.map +1 -1
  12. package/dist/actions/open-position/open-position.action.js +161 -26
  13. package/dist/actions/open-position/open-position.action.js.map +1 -1
  14. package/dist/actions/position-tracker/position-tracker.action.d.ts +6 -0
  15. package/dist/actions/position-tracker/position-tracker.action.d.ts.map +1 -1
  16. package/dist/actions/position-tracker/position-tracker.action.js +48 -0
  17. package/dist/actions/position-tracker/position-tracker.action.js.map +1 -1
  18. package/dist/actions/tracking-helpers.d.ts +16 -1
  19. package/dist/actions/tracking-helpers.d.ts.map +1 -1
  20. package/dist/actions/tracking-helpers.js +55 -9
  21. package/dist/actions/tracking-helpers.js.map +1 -1
  22. package/dist/actions/types.d.ts +10 -2
  23. package/dist/actions/types.d.ts.map +1 -1
  24. package/dist/actions/types.js +8 -0
  25. package/dist/actions/types.js.map +1 -1
  26. package/dist/cli/guide-commands.d.ts.map +1 -1
  27. package/dist/cli/guide-commands.js +84 -82
  28. package/dist/cli/guide-commands.js.map +1 -1
  29. package/dist/cli/senpi-commands.d.ts.map +1 -1
  30. package/dist/cli/senpi-commands.js +16 -110
  31. package/dist/cli/senpi-commands.js.map +1 -1
  32. package/dist/constants/dsl/index.d.ts +2 -0
  33. package/dist/constants/dsl/index.d.ts.map +1 -1
  34. package/dist/constants/dsl/index.js +2 -0
  35. package/dist/constants/dsl/index.js.map +1 -1
  36. package/dist/dsl/config/parse-tiers.d.ts.map +1 -1
  37. package/dist/dsl/config/parse-tiers.js +6 -2
  38. package/dist/dsl/config/parse-tiers.js.map +1 -1
  39. package/dist/dsl/engine-client/config-mapping.d.ts +3 -1
  40. package/dist/dsl/engine-client/config-mapping.d.ts.map +1 -1
  41. package/dist/dsl/engine-client/config-mapping.js +3 -1
  42. package/dist/dsl/engine-client/config-mapping.js.map +1 -1
  43. package/dist/dsl/engine-client/event-mapping.d.ts +2 -0
  44. package/dist/dsl/engine-client/event-mapping.d.ts.map +1 -1
  45. package/dist/dsl/engine-client/event-mapping.js +3 -0
  46. package/dist/dsl/engine-client/event-mapping.js.map +1 -1
  47. package/dist/dsl/events/build-closed-event.d.ts.map +1 -1
  48. package/dist/dsl/events/build-closed-event.js +1 -0
  49. package/dist/dsl/events/build-closed-event.js.map +1 -1
  50. package/dist/dsl/events/guards.d.ts.map +1 -1
  51. package/dist/dsl/events/guards.js +10 -0
  52. package/dist/dsl/events/guards.js.map +1 -1
  53. package/dist/dsl/events/handlers.d.ts +18 -2
  54. package/dist/dsl/events/handlers.d.ts.map +1 -1
  55. package/dist/dsl/events/handlers.js +304 -208
  56. package/dist/dsl/events/handlers.js.map +1 -1
  57. package/dist/dsl/events/initial-state.d.ts.map +1 -1
  58. package/dist/dsl/events/initial-state.js +3 -1
  59. package/dist/dsl/events/initial-state.js.map +1 -1
  60. package/dist/dsl/monitor/create-monitor.d.ts +15 -0
  61. package/dist/dsl/monitor/create-monitor.d.ts.map +1 -1
  62. package/dist/dsl/monitor/create-monitor.js +76 -9
  63. package/dist/dsl/monitor/create-monitor.js.map +1 -1
  64. package/dist/dsl/monitor/process-one-position.d.ts.map +1 -1
  65. package/dist/dsl/monitor/process-one-position.js +268 -82
  66. package/dist/dsl/monitor/process-one-position.js.map +1 -1
  67. package/dist/dsl/plugin/index.d.ts +16 -1
  68. package/dist/dsl/plugin/index.d.ts.map +1 -1
  69. package/dist/dsl/plugin/index.js +35 -4
  70. package/dist/dsl/plugin/index.js.map +1 -1
  71. package/dist/dsl/plugin/options.d.ts +18 -0
  72. package/dist/dsl/plugin/options.d.ts.map +1 -1
  73. package/dist/index.d.ts +14 -1
  74. package/dist/index.d.ts.map +1 -1
  75. package/dist/index.js +272 -32
  76. package/dist/index.js.map +1 -1
  77. package/dist/recording/emitter.d.ts +27 -0
  78. package/dist/recording/emitter.d.ts.map +1 -0
  79. package/dist/recording/emitter.js +2 -0
  80. package/dist/recording/emitter.js.map +1 -0
  81. package/dist/recording/identity.d.ts +34 -0
  82. package/dist/recording/identity.d.ts.map +1 -0
  83. package/dist/recording/identity.js +2 -0
  84. package/dist/recording/identity.js.map +1 -0
  85. package/dist/recording/index.d.ts +11 -0
  86. package/dist/recording/index.d.ts.map +1 -0
  87. package/dist/recording/index.js +2 -0
  88. package/dist/recording/index.js.map +1 -0
  89. package/dist/recording/noop-emitter.d.ts +23 -0
  90. package/dist/recording/noop-emitter.d.ts.map +1 -0
  91. package/dist/recording/noop-emitter.js +22 -0
  92. package/dist/recording/noop-emitter.js.map +1 -0
  93. package/dist/recording/otel/attributes.d.ts +35 -0
  94. package/dist/recording/otel/attributes.d.ts.map +1 -0
  95. package/dist/recording/otel/attributes.js +131 -0
  96. package/dist/recording/otel/attributes.js.map +1 -0
  97. package/dist/recording/otel/constants.d.ts +123 -0
  98. package/dist/recording/otel/constants.d.ts.map +1 -0
  99. package/dist/recording/otel/constants.js +172 -0
  100. package/dist/recording/otel/constants.js.map +1 -0
  101. package/dist/recording/otel/ids.d.ts +25 -0
  102. package/dist/recording/otel/ids.d.ts.map +1 -0
  103. package/dist/recording/otel/ids.js +37 -0
  104. package/dist/recording/otel/ids.js.map +1 -0
  105. package/dist/recording/otel/index.d.ts +13 -0
  106. package/dist/recording/otel/index.d.ts.map +1 -0
  107. package/dist/recording/otel/index.js +9 -0
  108. package/dist/recording/otel/index.js.map +1 -0
  109. package/dist/recording/otel/mappers.d.ts +100 -0
  110. package/dist/recording/otel/mappers.d.ts.map +1 -0
  111. package/dist/recording/otel/mappers.js +683 -0
  112. package/dist/recording/otel/mappers.js.map +1 -0
  113. package/dist/recording/otel/otel-emitter.d.ts +43 -0
  114. package/dist/recording/otel/otel-emitter.d.ts.map +1 -0
  115. package/dist/recording/otel/otel-emitter.js +99 -0
  116. package/dist/recording/otel/otel-emitter.js.map +1 -0
  117. package/dist/recording/otel/redaction.d.ts +47 -0
  118. package/dist/recording/otel/redaction.d.ts.map +1 -0
  119. package/dist/recording/otel/redaction.js +88 -0
  120. package/dist/recording/otel/redaction.js.map +1 -0
  121. package/dist/recording/records.d.ts +565 -0
  122. package/dist/recording/records.d.ts.map +1 -0
  123. package/dist/recording/records.js +14 -0
  124. package/dist/recording/records.js.map +1 -0
  125. package/dist/recording/transport/batcher.d.ts +59 -0
  126. package/dist/recording/transport/batcher.d.ts.map +1 -0
  127. package/dist/recording/transport/batcher.js +234 -0
  128. package/dist/recording/transport/batcher.js.map +1 -0
  129. package/dist/recording/transport/client.d.ts +41 -0
  130. package/dist/recording/transport/client.d.ts.map +1 -0
  131. package/dist/recording/transport/client.js +69 -0
  132. package/dist/recording/transport/client.js.map +1 -0
  133. package/dist/recording/transport/config.d.ts +53 -0
  134. package/dist/recording/transport/config.d.ts.map +1 -0
  135. package/dist/recording/transport/config.js +41 -0
  136. package/dist/recording/transport/config.js.map +1 -0
  137. package/dist/recording/transport/index.d.ts +16 -0
  138. package/dist/recording/transport/index.d.ts.map +1 -0
  139. package/dist/recording/transport/index.js +12 -0
  140. package/dist/recording/transport/index.js.map +1 -0
  141. package/dist/recording/transport/rows.d.ts +88 -0
  142. package/dist/recording/transport/rows.d.ts.map +1 -0
  143. package/dist/recording/transport/rows.js +15 -0
  144. package/dist/recording/transport/rows.js.map +1 -0
  145. package/dist/recording/wiring/emitter-factory.d.ts +39 -0
  146. package/dist/recording/wiring/emitter-factory.d.ts.map +1 -0
  147. package/dist/recording/wiring/emitter-factory.js +62 -0
  148. package/dist/recording/wiring/emitter-factory.js.map +1 -0
  149. package/dist/recording/wiring/identity.d.ts +27 -0
  150. package/dist/recording/wiring/identity.d.ts.map +1 -0
  151. package/dist/recording/wiring/identity.js +51 -0
  152. package/dist/recording/wiring/identity.js.map +1 -0
  153. package/dist/recording/wiring/index.d.ts +12 -0
  154. package/dist/recording/wiring/index.d.ts.map +1 -0
  155. package/dist/recording/wiring/index.js +9 -0
  156. package/dist/recording/wiring/index.js.map +1 -0
  157. package/dist/recording/wiring/record-builders.d.ts +107 -0
  158. package/dist/recording/wiring/record-builders.d.ts.map +1 -0
  159. package/dist/recording/wiring/record-builders.js +706 -0
  160. package/dist/recording/wiring/record-builders.js.map +1 -0
  161. package/dist/recording/wiring/subscriber.d.ts +28 -0
  162. package/dist/recording/wiring/subscriber.d.ts.map +1 -0
  163. package/dist/recording/wiring/subscriber.js +173 -0
  164. package/dist/recording/wiring/subscriber.js.map +1 -0
  165. package/dist/recording/wiring/values.d.ts +19 -0
  166. package/dist/recording/wiring/values.d.ts.map +1 -0
  167. package/dist/recording/wiring/values.js +49 -0
  168. package/dist/recording/wiring/values.js.map +1 -0
  169. package/dist/runtime/auto-update/command-runner.d.ts.map +1 -1
  170. package/dist/runtime/auto-update/command-runner.js +5 -1
  171. package/dist/runtime/auto-update/command-runner.js.map +1 -1
  172. package/dist/runtime/auto-update/resolve-package-name.d.ts +10 -0
  173. package/dist/runtime/auto-update/resolve-package-name.d.ts.map +1 -0
  174. package/dist/runtime/auto-update/resolve-package-name.js +35 -0
  175. package/dist/runtime/auto-update/resolve-package-name.js.map +1 -0
  176. package/dist/runtime/auto-update/run-update-command.d.ts +2 -0
  177. package/dist/runtime/auto-update/run-update-command.d.ts.map +1 -0
  178. package/dist/runtime/auto-update/run-update-command.js +37 -0
  179. package/dist/runtime/auto-update/run-update-command.js.map +1 -0
  180. package/dist/runtime/create-runtime-context.d.ts +2 -0
  181. package/dist/runtime/create-runtime-context.d.ts.map +1 -1
  182. package/dist/runtime/create-runtime-context.js +1 -0
  183. package/dist/runtime/create-runtime-context.js.map +1 -1
  184. package/dist/runtime/create-scanner-module.d.ts +4 -3
  185. package/dist/runtime/create-scanner-module.d.ts.map +1 -1
  186. package/dist/runtime/create-scanner-module.js +14 -5
  187. package/dist/runtime/create-scanner-module.js.map +1 -1
  188. package/dist/runtime/create-scanner-providers-for-run.d.ts.map +1 -1
  189. package/dist/runtime/create-scanner-providers-for-run.js +12 -1
  190. package/dist/runtime/create-scanner-providers-for-run.js.map +1 -1
  191. package/dist/runtime/load-runtime-config.d.ts +9 -0
  192. package/dist/runtime/load-runtime-config.d.ts.map +1 -1
  193. package/dist/runtime/load-runtime-config.js +41 -8
  194. package/dist/runtime/load-runtime-config.js.map +1 -1
  195. package/dist/runtime/map-strategies-registration.js +7 -8
  196. package/dist/runtime/map-strategies-registration.js.map +1 -1
  197. package/dist/runtime/map-strategies.d.ts.map +1 -1
  198. package/dist/runtime/map-strategies.js +12 -3
  199. package/dist/runtime/map-strategies.js.map +1 -1
  200. package/dist/runtime/recipe-version.d.ts +1 -1
  201. package/dist/runtime/recipe-version.d.ts.map +1 -1
  202. package/dist/runtime/recipe-version.js +1 -1
  203. package/dist/runtime/recipe-version.js.map +1 -1
  204. package/dist/runtime/reconcile-decide.d.ts +73 -0
  205. package/dist/runtime/reconcile-decide.d.ts.map +1 -0
  206. package/dist/runtime/reconcile-decide.js +186 -0
  207. package/dist/runtime/reconcile-decide.js.map +1 -0
  208. package/dist/runtime/reconcile-run.d.ts +62 -0
  209. package/dist/runtime/reconcile-run.d.ts.map +1 -0
  210. package/dist/runtime/reconcile-run.js +173 -0
  211. package/dist/runtime/reconcile-run.js.map +1 -0
  212. package/dist/runtime/reconcile-state.d.ts +44 -0
  213. package/dist/runtime/reconcile-state.d.ts.map +1 -1
  214. package/dist/runtime/reconcile-state.js +80 -44
  215. package/dist/runtime/reconcile-state.js.map +1 -1
  216. package/dist/runtime/risk-guard.d.ts +10 -0
  217. package/dist/runtime/risk-guard.d.ts.map +1 -1
  218. package/dist/runtime/risk-guard.js +23 -24
  219. package/dist/runtime/risk-guard.js.map +1 -1
  220. package/dist/runtime/run.d.ts.map +1 -1
  221. package/dist/runtime/run.js +3 -2
  222. package/dist/runtime/run.js.map +1 -1
  223. package/dist/runtime/runtime-schema.d.ts +4056 -793
  224. package/dist/runtime/runtime-schema.d.ts.map +1 -1
  225. package/dist/runtime/runtime-schema.js +183 -46
  226. package/dist/runtime/runtime-schema.js.map +1 -1
  227. package/dist/runtime/runtime-version.d.ts +3 -6
  228. package/dist/runtime/runtime-version.d.ts.map +1 -1
  229. package/dist/runtime/runtime-version.js +3 -6
  230. package/dist/runtime/runtime-version.js.map +1 -1
  231. package/dist/runtime/runtime.d.ts +47 -0
  232. package/dist/runtime/runtime.d.ts.map +1 -1
  233. package/dist/runtime/runtime.js +517 -134
  234. package/dist/runtime/runtime.js.map +1 -1
  235. package/dist/runtime/scanner-registry.d.ts +1 -1
  236. package/dist/runtime/scanner-registry.d.ts.map +1 -1
  237. package/dist/runtime/scanner-registry.js +3 -12
  238. package/dist/runtime/scanner-registry.js.map +1 -1
  239. package/dist/runtime/strategy-lifecycle.d.ts +45 -0
  240. package/dist/runtime/strategy-lifecycle.d.ts.map +1 -0
  241. package/dist/runtime/strategy-lifecycle.js +117 -0
  242. package/dist/runtime/strategy-lifecycle.js.map +1 -0
  243. package/dist/runtime/strategy-registry.d.ts +6 -0
  244. package/dist/runtime/strategy-registry.d.ts.map +1 -1
  245. package/dist/runtime/strategy-registry.js +1 -0
  246. package/dist/runtime/strategy-registry.js.map +1 -1
  247. package/dist/runtime/supervisor/long-running-supervisor.d.ts +222 -0
  248. package/dist/runtime/supervisor/long-running-supervisor.d.ts.map +1 -0
  249. package/dist/runtime/supervisor/long-running-supervisor.js +625 -0
  250. package/dist/runtime/supervisor/long-running-supervisor.js.map +1 -0
  251. package/dist/runtime/supervisor/orphan-sweep.d.ts +36 -0
  252. package/dist/runtime/supervisor/orphan-sweep.d.ts.map +1 -0
  253. package/dist/runtime/supervisor/orphan-sweep.js +255 -0
  254. package/dist/runtime/supervisor/orphan-sweep.js.map +1 -0
  255. package/dist/runtime/supervisor/supervisor-utils.d.ts +37 -0
  256. package/dist/runtime/supervisor/supervisor-utils.d.ts.map +1 -0
  257. package/dist/runtime/supervisor/supervisor-utils.js +175 -0
  258. package/dist/runtime/supervisor/supervisor-utils.js.map +1 -0
  259. package/dist/runtime-api/handlers/ingest-signals.d.ts +3 -3
  260. package/dist/runtime-api/handlers/ingest-signals.js +3 -3
  261. package/dist/runtime-api/intake/acceptance-record.d.ts +103 -0
  262. package/dist/runtime-api/intake/acceptance-record.d.ts.map +1 -0
  263. package/dist/runtime-api/intake/acceptance-record.js +192 -0
  264. package/dist/runtime-api/intake/acceptance-record.js.map +1 -0
  265. package/dist/runtime-api/intake/intake-context.d.ts +31 -0
  266. package/dist/runtime-api/intake/intake-context.d.ts.map +1 -0
  267. package/dist/runtime-api/intake/intake-context.js +21 -0
  268. package/dist/runtime-api/intake/intake-context.js.map +1 -0
  269. package/dist/runtime-api/intake/intake-mount.d.ts +118 -0
  270. package/dist/runtime-api/intake/intake-mount.d.ts.map +1 -0
  271. package/dist/runtime-api/intake/intake-mount.js +193 -0
  272. package/dist/runtime-api/intake/intake-mount.js.map +1 -0
  273. package/dist/runtime-api/intake/liveness-store.d.ts +32 -0
  274. package/dist/runtime-api/intake/liveness-store.d.ts.map +1 -0
  275. package/dist/runtime-api/intake/liveness-store.js +31 -0
  276. package/dist/runtime-api/intake/liveness-store.js.map +1 -0
  277. package/dist/runtime-api/intake/process-error-post.d.ts +15 -0
  278. package/dist/runtime-api/intake/process-error-post.d.ts.map +1 -0
  279. package/dist/runtime-api/intake/process-error-post.js +19 -0
  280. package/dist/runtime-api/intake/process-error-post.js.map +1 -0
  281. package/dist/runtime-api/intake/process-signal-post.d.ts +73 -0
  282. package/dist/runtime-api/intake/process-signal-post.d.ts.map +1 -0
  283. package/dist/runtime-api/intake/process-signal-post.js +188 -0
  284. package/dist/runtime-api/intake/process-signal-post.js.map +1 -0
  285. package/dist/runtime-api/intake/scanner-launcher.d.ts +133 -0
  286. package/dist/runtime-api/intake/scanner-launcher.d.ts.map +1 -0
  287. package/dist/runtime-api/intake/scanner-launcher.js +204 -0
  288. package/dist/runtime-api/intake/scanner-launcher.js.map +1 -0
  289. package/dist/runtime-api/intake/scanner-registry.d.ts +36 -0
  290. package/dist/runtime-api/intake/scanner-registry.d.ts.map +1 -0
  291. package/dist/runtime-api/intake/scanner-registry.js +29 -0
  292. package/dist/runtime-api/intake/scanner-registry.js.map +1 -0
  293. package/dist/runtime-api/intake/types.d.ts +61 -0
  294. package/dist/runtime-api/intake/types.d.ts.map +1 -0
  295. package/dist/runtime-api/intake/types.js +8 -0
  296. package/dist/runtime-api/intake/types.js.map +1 -0
  297. package/dist/runtime-api/routes/signals.d.ts +20 -40
  298. package/dist/runtime-api/routes/signals.d.ts.map +1 -1
  299. package/dist/runtime-api/routes/signals.js +119 -75
  300. package/dist/runtime-api/routes/signals.js.map +1 -1
  301. package/dist/runtime-api/routes/signals.schema.d.ts +24 -86
  302. package/dist/runtime-api/routes/signals.schema.d.ts.map +1 -1
  303. package/dist/runtime-api/routes/signals.schema.js +35 -50
  304. package/dist/runtime-api/routes/signals.schema.js.map +1 -1
  305. package/dist/runtime-api/server.d.ts +15 -6
  306. package/dist/runtime-api/server.d.ts.map +1 -1
  307. package/dist/runtime-api/server.js +12 -12
  308. package/dist/runtime-api/server.js.map +1 -1
  309. package/dist/scanners/events.d.ts +6 -0
  310. package/dist/scanners/events.d.ts.map +1 -1
  311. package/dist/scanners/events.js.map +1 -1
  312. package/dist/scanners/external/scaffold/__init__.py +16 -0
  313. package/dist/scanners/external/scaffold/__main__.py +155 -0
  314. package/dist/scanners/external/scaffold/ctx.py +78 -0
  315. package/dist/scanners/external/scaffold/delivery.py +263 -0
  316. package/dist/scanners/external/scaffold/entrypoint_loader.py +151 -0
  317. package/dist/scanners/external/scaffold/http_post.py +70 -0
  318. package/dist/scanners/external/scaffold/journal.py +247 -0
  319. package/dist/scanners/external/scaffold/loop_primitives.py +65 -0
  320. package/dist/scanners/external/scaffold/requirements.txt +11 -0
  321. package/dist/scanners/external/scaffold/scaffold.py +361 -0
  322. package/dist/scanners/external/scaffold/scaffold_state.py +114 -0
  323. package/dist/scanners/external/scaffold/senpi_mcp.py +250 -0
  324. package/dist/scanners/external/scaffold/signal_envelope.py +220 -0
  325. package/dist/scanners/external/scaffold/state_manager.py +175 -0
  326. package/dist/scanners/external-scanner-receiver.d.ts +17 -1
  327. package/dist/scanners/external-scanner-receiver.d.ts.map +1 -1
  328. package/dist/scanners/external-scanner-receiver.js +16 -3
  329. package/dist/scanners/external-scanner-receiver.js.map +1 -1
  330. package/dist/scanners/implementations/external-scanner.d.ts.map +1 -1
  331. package/dist/scanners/implementations/external-scanner.js +7 -1
  332. package/dist/scanners/implementations/external-scanner.js.map +1 -1
  333. package/dist/scanners/implementations/momentum.d.ts.map +1 -1
  334. package/dist/scanners/implementations/momentum.js +16 -0
  335. package/dist/scanners/implementations/momentum.js.map +1 -1
  336. package/dist/scanners/runtime-module.d.ts.map +1 -1
  337. package/dist/scanners/runtime-module.js +9 -1
  338. package/dist/scanners/runtime-module.js.map +1 -1
  339. package/dist/scripts/run-dsl-standalone-live.d.ts +1 -1
  340. package/dist/scripts/run-dsl-standalone-live.js +5 -3
  341. package/dist/scripts/run-dsl-standalone-live.js.map +1 -1
  342. package/dist/senpi/client.d.ts +56 -4
  343. package/dist/senpi/client.d.ts.map +1 -1
  344. package/dist/senpi/client.js +123 -24
  345. package/dist/senpi/client.js.map +1 -1
  346. package/dist/senpi/index.d.ts +2 -1
  347. package/dist/senpi/index.d.ts.map +1 -1
  348. package/dist/senpi/index.js +1 -1
  349. package/dist/senpi/index.js.map +1 -1
  350. package/dist/senpi/types.d.ts +1 -2
  351. package/dist/senpi/types.d.ts.map +1 -1
  352. package/dist/state/state-manager.d.ts +17 -0
  353. package/dist/state/state-manager.d.ts.map +1 -1
  354. package/dist/state/state-manager.js +55 -4
  355. package/dist/state/state-manager.js.map +1 -1
  356. package/dist/strategy/strategy-state.d.ts +9 -1
  357. package/dist/strategy/strategy-state.d.ts.map +1 -1
  358. package/dist/strategy/strategy-state.js +62 -9
  359. package/dist/strategy/strategy-state.js.map +1 -1
  360. package/dist/tracking/build-rehydrate-items.d.ts +15 -0
  361. package/dist/tracking/build-rehydrate-items.d.ts.map +1 -0
  362. package/dist/tracking/build-rehydrate-items.js +19 -0
  363. package/dist/tracking/build-rehydrate-items.js.map +1 -0
  364. package/dist/tracking/constants.d.ts.map +1 -1
  365. package/dist/tracking/constants.js +2 -0
  366. package/dist/tracking/constants.js.map +1 -1
  367. package/dist/tracking/index.d.ts +3 -0
  368. package/dist/tracking/index.d.ts.map +1 -1
  369. package/dist/tracking/index.js +2 -0
  370. package/dist/tracking/index.js.map +1 -1
  371. package/dist/tracking/position-id-registry.d.ts +69 -0
  372. package/dist/tracking/position-id-registry.d.ts.map +1 -0
  373. package/dist/tracking/position-id-registry.js +139 -0
  374. package/dist/tracking/position-id-registry.js.map +1 -0
  375. package/dist/tracking/spans/fan-out-span-transport.d.ts +22 -0
  376. package/dist/tracking/spans/fan-out-span-transport.d.ts.map +1 -0
  377. package/dist/tracking/spans/fan-out-span-transport.js +49 -0
  378. package/dist/tracking/spans/fan-out-span-transport.js.map +1 -0
  379. package/dist/tracking/spans/otel/fit-row-budget.d.ts +22 -0
  380. package/dist/tracking/spans/otel/fit-row-budget.d.ts.map +1 -0
  381. package/dist/tracking/spans/otel/fit-row-budget.js +91 -0
  382. package/dist/tracking/spans/otel/fit-row-budget.js.map +1 -0
  383. package/dist/tracking/spans/otel/map-span-to-trace-row.d.ts +16 -0
  384. package/dist/tracking/spans/otel/map-span-to-trace-row.d.ts.map +1 -0
  385. package/dist/tracking/spans/otel/map-span-to-trace-row.js +227 -0
  386. package/dist/tracking/spans/otel/map-span-to-trace-row.js.map +1 -0
  387. package/dist/tracking/spans/otel/recording-span-transport.d.ts +43 -0
  388. package/dist/tracking/spans/otel/recording-span-transport.d.ts.map +1 -0
  389. package/dist/tracking/spans/otel/recording-span-transport.js +67 -0
  390. package/dist/tracking/spans/otel/recording-span-transport.js.map +1 -0
  391. package/dist/tracking/spans/otel/span-ids.d.ts +22 -0
  392. package/dist/tracking/spans/otel/span-ids.d.ts.map +1 -0
  393. package/dist/tracking/spans/otel/span-ids.js +32 -0
  394. package/dist/tracking/spans/otel/span-ids.js.map +1 -0
  395. package/dist/tracking/spans/plugin-span-tracker.d.ts +6 -0
  396. package/dist/tracking/spans/plugin-span-tracker.d.ts.map +1 -1
  397. package/dist/tracking/spans/plugin-span-tracker.js +82 -9
  398. package/dist/tracking/spans/plugin-span-tracker.js.map +1 -1
  399. package/dist/tracking/spans/redact-pii.d.ts +3 -1
  400. package/dist/tracking/spans/redact-pii.d.ts.map +1 -1
  401. package/dist/tracking/spans/redact-pii.js +5 -1
  402. package/dist/tracking/spans/redact-pii.js.map +1 -1
  403. package/dist/tracking/spans/span-transport.d.ts +6 -0
  404. package/dist/tracking/spans/span-transport.d.ts.map +1 -1
  405. package/dist/tracking/spans/span-transport.js +1 -1
  406. package/dist/tracking/spans/span-transport.js.map +1 -1
  407. package/dist/types/dsl/index.d.ts +24 -1
  408. package/dist/types/dsl/index.d.ts.map +1 -1
  409. package/dist/types/hooks.d.ts +1 -0
  410. package/dist/types/hooks.d.ts.map +1 -1
  411. package/dist/types/hooks.js +1 -0
  412. package/dist/types/hooks.js.map +1 -1
  413. package/dist/types/runtime.d.ts +6 -0
  414. package/dist/types/runtime.d.ts.map +1 -1
  415. package/dist/types/scanner.d.ts +7 -0
  416. package/dist/types/scanner.d.ts.map +1 -1
  417. package/dist/types/strategy.d.ts +3 -1
  418. package/dist/types/strategy.d.ts.map +1 -1
  419. package/dist/utils/keyed-mutex.d.ts +37 -0
  420. package/dist/utils/keyed-mutex.d.ts.map +1 -0
  421. package/dist/utils/keyed-mutex.js +77 -0
  422. package/dist/utils/keyed-mutex.js.map +1 -0
  423. package/dist/utils/safe-spawn.d.ts +6 -0
  424. package/dist/utils/safe-spawn.d.ts.map +1 -0
  425. package/dist/utils/safe-spawn.js +62 -0
  426. package/dist/utils/safe-spawn.js.map +1 -0
  427. package/examples/strategies/README.md +17 -12
  428. package/examples/strategies/iguana/README.md +135 -0
  429. package/examples/strategies/iguana/recipe.yaml +137 -0
  430. package/examples/strategies/iguana/scanners/scan.py +243 -0
  431. package/examples/strategies/iguana/scanners/scoring.py +152 -0
  432. package/examples/strategies/raptor/README.md +156 -0
  433. package/examples/strategies/raptor/recipe.yaml +154 -0
  434. package/examples/strategies/raptor/scanners/scan.py +349 -0
  435. package/examples/strategies/raptor/scanners/scoring.py +452 -0
  436. package/examples/strategies/spider/README.md +89 -0
  437. package/examples/strategies/spider/scalp/recipe.yaml +129 -0
  438. package/examples/strategies/spider/scalp/scanners/scan.py +219 -0
  439. package/examples/strategies/spider/scalp/scanners/scoring.py +179 -0
  440. package/examples/strategies/spider/swing/recipe.yaml +137 -0
  441. package/examples/strategies/spider/swing/scanners/scan.py +334 -0
  442. package/examples/strategies/spider/swing/scanners/scoring.py +184 -0
  443. package/examples/strategies/turbine/README.md +166 -0
  444. package/examples/strategies/turbine/recipe-runners.yaml +123 -0
  445. package/examples/strategies/turbine/recipe-volume.yaml +129 -0
  446. package/examples/strategies/turbine/scanners/scan.py +283 -0
  447. package/examples/strategies/turbine/scanners/scoring.py +190 -0
  448. package/openclaw.plugin.json +12 -1
  449. package/package.json +3 -3
  450. package/dist/runtime-api/handlers/group-by-scanner.d.ts +0 -43
  451. package/dist/runtime-api/handlers/group-by-scanner.d.ts.map +0 -1
  452. package/dist/runtime-api/handlers/group-by-scanner.js +0 -43
  453. package/dist/runtime-api/handlers/group-by-scanner.js.map +0 -1
  454. package/dist/scanners/external/liquidation-watchdog/README.md +0 -107
  455. package/dist/scanners/external/liquidation-watchdog/liquidation-watchdog.yaml +0 -48
  456. package/dist/scanners/external/liquidation-watchdog/producer.mjs +0 -336
  457. package/dist/scanners/external/momentum/README.md +0 -148
  458. package/dist/scanners/external/momentum/momentum.yaml +0 -116
  459. package/dist/scanners/external/momentum/producer.mjs +0 -251
  460. package/dist/scanners/external/shared/ingest.mjs +0 -112
  461. package/examples/README.md +0 -89
  462. package/examples/scanners-consumer-quickstart.mjs +0 -134
  463. package/examples/scanners-emerging-movers-v4.mjs +0 -287
  464. package/examples/scanners-liquidation-watchdog.mjs +0 -341
  465. package/examples/scanners-live-mcp.mjs +0 -208
  466. package/examples/scanners-multi-strategy.mjs +0 -165
  467. package/examples/scanners-position-tracker-e2e.mjs +0 -225
  468. package/examples/scanners-scheduled-events.mjs +0 -96
  469. package/examples/scanners-senpi-provider-client.mjs +0 -182
  470. package/examples/scanners-single-strategy.mjs +0 -198
  471. package/examples/strategies/dsl-showcase.yaml +0 -68
  472. package/examples/strategies/dsl.yaml +0 -51
  473. package/examples/strategies/fox-minimal-loosened.yaml +0 -240
  474. package/examples/strategies/fox-minimal.yaml +0 -242
  475. package/examples/strategies/minimal.yaml +0 -46
  476. package/examples/strategies/momentum/how-it-works.md +0 -48
  477. package/examples/strategies/momentum/momentum-guarded.yaml +0 -161
  478. package/examples/strategies/risk-showcase.yaml +0 -93
  479. package/examples/strategies/viper.yaml +0 -67
  480. package/examples/strategies/wolf.yaml +0 -72
  481. package/examples/yamls/sample-with-dsl-and-emerging-movers.yaml +0 -123
@@ -9,6 +9,7 @@ import { createLlmDecision } from "../actions/llm-decision/index.js";
9
9
  import { StateManager } from "../state/index.js";
10
10
  import { createContextBuilder } from "../context/index.js";
11
11
  import { createRiskGuard, createRiskGuardStub } from "./risk-guard.js";
12
+ import { createStrategyLifecycle } from "./strategy-lifecycle.js";
12
13
  // RiskGuardianService removed — gate decisions are now real-time in checkGate
13
14
  import { createRiskAuditLog } from "../risk/risk-audit-log.js";
14
15
  import { createNotificationService } from "./notifications.js";
@@ -30,23 +31,31 @@ import { createActionNotificationSubscriber, isActionLifecycleNotificationsEnabl
30
31
  import { MaxLeverageCache } from "../leverage/max-leverage-cache.js";
31
32
  import { buildStateLayout } from "./state-layout.js";
32
33
  import { createLogger } from "../utils/logger.js";
33
- import { createTrackingHandler, EventTracker, BatchingTransport, NoOpTransport, TRACKING_API_BASE_URL, } from "../tracking/index.js";
34
+ import { createTrackingHandler, EventTracker, BatchingTransport, NoOpTransport, TRACKING_API_BASE_URL, PositionIdRegistry, positionRegistryKey, buildRehydrateItems, } from "../tracking/index.js";
34
35
  import { VERSION } from "../version.js";
35
36
  import { randomUUID } from "node:crypto";
36
37
  import { trackingContext } from "../tracking/context.js";
38
+ import { buildIdentity, createRecordingComponents, createRecordingSubscriber, resolveTelemetryEnabled, } from "../recording/wiring/index.js";
39
+ import { runReconcile } from "./reconcile-run.js";
40
+ import { KeyedMutex } from "../utils/keyed-mutex.js";
37
41
  const logger = createLogger("[senpi-core][runtime]");
42
+ /** Fixed retry interval for the boot-reconcile loop. */
43
+ const RECONCILE_RETRY_INTERVAL_MS = 15_000;
38
44
  export class Runtime {
39
45
  config;
40
46
  options;
41
47
  bus;
42
48
  hookSystem;
43
49
  stateManager;
50
+ positionIdRegistry;
44
51
  scannerModule;
45
52
  dslPlugin = null;
46
53
  // riskGuardian removed — gate decisions are now real-time in checkGate
47
54
  senpi = null;
48
55
  healthStateModule = null;
49
56
  trackingHandler = null;
57
+ recordingSubscriber = null;
58
+ recordingBatcher = null;
50
59
  started = false;
51
60
  startedAt = null;
52
61
  /** Serial signal processing: queue and consumer so only one signal is handled at a time. */
@@ -59,12 +68,27 @@ export class Runtime {
59
68
  actionRuntimeModule;
60
69
  /** Stored so we can call off() in stop() and avoid retaining Runtime via scanner EventEmitter. */
61
70
  onScannerRunComplete = null;
71
+ onScannerRunSkip = null;
72
+ onScannerRunError = null;
62
73
  /** Cached strategy id resolved from the runtime wallet on first {@link auditQuery} call. */
63
74
  cachedStrategyId = null;
64
75
  /** In-flight resolution promise; ensures concurrent first-burst callers reuse one `listStrategies`. */
65
76
  strategyIdResolution = null;
66
77
  /** Action-layer Telegram subscriber (open submit / close); disposed in {@link Runtime.stop}. */
67
78
  actionNotificationSubscriber = null;
79
+ // ─── reconcile gate + mutex ──────────────────────────────────────────────────
80
+ /** Serializes reconcile vs the trade loop. One shared key "reconcile". */
81
+ reconcileMutex = new KeyedMutex();
82
+ /** Deferred gate: consumer awaits this before touching slot counts / running actions. */
83
+ reconcileGate = null;
84
+ /** Whether the runtime has been requested to stop (stops the boot-reconcile retry loop). */
85
+ reconcileStopped = false;
86
+ /** NodeJS timeout handle for a pending reconcile retry; cleared in stop(). */
87
+ reconcileRetryTimer = null;
88
+ /** Set when the reconcile gate is resolved by a successful/immediate boot reconcile; used to evict the pre-gate backlog. NOT set on stop(). */
89
+ gateResolvedAt = null;
90
+ /** Count of stale (pre-gate-open) signals evicted; surfaced in logs. */
91
+ staleSignalsEvicted = 0;
68
92
  /**
69
93
  * Per-process UUID. Used as the synthetic session_key for direct-path
70
94
  * spans (and lets us group "all LLM calls from this runtime boot" in
@@ -202,6 +226,19 @@ export class Runtime {
202
226
  throw new AuditQueryError("UPSTREAM", `audit_query failed: ${message}`);
203
227
  }
204
228
  }
229
+ /**
230
+ * Repopulate the PositionIdRegistry's confirmed entries at boot from persisted DSL
231
+ * states. Best-effort: a failure here must not block runtime start.
232
+ */
233
+ async rehydratePositionIdRegistry() {
234
+ try {
235
+ const dslStates = await this.stateManager.listDslStates(this.strategyConfig.address);
236
+ this.positionIdRegistry.rehydrate(buildRehydrateItems(dslStates));
237
+ }
238
+ catch (err) {
239
+ logger.warn("position.id registry rehydrate failed, continuing with empty registry", { err });
240
+ }
241
+ }
205
242
  /**
206
243
  * Cached wallet → strategy-id lookup. Concurrent callers share one
207
244
  * in-flight `listStrategies` promise; the cached id is reused across
@@ -286,159 +323,351 @@ export class Runtime {
286
323
  this.trackingHandler = createTrackingHandler(this.bus, tracker);
287
324
  this.stateManager = new StateManager(stateDir);
288
325
  await this.stateManager.hydrate();
326
+ this.positionIdRegistry = new PositionIdRegistry();
289
327
  const senpi = mcpTransport
290
328
  ? new SenpiClient(mcpTransport)
291
329
  : new SenpiClient({ apiKey });
292
330
  if (!mcpTransport) {
293
- await senpi.connect();
331
+ // Best-effort eager connect: MCP unreachable at boot must NOT abort
332
+ // Runtime.start(). The client reconnects lazily on first use; the detached
333
+ // boot-reconcile loop holds the trading gate closed until a reconcile against
334
+ // the real exchange succeeds, so we never trade on an unreconciled view.
335
+ try {
336
+ await senpi.connect();
337
+ }
338
+ catch (err) {
339
+ logger.warn("[runtime] initial MCP connect failed; starting with gate closed, will connect lazily", {
340
+ err: err instanceof Error ? err.message : String(err),
341
+ });
342
+ }
294
343
  }
295
344
  this.senpi = senpi;
296
345
  this.strategyConfig = resolveStrategyConfig(this.config);
297
- // try {
298
- // const { reconcileStateWithBackend } = await import("./reconcile-state.js");
299
- // await reconcileStateWithBackend(this.stateManager, senpi, [this.strategyConfig.address]);
300
- // } catch (err) {
301
- // logger.warn("reconcile after hydrate failed, continuing", { err });
302
- // }
303
- const llmDecision = createLlmDecision({});
304
- const contextBuilder = createContextBuilder();
305
- const notifications = createNotificationService({
306
- ...this.config.notifications,
307
- mcpTransport: this.options.mcpTransport,
346
+ await this.rehydratePositionIdRegistry();
347
+ // Telemetry recording: subscribe the emitter to the bus (on by default; degrades to a noop
348
+ // emitter when disabled or when no token is present — never a boot failure). Identity + config
349
+ // fingerprint are built lazily from the unresolved config — only on the live path, and never
350
+ // from the resolved config (which would inline secrets).
351
+ const telemetryConfig = this.config.telemetry;
352
+ const recording = createRecordingComponents({
353
+ enabled: resolveTelemetryEnabled(telemetryConfig?.enabled, process.env.SENPI_TELEMETRY_ENABLED),
354
+ token: trackingApiKey,
355
+ identity: () => buildIdentity({
356
+ name: this.config.name,
357
+ recipeVersion: this.config.version,
358
+ strategyAddress: this.strategyConfig.address,
359
+ bootId: this.runtimeBootId,
360
+ unresolvedConfig: this.options.unresolvedConfig,
361
+ }),
362
+ scopeVersion: VERSION,
363
+ baseUrl: telemetryConfig?.url,
364
+ // v2.0.0: recipe carries flush_interval_seconds; the transport expects ms.
365
+ flushIntervalMs: typeof telemetryConfig?.flush_interval_seconds === "number"
366
+ ? telemetryConfig.flush_interval_seconds * 1000
367
+ : undefined,
308
368
  });
309
- const riskBlock = this.config.risk;
310
- const strategyAddress = this.strategyConfig.address;
311
- const auditLog = riskBlock ? createRiskAuditLog(stateDir) : undefined;
312
- const riskGuard = riskBlock && senpi
313
- ? createRiskGuard({
369
+ this.recordingBatcher = recording.batcher;
370
+ // Only attach the subscriber when telemetry is live (batcher present): with a noop emitter,
371
+ // per-event record assembly on the serial signal path would be pure dead work.
372
+ if (recording.batcher) {
373
+ this.recordingSubscriber = createRecordingSubscriber(this.bus, recording.emitter, {
374
+ unresolvedConfig: this.options.unresolvedConfig,
375
+ // Narrow read-only accessor over the registry — recording never sees the
376
+ // registry or RuntimeContext; sync map read, safe on the bus handler path.
377
+ resolvePositionId: (address, dex, asset) => this.positionIdRegistry.get(positionRegistryKey(address, dex, asset))?.positionId,
378
+ });
379
+ }
380
+ // Everything from here to `started = true` can throw; without the catch, stop() would
381
+ // early-return on `!this.started` and the recording batcher/subscriber would leak.
382
+ try {
383
+ // try {
384
+ // const { reconcileStateWithBackend } = await import("./reconcile-state.js");
385
+ // await reconcileStateWithBackend(this.stateManager, senpi, [this.strategyConfig.address]);
386
+ // } catch (err) {
387
+ // logger.warn("reconcile after hydrate failed, continuing", { err });
388
+ // }
389
+ const llmDecision = createLlmDecision({});
390
+ const contextBuilder = createContextBuilder();
391
+ const notifications = createNotificationService({
392
+ ...this.config.notifications,
393
+ mcpTransport: this.options.mcpTransport,
394
+ });
395
+ const riskBlock = this.config.risk;
396
+ const strategyAddress = this.strategyConfig.address;
397
+ const auditLog = riskBlock ? createRiskAuditLog(stateDir) : undefined;
398
+ // In-memory strategy-lifecycle tracker: owns the self-pause state that
399
+ // RiskGuard used to hold and fires the hook + notification on a running→paused
400
+ // transition. RiskGuard stays stateless and only reports gate evaluations.
401
+ const lifecycle = createStrategyLifecycle({
402
+ hookSystem: this.hookSystem,
403
+ notifications,
404
+ runtimeName: this.config.name,
405
+ });
406
+ const riskGuard = riskBlock && senpi
407
+ ? createRiskGuard({
408
+ senpi,
409
+ notifications,
410
+ strategies: new Map([[strategyAddress, this.strategyConfig]]),
411
+ // Human strategy label for alerts; risk-guard falls back to the
412
+ // truncated address when an address has no name here.
413
+ strategyNames: { [strategyAddress]: this.config.name },
414
+ auditLog,
415
+ lifecycleTracker: lifecycle,
416
+ })
417
+ : createRiskGuardStub();
418
+ logger.info("Runtime.start() creating scanner module");
419
+ const layout = buildStateLayout(stateDir);
420
+ // Augment caller-supplied providers with StateManager-backed DSL state access
421
+ const augmentedProviders = {
422
+ ...scannerProviders,
423
+ getDslStatesForStrategy: scannerProviders?.getDslStatesForStrategy
424
+ ?? (async (address) => this.stateManager.listDslStates(address)),
425
+ };
426
+ this.scannerModule = createScannerModuleFromRuntimeConfig(this.config, layout.scannerRoot, augmentedProviders);
427
+ logger.info("Runtime.start() scanner module created, calling start()");
428
+ // Pre-load max leverage cache (non-blocking — log warning on failure)
429
+ const maxLeverageCache = new MaxLeverageCache(senpi);
430
+ try {
431
+ await maxLeverageCache.load();
432
+ }
433
+ catch (err) {
434
+ logger.warn("failed to pre-load max leverage cache, will retry on first use", { err });
435
+ }
436
+ // Build RuntimeContext once per trading recipe and reuse for all actions.
437
+ const runtimeContext = createRuntimeContext(this.strategyConfig, {
314
438
  senpi,
439
+ hookSystem: this.hookSystem,
440
+ llmDecision,
441
+ contextBuilder,
442
+ riskGuard,
315
443
  notifications,
316
- strategies: new Map([[strategyAddress, this.strategyConfig]]),
317
- auditLog,
318
- })
319
- : createRiskGuardStub();
320
- logger.info("Runtime.start() creating scanner module");
321
- const layout = buildStateLayout(stateDir);
322
- // Augment caller-supplied providers with StateManager-backed DSL state access
323
- const augmentedProviders = {
324
- ...scannerProviders,
325
- getDslStatesForStrategy: scannerProviders?.getDslStatesForStrategy
326
- ?? (async (address) => this.stateManager.listDslStates(address)),
327
- };
328
- this.scannerModule = createScannerModuleFromRuntimeConfig(this.config, layout.scannerRoot, augmentedProviders);
329
- logger.info("Runtime.start() scanner module created, calling start()");
330
- // Pre-load max leverage cache (non-blocking — log warning on failure)
331
- const maxLeverageCache = new MaxLeverageCache(senpi);
332
- try {
333
- await maxLeverageCache.load();
334
- }
335
- catch (err) {
336
- logger.warn("failed to pre-load max leverage cache, will retry on first use", { err });
337
- }
338
- // Build RuntimeContext once per trading recipe and reuse for all actions.
339
- const runtimeContext = createRuntimeContext(this.strategyConfig, {
340
- senpi,
341
- hookSystem: this.hookSystem,
342
- llmDecision,
343
- contextBuilder,
344
- riskGuard,
345
- notifications,
346
- scannerModule: this.scannerModule,
347
- maxLeverageCache,
348
- });
349
- this.actionRuntimeModule = new ActionRuntimeModule({ stateDir: layout.actionRoot });
350
- const { runActionsForSignal } = await createActions(this.config, {
351
- bus: this.bus,
352
- senpi,
353
- stateManager: this.stateManager,
354
- hookSystem: this.hookSystem,
355
- llmDecision,
356
- contextBuilder,
357
- riskGuard,
358
- notifications,
359
- runtimeContext,
360
- actionModule: this.actionRuntimeModule,
361
- });
362
- this.runActionsForSignal = runActionsForSignal;
363
- const notificationsConfig = this.config.notifications;
364
- if (hasDsl) {
365
- const dslNotificationsDisabled = notificationsConfig?.dsl_lifecycle === false;
366
- const dslNotifySlUpdates = notificationsConfig?.dsl_notify_sl_updates === true;
367
- this.dslPlugin = await DslPluginClass.create({
368
- config: exitConfig,
444
+ scannerModule: this.scannerModule,
445
+ maxLeverageCache,
446
+ positionIdRegistry: this.positionIdRegistry,
447
+ });
448
+ this.actionRuntimeModule = new ActionRuntimeModule({ stateDir: layout.actionRoot });
449
+ const { runActionsForSignal } = await createActions(this.config, {
369
450
  bus: this.bus,
370
- stateDir,
451
+ senpi,
371
452
  stateManager: this.stateManager,
372
- senpiClient: senpi,
373
- strategyStates: createStrategyStatesMap(this.strategyConfig, senpi),
374
- notifications: dslNotificationsDisabled ? undefined : notifications,
375
- notifySlUpdates: dslNotifySlUpdates,
376
- strategyName: this.config.name,
453
+ hookSystem: this.hookSystem,
454
+ llmDecision,
455
+ contextBuilder,
456
+ riskGuard,
457
+ notifications,
458
+ runtimeContext,
459
+ actionModule: this.actionRuntimeModule,
377
460
  });
378
- }
379
- else {
380
- this.dslPlugin = null;
381
- }
382
- if (isActionLifecycleNotificationsEnabled(notificationsConfig)) {
383
- this.actionNotificationSubscriber = createActionNotificationSubscriber(this.bus, notifications, {
384
- strategyName: this.config.name,
461
+ this.runActionsForSignal = runActionsForSignal;
462
+ // Create the reconcile gate BEFORE DslPlugin.create() so the monitor's
463
+ // first synchronous tick (fired inside create()) sees a gate that already exists.
464
+ this.reconcileGate = (() => {
465
+ let resolveInner;
466
+ const promise = new Promise((r) => { resolveInner = r; });
467
+ const gate = { promise, resolved: false, resolve: () => { } };
468
+ gate.resolve = () => {
469
+ if (!gate.resolved) {
470
+ gate.resolved = true;
471
+ resolveInner();
472
+ }
473
+ };
474
+ return gate;
475
+ })();
476
+ // Build strategyStates map once — shared by DslPlugin and the reconcile loop.
477
+ const strategyStatesMap = createStrategyStatesMap(this.strategyConfig, senpi);
478
+ const notificationsConfig = this.config.notifications;
479
+ if (hasDsl) {
480
+ const dslNotificationsDisabled = notificationsConfig?.dsl_lifecycle === false;
481
+ const dslNotifySlUpdates = notificationsConfig?.dsl_notify_sl_updates === true;
482
+ this.dslPlugin = await DslPluginClass.create({
483
+ config: exitConfig,
484
+ bus: this.bus,
485
+ stateDir,
486
+ stateManager: this.stateManager,
487
+ senpiClient: senpi,
488
+ strategyStates: strategyStatesMap,
489
+ notifications: dslNotificationsDisabled ? undefined : notifications,
490
+ notifySlUpdates: dslNotifySlUpdates,
491
+ strategyName: this.config.name,
492
+ // Monitor runs the unified periodic reconcile (adopt/resize/gone), serialized
493
+ // against the trade loop on the same reconcileMutex key, and can resolve the boot gate.
494
+ reconcileSerialize: (fn) => this.reconcileMutex.withKeyLock("reconcile", fn),
495
+ reconcileGateResolve: () => this.resolveReconcileGate(),
496
+ });
497
+ }
498
+ else {
499
+ this.dslPlugin = null;
500
+ }
501
+ // Launch detached boot-reconcile loop (does NOT block start()).
502
+ // Last-resort guard: an unexpected throw here would otherwise become an
503
+ // unhandled rejection and silently kill the loop. Do NOT resolve the gate
504
+ // on crash — that would fail-open trading on an unreconciled view; the
505
+ // monitor's unified reconcile self-heals the gate instead.
506
+ void this.runBootReconcileLoop(strategyStatesMap).catch((err) => {
507
+ logger.error("[runtime][reconcile] boot reconcile loop crashed", { err });
385
508
  });
509
+ if (isActionLifecycleNotificationsEnabled(notificationsConfig)) {
510
+ this.actionNotificationSubscriber = createActionNotificationSubscriber(this.bus, notifications, {
511
+ strategyName: this.config.name,
512
+ });
513
+ }
514
+ else {
515
+ this.actionNotificationSubscriber = null;
516
+ }
517
+ initRisk(this.bus);
518
+ this.healthStateModule = createHealthStateModule({
519
+ runtimeName: this.config.name,
520
+ stateDir,
521
+ startedAt: this.startedAt,
522
+ providers: {
523
+ scanners: this.scannerModule,
524
+ dsl: this.dslPlugin ?? createDisabledDslProvider(),
525
+ actions: this.actionRuntimeModule,
526
+ risk: riskBlock
527
+ ? createRiskHealthProvider(riskGuard, strategyAddress)
528
+ : undefined,
529
+ },
530
+ });
531
+ this.onScannerRunComplete = (event) => {
532
+ console.info("[senpi-runtime] [ingest-trace] onScannerRunComplete → enqueue", JSON.stringify({
533
+ address: event.result.address,
534
+ scannerId: event.result.scannerId,
535
+ signalCount: Array.isArray(event.result.signals) ? event.result.signals.length : 0,
536
+ status: event.result.status,
537
+ queueDepth: this.signalQueue.length + 1,
538
+ }));
539
+ const correlationId = randomUUID();
540
+ // Telemetry-owned per-scan-run id (NOT the deprecated correlation id): stamped on the
541
+ // scanner_run emit and echoed through the pass so scan + pass land in one trace.
542
+ const runId = randomUUID();
543
+ this.signalQueue.push({ result: event.result, correlationId, enqueuedAt: Date.now(), runId });
544
+ if (this.signalQueueWait) {
545
+ const w = this.signalQueueWait;
546
+ this.signalQueueWait = null;
547
+ w();
548
+ }
549
+ // Emit scanner run for tracking (startedAt is data stamping for telemetry durations)
550
+ this.bus.emit("tracking.scanner_run", {
551
+ address: event.result.address,
552
+ data: {
553
+ ...event.result,
554
+ startedAt: event.startedAt,
555
+ runId,
556
+ __correlationId: correlationId,
557
+ },
558
+ timestamp: new Date().toISOString(),
559
+ });
560
+ // Forward scanner summary alerts (e.g. watchdog) to notification service
561
+ const alerts = event.result.summary?.alerts;
562
+ if (Array.isArray(alerts) && alerts.length > 0) {
563
+ const header = `[${event.result.scannerId}] ${alerts.length} alert(s):`;
564
+ const lines = alerts.map((a) => ` ${a.level ?? "ALERT"}: ${a.message ?? ""}`);
565
+ notifications.notify(`${header}\n${lines.join("\n")}`).catch(() => { });
566
+ }
567
+ };
568
+ this.scannerModule.on("scanner:run:complete", this.onScannerRunComplete);
569
+ // Surface skipped/errored scanner runs on the bus for telemetry (add-only observation events —
570
+ // distinct names so existing `tracking.scanner_run` consumers see an unchanged payload mix).
571
+ // Neither enqueues a signal: only completed runs feed the signal queue.
572
+ this.onScannerRunSkip = (event) => {
573
+ this.bus.emit("tracking.scanner_run_skipped", {
574
+ address: event.address,
575
+ data: {
576
+ scannerId: event.scannerId,
577
+ status: event.status,
578
+ reason: event.reason,
579
+ timestamp: event.timestamp,
580
+ startedAt: event.startedAt,
581
+ },
582
+ timestamp: new Date().toISOString(),
583
+ });
584
+ };
585
+ this.onScannerRunError = (event) => {
586
+ this.bus.emit("tracking.scanner_run_error", {
587
+ address: event.address,
588
+ data: {
589
+ scannerId: event.scannerId,
590
+ status: "error",
591
+ reason: typeof event.error === "string" ? event.error : String(event.error),
592
+ timestamp: event.timestamp,
593
+ startedAt: event.startedAt,
594
+ },
595
+ timestamp: new Date().toISOString(),
596
+ });
597
+ };
598
+ this.scannerModule.on("scanner:run:skip", this.onScannerRunSkip);
599
+ this.scannerModule.on("scanner:run:error", this.onScannerRunError);
600
+ this.signalConsumerDone = this.runSignalConsumer();
601
+ logger.info("Runtime.start() invoking scannerModule.start()");
602
+ await this.scannerModule.start();
603
+ logger.info("Runtime.start() scannerModule.start() returned");
604
+ this.started = true;
386
605
  }
387
- else {
388
- this.actionNotificationSubscriber = null;
389
- }
390
- initRisk(this.bus);
391
- this.healthStateModule = createHealthStateModule({
392
- runtimeName: this.config.name,
393
- stateDir,
394
- startedAt: this.startedAt,
395
- providers: {
396
- scanners: this.scannerModule,
397
- dsl: this.dslPlugin ?? createDisabledDslProvider(),
398
- actions: this.actionRuntimeModule,
399
- risk: riskBlock
400
- ? createRiskHealthProvider(riskGuard, strategyAddress)
401
- : undefined,
402
- },
403
- });
404
- this.onScannerRunComplete = (event) => {
405
- console.info("[senpi-runtime] [ingest-trace] onScannerRunComplete → enqueue", JSON.stringify({
406
- address: event.result.address,
407
- scannerId: event.result.scannerId,
408
- signalCount: Array.isArray(event.result.signals) ? event.result.signals.length : 0,
409
- status: event.result.status,
410
- queueDepth: this.signalQueue.length + 1,
411
- }));
412
- const correlationId = randomUUID();
413
- this.signalQueue.push({ result: event.result, correlationId });
606
+ catch (err) {
607
+ // A throw here can land after the detached boot-reconcile loop was
608
+ // launched but before `started = true`. Since stop() early-
609
+ // returns on `!this.started`, the loop would otherwise retry forever and
610
+ // leak its 15s retry timer. Tear it down on the failed-start path.
611
+ this.reconcileStopped = true;
612
+ if (this.reconcileRetryTimer !== null) {
613
+ clearTimeout(this.reconcileRetryTimer);
614
+ this.reconcileRetryTimer = null;
615
+ }
616
+ // A failed start must NOT open the trade gate. The signal consumer was
617
+ // already launched (signalConsumerDone); without stopping it, resolving
618
+ // the gate would let it run runActionsForSignal on an unreconciled view, and
619
+ // stop() would no-op on `!this.started`. Stop the consumer FIRST so that when
620
+ // we resolve the gate (to unblock a consumer parked on gate.promise) it bails at
621
+ // the post-gate `signalConsumerStopped` check instead of trading. Then drain it
622
+ // so partial state is torn down here (stop() early-returns on !started).
623
+ this.signalConsumerStopped = true;
414
624
  if (this.signalQueueWait) {
415
625
  const w = this.signalQueueWait;
416
626
  this.signalQueueWait = null;
417
627
  w();
418
628
  }
419
- // Emit scanner run for tracking
420
- this.bus.emit("tracking.scanner_run", {
421
- address: event.result.address,
422
- data: {
423
- ...event.result,
424
- __correlationId: correlationId,
425
- },
426
- timestamp: new Date().toISOString(),
427
- });
428
- // Forward scanner summary alerts (e.g. watchdog) to notification service
429
- const alerts = event.result.summary?.alerts;
430
- if (Array.isArray(alerts) && alerts.length > 0) {
431
- const header = `[${event.result.scannerId}] ${alerts.length} alert(s):`;
432
- const lines = alerts.map((a) => ` ${a.level ?? "ALERT"}: ${a.message ?? ""}`);
433
- notifications.notify(`${header}\n${lines.join("\n")}`).catch(() => { });
629
+ this.reconcileGate?.resolve();
630
+ if (this.signalConsumerDone) {
631
+ await this.signalConsumerDone;
632
+ this.signalConsumerDone = null;
434
633
  }
435
- };
436
- this.scannerModule.on("scanner:run:complete", this.onScannerRunComplete);
437
- this.signalConsumerDone = this.runSignalConsumer();
438
- logger.info("Runtime.start() invoking scannerModule.start()");
439
- await this.scannerModule.start();
440
- logger.info("Runtime.start() scannerModule.start() returned");
441
- this.started = true;
634
+ // stop() early-returns on `!this.started`, so it cannot tear down resources
635
+ // built before the throw. Clean up the leak-prone partial state here: scanner event
636
+ // listeners, the DSL monitor interval, and the MCP connection. Best-effort — a
637
+ // teardown error must not mask the original boot error.
638
+ try {
639
+ if (this.onScannerRunComplete != null) {
640
+ this.scannerModule.off("scanner:run:complete", this.onScannerRunComplete);
641
+ this.onScannerRunComplete = null;
642
+ }
643
+ if (this.onScannerRunSkip != null) {
644
+ this.scannerModule.off("scanner:run:skip", this.onScannerRunSkip);
645
+ this.onScannerRunSkip = null;
646
+ }
647
+ if (this.onScannerRunError != null) {
648
+ this.scannerModule.off("scanner:run:error", this.onScannerRunError);
649
+ this.onScannerRunError = null;
650
+ }
651
+ if (this.actionNotificationSubscriber != null) {
652
+ this.actionNotificationSubscriber.dispose();
653
+ this.actionNotificationSubscriber = null;
654
+ }
655
+ if (this.dslPlugin) {
656
+ this.dslPlugin.stop();
657
+ this.dslPlugin = null;
658
+ }
659
+ if (this.senpi) {
660
+ await this.senpi.disconnect();
661
+ this.senpi = null;
662
+ }
663
+ }
664
+ catch (cleanupErr) {
665
+ logger.warn("[runtime] partial-state cleanup error on failed start (ignored)", { cleanupErr });
666
+ }
667
+ // Recording-only cleanup (telemetry must not leak on a failed boot); the error rethrows.
668
+ await this.disposeRecording();
669
+ throw err;
670
+ }
442
671
  this.bus.emit("tracking.runtime_started", {
443
672
  address: this.strategyConfig.address,
444
673
  data: {
@@ -497,6 +726,33 @@ export class Runtime {
497
726
  runtimeBootId: this.runtimeBootId,
498
727
  }, async () => {
499
728
  try {
729
+ // Block until the first boot reconcile succeeds (or runtime is stopped).
730
+ await this.reconcileGate?.promise;
731
+ // If stop() resolved the gate during shutdown, do NOT trade and do NOT
732
+ // contend for reconcileMutex — a boot reconcile that is still in-flight
733
+ // (or stuck) holds that key, and blocking here would hang stop()'s
734
+ // `await signalConsumerDone`. Bail before the mutex acquire.
735
+ if (this.signalConsumerStopped) {
736
+ return;
737
+ }
738
+ // Evict the blackout backlog. Items enqueued before the gate
739
+ // resolved were formed while the runtime could not confirm its own
740
+ // positions (unreconciled / exchange-flaky), so acting on them now is
741
+ // stale — the scanner re-emits fresh signals once reconciled. Strict
742
+ // `<`: items enqueued at/after gate-open are processed normally. This
743
+ // is gate-scoped, NOT a queue TTL — nothing is evicted once the
744
+ // backlog is cleared.
745
+ if (this.gateResolvedAt != null && queuedItem.enqueuedAt < this.gateResolvedAt) {
746
+ this.staleSignalsEvicted++;
747
+ logger.warn("[runtime] evicting stale pre-reconcile signal (enqueued before gate open)", {
748
+ address: queuedItem.result.address,
749
+ scannerId: queuedItem.result.scannerId,
750
+ enqueuedAt: queuedItem.enqueuedAt,
751
+ gateResolvedAt: this.gateResolvedAt,
752
+ totalEvicted: this.staleSignalsEvicted,
753
+ });
754
+ return;
755
+ }
500
756
  console.info("[senpi-runtime] [ingest-trace] consumer dequeue → runActionsForSignal", JSON.stringify({
501
757
  address: queuedItem.result.address,
502
758
  scannerId: queuedItem.result.scannerId,
@@ -515,11 +771,13 @@ export class Runtime {
515
771
  data: {
516
772
  ...payload,
517
773
  __correlationId: queuedItem.correlationId,
774
+ __scanRunId: queuedItem.runId,
518
775
  },
519
776
  timestamp: new Date().toISOString(),
520
777
  };
521
778
  this.bus.emit(HOOK_EVENT.ON_SIGNAL_DETECTED, hookEvent);
522
- await this.runActionsForSignal(hookEvent);
779
+ // Serialize trade loop vs reconcile — reconcileMutex outer, key-lock inner.
780
+ await this.reconcileMutex.withKeyLock("reconcile", () => this.runActionsForSignal(hookEvent));
523
781
  console.info("[senpi-runtime] [ingest-trace] runActionsForSignal complete", JSON.stringify({ address: queuedItem.result.address, scannerId: queuedItem.result.scannerId }));
524
782
  }
525
783
  catch (err) {
@@ -530,16 +788,130 @@ export class Runtime {
530
788
  error: err,
531
789
  address: queuedItem.result.address,
532
790
  scannerId: queuedItem.result.scannerId,
791
+ runId: queuedItem.runId,
533
792
  timestamp: new Date().toISOString(),
534
793
  });
535
794
  }
536
795
  });
537
796
  }
538
797
  }
798
+ // ─── boot reconcile loop ──────────────────────────────────────────────────────
799
+ /**
800
+ * Resolve the reconcile gate on a SUCCESSFUL reconcile (boot loop OR a periodic monitor
801
+ * reconcile). Sets `gateResolvedAt` so stale-signal eviction works regardless of
802
+ * which path resolves first. Idempotent: a no-op once the gate is resolved. NOT used by
803
+ * stop() — stop() force-resolves via `gate.resolve()` WITHOUT setting `gateResolvedAt`, so a
804
+ * shutdown never enables eviction (the consumer bails on `signalConsumerStopped` instead).
805
+ */
806
+ resolveReconcileGate() {
807
+ const gate = this.reconcileGate;
808
+ if (!gate || gate.resolved)
809
+ return;
810
+ this.gateResolvedAt = Date.now();
811
+ gate.resolve();
812
+ }
813
+ /**
814
+ * Detached boot-reconcile loop: runs runReconcile repeatedly until success or until
815
+ * the runtime is stopped. Resolves the reconcileGate on first success.
816
+ * If dslPlugin is null, the gate resolves immediately (nothing to reconcile into).
817
+ */
818
+ async runBootReconcileLoop(strategyStatesMap) {
819
+ const address = this.strategyConfig.address;
820
+ const gate = this.reconcileGate;
821
+ const serialize = (fn) => this.reconcileMutex.withKeyLock("reconcile", fn);
822
+ if (this.dslPlugin == null) {
823
+ logger.info("[runtime][reconcile] no DSL plugin — resolving gate immediately", { address });
824
+ this.resolveReconcileGate();
825
+ return;
826
+ }
827
+ const strategyState = strategyStatesMap.get(address);
828
+ if (!strategyState) {
829
+ logger.warn("[runtime][reconcile] strategyState not found in map — resolving gate immediately", { address });
830
+ this.resolveReconcileGate();
831
+ return;
832
+ }
833
+ let attempt = 0;
834
+ while (!this.reconcileStopped) {
835
+ attempt++;
836
+ const t0 = Date.now();
837
+ let result;
838
+ try {
839
+ result = await runReconcile({
840
+ address,
841
+ strategyState,
842
+ senpi: this.senpi,
843
+ stateManager: this.stateManager,
844
+ adopter: this.dslPlugin,
845
+ bus: this.bus,
846
+ serialize,
847
+ });
848
+ }
849
+ catch (err) {
850
+ logger.warn("[runtime][reconcile] runReconcile threw unexpectedly", { address, attempt, err });
851
+ result = { success: false, counts: { adopted: 0, resized: 0, archived: 0 } };
852
+ }
853
+ const durationMs = Date.now() - t0;
854
+ const { adopted, resized, archived } = result.counts;
855
+ // Telemetry must never break reconcile control flow. bus.emit is a Node
856
+ // EventEmitter: a listener that throws synchronously makes emit re-throw,
857
+ // which would reject this loop and leave the gate forever closed. Contain it.
858
+ try {
859
+ this.bus.emit("tracking.runtime_reconciled", {
860
+ address,
861
+ data: { adopted, resized, archived, success: result.success, attempt, durationMs },
862
+ timestamp: new Date().toISOString(),
863
+ });
864
+ }
865
+ catch (err) {
866
+ logger.warn("[runtime][reconcile] tracking.runtime_reconciled listener threw; contained", {
867
+ address,
868
+ attempt,
869
+ err,
870
+ });
871
+ }
872
+ if (result.success) {
873
+ logger.info("[runtime][reconcile] boot reconcile succeeded", { address, attempt, adopted, resized, archived });
874
+ this.resolveReconcileGate();
875
+ return;
876
+ }
877
+ logger.warn("[runtime][reconcile] boot reconcile failed, retrying", { address, attempt, durationMs });
878
+ // Wait RECONCILE_RETRY_INTERVAL_MS, but bail early if stopped.
879
+ await new Promise((resolve) => {
880
+ this.reconcileRetryTimer = setTimeout(() => {
881
+ this.reconcileRetryTimer = null;
882
+ resolve();
883
+ }, RECONCILE_RETRY_INTERVAL_MS);
884
+ });
885
+ }
886
+ // Runtime stopped while retrying — resolve gate so consumer unblocks cleanly.
887
+ gate.resolve();
888
+ }
889
+ /**
890
+ * Dispose the recording subscriber, then flush + stop the batcher (best-effort). Idempotent;
891
+ * shared by stop() and the failed-start cleanup path in start().
892
+ */
893
+ async disposeRecording() {
894
+ if (this.recordingSubscriber) {
895
+ this.recordingSubscriber.dispose();
896
+ this.recordingSubscriber = null;
897
+ }
898
+ if (this.recordingBatcher) {
899
+ await this.recordingBatcher.shutdown().catch(() => { });
900
+ this.recordingBatcher = null;
901
+ }
902
+ }
539
903
  async stop() {
540
904
  if (!this.started)
541
905
  return;
542
906
  this.started = false;
907
+ // Stop the boot-reconcile retry loop and unblock any awaiting consumer.
908
+ this.reconcileStopped = true;
909
+ if (this.reconcileRetryTimer !== null) {
910
+ clearTimeout(this.reconcileRetryTimer);
911
+ this.reconcileRetryTimer = null;
912
+ }
913
+ // Resolve the gate so the consumer doesn't hang waiting for a reconcile that won't come.
914
+ this.reconcileGate?.resolve();
543
915
  this.bus.emit("tracking.runtime_stopped", {
544
916
  address: this.strategyConfig.address,
545
917
  data: {
@@ -564,6 +936,14 @@ export class Runtime {
564
936
  this.scannerModule.off("scanner:run:complete", this.onScannerRunComplete);
565
937
  this.onScannerRunComplete = null;
566
938
  }
939
+ if (this.onScannerRunSkip != null) {
940
+ this.scannerModule.off("scanner:run:skip", this.onScannerRunSkip);
941
+ this.onScannerRunSkip = null;
942
+ }
943
+ if (this.onScannerRunError != null) {
944
+ this.scannerModule.off("scanner:run:error", this.onScannerRunError);
945
+ this.onScannerRunError = null;
946
+ }
567
947
  if (this.actionNotificationSubscriber != null) {
568
948
  this.actionNotificationSubscriber.dispose();
569
949
  this.actionNotificationSubscriber = null;
@@ -582,6 +962,9 @@ export class Runtime {
582
962
  await this.trackingHandler.dispose();
583
963
  this.trackingHandler = null;
584
964
  }
965
+ // Telemetry recording teardown: stop the subscriber, then flush + stop the batcher (best-effort)
966
+ // so the just-recorded runtime_stopped row ships before the process exits.
967
+ await this.disposeRecording();
585
968
  if (this.bus.removeAllListeners) {
586
969
  this.bus.removeAllListeners();
587
970
  }