@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
@@ -0,0 +1,250 @@
1
+ """`ctx.senpi_mcp` — the MCP client capability (runtime v2.0.0, Block B5).
2
+
3
+ The author's `scan(inputs, ctx)` is SYNC. `ctx.senpi_mcp.call_tool(name, args)`
4
+ is therefore a SYNC surface: the author never sees `await`. Internally it bridges
5
+ the OFFICIAL MCP Python SDK (`mcp`), which is async-only:
6
+
7
+ from mcp import ClientSession
8
+ from mcp.client.streamable_http import streamablehttp_client
9
+
10
+ async with streamablehttp_client(url, headers=...) as (read, write, _):
11
+ async with ClientSession(read, write) as session:
12
+ await session.initialize()
13
+ result = await session.call_tool(name, arguments=args)
14
+
15
+ DECISION (locked, execution-plan B5): use the SDK the STANDARD way — a SINGLE
16
+ PERSISTENT `ClientSession` created ONCE (and `initialize()`d once), reused across
17
+ every call. NO extra guards: no custom timeout, no reconnect/retry wrapper, no
18
+ pooling toggle, no fresh-connection-per-call. The async context managers must
19
+ STAY OPEN for the client's lifetime, so we drive them on a dedicated event loop
20
+ running in a background thread; `call_tool` submits work onto that loop and blocks
21
+ for the result (the sync↔async bridge).
22
+
23
+ Response normalization MATCHES producer.mjs `createSenpiToolClient`:
24
+ 1. isError truthy -> RAISE with the error text (never a silent None).
25
+ 2. structuredContent present -> return it.
26
+ 3. else first text content -> json.loads it (fallback to the raw text).
27
+ 4. else -> return content as-is.
28
+
29
+ The `mcp` package is LAZY-IMPORTED on first connect (NOT at module top), so
30
+ `import scaffold.senpi_mcp` works even where `mcp` is not installed. Missing creds
31
+ are LOUD AT FIRST USE: `call_tool` raises, construction never does.
32
+
33
+ TEARDOWN (intentional, one-process-per-scanner model): there is NO explicit
34
+ close()/shutdown for the persistent session. The background loop runs on a DAEMON
35
+ thread, so it dies with the process. The scaffold runs exactly ONE client per
36
+ process for that process's whole life — the supervisor restarts by spawning a
37
+ FRESH child process (not by re-running run_scaffold in-place), so a single client
38
+ is never replaced in-process and there is no loop/session leak across restart.
39
+ On graceful stop (SIGTERM/SIGINT) run_scaffold exits its loop and the process
40
+ returns; on a hard kill the OS reclaims the thread. We deliberately do NOT drive
41
+ an AsyncExitStack.aclose() from a shutdown hook: it buys nothing over the dropped
42
+ TCP connection (streamable-http is request/response, no protocol goodbye) and a
43
+ cross-thread aclose() on a wedged transport could itself hang a path that today
44
+ cannot hang.
45
+ """
46
+
47
+ from __future__ import annotations
48
+
49
+ import asyncio
50
+ import json
51
+ import threading
52
+ from typing import Any, Iterable, Optional
53
+
54
+
55
+ # --------------------------------------------------------------------------
56
+ # Producer MCP write boundary — read-only by default.
57
+ # --------------------------------------------------------------------------
58
+ #
59
+ # A supervised producer's scan(inputs, ctx) runs in-process with the strategy's
60
+ # full-capability SENPI_API_KEY. Without a boundary it could call ANY MCP tool —
61
+ # including money/state mutations — bypassing every runtime guard (risk-guard,
62
+ # DSL, slots, dedup). MUTATION_TOOLS enumerates those money/state-mutating tools;
63
+ # call_tool BLOCKS them by default unless the EXACT tool name is on the client's
64
+ # write_allowlist (least privilege — one permitted tool does not unlock others).
65
+ #
66
+ # Read tools (discovery_*, leaderboard_*, market_*, strategy_get*, strategy_list,
67
+ # execution_get*, account_get*, user_get*, arena_*, audit_*, get_*,
68
+ # list_senpi_guides, read_senpi_guide, ratchet_stop_get/list/events) are NOT in
69
+ # this set and therefore always pass.
70
+ MUTATION_TOOLS: frozenset[str] = frozenset(
71
+ {
72
+ "create_position",
73
+ "close_position",
74
+ "edit_position",
75
+ "cancel_order",
76
+ "send_usdc",
77
+ "transfer_spot_to_perps",
78
+ "strategy_create",
79
+ "strategy_create_custom_strategy",
80
+ "strategy_close",
81
+ "strategy_close_positions",
82
+ "strategy_update",
83
+ "strategy_pause",
84
+ "strategy_top_up",
85
+ "strategy_withdraw_funds",
86
+ "strategy_bridge_funds_from_hyperliquid_to_evm",
87
+ "ratchet_stop_add",
88
+ "ratchet_stop_edit",
89
+ "ratchet_stop_delete",
90
+ "user_claim_referral_rewards",
91
+ }
92
+ )
93
+
94
+ # THE allowlist a scaffold maintainer edits to permit a mutation tool for
95
+ # producers. EMPTY BY DEFAULT — every MUTATION_TOOLS entry is blocked. The ONLY
96
+ # way to permit a mutation is to add its exact tool name to this frozenset
97
+ # (e.g. {"create_position"}). This is scaffold-maintainer-owned source: it is
98
+ # not operator/env-configurable and is not reachable by authored producer code.
99
+ PRODUCER_WRITE_ALLOWLIST: frozenset[str] = frozenset()
100
+
101
+
102
+ class SenpiMcpClient:
103
+ """Sync MCP client over the official async SDK with one persistent session.
104
+
105
+ Construction is cheap and never touches the network or imports `mcp`. The
106
+ first `call_tool` lazily imports the SDK, spins up a private event loop on a
107
+ background thread, opens the transport + ClientSession ONCE, and initializes
108
+ it ONCE. Every subsequent call reuses that same session.
109
+ """
110
+
111
+ def __init__(
112
+ self,
113
+ api_key: Optional[str] = None,
114
+ mcp_url: Optional[str] = None,
115
+ write_allowlist: Iterable[str] = (),
116
+ ) -> None:
117
+ self._api_key = api_key
118
+ self._mcp_url = mcp_url
119
+ # Mutation tools the operator has explicitly permitted. EMPTY by default
120
+ # → every MUTATION_TOOLS entry is blocked (read-only producer boundary).
121
+ self._write_allowlist: frozenset[str] = frozenset(write_allowlist)
122
+
123
+ # Persistent bridge state — created lazily on first call_tool.
124
+ self._loop: Optional[asyncio.AbstractEventLoop] = None
125
+ self._thread: Optional[threading.Thread] = None
126
+ self._session: Any = None
127
+ self._stack: Any = None
128
+ self._connected = False
129
+ self._connect_lock = threading.Lock()
130
+
131
+ # -- public sync surface ----------------------------------------------
132
+
133
+ def call_tool(self, name: str, args: Optional[dict] = None) -> Any:
134
+ """Invoke an MCP tool synchronously; return the unwrapped result.
135
+
136
+ Raises (loud, never a silent None) when the tool is a money/state
137
+ mutation not on the write allowlist, when creds are missing, or when the
138
+ tool reports `isError`.
139
+ """
140
+ # Read-only producer boundary, enforced PRE-CONNECT (no transport opened
141
+ # for a blocked write). A mutation tool passes only if its exact name is
142
+ # on the write allowlist (least privilege — one tool ≠ all).
143
+ if name in MUTATION_TOOLS and name not in self._write_allowlist:
144
+ raise PermissionError(
145
+ f'senpi_mcp: tool "{name}" is a money/state-mutating MCP tool and '
146
+ "is blocked — producers are READ-ONLY by default. The ONLY way to "
147
+ f'permit it is to add "{name}" to the PRODUCER_WRITE_ALLOWLIST '
148
+ "frozenset in src/scanners/external/scaffold/senpi_mcp.py "
149
+ "(scaffold-maintainer-owned source; not operator/env-configurable; "
150
+ "not reachable by authored producer code)."
151
+ )
152
+
153
+ self._ensure_connected()
154
+ result = self._run(self._session.call_tool(name, arguments=args))
155
+ return self._unwrap(name, result)
156
+
157
+ # -- persistent session lifecycle -------------------------------------
158
+
159
+ def _ensure_connected(self) -> None:
160
+ if self._connected:
161
+ return
162
+ with self._connect_lock:
163
+ if self._connected:
164
+ return
165
+
166
+ # Loud at first use: creds are required to reach the MCP server.
167
+ if not self._api_key:
168
+ raise RuntimeError(
169
+ "senpi_mcp: SENPI_API_KEY is not set; cannot call MCP tools "
170
+ "(creds are resolved at launch from SENPI_API_KEY/SENPI_MCP_URL)."
171
+ )
172
+ if not self._mcp_url:
173
+ raise RuntimeError(
174
+ "senpi_mcp: SENPI_MCP_URL is not set; cannot call MCP tools "
175
+ "(creds are resolved at launch from SENPI_API_KEY/SENPI_MCP_URL)."
176
+ )
177
+
178
+ # Dedicated event loop on a background thread. The async context
179
+ # managers (transport + session) must stay OPEN for the client's
180
+ # lifetime, so we cannot use asyncio.run() per call — that would
181
+ # tear the session down between calls.
182
+ self._loop = asyncio.new_event_loop()
183
+ self._thread = threading.Thread(
184
+ target=self._loop.run_forever,
185
+ name="senpi-mcp-loop",
186
+ daemon=True,
187
+ )
188
+ self._thread.start()
189
+
190
+ self._run(self._connect())
191
+ self._connected = True
192
+
193
+ async def _connect(self) -> None:
194
+ """Open the transport + ClientSession ONCE and initialize ONCE.
195
+
196
+ Lazy-import the SDK here so `import scaffold.senpi_mcp` succeeds in envs
197
+ without `mcp` installed (tests inject a fake `mcp` into sys.modules).
198
+ """
199
+ from mcp import ClientSession
200
+ from mcp.client.streamable_http import streamablehttp_client
201
+
202
+ # Keep the async context managers alive by holding their __aenter__
203
+ # values on self and only __aexit__-ing them at close. We use
204
+ # AsyncExitStack so both nest correctly and unwind in order.
205
+ from contextlib import AsyncExitStack
206
+
207
+ self._stack = AsyncExitStack()
208
+ headers = {"Authorization": f"Bearer {self._api_key}"}
209
+ read, write, _ = await self._stack.enter_async_context(
210
+ streamablehttp_client(self._mcp_url, headers=headers)
211
+ )
212
+ session = await self._stack.enter_async_context(ClientSession(read, write))
213
+ await session.initialize()
214
+ self._session = session
215
+
216
+ def _run(self, coro: Any) -> Any:
217
+ """Drive a coroutine to completion on the persistent loop, blocking."""
218
+ future = asyncio.run_coroutine_threadsafe(coro, self._loop)
219
+ return future.result()
220
+
221
+ # -- response normalization (matches producer.mjs createSenpiToolClient) --
222
+
223
+ @staticmethod
224
+ def _unwrap(name: str, result: Any) -> Any:
225
+ if getattr(result, "isError", False):
226
+ content = getattr(result, "content", None)
227
+ if (
228
+ isinstance(content, list)
229
+ and len(content) > 0
230
+ and getattr(content[0], "type", None) == "text"
231
+ ):
232
+ error_text = content[0].text
233
+ else:
234
+ error_text = json.dumps(content, default=str)
235
+ raise RuntimeError(f'MCP tool "{name}" returned error: {error_text}')
236
+
237
+ structured = getattr(result, "structuredContent", None)
238
+ if structured is not None:
239
+ return structured
240
+
241
+ content = getattr(result, "content", None)
242
+ if isinstance(content, list) and len(content) > 0:
243
+ first = content[0]
244
+ if getattr(first, "type", None) == "text":
245
+ try:
246
+ return json.loads(first.text)
247
+ except (ValueError, TypeError):
248
+ return first.text
249
+
250
+ return content
@@ -0,0 +1,258 @@
1
+ """Pure candidate -> wire-signal mapping (v2: lenient + loud).
2
+
3
+ candidate_to_signal(
4
+ candidate,
5
+ produced_at_ms,
6
+ *,
7
+ signal_id=None, # stable production id (journal eid); minted if absent
8
+ signal_data_schema, # dict {key: {type, required?}} | None
9
+ default_signal_validity_seconds, # int REQUIRED fallback TTL (seconds)
10
+ on_reject=None, # callback(reason_dict) on reject -> /errors
11
+ ) -> dict | None
12
+
13
+ Returns the wire dict on success:
14
+ {signal_id, asset, direction, produced_at, valid_until, data}
15
+ plus signal_type only when the author set a non-empty string, and the canonical
16
+ sizing fields `marginPct` (percent 0–100 of withdrawable, not a fraction) and/or
17
+ `leverage` at the TOP LEVEL (not inside `data`) when the candidate sets them — the
18
+ runtime reads signal.marginPct / signal.leverage directly. A present-but-non-positive
19
+ leverage, or a marginPct outside (0, 100], is a LOUD reject.
20
+
21
+ Returns None (never raises for a bad CANDIDATE) when the candidate is invalid,
22
+ and — when on_reject is supplied — calls on_reject(reason) so the rejection is
23
+ LOUD (logged AND posted to /errors), never a silent drop.
24
+
25
+ v2 contract (design §4):
26
+ - direction is NORMALIZED case: "long"/"LONG"/"Long" -> "LONG"; "short"/.. -> "SHORT".
27
+ Surrounding whitespace is stripped. "buy"/"sell"/""/non-string -> REJECT.
28
+ - asset + direction are MANDATORY (non-empty string asset).
29
+ - `data` is VALIDATED against signal_data_schema (when a dict is supplied):
30
+ missing-required / wrong-type / extra (unknown) keys all REJECT. A None schema
31
+ means "no validation" (passthrough — used when no schema is threaded in).
32
+ - valid_until = produced_at_ms + (valid_for_seconds else
33
+ default_signal_validity_seconds) * 1000. The v1 produced_at + 2*interval default
34
+ is GONE; there is no interval_ms arg. A non-positive / non-int valid_for_seconds
35
+ is REJECTED. A MISSING default_signal_validity_seconds (None) when it is NEEDED
36
+ fails LOUD (raises) — no magic fallback.
37
+ - author absolute `valid_until` is DROPPED (never honored, never leaks).
38
+ - The keys on the wire are {signal_id, asset, direction, produced_at,
39
+ valid_until, data} (+ optional signal_type, marginPct, leverage).
40
+ `marginPct`/`leverage` are the canonical top-level sizing fields (validated when
41
+ present; `marginPct` is a percent 0–100 of withdrawable — not a fraction, not a
42
+ USD value). `signal_id` is the
43
+ scaffold-minted
44
+ stable production id (the journal eid), threaded in by the delivery sink — it is
45
+ the intake dedup key. An author-supplied `signal_id` in the candidate dict is
46
+ IGNORED: the scaffold owns the dedup key, an author cannot spoof it. Apart from
47
+ signal_id/signal_type, author bookkeeping never leaks.
48
+ """
49
+
50
+ from __future__ import annotations
51
+
52
+ import uuid
53
+ from typing import Any, Optional
54
+
55
+
56
+ # JSON type name -> Python type(s) for schema validation. `bool` is excluded from
57
+ # "number" because a bool is an int subclass in Python but is not a numeric value.
58
+ def _is_number(value: Any) -> bool:
59
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
60
+
61
+
62
+ def _is_string(value: Any) -> bool:
63
+ return isinstance(value, str)
64
+
65
+
66
+ def _is_boolean(value: Any) -> bool:
67
+ return isinstance(value, bool)
68
+
69
+
70
+ def _is_object(value: Any) -> bool:
71
+ return isinstance(value, dict)
72
+
73
+
74
+ def _is_array(value: Any) -> bool:
75
+ return isinstance(value, list)
76
+
77
+
78
+ _TYPE_CHECKS = {
79
+ "number": _is_number,
80
+ "string": _is_string,
81
+ "boolean": _is_boolean,
82
+ "object": _is_object,
83
+ "array": _is_array,
84
+ }
85
+
86
+
87
+ def _validate_data_against_schema(data: dict, schema: dict) -> Optional[str]:
88
+ """Validate `data` against `schema`. Returns a reason string on violation,
89
+ or None when valid. additionalProperties:false — unknown keys reject."""
90
+ allowed = set(schema.keys())
91
+
92
+ # Extra (unknown) keys reject.
93
+ for key in data:
94
+ if key not in allowed:
95
+ return f"data has unknown key {key!r} (not in signal_data_schema)"
96
+
97
+ # Missing-required and wrong-type.
98
+ for key, spec in schema.items():
99
+ spec = spec if isinstance(spec, dict) else {}
100
+ required = spec.get("required", True) # required unless explicitly False
101
+ if key not in data:
102
+ if required:
103
+ return f"data missing required key {key!r}"
104
+ continue
105
+ declared_type = spec.get("type")
106
+ check = _TYPE_CHECKS.get(declared_type)
107
+ if check is not None and not check(data[key]):
108
+ return (
109
+ f"data key {key!r} has wrong type "
110
+ f"(expected {declared_type}, got {type(data[key]).__name__})"
111
+ )
112
+ return None
113
+
114
+
115
+ # Top-level candidate keys the envelope recognizes and lifts onto the wire signal.
116
+ # Anything else an author sets at the top level is dropped (it never leaks to the
117
+ # wire by design) — `on_warn` names it so a removed/typo'd sizing field (e.g.
118
+ # `marginUsd`, or `marginpct` miscased) is visible instead of vanishing silently.
119
+ _RECOGNIZED_CANDIDATE_KEYS = frozenset(
120
+ {
121
+ "asset",
122
+ "direction",
123
+ "valid_for_seconds",
124
+ "data",
125
+ "leverage",
126
+ "marginPct",
127
+ "signal_type",
128
+ "signal_id", # author-supplied id is intentionally ignored; don't warn on it
129
+ }
130
+ )
131
+
132
+
133
+ def candidate_to_signal(
134
+ candidate: Any,
135
+ produced_at_ms: int,
136
+ *,
137
+ signal_id: Optional[str] = None,
138
+ signal_data_schema: Optional[dict],
139
+ default_signal_validity_seconds: Optional[int],
140
+ on_reject=None,
141
+ on_warn=None,
142
+ ) -> dict | None:
143
+ """Wrap a scan() candidate into a wire signal dict (v2).
144
+
145
+ Returns the signal dict on success, None when the candidate is invalid (and
146
+ calls on_reject(reason) so the rejection is loud). Raises only when the
147
+ OPERATOR config is wrong (missing default_signal_validity_seconds when needed).
148
+ """
149
+
150
+ def _reject(reason: str) -> None:
151
+ if on_reject is not None:
152
+ on_reject({"reason": reason, "candidate": repr(candidate)})
153
+
154
+ if not isinstance(candidate, dict):
155
+ _reject(f"candidate is not a mapping (got {type(candidate).__name__})")
156
+ return None
157
+
158
+ # -- asset: mandatory, non-empty string --------------------------------
159
+ asset = candidate.get("asset")
160
+ if not isinstance(asset, str) or not asset.strip():
161
+ _reject(f"asset missing/blank/non-string (got {asset!r})")
162
+ return None
163
+
164
+ # -- direction: mandatory string, case-normalized to LONG / SHORT ------
165
+ direction = candidate.get("direction")
166
+ if not isinstance(direction, str) or isinstance(direction, bool):
167
+ _reject(f"direction is not a string (got {direction!r})")
168
+ return None
169
+ normalized = direction.strip().upper()
170
+ if normalized not in ("LONG", "SHORT"):
171
+ _reject(f"direction must be long/short (got {direction!r})")
172
+ return None
173
+
174
+ # -- valid_until from valid_for_seconds else the default ---------------
175
+ # (compute BEFORE schema so a missing operator default still fails loud.)
176
+ if "valid_for_seconds" in candidate:
177
+ vfs = candidate["valid_for_seconds"]
178
+ # int only (bool excluded), strictly positive.
179
+ if not isinstance(vfs, int) or isinstance(vfs, bool) or vfs <= 0:
180
+ _reject(f"valid_for_seconds must be a positive int (got {vfs!r})")
181
+ return None
182
+ validity_seconds = vfs
183
+ else:
184
+ if default_signal_validity_seconds is None:
185
+ # OPERATOR error, not a candidate bug — fail LOUD (no magic fallback).
186
+ raise ValueError(
187
+ "default_signal_validity_seconds is required when a candidate has "
188
+ "no valid_for_seconds; got None (no magic fallback in v2)."
189
+ )
190
+ validity_seconds = default_signal_validity_seconds
191
+
192
+ valid_until = produced_at_ms + validity_seconds * 1000
193
+
194
+ # -- data: validate against schema (when supplied) ---------------------
195
+ data = candidate.get("data", {})
196
+ if not isinstance(data, dict):
197
+ data = {}
198
+ if signal_data_schema is not None:
199
+ violation = _validate_data_against_schema(data, signal_data_schema)
200
+ if violation is not None:
201
+ _reject(violation)
202
+ return None
203
+
204
+ # -- canonical sizing: marginPct / leverage ride at the TOP LEVEL of the wire
205
+ # signal, NOT inside `data`. `marginPct` is a percent (0–100] of withdrawable
206
+ # (NOT a fraction, NOT a USD value); the runtime consumes signal.marginPct /
207
+ # signal.leverage directly (data is freeform context only), so per-signal
208
+ # sizing/leverage from the producer is honored instead of silently dropped.
209
+ # Present-but-invalid is a LOUD reject — sizing must never fall back silently.
210
+ sizing: dict = {}
211
+ if candidate.get("leverage") is not None:
212
+ value = candidate["leverage"]
213
+ if not _is_number(value) or value <= 0:
214
+ _reject(f"leverage must be a positive number when set (got {value!r})")
215
+ return None
216
+ sizing["leverage"] = value
217
+
218
+ # marginPct is a PERCENT of withdrawable (0–100], not a USD value and not a
219
+ # fraction — same units/basis as the runtime's config `margin_pct`. Bounded
220
+ # (fail-closed) so an out-of-range percent never sizes silently.
221
+ margin_pct = candidate.get("marginPct")
222
+ if margin_pct is not None:
223
+ if not _is_number(margin_pct) or margin_pct <= 0 or margin_pct > 100:
224
+ _reject(
225
+ f"marginPct must be a number in (0, 100] when set (got {margin_pct!r})"
226
+ )
227
+ return None
228
+ sizing["marginPct"] = margin_pct
229
+
230
+ sig: dict = {
231
+ # scaffold-minted stable production id (journal eid); the author cannot
232
+ # override it via the candidate dict — the kwarg is authoritative. The
233
+ # delivery sink threads the eid in; when no id is supplied a stable one is
234
+ # minted so the wire ALWAYS carries a signal_id (required end-to-end).
235
+ "signal_id": signal_id if (isinstance(signal_id, str) and signal_id) else uuid.uuid4().hex,
236
+ "asset": asset,
237
+ "direction": normalized,
238
+ "produced_at": produced_at_ms,
239
+ "valid_until": valid_until,
240
+ "data": data,
241
+ }
242
+
243
+ # Lift the validated sizing fields onto the wire signal at the top level.
244
+ sig.update(sizing)
245
+
246
+ signal_type = candidate.get("signal_type")
247
+ if signal_type and isinstance(signal_type, str):
248
+ sig["signal_type"] = signal_type
249
+
250
+ # The signal IS valid and will emit — but warn (don't reject) about any
251
+ # top-level key we did not lift, so a producer whose sizing field was dropped
252
+ # (removed/typo'd) sees why instead of debugging a silently mis-sized signal.
253
+ if on_warn is not None:
254
+ dropped = sorted(k for k in candidate if k not in _RECOGNIZED_CANDIDATE_KEYS)
255
+ if dropped:
256
+ on_warn({"dropped": dropped, "asset": asset})
257
+
258
+ return sig
@@ -0,0 +1,175 @@
1
+ """Disk-backed, bounded, transactional state series for the scaffold core.
2
+
3
+ `StateManager` is the `ctx.state` capability the supervised external scanner
4
+ author sees: a list-like series of dict records, persisted between ticks and
5
+ bounded by `state_history_max_count`.
6
+
7
+ Shape (per scanner-and-ctx-design.md §2.3):
8
+
9
+ StateManager(state_path, state_history_max_count)
10
+
11
+ Author surface:
12
+ append(record) record MUST be a dict; a reserved `recorded_at` (float
13
+ SECONDS, time.time() magnitude — never ms) is injected.
14
+ scaffold wins on a `recorded_at` collision. returns None.
15
+ RAISES when state_history_max_count is 0/unset — history
16
+ disabled is a hard error, never a silent no-op.
17
+ recent(n) last n entries, chronological (oldest->newest); n<=0 -> [].
18
+ last() most recent entry, or None if empty.
19
+ __len__ / __getitem__ (index + slice) / __iter__ (oldest -> newest).
20
+
21
+ Internals: backed by collections.deque(maxlen=state_history_max_count).
22
+ Loading an on-disk series longer than the bound keeps the NEWEST entries
23
+ (deque eviction drops the oldest).
24
+
25
+ Transactional (one commit per tick):
26
+ commit() persists the working buffer via the atomic write_state.
27
+ JSON-serializability is enforced LOUD here — a failed persist
28
+ RAISES and does NOT advance the committed snapshot, leaving the
29
+ prior on-disk state intact.
30
+ rollback() discards mid-tick mutations: the working buffer is restored to
31
+ the last committed snapshot.
32
+ read-your-writes within a tick: appended records are visible via
33
+ len/recent/last/iter/getitem BEFORE commit.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import copy
39
+ import time
40
+ from collections import deque
41
+
42
+ from .scaffold_state import read_state, write_state
43
+
44
+ # Reserved, scaffold-owned key injected into every record. Float seconds.
45
+ RECORDED_AT_KEY = "recorded_at"
46
+
47
+
48
+ class StateManager:
49
+ """A disk-backed, bounded, transactional series of dict records."""
50
+
51
+ def __init__(self, state_path: str, state_history_max_count):
52
+ self._state_path = state_path
53
+ # 0 / None / falsy => history disabled. Kept as-is so append can raise.
54
+ self._max_count = state_history_max_count
55
+
56
+ # Load any persisted series. read_state never raises: missing/corrupt
57
+ # -> None. A non-list payload is treated as "no usable history".
58
+ # state_path None => no disk persistence (commit advances the in-memory
59
+ # snapshot but never writes). read_state needs a real path.
60
+ loaded = read_state(state_path) if state_path is not None else None
61
+ if not isinstance(loaded, list):
62
+ loaded = []
63
+
64
+ # The committed snapshot is the last durably-persisted series; the
65
+ # working buffer is what the current tick reads/mutates. Both are
66
+ # bounded the same way (deque(maxlen=...)); loading a longer-than-bound
67
+ # series keeps the NEWEST entries (deque evicts from the left).
68
+ self._committed = self._new_deque(loaded)
69
+ self._working = self._snapshot(self._committed)
70
+
71
+ # -- internals ---------------------------------------------------------
72
+
73
+ def _new_deque(self, initial=()):
74
+ """A deque bounded by max_count. When history is disabled (max_count is
75
+ 0/None) the bound is 0 — nothing can ever be buffered."""
76
+ maxlen = self._max_count if self._max_count else 0
77
+ return deque(initial, maxlen=maxlen)
78
+
79
+ def _snapshot(self, source):
80
+ """An independent bounded deque whose records share NO mutable state
81
+ with `source`. Committed and working buffers must never alias the same
82
+ dict objects — otherwise a mid-tick mutation of a record (an author
83
+ scribbling on a dict handed back by last()/recent()/getitem) would
84
+ survive a rollback and corrupt the very snapshot the rollback restores.
85
+ Deep-copy at every snapshot boundary (load / commit / rollback)."""
86
+ return self._new_deque(copy.deepcopy(entry) for entry in source)
87
+
88
+ # -- author surface ----------------------------------------------------
89
+
90
+ def append(self, record) -> None:
91
+ """Append a dict record to the working buffer.
92
+
93
+ Injects the reserved `recorded_at` (float seconds, scaffold wins on
94
+ collision). Raises TypeError if record is not a dict. Raises if history
95
+ is disabled (state_history_max_count 0/unset) — never a silent no-op.
96
+ """
97
+ if not self._max_count:
98
+ raise ValueError(
99
+ "state is disabled: state_history_max_count is 0 or unset "
100
+ "(set it > 0 to use ctx.state.append)"
101
+ )
102
+ # bool is an int subclass but never a dict; explicit dict check rejects
103
+ # lists/tuples/sets/strings/numbers/None/objects/bool alike.
104
+ if not isinstance(record, dict):
105
+ raise TypeError(
106
+ f"state record must be a dict, got {type(record).__name__}"
107
+ )
108
+
109
+ # Copy so the author's dict is never mutated, then stamp recorded_at.
110
+ # scaffold wins on collision: assign AFTER copying author keys.
111
+ entry = dict(record)
112
+ entry[RECORDED_AT_KEY] = time.time()
113
+ self._working.append(entry)
114
+ return None
115
+
116
+ def recent(self, n) -> list:
117
+ """The last n entries, chronological (oldest->newest).
118
+
119
+ n <= 0 returns []; n greater than the buffer returns the whole buffer.
120
+ Negative n is NOT a from-the-end slice — it is meaningless for "last n"
121
+ and yields [].
122
+ """
123
+ if n <= 0:
124
+ return []
125
+ items = list(self._working)
126
+ return items[-n:]
127
+
128
+ def last(self):
129
+ """The most recent entry, or None if empty."""
130
+ if not self._working:
131
+ return None
132
+ return self._working[-1]
133
+
134
+ # -- sequence protocol -------------------------------------------------
135
+
136
+ def __len__(self) -> int:
137
+ return len(self._working)
138
+
139
+ def __getitem__(self, key):
140
+ # deque supports integer indexing (raising IndexError out of range) but
141
+ # not slicing; materialise a list so slices work with Python semantics
142
+ # (clamping, steps, negative bounds) and index errors still propagate.
143
+ if isinstance(key, slice):
144
+ return list(self._working)[key]
145
+ return self._working[key]
146
+
147
+ def __iter__(self):
148
+ return iter(self._working)
149
+
150
+ # -- transaction -------------------------------------------------------
151
+
152
+ def commit(self) -> None:
153
+ """Persist the working buffer atomically via write_state.
154
+
155
+ JSON-serializability is enforced LOUD: write_state returns False on a
156
+ non-serializable value (or IO failure) without touching the existing
157
+ file. We raise on that False so a failed persist never silently
158
+ advances the committed snapshot — the prior on-disk state stays intact.
159
+ """
160
+ payload = list(self._working)
161
+ # No disk path => commit advances the in-memory snapshot only.
162
+ ok = True if self._state_path is None else write_state(self._state_path, payload)
163
+ if not ok:
164
+ raise RuntimeError(
165
+ f"failed to persist state to {self._state_path} "
166
+ "(non-serializable value or IO error); state not advanced"
167
+ )
168
+ # Durable: advance the committed snapshot to match what is on disk.
169
+ # Deep-copy so the committed snapshot does not alias working records.
170
+ self._committed = self._snapshot(self._working)
171
+
172
+ def rollback(self) -> None:
173
+ """Discard mid-tick mutations: restore the working buffer to the last
174
+ committed snapshot. Never touches disk."""
175
+ self._working = self._snapshot(self._committed)