@senpi-ai/runtime 1.1.3 → 3.0.4

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 (483) 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 +155 -35
  13. package/dist/actions/open-position/open-position.action.js.map +1 -1
  14. package/dist/actions/open-position/resolve-margin.d.ts +18 -3
  15. package/dist/actions/open-position/resolve-margin.d.ts.map +1 -1
  16. package/dist/actions/open-position/resolve-margin.js +22 -9
  17. package/dist/actions/open-position/resolve-margin.js.map +1 -1
  18. package/dist/actions/position-tracker/position-tracker.action.d.ts +6 -0
  19. package/dist/actions/position-tracker/position-tracker.action.d.ts.map +1 -1
  20. package/dist/actions/position-tracker/position-tracker.action.js +48 -0
  21. package/dist/actions/position-tracker/position-tracker.action.js.map +1 -1
  22. package/dist/actions/tracking-helpers.d.ts +16 -1
  23. package/dist/actions/tracking-helpers.d.ts.map +1 -1
  24. package/dist/actions/tracking-helpers.js +55 -9
  25. package/dist/actions/tracking-helpers.js.map +1 -1
  26. package/dist/actions/types.d.ts +10 -2
  27. package/dist/actions/types.d.ts.map +1 -1
  28. package/dist/actions/types.js +8 -0
  29. package/dist/actions/types.js.map +1 -1
  30. package/dist/cli/guide-commands.d.ts.map +1 -1
  31. package/dist/cli/guide-commands.js +102 -82
  32. package/dist/cli/guide-commands.js.map +1 -1
  33. package/dist/cli/senpi-commands.d.ts.map +1 -1
  34. package/dist/cli/senpi-commands.js +16 -110
  35. package/dist/cli/senpi-commands.js.map +1 -1
  36. package/dist/constants/dsl/index.d.ts +2 -0
  37. package/dist/constants/dsl/index.d.ts.map +1 -1
  38. package/dist/constants/dsl/index.js +2 -0
  39. package/dist/constants/dsl/index.js.map +1 -1
  40. package/dist/dsl/config/parse-tiers.d.ts.map +1 -1
  41. package/dist/dsl/config/parse-tiers.js +6 -2
  42. package/dist/dsl/config/parse-tiers.js.map +1 -1
  43. package/dist/dsl/engine-client/config-mapping.d.ts +3 -1
  44. package/dist/dsl/engine-client/config-mapping.d.ts.map +1 -1
  45. package/dist/dsl/engine-client/config-mapping.js +3 -1
  46. package/dist/dsl/engine-client/config-mapping.js.map +1 -1
  47. package/dist/dsl/engine-client/event-mapping.d.ts +2 -0
  48. package/dist/dsl/engine-client/event-mapping.d.ts.map +1 -1
  49. package/dist/dsl/engine-client/event-mapping.js +3 -0
  50. package/dist/dsl/engine-client/event-mapping.js.map +1 -1
  51. package/dist/dsl/events/build-closed-event.d.ts.map +1 -1
  52. package/dist/dsl/events/build-closed-event.js +1 -0
  53. package/dist/dsl/events/build-closed-event.js.map +1 -1
  54. package/dist/dsl/events/guards.d.ts.map +1 -1
  55. package/dist/dsl/events/guards.js +10 -0
  56. package/dist/dsl/events/guards.js.map +1 -1
  57. package/dist/dsl/events/handlers.d.ts +18 -2
  58. package/dist/dsl/events/handlers.d.ts.map +1 -1
  59. package/dist/dsl/events/handlers.js +304 -208
  60. package/dist/dsl/events/handlers.js.map +1 -1
  61. package/dist/dsl/events/initial-state.d.ts.map +1 -1
  62. package/dist/dsl/events/initial-state.js +3 -1
  63. package/dist/dsl/events/initial-state.js.map +1 -1
  64. package/dist/dsl/monitor/create-monitor.d.ts +15 -0
  65. package/dist/dsl/monitor/create-monitor.d.ts.map +1 -1
  66. package/dist/dsl/monitor/create-monitor.js +76 -9
  67. package/dist/dsl/monitor/create-monitor.js.map +1 -1
  68. package/dist/dsl/monitor/process-one-position.d.ts.map +1 -1
  69. package/dist/dsl/monitor/process-one-position.js +268 -82
  70. package/dist/dsl/monitor/process-one-position.js.map +1 -1
  71. package/dist/dsl/plugin/index.d.ts +16 -1
  72. package/dist/dsl/plugin/index.d.ts.map +1 -1
  73. package/dist/dsl/plugin/index.js +35 -4
  74. package/dist/dsl/plugin/index.js.map +1 -1
  75. package/dist/dsl/plugin/options.d.ts +18 -0
  76. package/dist/dsl/plugin/options.d.ts.map +1 -1
  77. package/dist/index.d.ts +14 -1
  78. package/dist/index.d.ts.map +1 -1
  79. package/dist/index.js +276 -32
  80. package/dist/index.js.map +1 -1
  81. package/dist/recording/emitter.d.ts +27 -0
  82. package/dist/recording/emitter.d.ts.map +1 -0
  83. package/dist/recording/emitter.js +2 -0
  84. package/dist/recording/emitter.js.map +1 -0
  85. package/dist/recording/identity.d.ts +34 -0
  86. package/dist/recording/identity.d.ts.map +1 -0
  87. package/dist/recording/identity.js +2 -0
  88. package/dist/recording/identity.js.map +1 -0
  89. package/dist/recording/index.d.ts +11 -0
  90. package/dist/recording/index.d.ts.map +1 -0
  91. package/dist/recording/index.js +2 -0
  92. package/dist/recording/index.js.map +1 -0
  93. package/dist/recording/noop-emitter.d.ts +23 -0
  94. package/dist/recording/noop-emitter.d.ts.map +1 -0
  95. package/dist/recording/noop-emitter.js +22 -0
  96. package/dist/recording/noop-emitter.js.map +1 -0
  97. package/dist/recording/otel/attributes.d.ts +35 -0
  98. package/dist/recording/otel/attributes.d.ts.map +1 -0
  99. package/dist/recording/otel/attributes.js +131 -0
  100. package/dist/recording/otel/attributes.js.map +1 -0
  101. package/dist/recording/otel/constants.d.ts +123 -0
  102. package/dist/recording/otel/constants.d.ts.map +1 -0
  103. package/dist/recording/otel/constants.js +172 -0
  104. package/dist/recording/otel/constants.js.map +1 -0
  105. package/dist/recording/otel/ids.d.ts +25 -0
  106. package/dist/recording/otel/ids.d.ts.map +1 -0
  107. package/dist/recording/otel/ids.js +37 -0
  108. package/dist/recording/otel/ids.js.map +1 -0
  109. package/dist/recording/otel/index.d.ts +13 -0
  110. package/dist/recording/otel/index.d.ts.map +1 -0
  111. package/dist/recording/otel/index.js +9 -0
  112. package/dist/recording/otel/index.js.map +1 -0
  113. package/dist/recording/otel/mappers.d.ts +100 -0
  114. package/dist/recording/otel/mappers.d.ts.map +1 -0
  115. package/dist/recording/otel/mappers.js +683 -0
  116. package/dist/recording/otel/mappers.js.map +1 -0
  117. package/dist/recording/otel/otel-emitter.d.ts +43 -0
  118. package/dist/recording/otel/otel-emitter.d.ts.map +1 -0
  119. package/dist/recording/otel/otel-emitter.js +99 -0
  120. package/dist/recording/otel/otel-emitter.js.map +1 -0
  121. package/dist/recording/otel/redaction.d.ts +47 -0
  122. package/dist/recording/otel/redaction.d.ts.map +1 -0
  123. package/dist/recording/otel/redaction.js +88 -0
  124. package/dist/recording/otel/redaction.js.map +1 -0
  125. package/dist/recording/records.d.ts +565 -0
  126. package/dist/recording/records.d.ts.map +1 -0
  127. package/dist/recording/records.js +14 -0
  128. package/dist/recording/records.js.map +1 -0
  129. package/dist/recording/transport/batcher.d.ts +59 -0
  130. package/dist/recording/transport/batcher.d.ts.map +1 -0
  131. package/dist/recording/transport/batcher.js +234 -0
  132. package/dist/recording/transport/batcher.js.map +1 -0
  133. package/dist/recording/transport/client.d.ts +41 -0
  134. package/dist/recording/transport/client.d.ts.map +1 -0
  135. package/dist/recording/transport/client.js +69 -0
  136. package/dist/recording/transport/client.js.map +1 -0
  137. package/dist/recording/transport/config.d.ts +53 -0
  138. package/dist/recording/transport/config.d.ts.map +1 -0
  139. package/dist/recording/transport/config.js +41 -0
  140. package/dist/recording/transport/config.js.map +1 -0
  141. package/dist/recording/transport/index.d.ts +16 -0
  142. package/dist/recording/transport/index.d.ts.map +1 -0
  143. package/dist/recording/transport/index.js +12 -0
  144. package/dist/recording/transport/index.js.map +1 -0
  145. package/dist/recording/transport/rows.d.ts +88 -0
  146. package/dist/recording/transport/rows.d.ts.map +1 -0
  147. package/dist/recording/transport/rows.js +15 -0
  148. package/dist/recording/transport/rows.js.map +1 -0
  149. package/dist/recording/wiring/emitter-factory.d.ts +39 -0
  150. package/dist/recording/wiring/emitter-factory.d.ts.map +1 -0
  151. package/dist/recording/wiring/emitter-factory.js +62 -0
  152. package/dist/recording/wiring/emitter-factory.js.map +1 -0
  153. package/dist/recording/wiring/identity.d.ts +27 -0
  154. package/dist/recording/wiring/identity.d.ts.map +1 -0
  155. package/dist/recording/wiring/identity.js +51 -0
  156. package/dist/recording/wiring/identity.js.map +1 -0
  157. package/dist/recording/wiring/index.d.ts +12 -0
  158. package/dist/recording/wiring/index.d.ts.map +1 -0
  159. package/dist/recording/wiring/index.js +9 -0
  160. package/dist/recording/wiring/index.js.map +1 -0
  161. package/dist/recording/wiring/record-builders.d.ts +107 -0
  162. package/dist/recording/wiring/record-builders.d.ts.map +1 -0
  163. package/dist/recording/wiring/record-builders.js +706 -0
  164. package/dist/recording/wiring/record-builders.js.map +1 -0
  165. package/dist/recording/wiring/subscriber.d.ts +28 -0
  166. package/dist/recording/wiring/subscriber.d.ts.map +1 -0
  167. package/dist/recording/wiring/subscriber.js +173 -0
  168. package/dist/recording/wiring/subscriber.js.map +1 -0
  169. package/dist/recording/wiring/values.d.ts +19 -0
  170. package/dist/recording/wiring/values.d.ts.map +1 -0
  171. package/dist/recording/wiring/values.js +49 -0
  172. package/dist/recording/wiring/values.js.map +1 -0
  173. package/dist/runtime/auto-update/command-runner.d.ts.map +1 -1
  174. package/dist/runtime/auto-update/command-runner.js +5 -1
  175. package/dist/runtime/auto-update/command-runner.js.map +1 -1
  176. package/dist/runtime/auto-update/resolve-package-name.d.ts +10 -0
  177. package/dist/runtime/auto-update/resolve-package-name.d.ts.map +1 -0
  178. package/dist/runtime/auto-update/resolve-package-name.js +35 -0
  179. package/dist/runtime/auto-update/resolve-package-name.js.map +1 -0
  180. package/dist/runtime/auto-update/run-update-command.d.ts +2 -0
  181. package/dist/runtime/auto-update/run-update-command.d.ts.map +1 -0
  182. package/dist/runtime/auto-update/run-update-command.js +37 -0
  183. package/dist/runtime/auto-update/run-update-command.js.map +1 -0
  184. package/dist/runtime/create-runtime-context.d.ts +2 -0
  185. package/dist/runtime/create-runtime-context.d.ts.map +1 -1
  186. package/dist/runtime/create-runtime-context.js +1 -0
  187. package/dist/runtime/create-runtime-context.js.map +1 -1
  188. package/dist/runtime/create-scanner-module.d.ts +4 -3
  189. package/dist/runtime/create-scanner-module.d.ts.map +1 -1
  190. package/dist/runtime/create-scanner-module.js +14 -5
  191. package/dist/runtime/create-scanner-module.js.map +1 -1
  192. package/dist/runtime/create-scanner-providers-for-run.d.ts.map +1 -1
  193. package/dist/runtime/create-scanner-providers-for-run.js +12 -1
  194. package/dist/runtime/create-scanner-providers-for-run.js.map +1 -1
  195. package/dist/runtime/load-runtime-config.d.ts +9 -0
  196. package/dist/runtime/load-runtime-config.d.ts.map +1 -1
  197. package/dist/runtime/load-runtime-config.js +41 -8
  198. package/dist/runtime/load-runtime-config.js.map +1 -1
  199. package/dist/runtime/map-strategies-registration.js +7 -8
  200. package/dist/runtime/map-strategies-registration.js.map +1 -1
  201. package/dist/runtime/map-strategies.d.ts.map +1 -1
  202. package/dist/runtime/map-strategies.js +12 -3
  203. package/dist/runtime/map-strategies.js.map +1 -1
  204. package/dist/runtime/recipe-version.d.ts +1 -1
  205. package/dist/runtime/recipe-version.d.ts.map +1 -1
  206. package/dist/runtime/recipe-version.js +1 -1
  207. package/dist/runtime/recipe-version.js.map +1 -1
  208. package/dist/runtime/reconcile-decide.d.ts +73 -0
  209. package/dist/runtime/reconcile-decide.d.ts.map +1 -0
  210. package/dist/runtime/reconcile-decide.js +186 -0
  211. package/dist/runtime/reconcile-decide.js.map +1 -0
  212. package/dist/runtime/reconcile-run.d.ts +62 -0
  213. package/dist/runtime/reconcile-run.d.ts.map +1 -0
  214. package/dist/runtime/reconcile-run.js +173 -0
  215. package/dist/runtime/reconcile-run.js.map +1 -0
  216. package/dist/runtime/reconcile-state.d.ts +44 -0
  217. package/dist/runtime/reconcile-state.d.ts.map +1 -1
  218. package/dist/runtime/reconcile-state.js +80 -44
  219. package/dist/runtime/reconcile-state.js.map +1 -1
  220. package/dist/runtime/risk-guard.d.ts.map +1 -1
  221. package/dist/runtime/risk-guard.js +17 -12
  222. package/dist/runtime/risk-guard.js.map +1 -1
  223. package/dist/runtime/run.d.ts.map +1 -1
  224. package/dist/runtime/run.js +3 -2
  225. package/dist/runtime/run.js.map +1 -1
  226. package/dist/runtime/runtime-schema.d.ts +4056 -793
  227. package/dist/runtime/runtime-schema.d.ts.map +1 -1
  228. package/dist/runtime/runtime-schema.js +183 -46
  229. package/dist/runtime/runtime-schema.js.map +1 -1
  230. package/dist/runtime/runtime-version.d.ts +3 -6
  231. package/dist/runtime/runtime-version.d.ts.map +1 -1
  232. package/dist/runtime/runtime-version.js +3 -6
  233. package/dist/runtime/runtime-version.js.map +1 -1
  234. package/dist/runtime/runtime.d.ts +47 -0
  235. package/dist/runtime/runtime.d.ts.map +1 -1
  236. package/dist/runtime/runtime.js +516 -146
  237. package/dist/runtime/runtime.js.map +1 -1
  238. package/dist/runtime/scanner-registry.d.ts +1 -1
  239. package/dist/runtime/scanner-registry.d.ts.map +1 -1
  240. package/dist/runtime/scanner-registry.js +3 -12
  241. package/dist/runtime/scanner-registry.js.map +1 -1
  242. package/dist/runtime/strategy-registry.d.ts +6 -0
  243. package/dist/runtime/strategy-registry.d.ts.map +1 -1
  244. package/dist/runtime/strategy-registry.js +1 -0
  245. package/dist/runtime/strategy-registry.js.map +1 -1
  246. package/dist/runtime/supervisor/long-running-supervisor.d.ts +222 -0
  247. package/dist/runtime/supervisor/long-running-supervisor.d.ts.map +1 -0
  248. package/dist/runtime/supervisor/long-running-supervisor.js +625 -0
  249. package/dist/runtime/supervisor/long-running-supervisor.js.map +1 -0
  250. package/dist/runtime/supervisor/orphan-sweep.d.ts +36 -0
  251. package/dist/runtime/supervisor/orphan-sweep.d.ts.map +1 -0
  252. package/dist/runtime/supervisor/orphan-sweep.js +255 -0
  253. package/dist/runtime/supervisor/orphan-sweep.js.map +1 -0
  254. package/dist/runtime/supervisor/supervisor-utils.d.ts +37 -0
  255. package/dist/runtime/supervisor/supervisor-utils.d.ts.map +1 -0
  256. package/dist/runtime/supervisor/supervisor-utils.js +175 -0
  257. package/dist/runtime/supervisor/supervisor-utils.js.map +1 -0
  258. package/dist/runtime-api/handlers/ingest-signals.d.ts +3 -3
  259. package/dist/runtime-api/handlers/ingest-signals.js +3 -3
  260. package/dist/runtime-api/intake/acceptance-record.d.ts +103 -0
  261. package/dist/runtime-api/intake/acceptance-record.d.ts.map +1 -0
  262. package/dist/runtime-api/intake/acceptance-record.js +192 -0
  263. package/dist/runtime-api/intake/acceptance-record.js.map +1 -0
  264. package/dist/runtime-api/intake/intake-context.d.ts +31 -0
  265. package/dist/runtime-api/intake/intake-context.d.ts.map +1 -0
  266. package/dist/runtime-api/intake/intake-context.js +21 -0
  267. package/dist/runtime-api/intake/intake-context.js.map +1 -0
  268. package/dist/runtime-api/intake/intake-mount.d.ts +118 -0
  269. package/dist/runtime-api/intake/intake-mount.d.ts.map +1 -0
  270. package/dist/runtime-api/intake/intake-mount.js +202 -0
  271. package/dist/runtime-api/intake/intake-mount.js.map +1 -0
  272. package/dist/runtime-api/intake/liveness-store.d.ts +32 -0
  273. package/dist/runtime-api/intake/liveness-store.d.ts.map +1 -0
  274. package/dist/runtime-api/intake/liveness-store.js +31 -0
  275. package/dist/runtime-api/intake/liveness-store.js.map +1 -0
  276. package/dist/runtime-api/intake/process-error-post.d.ts +15 -0
  277. package/dist/runtime-api/intake/process-error-post.d.ts.map +1 -0
  278. package/dist/runtime-api/intake/process-error-post.js +19 -0
  279. package/dist/runtime-api/intake/process-error-post.js.map +1 -0
  280. package/dist/runtime-api/intake/process-signal-post.d.ts +73 -0
  281. package/dist/runtime-api/intake/process-signal-post.d.ts.map +1 -0
  282. package/dist/runtime-api/intake/process-signal-post.js +188 -0
  283. package/dist/runtime-api/intake/process-signal-post.js.map +1 -0
  284. package/dist/runtime-api/intake/scanner-launcher.d.ts +133 -0
  285. package/dist/runtime-api/intake/scanner-launcher.d.ts.map +1 -0
  286. package/dist/runtime-api/intake/scanner-launcher.js +204 -0
  287. package/dist/runtime-api/intake/scanner-launcher.js.map +1 -0
  288. package/dist/runtime-api/intake/scanner-registry.d.ts +36 -0
  289. package/dist/runtime-api/intake/scanner-registry.d.ts.map +1 -0
  290. package/dist/runtime-api/intake/scanner-registry.js +29 -0
  291. package/dist/runtime-api/intake/scanner-registry.js.map +1 -0
  292. package/dist/runtime-api/intake/types.d.ts +60 -0
  293. package/dist/runtime-api/intake/types.d.ts.map +1 -0
  294. package/dist/runtime-api/intake/types.js +8 -0
  295. package/dist/runtime-api/intake/types.js.map +1 -0
  296. package/dist/runtime-api/routes/signals.d.ts +20 -40
  297. package/dist/runtime-api/routes/signals.d.ts.map +1 -1
  298. package/dist/runtime-api/routes/signals.js +120 -75
  299. package/dist/runtime-api/routes/signals.js.map +1 -1
  300. package/dist/runtime-api/routes/signals.schema.d.ts +23 -86
  301. package/dist/runtime-api/routes/signals.schema.d.ts.map +1 -1
  302. package/dist/runtime-api/routes/signals.schema.js +37 -50
  303. package/dist/runtime-api/routes/signals.schema.js.map +1 -1
  304. package/dist/runtime-api/server.d.ts +15 -6
  305. package/dist/runtime-api/server.d.ts.map +1 -1
  306. package/dist/runtime-api/server.js +12 -12
  307. package/dist/runtime-api/server.js.map +1 -1
  308. package/dist/scanners/events.d.ts +6 -0
  309. package/dist/scanners/events.d.ts.map +1 -1
  310. package/dist/scanners/events.js.map +1 -1
  311. package/dist/scanners/external/scaffold/__init__.py +16 -0
  312. package/dist/scanners/external/scaffold/__main__.py +155 -0
  313. package/dist/scanners/external/scaffold/ctx.py +78 -0
  314. package/dist/scanners/external/scaffold/delivery.py +282 -0
  315. package/dist/scanners/external/scaffold/entrypoint_loader.py +151 -0
  316. package/dist/scanners/external/scaffold/http_post.py +70 -0
  317. package/dist/scanners/external/scaffold/journal.py +247 -0
  318. package/dist/scanners/external/scaffold/loop_primitives.py +65 -0
  319. package/dist/scanners/external/scaffold/requirements.txt +11 -0
  320. package/dist/scanners/external/scaffold/scaffold.py +361 -0
  321. package/dist/scanners/external/scaffold/scaffold_state.py +114 -0
  322. package/dist/scanners/external/scaffold/senpi_mcp.py +250 -0
  323. package/dist/scanners/external/scaffold/signal_envelope.py +258 -0
  324. package/dist/scanners/external/scaffold/state_manager.py +175 -0
  325. package/dist/scanners/external-scanner-receiver.d.ts +23 -1
  326. package/dist/scanners/external-scanner-receiver.d.ts.map +1 -1
  327. package/dist/scanners/external-scanner-receiver.js +24 -3
  328. package/dist/scanners/external-scanner-receiver.js.map +1 -1
  329. package/dist/scanners/implementations/external-scanner.d.ts.map +1 -1
  330. package/dist/scanners/implementations/external-scanner.js +7 -1
  331. package/dist/scanners/implementations/external-scanner.js.map +1 -1
  332. package/dist/scanners/implementations/momentum.d.ts.map +1 -1
  333. package/dist/scanners/implementations/momentum.js +16 -0
  334. package/dist/scanners/implementations/momentum.js.map +1 -1
  335. package/dist/scanners/providers/factory.d.ts.map +1 -1
  336. package/dist/scanners/providers/factory.js +17 -19
  337. package/dist/scanners/providers/factory.js.map +1 -1
  338. package/dist/scanners/runtime-module.d.ts.map +1 -1
  339. package/dist/scanners/runtime-module.js +9 -1
  340. package/dist/scanners/runtime-module.js.map +1 -1
  341. package/dist/scripts/run-dsl-standalone-live.d.ts +1 -1
  342. package/dist/scripts/run-dsl-standalone-live.js +5 -3
  343. package/dist/scripts/run-dsl-standalone-live.js.map +1 -1
  344. package/dist/senpi/client.d.ts +56 -4
  345. package/dist/senpi/client.d.ts.map +1 -1
  346. package/dist/senpi/client.js +123 -24
  347. package/dist/senpi/client.js.map +1 -1
  348. package/dist/senpi/index.d.ts +2 -1
  349. package/dist/senpi/index.d.ts.map +1 -1
  350. package/dist/senpi/index.js +1 -1
  351. package/dist/senpi/index.js.map +1 -1
  352. package/dist/senpi/types.d.ts +1 -2
  353. package/dist/senpi/types.d.ts.map +1 -1
  354. package/dist/state/state-manager.d.ts +17 -0
  355. package/dist/state/state-manager.d.ts.map +1 -1
  356. package/dist/state/state-manager.js +55 -4
  357. package/dist/state/state-manager.js.map +1 -1
  358. package/dist/strategy/strategy-state.d.ts +9 -1
  359. package/dist/strategy/strategy-state.d.ts.map +1 -1
  360. package/dist/strategy/strategy-state.js +78 -28
  361. package/dist/strategy/strategy-state.js.map +1 -1
  362. package/dist/tracking/build-rehydrate-items.d.ts +15 -0
  363. package/dist/tracking/build-rehydrate-items.d.ts.map +1 -0
  364. package/dist/tracking/build-rehydrate-items.js +19 -0
  365. package/dist/tracking/build-rehydrate-items.js.map +1 -0
  366. package/dist/tracking/constants.d.ts.map +1 -1
  367. package/dist/tracking/constants.js +2 -0
  368. package/dist/tracking/constants.js.map +1 -1
  369. package/dist/tracking/index.d.ts +3 -0
  370. package/dist/tracking/index.d.ts.map +1 -1
  371. package/dist/tracking/index.js +2 -0
  372. package/dist/tracking/index.js.map +1 -1
  373. package/dist/tracking/position-id-registry.d.ts +69 -0
  374. package/dist/tracking/position-id-registry.d.ts.map +1 -0
  375. package/dist/tracking/position-id-registry.js +139 -0
  376. package/dist/tracking/position-id-registry.js.map +1 -0
  377. package/dist/tracking/spans/fan-out-span-transport.d.ts +22 -0
  378. package/dist/tracking/spans/fan-out-span-transport.d.ts.map +1 -0
  379. package/dist/tracking/spans/fan-out-span-transport.js +49 -0
  380. package/dist/tracking/spans/fan-out-span-transport.js.map +1 -0
  381. package/dist/tracking/spans/otel/fit-row-budget.d.ts +22 -0
  382. package/dist/tracking/spans/otel/fit-row-budget.d.ts.map +1 -0
  383. package/dist/tracking/spans/otel/fit-row-budget.js +91 -0
  384. package/dist/tracking/spans/otel/fit-row-budget.js.map +1 -0
  385. package/dist/tracking/spans/otel/map-span-to-trace-row.d.ts +16 -0
  386. package/dist/tracking/spans/otel/map-span-to-trace-row.d.ts.map +1 -0
  387. package/dist/tracking/spans/otel/map-span-to-trace-row.js +227 -0
  388. package/dist/tracking/spans/otel/map-span-to-trace-row.js.map +1 -0
  389. package/dist/tracking/spans/otel/recording-span-transport.d.ts +43 -0
  390. package/dist/tracking/spans/otel/recording-span-transport.d.ts.map +1 -0
  391. package/dist/tracking/spans/otel/recording-span-transport.js +67 -0
  392. package/dist/tracking/spans/otel/recording-span-transport.js.map +1 -0
  393. package/dist/tracking/spans/otel/span-ids.d.ts +22 -0
  394. package/dist/tracking/spans/otel/span-ids.d.ts.map +1 -0
  395. package/dist/tracking/spans/otel/span-ids.js +32 -0
  396. package/dist/tracking/spans/otel/span-ids.js.map +1 -0
  397. package/dist/tracking/spans/plugin-span-tracker.d.ts +6 -0
  398. package/dist/tracking/spans/plugin-span-tracker.d.ts.map +1 -1
  399. package/dist/tracking/spans/plugin-span-tracker.js +82 -9
  400. package/dist/tracking/spans/plugin-span-tracker.js.map +1 -1
  401. package/dist/tracking/spans/redact-pii.d.ts +3 -1
  402. package/dist/tracking/spans/redact-pii.d.ts.map +1 -1
  403. package/dist/tracking/spans/redact-pii.js +5 -1
  404. package/dist/tracking/spans/redact-pii.js.map +1 -1
  405. package/dist/tracking/spans/span-transport.d.ts +6 -0
  406. package/dist/tracking/spans/span-transport.d.ts.map +1 -1
  407. package/dist/tracking/spans/span-transport.js +1 -1
  408. package/dist/tracking/spans/span-transport.js.map +1 -1
  409. package/dist/types/dsl/index.d.ts +24 -1
  410. package/dist/types/dsl/index.d.ts.map +1 -1
  411. package/dist/types/runtime.d.ts +6 -0
  412. package/dist/types/runtime.d.ts.map +1 -1
  413. package/dist/types/scanner.d.ts +16 -0
  414. package/dist/types/scanner.d.ts.map +1 -1
  415. package/dist/types/strategy.d.ts +3 -1
  416. package/dist/types/strategy.d.ts.map +1 -1
  417. package/dist/utils/clearing-house-aggregate.d.ts +32 -0
  418. package/dist/utils/clearing-house-aggregate.d.ts.map +1 -0
  419. package/dist/utils/clearing-house-aggregate.js +41 -0
  420. package/dist/utils/clearing-house-aggregate.js.map +1 -0
  421. package/dist/utils/keyed-mutex.d.ts +37 -0
  422. package/dist/utils/keyed-mutex.d.ts.map +1 -0
  423. package/dist/utils/keyed-mutex.js +77 -0
  424. package/dist/utils/keyed-mutex.js.map +1 -0
  425. package/dist/utils/safe-spawn.d.ts +6 -0
  426. package/dist/utils/safe-spawn.d.ts.map +1 -0
  427. package/dist/utils/safe-spawn.js +62 -0
  428. package/dist/utils/safe-spawn.js.map +1 -0
  429. package/examples/strategies/README.md +17 -12
  430. package/examples/strategies/iguana/README.md +135 -0
  431. package/examples/strategies/iguana/recipe.yaml +137 -0
  432. package/examples/strategies/iguana/scanners/scan.py +242 -0
  433. package/examples/strategies/iguana/scanners/scoring.py +152 -0
  434. package/examples/strategies/raptor/README.md +156 -0
  435. package/examples/strategies/raptor/recipe.yaml +154 -0
  436. package/examples/strategies/raptor/scanners/scan.py +348 -0
  437. package/examples/strategies/raptor/scanners/scoring.py +452 -0
  438. package/examples/strategies/spider/README.md +89 -0
  439. package/examples/strategies/spider/scalp/recipe.yaml +129 -0
  440. package/examples/strategies/spider/scalp/scanners/scan.py +219 -0
  441. package/examples/strategies/spider/scalp/scanners/scoring.py +179 -0
  442. package/examples/strategies/spider/swing/recipe.yaml +137 -0
  443. package/examples/strategies/spider/swing/scanners/scan.py +334 -0
  444. package/examples/strategies/spider/swing/scanners/scoring.py +184 -0
  445. package/examples/strategies/turbine/README.md +169 -0
  446. package/examples/strategies/turbine/recipe-runners.yaml +123 -0
  447. package/examples/strategies/turbine/recipe-volume.yaml +129 -0
  448. package/examples/strategies/turbine/scanners/scan.py +287 -0
  449. package/examples/strategies/turbine/scanners/scoring.py +190 -0
  450. package/openclaw.plugin.json +12 -1
  451. package/package.json +3 -3
  452. package/dist/runtime-api/handlers/group-by-scanner.d.ts +0 -43
  453. package/dist/runtime-api/handlers/group-by-scanner.d.ts.map +0 -1
  454. package/dist/runtime-api/handlers/group-by-scanner.js +0 -43
  455. package/dist/runtime-api/handlers/group-by-scanner.js.map +0 -1
  456. package/dist/scanners/external/liquidation-watchdog/README.md +0 -107
  457. package/dist/scanners/external/liquidation-watchdog/liquidation-watchdog.yaml +0 -48
  458. package/dist/scanners/external/liquidation-watchdog/producer.mjs +0 -336
  459. package/dist/scanners/external/momentum/README.md +0 -148
  460. package/dist/scanners/external/momentum/momentum.yaml +0 -116
  461. package/dist/scanners/external/momentum/producer.mjs +0 -251
  462. package/dist/scanners/external/shared/ingest.mjs +0 -112
  463. package/examples/README.md +0 -89
  464. package/examples/scanners-consumer-quickstart.mjs +0 -134
  465. package/examples/scanners-emerging-movers-v4.mjs +0 -287
  466. package/examples/scanners-liquidation-watchdog.mjs +0 -341
  467. package/examples/scanners-live-mcp.mjs +0 -208
  468. package/examples/scanners-multi-strategy.mjs +0 -165
  469. package/examples/scanners-position-tracker-e2e.mjs +0 -225
  470. package/examples/scanners-scheduled-events.mjs +0 -96
  471. package/examples/scanners-senpi-provider-client.mjs +0 -182
  472. package/examples/scanners-single-strategy.mjs +0 -198
  473. package/examples/strategies/dsl-showcase.yaml +0 -68
  474. package/examples/strategies/dsl.yaml +0 -51
  475. package/examples/strategies/fox-minimal-loosened.yaml +0 -240
  476. package/examples/strategies/fox-minimal.yaml +0 -242
  477. package/examples/strategies/minimal.yaml +0 -46
  478. package/examples/strategies/momentum/how-it-works.md +0 -48
  479. package/examples/strategies/momentum/momentum-guarded.yaml +0 -161
  480. package/examples/strategies/risk-showcase.yaml +0 -93
  481. package/examples/strategies/viper.yaml +0 -67
  482. package/examples/strategies/wolf.yaml +0 -72
  483. package/examples/yamls/sample-with-dsl-and-emerging-movers.yaml +0 -123
@@ -31,23 +31,31 @@ import { createActionNotificationSubscriber, isActionLifecycleNotificationsEnabl
31
31
  import { MaxLeverageCache } from "../leverage/max-leverage-cache.js";
32
32
  import { buildStateLayout } from "./state-layout.js";
33
33
  import { createLogger } from "../utils/logger.js";
34
- 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";
35
35
  import { VERSION } from "../version.js";
36
36
  import { randomUUID } from "node:crypto";
37
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";
38
41
  const logger = createLogger("[senpi-core][runtime]");
42
+ /** Fixed retry interval for the boot-reconcile loop. */
43
+ const RECONCILE_RETRY_INTERVAL_MS = 15_000;
39
44
  export class Runtime {
40
45
  config;
41
46
  options;
42
47
  bus;
43
48
  hookSystem;
44
49
  stateManager;
50
+ positionIdRegistry;
45
51
  scannerModule;
46
52
  dslPlugin = null;
47
53
  // riskGuardian removed — gate decisions are now real-time in checkGate
48
54
  senpi = null;
49
55
  healthStateModule = null;
50
56
  trackingHandler = null;
57
+ recordingSubscriber = null;
58
+ recordingBatcher = null;
51
59
  started = false;
52
60
  startedAt = null;
53
61
  /** Serial signal processing: queue and consumer so only one signal is handled at a time. */
@@ -60,12 +68,27 @@ export class Runtime {
60
68
  actionRuntimeModule;
61
69
  /** Stored so we can call off() in stop() and avoid retaining Runtime via scanner EventEmitter. */
62
70
  onScannerRunComplete = null;
71
+ onScannerRunSkip = null;
72
+ onScannerRunError = null;
63
73
  /** Cached strategy id resolved from the runtime wallet on first {@link auditQuery} call. */
64
74
  cachedStrategyId = null;
65
75
  /** In-flight resolution promise; ensures concurrent first-burst callers reuse one `listStrategies`. */
66
76
  strategyIdResolution = null;
67
77
  /** Action-layer Telegram subscriber (open submit / close); disposed in {@link Runtime.stop}. */
68
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;
69
92
  /**
70
93
  * Per-process UUID. Used as the synthetic session_key for direct-path
71
94
  * spans (and lets us group "all LLM calls from this runtime boot" in
@@ -203,6 +226,19 @@ export class Runtime {
203
226
  throw new AuditQueryError("UPSTREAM", `audit_query failed: ${message}`);
204
227
  }
205
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
+ }
206
242
  /**
207
243
  * Cached wallet → strategy-id lookup. Concurrent callers share one
208
244
  * in-flight `listStrategies` promise; the cached id is reused across
@@ -287,171 +323,351 @@ export class Runtime {
287
323
  this.trackingHandler = createTrackingHandler(this.bus, tracker);
288
324
  this.stateManager = new StateManager(stateDir);
289
325
  await this.stateManager.hydrate();
326
+ this.positionIdRegistry = new PositionIdRegistry();
290
327
  const senpi = mcpTransport
291
328
  ? new SenpiClient(mcpTransport)
292
329
  : new SenpiClient({ apiKey });
293
330
  if (!mcpTransport) {
294
- 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
+ }
295
343
  }
296
344
  this.senpi = senpi;
297
345
  this.strategyConfig = resolveStrategyConfig(this.config);
298
- // try {
299
- // const { reconcileStateWithBackend } = await import("./reconcile-state.js");
300
- // await reconcileStateWithBackend(this.stateManager, senpi, [this.strategyConfig.address]);
301
- // } catch (err) {
302
- // logger.warn("reconcile after hydrate failed, continuing", { err });
303
- // }
304
- const llmDecision = createLlmDecision({});
305
- const contextBuilder = createContextBuilder();
306
- const notifications = createNotificationService({
307
- ...this.config.notifications,
308
- mcpTransport: this.options.mcpTransport,
309
- });
310
- const riskBlock = this.config.risk;
311
- const strategyAddress = this.strategyConfig.address;
312
- const auditLog = riskBlock ? createRiskAuditLog(stateDir) : undefined;
313
- // In-memory strategy-lifecycle tracker (§4 seed): owns the self-pause state that
314
- // RiskGuard used to hold and fires the hook + notification on a running→paused
315
- // transition. RiskGuard stays stateless and only reports gate evaluations.
316
- const lifecycle = createStrategyLifecycle({
317
- hookSystem: this.hookSystem,
318
- notifications,
319
- runtimeName: this.config.name,
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,
320
368
  });
321
- const riskGuard = riskBlock && senpi
322
- ? 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, {
323
438
  senpi,
439
+ hookSystem: this.hookSystem,
440
+ llmDecision,
441
+ contextBuilder,
442
+ riskGuard,
324
443
  notifications,
325
- strategies: new Map([[strategyAddress, this.strategyConfig]]),
326
- // Human strategy label for alerts; risk-guard falls back to the
327
- // truncated address when an address has no name here.
328
- strategyNames: { [strategyAddress]: this.config.name },
329
- auditLog,
330
- lifecycleTracker: lifecycle,
331
- })
332
- : createRiskGuardStub();
333
- logger.info("Runtime.start() creating scanner module");
334
- const layout = buildStateLayout(stateDir);
335
- // Augment caller-supplied providers with StateManager-backed DSL state access
336
- const augmentedProviders = {
337
- ...scannerProviders,
338
- getDslStatesForStrategy: scannerProviders?.getDslStatesForStrategy
339
- ?? (async (address) => this.stateManager.listDslStates(address)),
340
- };
341
- this.scannerModule = createScannerModuleFromRuntimeConfig(this.config, layout.scannerRoot, augmentedProviders);
342
- logger.info("Runtime.start() scanner module created, calling start()");
343
- // Pre-load max leverage cache (non-blocking — log warning on failure)
344
- const maxLeverageCache = new MaxLeverageCache(senpi);
345
- try {
346
- await maxLeverageCache.load();
347
- }
348
- catch (err) {
349
- logger.warn("failed to pre-load max leverage cache, will retry on first use", { err });
350
- }
351
- // Build RuntimeContext once per trading recipe and reuse for all actions.
352
- const runtimeContext = createRuntimeContext(this.strategyConfig, {
353
- senpi,
354
- hookSystem: this.hookSystem,
355
- llmDecision,
356
- contextBuilder,
357
- riskGuard,
358
- notifications,
359
- scannerModule: this.scannerModule,
360
- maxLeverageCache,
361
- });
362
- this.actionRuntimeModule = new ActionRuntimeModule({ stateDir: layout.actionRoot });
363
- const { runActionsForSignal } = await createActions(this.config, {
364
- bus: this.bus,
365
- senpi,
366
- stateManager: this.stateManager,
367
- hookSystem: this.hookSystem,
368
- llmDecision,
369
- contextBuilder,
370
- riskGuard,
371
- notifications,
372
- runtimeContext,
373
- actionModule: this.actionRuntimeModule,
374
- });
375
- this.runActionsForSignal = runActionsForSignal;
376
- const notificationsConfig = this.config.notifications;
377
- if (hasDsl) {
378
- const dslNotificationsDisabled = notificationsConfig?.dsl_lifecycle === false;
379
- const dslNotifySlUpdates = notificationsConfig?.dsl_notify_sl_updates === true;
380
- this.dslPlugin = await DslPluginClass.create({
381
- 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, {
382
450
  bus: this.bus,
383
- stateDir,
451
+ senpi,
384
452
  stateManager: this.stateManager,
385
- senpiClient: senpi,
386
- strategyStates: createStrategyStatesMap(this.strategyConfig, senpi),
387
- notifications: dslNotificationsDisabled ? undefined : notifications,
388
- notifySlUpdates: dslNotifySlUpdates,
389
- strategyName: this.config.name,
453
+ hookSystem: this.hookSystem,
454
+ llmDecision,
455
+ contextBuilder,
456
+ riskGuard,
457
+ notifications,
458
+ runtimeContext,
459
+ actionModule: this.actionRuntimeModule,
390
460
  });
391
- }
392
- else {
393
- this.dslPlugin = null;
394
- }
395
- if (isActionLifecycleNotificationsEnabled(notificationsConfig)) {
396
- this.actionNotificationSubscriber = createActionNotificationSubscriber(this.bus, notifications, {
397
- 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 });
398
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;
399
605
  }
400
- else {
401
- this.actionNotificationSubscriber = null;
402
- }
403
- initRisk(this.bus);
404
- this.healthStateModule = createHealthStateModule({
405
- runtimeName: this.config.name,
406
- stateDir,
407
- startedAt: this.startedAt,
408
- providers: {
409
- scanners: this.scannerModule,
410
- dsl: this.dslPlugin ?? createDisabledDslProvider(),
411
- actions: this.actionRuntimeModule,
412
- risk: riskBlock
413
- ? createRiskHealthProvider(riskGuard, strategyAddress)
414
- : undefined,
415
- },
416
- });
417
- this.onScannerRunComplete = (event) => {
418
- console.info("[senpi-runtime] [ingest-trace] onScannerRunComplete → enqueue", JSON.stringify({
419
- address: event.result.address,
420
- scannerId: event.result.scannerId,
421
- signalCount: Array.isArray(event.result.signals) ? event.result.signals.length : 0,
422
- status: event.result.status,
423
- queueDepth: this.signalQueue.length + 1,
424
- }));
425
- const correlationId = randomUUID();
426
- 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;
427
624
  if (this.signalQueueWait) {
428
625
  const w = this.signalQueueWait;
429
626
  this.signalQueueWait = null;
430
627
  w();
431
628
  }
432
- // Emit scanner run for tracking
433
- this.bus.emit("tracking.scanner_run", {
434
- address: event.result.address,
435
- data: {
436
- ...event.result,
437
- __correlationId: correlationId,
438
- },
439
- timestamp: new Date().toISOString(),
440
- });
441
- // Forward scanner summary alerts (e.g. watchdog) to notification service
442
- const alerts = event.result.summary?.alerts;
443
- if (Array.isArray(alerts) && alerts.length > 0) {
444
- const header = `[${event.result.scannerId}] ${alerts.length} alert(s):`;
445
- const lines = alerts.map((a) => ` ${a.level ?? "ALERT"}: ${a.message ?? ""}`);
446
- notifications.notify(`${header}\n${lines.join("\n")}`).catch(() => { });
629
+ this.reconcileGate?.resolve();
630
+ if (this.signalConsumerDone) {
631
+ await this.signalConsumerDone;
632
+ this.signalConsumerDone = null;
447
633
  }
448
- };
449
- this.scannerModule.on("scanner:run:complete", this.onScannerRunComplete);
450
- this.signalConsumerDone = this.runSignalConsumer();
451
- logger.info("Runtime.start() invoking scannerModule.start()");
452
- await this.scannerModule.start();
453
- logger.info("Runtime.start() scannerModule.start() returned");
454
- 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
+ }
455
671
  this.bus.emit("tracking.runtime_started", {
456
672
  address: this.strategyConfig.address,
457
673
  data: {
@@ -510,6 +726,33 @@ export class Runtime {
510
726
  runtimeBootId: this.runtimeBootId,
511
727
  }, async () => {
512
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
+ }
513
756
  console.info("[senpi-runtime] [ingest-trace] consumer dequeue → runActionsForSignal", JSON.stringify({
514
757
  address: queuedItem.result.address,
515
758
  scannerId: queuedItem.result.scannerId,
@@ -528,11 +771,13 @@ export class Runtime {
528
771
  data: {
529
772
  ...payload,
530
773
  __correlationId: queuedItem.correlationId,
774
+ __scanRunId: queuedItem.runId,
531
775
  },
532
776
  timestamp: new Date().toISOString(),
533
777
  };
534
778
  this.bus.emit(HOOK_EVENT.ON_SIGNAL_DETECTED, hookEvent);
535
- await this.runActionsForSignal(hookEvent);
779
+ // Serialize trade loop vs reconcile — reconcileMutex outer, key-lock inner.
780
+ await this.reconcileMutex.withKeyLock("reconcile", () => this.runActionsForSignal(hookEvent));
536
781
  console.info("[senpi-runtime] [ingest-trace] runActionsForSignal complete", JSON.stringify({ address: queuedItem.result.address, scannerId: queuedItem.result.scannerId }));
537
782
  }
538
783
  catch (err) {
@@ -543,16 +788,130 @@ export class Runtime {
543
788
  error: err,
544
789
  address: queuedItem.result.address,
545
790
  scannerId: queuedItem.result.scannerId,
791
+ runId: queuedItem.runId,
546
792
  timestamp: new Date().toISOString(),
547
793
  });
548
794
  }
549
795
  });
550
796
  }
551
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
+ }
552
903
  async stop() {
553
904
  if (!this.started)
554
905
  return;
555
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();
556
915
  this.bus.emit("tracking.runtime_stopped", {
557
916
  address: this.strategyConfig.address,
558
917
  data: {
@@ -577,6 +936,14 @@ export class Runtime {
577
936
  this.scannerModule.off("scanner:run:complete", this.onScannerRunComplete);
578
937
  this.onScannerRunComplete = null;
579
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
+ }
580
947
  if (this.actionNotificationSubscriber != null) {
581
948
  this.actionNotificationSubscriber.dispose();
582
949
  this.actionNotificationSubscriber = null;
@@ -595,6 +962,9 @@ export class Runtime {
595
962
  await this.trackingHandler.dispose();
596
963
  this.trackingHandler = null;
597
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();
598
968
  if (this.bus.removeAllListeners) {
599
969
  this.bus.removeAllListeners();
600
970
  }