observability-toolkit-hooks 0.0.0-stage → 1.0.1

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 (306) hide show
  1. package/CONFIG.md +144 -0
  2. package/LICENSE +95 -0
  3. package/README.md +201 -2
  4. package/dist/handlers/compact.js +38 -0
  5. package/dist/handlers/mcp-status.js +66 -0
  6. package/dist/handlers/notification.js +45 -0
  7. package/dist/handlers/post-tool-agent.js +157 -0
  8. package/dist/handlers/post-tool-changelog-sync.js +148 -0
  9. package/dist/handlers/post-tool-code-structure.js +116 -0
  10. package/dist/handlers/post-tool-edit-ledger.js +15 -0
  11. package/dist/handlers/post-tool-failure.js +83 -0
  12. package/dist/handlers/post-tool-git.js +79 -0
  13. package/dist/handlers/post-tool-mcp.js +105 -0
  14. package/dist/handlers/post-tool-outcome.js +48 -0
  15. package/dist/handlers/post-tool-task-state.js +74 -0
  16. package/dist/handlers/post-tool.js +132 -0
  17. package/dist/handlers/pre-tool-agent.js +192 -0
  18. package/dist/handlers/pre-tool.js +218 -0
  19. package/dist/handlers/session-end.js +39 -0
  20. package/dist/handlers/session-start.js +262 -0
  21. package/dist/handlers/stop-error-reminder.js +195 -0
  22. package/dist/handlers/stop-quality-evaluation.js +58 -0
  23. package/dist/handlers/stop-session-summary.js +62 -0
  24. package/dist/handlers/stop-token-metrics.js +83 -0
  25. package/dist/handlers/stop.js +25 -0
  26. package/dist/handlers/subagent.js +105 -0
  27. package/dist/handlers/tool-event-router.js +39 -0
  28. package/dist/handlers/user-prompt.js +218 -0
  29. package/dist/hook-runner.js +10 -0
  30. package/dist/hook-runner.js.map +7 -0
  31. package/dist/lib/agent/agent-context.js +123 -0
  32. package/dist/lib/agent/agent-evaluations.js +155 -0
  33. package/dist/lib/agent/agent-file-budget.js +65 -0
  34. package/dist/lib/agent/agent-sources.js +165 -0
  35. package/dist/lib/agent/synth-spans.js +51 -0
  36. package/dist/lib/core/bounded-label.js +6 -0
  37. package/dist/lib/core/category-rules.js +11 -0
  38. package/dist/lib/core/child-result.js +19 -0
  39. package/dist/lib/core/config-dir-recovery.js +22 -0
  40. package/dist/lib/core/constants.js +171 -0
  41. package/dist/lib/core/detached-runner.js +55 -0
  42. package/dist/lib/core/file-utils.js +353 -0
  43. package/dist/lib/core/format-utils.js +51 -0
  44. package/dist/lib/core/http-utils.js +74 -0
  45. package/dist/lib/core/http1-fetch.js +14 -0
  46. package/dist/lib/core/identity-key-resolver.js +149 -0
  47. package/dist/lib/core/jsonl-tail.js +207 -0
  48. package/dist/lib/core/load-envrc.js +72 -0
  49. package/dist/lib/core/parsers.js +43 -0
  50. package/dist/lib/core/regex.js +27 -0
  51. package/dist/lib/core/settings-env.js +31 -0
  52. package/dist/lib/core/shell-command.js +122 -0
  53. package/dist/lib/core/units.js +97 -0
  54. package/dist/lib/git/git-cache.js +158 -0
  55. package/dist/lib/git/git-commit.js +189 -0
  56. package/dist/lib/git/git-exec.js +30 -0
  57. package/dist/lib/mcp/mcp-completeness.js +40 -0
  58. package/dist/lib/mcp/mcp-config.js +118 -0
  59. package/dist/lib/mcp/mcp-failure-latch.js +22 -0
  60. package/dist/lib/mcp/mcp-identity-launcher.js +43 -0
  61. package/dist/lib/otel/attributes.js +322 -0
  62. package/dist/lib/otel/evaluation-attrs.js +51 -0
  63. package/dist/lib/otel/file-exporters.js +169 -0
  64. package/dist/lib/otel/host-resource.js +61 -0
  65. package/dist/lib/otel/otel-headers-helper.js +26 -0
  66. package/dist/lib/otel/otel-monitor.js +181 -0
  67. package/dist/lib/otel/otel.js +235 -0
  68. package/dist/lib/otel/otlp-headers.js +101 -0
  69. package/dist/lib/otel/otlp-post.js +122 -0
  70. package/dist/lib/otel/otlp-serialize.js +142 -0
  71. package/dist/lib/otel/otlp-signal.js +2 -0
  72. package/dist/lib/otel/remote-spans.js +142 -0
  73. package/dist/lib/otel/service-identity.js +10 -0
  74. package/dist/lib/otel/telemetry-alerts.js +43 -0
  75. package/dist/lib/otel/token-metrics.js +122 -0
  76. package/dist/lib/otel/trace-context.js +81 -0
  77. package/dist/lib/quality/judge-meta-eval.js +70 -0
  78. package/dist/lib/quality/judge-prompts.js +104 -0
  79. package/dist/lib/quality/judge-providers.js +193 -0
  80. package/dist/lib/quality/judge-transport.js +93 -0
  81. package/dist/lib/quality/llm-judge.js +170 -0
  82. package/dist/lib/quality/quality-budget.js +99 -0
  83. package/dist/lib/quality/quality-degradation.js +156 -0
  84. package/dist/lib/quality/quality-eval-handoff.js +74 -0
  85. package/dist/lib/quality/quality-evaluator.js +178 -0
  86. package/dist/lib/quality/quality-sampler.js +43 -0
  87. package/dist/lib/quality/quality-signals.js +150 -0
  88. package/dist/lib/runtime/categorizers.js +101 -0
  89. package/dist/lib/runtime/hook-input.js +16 -0
  90. package/dist/lib/runtime/hook-output.js +50 -0
  91. package/dist/lib/runtime/output-analyzer.js +160 -0
  92. package/dist/lib/runtime/run-handlers.js +32 -0
  93. package/dist/lib/runtime/tool-input.js +111 -0
  94. package/dist/lib/runtime/tool-output.js +44 -0
  95. package/dist/lib/runtime/unknown-tool.js +32 -0
  96. package/dist/lib/session/edit-ledger.js +29 -0
  97. package/dist/lib/session/forked-skill.js +39 -0
  98. package/dist/lib/session/handoffs.js +77 -0
  99. package/dist/lib/session/session-state.js +169 -0
  100. package/dist/lib/session/skill-rules.js +196 -0
  101. package/dist/lib/session/task-tracker.js +83 -0
  102. package/dist/lib/shipper/shipper-credentials.js +38 -0
  103. package/dist/lib/shipper/shipper-cursor.js +89 -0
  104. package/dist/lib/shipper/shipper-status.js +174 -0
  105. package/dist/lib/shipper/span-shipper.js +272 -0
  106. package/dist/lib/shipper/telemetry-shipper.js +39 -0
  107. package/dist/lib/transcript/agent-transcript-metrics.js +34 -0
  108. package/dist/lib/transcript/context-breakdown.js +134 -0
  109. package/dist/lib/transcript/context-history.js +69 -0
  110. package/dist/lib/transcript/context-tracker.js +226 -0
  111. package/dist/lib/transcript/message-count.js +49 -0
  112. package/dist/lib/transcript/model-ids.js +36 -0
  113. package/dist/lib/transcript/model-pricing.js +153 -0
  114. package/dist/lib/transcript/token-metrics-checkpoint.js +152 -0
  115. package/dist/lib/transcript/tool-call-durations.js +64 -0
  116. package/dist/lib/transcript/transcript-entry.js +67 -0
  117. package/dist/lib/transcript/transcript-fold.js +130 -0
  118. package/dist/lib/transcript/transcript-layout.js +39 -0
  119. package/dist/lib/transcript/transcript-parser.js +117 -0
  120. package/dist/runner/agent-context-4XTCLMLZ.js +23 -0
  121. package/dist/runner/agent-context-4XTCLMLZ.js.map +7 -0
  122. package/dist/runner/agent-file-budget-Q33ESBBE.js +68 -0
  123. package/dist/runner/agent-file-budget-Q33ESBBE.js.map +7 -0
  124. package/dist/runner/agent-transcript-metrics-W5CZZFMI.js +39 -0
  125. package/dist/runner/agent-transcript-metrics-W5CZZFMI.js.map +7 -0
  126. package/dist/runner/chunk-2NTNAJZE.js +49 -0
  127. package/dist/runner/chunk-2NTNAJZE.js.map +7 -0
  128. package/dist/runner/chunk-4KWBQTTG.js +78 -0
  129. package/dist/runner/chunk-4KWBQTTG.js.map +7 -0
  130. package/dist/runner/chunk-52RY6LQT.js +699 -0
  131. package/dist/runner/chunk-52RY6LQT.js.map +7 -0
  132. package/dist/runner/chunk-7OM5CYES.js +8695 -0
  133. package/dist/runner/chunk-7OM5CYES.js.map +7 -0
  134. package/dist/runner/chunk-7PEOKGYR.js +1568 -0
  135. package/dist/runner/chunk-7PEOKGYR.js.map +7 -0
  136. package/dist/runner/chunk-AGSGKELQ.js +126 -0
  137. package/dist/runner/chunk-AGSGKELQ.js.map +7 -0
  138. package/dist/runner/chunk-AVM7PJFW.js +12 -0
  139. package/dist/runner/chunk-AVM7PJFW.js.map +7 -0
  140. package/dist/runner/chunk-C3WHUMU5.js +178 -0
  141. package/dist/runner/chunk-C3WHUMU5.js.map +7 -0
  142. package/dist/runner/chunk-DGB4NSSD.js +157 -0
  143. package/dist/runner/chunk-DGB4NSSD.js.map +7 -0
  144. package/dist/runner/chunk-DNSTWC26.js +151 -0
  145. package/dist/runner/chunk-DNSTWC26.js.map +7 -0
  146. package/dist/runner/chunk-FDJJ3TYU.js +449 -0
  147. package/dist/runner/chunk-FDJJ3TYU.js.map +7 -0
  148. package/dist/runner/chunk-FGKYDQHZ.js +137 -0
  149. package/dist/runner/chunk-FGKYDQHZ.js.map +7 -0
  150. package/dist/runner/chunk-GG2I4TGI.js +582 -0
  151. package/dist/runner/chunk-GG2I4TGI.js.map +7 -0
  152. package/dist/runner/chunk-GNNKUMRF.js +60 -0
  153. package/dist/runner/chunk-GNNKUMRF.js.map +7 -0
  154. package/dist/runner/chunk-I7TD2QVR.js +118 -0
  155. package/dist/runner/chunk-I7TD2QVR.js.map +7 -0
  156. package/dist/runner/chunk-IJ4SLUBV.js +78 -0
  157. package/dist/runner/chunk-IJ4SLUBV.js.map +7 -0
  158. package/dist/runner/chunk-IY7AP7NA.js +32 -0
  159. package/dist/runner/chunk-IY7AP7NA.js.map +7 -0
  160. package/dist/runner/chunk-J3F3Z3EQ.js +177 -0
  161. package/dist/runner/chunk-J3F3Z3EQ.js.map +7 -0
  162. package/dist/runner/chunk-JLEO5OHU.js +104 -0
  163. package/dist/runner/chunk-JLEO5OHU.js.map +7 -0
  164. package/dist/runner/chunk-JRNNLOPR.js +168 -0
  165. package/dist/runner/chunk-JRNNLOPR.js.map +7 -0
  166. package/dist/runner/chunk-KGSA5JYP.js +82 -0
  167. package/dist/runner/chunk-KGSA5JYP.js.map +7 -0
  168. package/dist/runner/chunk-LBCZAYFR.js +125 -0
  169. package/dist/runner/chunk-LBCZAYFR.js.map +7 -0
  170. package/dist/runner/chunk-LHWRXY2G.js +41 -0
  171. package/dist/runner/chunk-LHWRXY2G.js.map +7 -0
  172. package/dist/runner/chunk-LQ2LGUYJ.js +41 -0
  173. package/dist/runner/chunk-LQ2LGUYJ.js.map +7 -0
  174. package/dist/runner/chunk-LYY6RCIE.js +158 -0
  175. package/dist/runner/chunk-LYY6RCIE.js.map +7 -0
  176. package/dist/runner/chunk-M4R4QIQH.js +41 -0
  177. package/dist/runner/chunk-M4R4QIQH.js.map +7 -0
  178. package/dist/runner/chunk-MC75VXMX.js +207 -0
  179. package/dist/runner/chunk-MC75VXMX.js.map +7 -0
  180. package/dist/runner/chunk-NKZU4RRG.js +104 -0
  181. package/dist/runner/chunk-NKZU4RRG.js.map +7 -0
  182. package/dist/runner/chunk-PJHWHJ3K.js +56 -0
  183. package/dist/runner/chunk-PJHWHJ3K.js.map +7 -0
  184. package/dist/runner/chunk-RIGVYJ2O.js +114 -0
  185. package/dist/runner/chunk-RIGVYJ2O.js.map +7 -0
  186. package/dist/runner/chunk-RWRGC7ZK.js +93 -0
  187. package/dist/runner/chunk-RWRGC7ZK.js.map +7 -0
  188. package/dist/runner/chunk-SRMAJQMV.js +54 -0
  189. package/dist/runner/chunk-SRMAJQMV.js.map +7 -0
  190. package/dist/runner/chunk-TRMFD36J.js +47 -0
  191. package/dist/runner/chunk-TRMFD36J.js.map +7 -0
  192. package/dist/runner/chunk-U4IOZYQ3.js +21 -0
  193. package/dist/runner/chunk-U4IOZYQ3.js.map +7 -0
  194. package/dist/runner/chunk-UEXDE3WP.js +83 -0
  195. package/dist/runner/chunk-UEXDE3WP.js.map +7 -0
  196. package/dist/runner/chunk-UW3GQZSM.js +50 -0
  197. package/dist/runner/chunk-UW3GQZSM.js.map +7 -0
  198. package/dist/runner/chunk-V2GSP6VR.js +46 -0
  199. package/dist/runner/chunk-V2GSP6VR.js.map +7 -0
  200. package/dist/runner/chunk-VOV4Y5VU.js +81 -0
  201. package/dist/runner/chunk-VOV4Y5VU.js.map +7 -0
  202. package/dist/runner/chunk-VT5T6OEI.js +65 -0
  203. package/dist/runner/chunk-VT5T6OEI.js.map +7 -0
  204. package/dist/runner/chunk-VUYVFWIN.js +12 -0
  205. package/dist/runner/chunk-VUYVFWIN.js.map +7 -0
  206. package/dist/runner/chunk-VVGOPPEN.js +36 -0
  207. package/dist/runner/chunk-VVGOPPEN.js.map +7 -0
  208. package/dist/runner/chunk-VXFSLM6P.js +14 -0
  209. package/dist/runner/chunk-VXFSLM6P.js.map +7 -0
  210. package/dist/runner/chunk-W3EK7JUT.js +26125 -0
  211. package/dist/runner/chunk-W3EK7JUT.js.map +7 -0
  212. package/dist/runner/chunk-WJHNCOUF.js +52 -0
  213. package/dist/runner/chunk-WJHNCOUF.js.map +7 -0
  214. package/dist/runner/chunk-WU7ANGCW.js +269 -0
  215. package/dist/runner/chunk-WU7ANGCW.js.map +7 -0
  216. package/dist/runner/chunk-X7XLMSZX.js +44 -0
  217. package/dist/runner/chunk-X7XLMSZX.js.map +7 -0
  218. package/dist/runner/chunk-XSO3B4QN.js +124 -0
  219. package/dist/runner/chunk-XSO3B4QN.js.map +7 -0
  220. package/dist/runner/chunk-YGFN3LN2.js +174 -0
  221. package/dist/runner/chunk-YGFN3LN2.js.map +7 -0
  222. package/dist/runner/chunk-YHYDBLVB.js +33 -0
  223. package/dist/runner/chunk-YHYDBLVB.js.map +7 -0
  224. package/dist/runner/compact-36NP3PKT.js +60 -0
  225. package/dist/runner/compact-36NP3PKT.js.map +7 -0
  226. package/dist/runner/getMachineId-bsd-AGENNHN6.js +42 -0
  227. package/dist/runner/getMachineId-bsd-AGENNHN6.js.map +7 -0
  228. package/dist/runner/getMachineId-bsd-I5WZGCL4.js +33 -0
  229. package/dist/runner/getMachineId-bsd-I5WZGCL4.js.map +7 -0
  230. package/dist/runner/getMachineId-bsd-ZXK225P7.js +33 -0
  231. package/dist/runner/getMachineId-bsd-ZXK225P7.js.map +7 -0
  232. package/dist/runner/getMachineId-darwin-47GDLEXL.js +42 -0
  233. package/dist/runner/getMachineId-darwin-47GDLEXL.js.map +7 -0
  234. package/dist/runner/getMachineId-darwin-5CRLMDD6.js +33 -0
  235. package/dist/runner/getMachineId-darwin-5CRLMDD6.js.map +7 -0
  236. package/dist/runner/getMachineId-darwin-ADG4I32N.js +33 -0
  237. package/dist/runner/getMachineId-darwin-ADG4I32N.js.map +7 -0
  238. package/dist/runner/getMachineId-linux-5KVS3T2M.js +27 -0
  239. package/dist/runner/getMachineId-linux-5KVS3T2M.js.map +7 -0
  240. package/dist/runner/getMachineId-linux-GDFB5GSO.js +34 -0
  241. package/dist/runner/getMachineId-linux-GDFB5GSO.js.map +7 -0
  242. package/dist/runner/getMachineId-linux-NQMWCRO3.js +27 -0
  243. package/dist/runner/getMachineId-linux-NQMWCRO3.js.map +7 -0
  244. package/dist/runner/getMachineId-unsupported-5PFIGMVX.js +18 -0
  245. package/dist/runner/getMachineId-unsupported-5PFIGMVX.js.map +7 -0
  246. package/dist/runner/getMachineId-unsupported-DW27K3ZX.js +18 -0
  247. package/dist/runner/getMachineId-unsupported-DW27K3ZX.js.map +7 -0
  248. package/dist/runner/getMachineId-unsupported-XV3FHTHD.js +25 -0
  249. package/dist/runner/getMachineId-unsupported-XV3FHTHD.js.map +7 -0
  250. package/dist/runner/getMachineId-win-5JVMW3EI.js +44 -0
  251. package/dist/runner/getMachineId-win-5JVMW3EI.js.map +7 -0
  252. package/dist/runner/getMachineId-win-SNESQF7R.js +35 -0
  253. package/dist/runner/getMachineId-win-SNESQF7R.js.map +7 -0
  254. package/dist/runner/getMachineId-win-UJYHSBM2.js +35 -0
  255. package/dist/runner/getMachineId-win-UJYHSBM2.js.map +7 -0
  256. package/dist/runner/git-commit-BA53DOJQ.js +30 -0
  257. package/dist/runner/git-commit-BA53DOJQ.js.map +7 -0
  258. package/dist/runner/hook-runner-JHH6PGKE.js +220 -0
  259. package/dist/runner/hook-runner-JHH6PGKE.js.map +7 -0
  260. package/dist/runner/judge-transport-R4TF5LEH.js +91 -0
  261. package/dist/runner/judge-transport-R4TF5LEH.js.map +7 -0
  262. package/dist/runner/mcp-status-QEUH2KGX.js +89 -0
  263. package/dist/runner/mcp-status-QEUH2KGX.js.map +7 -0
  264. package/dist/runner/notification-FKMBCSXF.js +69 -0
  265. package/dist/runner/notification-FKMBCSXF.js.map +7 -0
  266. package/dist/runner/post-tool-3MRHTBKH.js +192 -0
  267. package/dist/runner/post-tool-3MRHTBKH.js.map +7 -0
  268. package/dist/runner/post-tool-agent-BB34MNHI.js +370 -0
  269. package/dist/runner/post-tool-agent-BB34MNHI.js.map +7 -0
  270. package/dist/runner/post-tool-changelog-sync-OP2TT2I7.js +147 -0
  271. package/dist/runner/post-tool-changelog-sync-OP2TT2I7.js.map +7 -0
  272. package/dist/runner/post-tool-code-structure-LE7J2SC2.js +130 -0
  273. package/dist/runner/post-tool-code-structure-LE7J2SC2.js.map +7 -0
  274. package/dist/runner/post-tool-edit-ledger-IJMEYHKF.js +30 -0
  275. package/dist/runner/post-tool-edit-ledger-IJMEYHKF.js.map +7 -0
  276. package/dist/runner/post-tool-failure-XTH2I2Z7.js +111 -0
  277. package/dist/runner/post-tool-failure-XTH2I2Z7.js.map +7 -0
  278. package/dist/runner/post-tool-git-E46HZGZO.js +94 -0
  279. package/dist/runner/post-tool-git-E46HZGZO.js.map +7 -0
  280. package/dist/runner/post-tool-mcp-AMCDY5GH.js +144 -0
  281. package/dist/runner/post-tool-mcp-AMCDY5GH.js.map +7 -0
  282. package/dist/runner/post-tool-task-state-TLDOI33H.js +100 -0
  283. package/dist/runner/post-tool-task-state-TLDOI33H.js.map +7 -0
  284. package/dist/runner/pre-tool-SQE2FZQO.js +245 -0
  285. package/dist/runner/pre-tool-SQE2FZQO.js.map +7 -0
  286. package/dist/runner/pre-tool-agent-OZUPVFUI.js +218 -0
  287. package/dist/runner/pre-tool-agent-OZUPVFUI.js.map +7 -0
  288. package/dist/runner/quality-evaluator-XYNDKDRG.js +901 -0
  289. package/dist/runner/quality-evaluator-XYNDKDRG.js.map +7 -0
  290. package/dist/runner/session-end-3MJTDLLA.js +57 -0
  291. package/dist/runner/session-end-3MJTDLLA.js.map +7 -0
  292. package/dist/runner/session-start-5ZMCLKBS.js +352 -0
  293. package/dist/runner/session-start-5ZMCLKBS.js.map +7 -0
  294. package/dist/runner/shipper-status-MADX6SPG.js +37 -0
  295. package/dist/runner/shipper-status-MADX6SPG.js.map +7 -0
  296. package/dist/runner/span-shipper-4HQDHC47.js +3408 -0
  297. package/dist/runner/span-shipper-4HQDHC47.js.map +7 -0
  298. package/dist/runner/stop-RTKSIYJV.js +596 -0
  299. package/dist/runner/stop-RTKSIYJV.js.map +7 -0
  300. package/dist/runner/subagent-CBCG4OLZ.js +116 -0
  301. package/dist/runner/subagent-CBCG4OLZ.js.map +7 -0
  302. package/dist/runner/token-metrics-AD2RAFGM.js +31 -0
  303. package/dist/runner/token-metrics-AD2RAFGM.js.map +7 -0
  304. package/dist/runner/user-prompt-T5NZ2UJD.js +376 -0
  305. package/dist/runner/user-prompt-T5NZ2UJD.js.map +7 -0
  306. package/package.json +70 -5
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Pending session-to-session handoffs (`docs/handoffs/*.md`), surfaced at SessionStart.
3
+ * Deliberately a plain directory listing: drop a `.md`, delete it when done.
4
+ * `ageDays` is reported because a stale banner line is the one that gets tuned out (CCH6a).
5
+ */
6
+ import { statSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ import { readdirOrEmpty } from '../core/file-utils.js';
9
+ import { TIME_MS } from '../core/units.js';
10
+ /** Directory, relative to the repo root, that holds handoff documents. */
11
+ export const HANDOFF_DIR = join('docs', 'handoffs');
12
+ /** Parent levels searched above the CWD for the handoff directory. */
13
+ const MAX_PARENT_LEVELS = 3;
14
+ /** Cap on handoffs listed, so a forgotten directory cannot flood the banner. */
15
+ const MAX_HANDOFFS = 5;
16
+ /** Age at which a handoff is called out as possibly abandoned. */
17
+ export const STALE_HANDOFF_DAYS = 14;
18
+ /** Locate `docs/handoffs` at `startDir` or up to `MAX_PARENT_LEVELS` above it (bounded for SessionStart latency). */
19
+ function findHandoffDir(startDir) {
20
+ let cur = startDir;
21
+ for (let level = 0; level <= MAX_PARENT_LEVELS; level++) {
22
+ const dir = join(cur, HANDOFF_DIR);
23
+ try {
24
+ if (statSync(dir).isDirectory()) {
25
+ // '../' per level climbed, so the printed path pastes from the CWD.
26
+ return { dir, prefix: '../'.repeat(level) };
27
+ }
28
+ }
29
+ catch {
30
+ // best-effort
31
+ }
32
+ const parent = join(cur, '..');
33
+ if (parent === cur)
34
+ break;
35
+ cur = parent;
36
+ }
37
+ return null;
38
+ }
39
+ /** Pending handoffs, newest first; empty and never throws when the directory is absent or unreadable. */
40
+ export function findPendingHandoffs(startDir, now = Date.now()) {
41
+ const found = findHandoffDir(startDir);
42
+ if (!found)
43
+ return [];
44
+ const handoffs = [];
45
+ for (const name of readdirOrEmpty(found.dir)) {
46
+ if (!name.endsWith('.md'))
47
+ continue;
48
+ try {
49
+ const { mtimeMs } = statSync(join(found.dir, name));
50
+ handoffs.push({
51
+ path: `${found.prefix}${HANDOFF_DIR}/${name}`,
52
+ ageDays: Math.floor((now - mtimeMs) / TIME_MS.DAY),
53
+ mtimeMs,
54
+ });
55
+ }
56
+ catch {
57
+ // best-effort
58
+ }
59
+ }
60
+ return handoffs
61
+ .sort((a, b) => b.mtimeMs - a.mtimeMs)
62
+ .slice(0, MAX_HANDOFFS)
63
+ .map(({ path, ageDays }) => ({ path, ageDays }));
64
+ }
65
+ /** Banner lines addressed to Claude (SessionStart stdout is injected). "Read and propose", not "do": the user may have moved on. */
66
+ export function formatHandoffBanner(handoffs) {
67
+ if (handoffs.length === 0)
68
+ return [];
69
+ const lines = ['', `Pending handoff${handoffs.length === 1 ? '' : 's'} from a previous session:`];
70
+ for (const { path, ageDays } of handoffs) {
71
+ const age = ageDays === 0 ? 'today' : `${ageDays}d old`;
72
+ const stale = ageDays >= STALE_HANDOFF_DAYS ? ' — stale, confirm it is still wanted' : '';
73
+ lines.push(` ${path} (${age})${stale}`);
74
+ }
75
+ lines.push('Read these before other work, then propose next steps and confirm with the user.');
76
+ return lines;
77
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * `~/.claude/session-state/<session id>/`: the one root for everything a session
3
+ * hands between its spawn-per-event hook processes, with `pruneSessionState` as
4
+ * the one retention rule. Records that outlive a session live in dot-prefixed
5
+ * siblings (`.projects/<key>/`, `.quality`, `.host`), names no
6
+ * session id can collide with.
7
+ */
8
+ import { existsSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
9
+ import { dirname, join } from 'node:path';
10
+ import { CLAUDE_HOME } from '../core/constants.js';
11
+ import { ensureDirExists, isJsonObject, isSameFile, loadJson, readdirOrEmpty, toSafeFilename, writeJsonAtomic } from '../core/file-utils.js';
12
+ import { DURATION_MS, TIME_MS } from '../core/units.js';
13
+ const SESSION_STATE_DIRNAME = 'session-state';
14
+ export const PROJECTS_DIRNAME = '.projects';
15
+ /** The judge's daily budget and drift window (HDF3). */
16
+ export const QUALITY_DIRNAME = '.quality';
17
+ /** The resolved `host.id` (HSF25) and the identity email cache (HTR3). */
18
+ const HOST_DIRNAME = '.host';
19
+ /** Task state must survive until a resume; it is the longest-lived record here and sets the retention. */
20
+ const SESSION_STATE_RETENTION_MS = DURATION_MS.THIRTY_DAYS;
21
+ export const CONVERSATION_ID_ENV = 'CLAUDE_CONVERSATION_ID';
22
+ /** A genuine thread id only, never synthesized: undefined when neither the override nor the session id is set. */
23
+ export function conversationIdOf(sessionId) {
24
+ return process.env[CONVERSATION_ID_ENV] || sessionId || undefined;
25
+ }
26
+ /**
27
+ * Atomic once-per-session claim via a `wx` write on a marker under the session dir
28
+ * (`sessionMarkerPath`). `onWriteError` defaults to 'deny'. Pass an uncached `mkdir`
29
+ * when the parent may be deleted between calls in one process: the default
30
+ * `ensureDirExists` is memoized.
31
+ */
32
+ export function claimOnce(markerPath, options) {
33
+ if (existsSync(markerPath))
34
+ return false;
35
+ const parentDir = dirname(markerPath);
36
+ try {
37
+ (options?.mkdir ?? ensureDirExists)(parentDir);
38
+ writeFileSync(markerPath, new Date().toISOString(), { flag: 'wx' });
39
+ return true;
40
+ }
41
+ catch {
42
+ // A marker appearing between the check and the write is the latch working.
43
+ if (existsSync(markerPath))
44
+ return false;
45
+ return options?.onWriteError === 'grant';
46
+ }
47
+ }
48
+ export function sessionStateRoot() {
49
+ return join(CLAUDE_HOME, SESSION_STATE_DIRNAME);
50
+ }
51
+ export function sessionStateDir(sessionId, root = sessionStateRoot()) {
52
+ return join(root, toSafeFilename(sessionId));
53
+ }
54
+ const MARKER_EXTENSION = '.marker';
55
+ /** A `claimOnce` latch under the session dir; `name` may carry a subdirectory. `root` keeps tests out of $HOME. */
56
+ export function sessionMarkerPath(sessionId, name, root = sessionStateRoot()) {
57
+ return join(sessionStateDir(sessionId, root), `${name}${MARKER_EXTENSION}`);
58
+ }
59
+ /** Claude Code's `~/.claude/projects/<slug>/` spelling; the bash pointer readers derive it with `tr '/.' '--'`, keep in step. */
60
+ export function projectSlug(projectDir) {
61
+ return projectDir.replace(/[/.]/g, '-');
62
+ }
63
+ /** Keyed by project slug, or by conversation id for the predecessor edge. */
64
+ export function projectStateDir(key, root = sessionStateRoot()) {
65
+ return join(root, PROJECTS_DIRNAME, toSafeFilename(key));
66
+ }
67
+ export function qualityStateDir(root = sessionStateRoot()) {
68
+ return join(root, QUALITY_DIRNAME);
69
+ }
70
+ export function hostStateDir(root = sessionStateRoot()) {
71
+ return join(root, HOST_DIRNAME);
72
+ }
73
+ /**
74
+ * `expired` is the parsed-but-expired checkpoint, for callers that still need e.g. a
75
+ * watermark. The file stays until the caller's next save overwrites it: unlinking it
76
+ * here would lose the watermark if the caller died before saving.
77
+ */
78
+ export function loadSessionCheckpoint(sessionId, file, isValid, ttlMs = TIME_MS.DAY) {
79
+ const filePath = join(sessionStateDir(sessionId), file);
80
+ const cp = loadJson(filePath);
81
+ if (!cp || !isValid(cp))
82
+ return { live: null, expired: null };
83
+ const ts = cp.timestamp;
84
+ if (typeof ts !== 'number' || Date.now() - ts > ttlMs)
85
+ return { live: null, expired: cp };
86
+ return { live: cp, expired: null };
87
+ }
88
+ /** The byte offset to resume from; 0 with no checkpoint or a file shrunk below its offset (truncation/rewrite). */
89
+ export function resumeOffset(cp, fileSize) {
90
+ if (!cp || fileSize < cp.offset)
91
+ return 0;
92
+ return cp.offset;
93
+ }
94
+ /** Non-fatal on failure: the next extraction falls back to a full parse. */
95
+ export function saveSessionCheckpoint(sessionId, file, data) {
96
+ // Atomic, because a torn checkpoint would fail validation and the next read would re-add the whole transcript.
97
+ writeJsonAtomic(join(sessionStateDir(sessionId), file), data, { silent: true });
98
+ }
99
+ /** A checkpoint TTL for state derived from an append-only transcript, which age cannot invalidate. */
100
+ const NEVER_EXPIRES_MS = Number.POSITIVE_INFINITY;
101
+ /** A per-session checkpoint of state derived from one transcript; the envelope is validated here, the body by `isValidBody`. */
102
+ export function transcriptCheckpointStore(options) {
103
+ const { file, version, isValidBody, ttlMs = NEVER_EXPIRES_MS } = options;
104
+ const isValid = (value) => isJsonObject(value)
105
+ && value.version === version
106
+ && typeof value.transcript === 'string'
107
+ && isValidBody(value);
108
+ return {
109
+ load(sessionId, transcript) {
110
+ const cp = loadSessionCheckpoint(sessionId, file, isValid, ttlMs).live;
111
+ return cp && isSameFile(cp.transcript, transcript) ? cp : null;
112
+ },
113
+ save(sessionId, transcript, body) {
114
+ const envelope = { version, transcript, timestamp: Date.now() };
115
+ saveSessionCheckpoint(sessionId, file, { ...body, ...envelope });
116
+ },
117
+ };
118
+ }
119
+ // Pointer files read by the GCS1 pre-commit and GCS2 conventional-commit bash guards; the format is a contract.
120
+ const CURRENT_SESSION_ID = 'current-session-id';
121
+ const SESSION_START_BRANCH = 'session-start-branch';
122
+ function writeTextBestEffort(dir, name, text) {
123
+ try {
124
+ ensureDirExists(dir);
125
+ writeFileSync(join(dir, name), text, 'utf8');
126
+ }
127
+ catch {
128
+ // Readers fail open when the file is absent.
129
+ }
130
+ }
131
+ /** Plain text, one line, no trailing newline. */
132
+ export function saveCurrentSessionId(sessionId, projectDir) {
133
+ writeTextBestEffort(projectStateDir(projectSlug(projectDir)), CURRENT_SESSION_ID, sessionId);
134
+ }
135
+ export function saveSessionStartBranch(sessionId, branch) {
136
+ writeTextBestEffort(sessionStateDir(sessionId), SESSION_START_BRANCH, branch);
137
+ }
138
+ function newestMtimeMs(dir) {
139
+ let newest = statSync(dir).mtimeMs;
140
+ for (const name of readdirSync(dir)) {
141
+ try {
142
+ newest = Math.max(newest, statSync(join(dir, name)).mtimeMs);
143
+ }
144
+ catch {
145
+ // Raced away between readdir and stat.
146
+ }
147
+ }
148
+ return newest;
149
+ }
150
+ /** The one retention sweep. Never throws. Dot-prefixed siblings are never touched; a session id cannot start with a dot. */
151
+ export function pruneSessionState(maxAgeMs = SESSION_STATE_RETENTION_MS, root = sessionStateRoot()) {
152
+ let removed = 0;
153
+ const cutoff = Date.now() - maxAgeMs;
154
+ for (const name of readdirOrEmpty(root)) {
155
+ if (name.startsWith('.'))
156
+ continue;
157
+ const dir = join(root, name);
158
+ try {
159
+ if (!statSync(dir).isDirectory() || newestMtimeMs(dir) >= cutoff)
160
+ continue;
161
+ rmSync(dir, { recursive: true, force: true });
162
+ removed++;
163
+ }
164
+ catch {
165
+ // Unreadable or already gone; the next sweep sees it again.
166
+ }
167
+ }
168
+ return removed;
169
+ }
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Skill activation rules: where the file may live and what counts as one.
3
+ * The first candidate that parses AND carries `skills` wins; a present but
4
+ * unusable file is reported and skipped, since an example scaffold once
5
+ * shadowed the real file for every session rooted at `~/.claude`.
6
+ * Intent patterns compile only from a trusted candidate: a project file can
7
+ * come from a cloned repo, and no shape check bounds regex backtracking.
8
+ * Skill names must be slugs, since a matched name is printed into Claude's context.
9
+ */
10
+ import { readFileSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+ import { THRESHOLDS } from '../core/constants.js';
13
+ import { isJsonObject } from '../core/file-utils.js';
14
+ export const PRIORITIES = ['critical', 'high', 'medium', 'low'];
15
+ const SKILL_TYPES = ['guardrail', 'domain'];
16
+ const ENFORCEMENTS = ['block', 'suggest', 'warn'];
17
+ const RULES_RELATIVE_PATH = ['skills', 'skill-rules.json'];
18
+ const DEFAULT_PROJECT_DIRNAME = 'project';
19
+ /** Candidate rule files, most specific first; only the home file's intent patterns are trusted. */
20
+ export function skillRulesCandidates(claudeHome, projectDir, home) {
21
+ const project = projectDir || join(home ?? '', DEFAULT_PROJECT_DIRNAME);
22
+ return [
23
+ { path: join(project, '.claude', ...RULES_RELATIVE_PATH), trustPatterns: false },
24
+ { path: join(claudeHome, ...RULES_RELATIVE_PATH), trustPatterns: true },
25
+ ];
26
+ }
27
+ function isSkillRulesFile(value) {
28
+ return isJsonObject(value) && isJsonObject(value.skills);
29
+ }
30
+ function isOptionalStringArray(value) {
31
+ return value === undefined || (Array.isArray(value) && value.every((item) => typeof item === 'string'));
32
+ }
33
+ /** A blank keyword or pattern matches every prompt. */
34
+ const hasBlankTrigger = (triggers) => (triggers ?? []).some((trigger) => !trigger.trim());
35
+ /** A Skill tool name: lowercase slug, optionally `plugin:`-namespaced, at most 64 characters. */
36
+ const SKILL_NAME_PATTERN = /^[a-z0-9][a-z0-9:_-]{0,63}$/;
37
+ const isOneOf = (known, value) => known.some((candidate) => candidate === value);
38
+ /** Checks the name, then every field `SkillRule` types: shape, type, enforcement, priority and trigger lists. */
39
+ function invalidSkillReason(name, entry) {
40
+ if (!SKILL_NAME_PATTERN.test(name))
41
+ return 'invalid-name';
42
+ if (!isJsonObject(entry))
43
+ return 'not-an-object';
44
+ const { type, enforcement, priority, promptTriggers } = entry;
45
+ if (!isOneOf(SKILL_TYPES, type))
46
+ return 'unknown-type';
47
+ if (!isOneOf(ENFORCEMENTS, enforcement))
48
+ return 'unknown-enforcement';
49
+ if (!isOneOf(PRIORITIES, priority))
50
+ return 'unknown-priority';
51
+ return invalidTriggersReason(promptTriggers);
52
+ }
53
+ function invalidTriggersReason(promptTriggers) {
54
+ if (promptTriggers === undefined)
55
+ return undefined;
56
+ if (!isJsonObject(promptTriggers))
57
+ return 'malformed-triggers';
58
+ const { keywords, intentPatterns } = promptTriggers;
59
+ if (!isOptionalStringArray(keywords) || !isOptionalStringArray(intentPatterns))
60
+ return 'malformed-triggers';
61
+ return hasBlankTrigger(keywords) || hasBlankTrigger(intentPatterns) ? 'empty-trigger' : undefined;
62
+ }
63
+ /**
64
+ * A quantified group, rejected before compilation: `(a+)+`, `(a|b)*`, `(\w+\s?)+` all
65
+ * backtrack exponentially. `(…)?` is bounded and allowed.
66
+ */
67
+ const REPEATED_GROUP_SHAPE = /\)[+*{]/;
68
+ const UNSAFE_PATTERN_MESSAGE = 'Skipping unsafe regex pattern (repeated group)';
69
+ const UNTRUSTED_PATTERN_MESSAGE = 'Skipping intent pattern from an untrusted skill-rules.json';
70
+ const OVERSIZED_PATTERN_MESSAGE = 'Skipping oversized intent pattern';
71
+ const INVALID_PATTERN_MESSAGE = 'Skipping invalid regex pattern';
72
+ /** The gap intent patterns put between their words, captured so a split keeps it: `(fix|add).*?tests?`. */
73
+ const WORD_GAP = /(\.\*\??)/;
74
+ const NOT_AFTER_WORD = '(?<!\\w)';
75
+ /**
76
+ * Each gap-separated segment must start a word, or `(fix).*?tests?` fires on "fix
77
+ * the latest build". Only the start is bounded, so inflections still match: "type
78
+ * errors", "sentry monitoring". A lookbehind rather than `\b`, so a segment opening
79
+ * on punctuation still matches. A segment that does not compile alone (a gap inside
80
+ * a group) stays as written; the others are still bounded.
81
+ */
82
+ function wordStartSegments(pattern) {
83
+ return pattern.split(WORD_GAP).map((part, index) => {
84
+ // Odd indexes are the captured gaps.
85
+ if (index % 2 === 1 || part === '')
86
+ return part;
87
+ const bounded = `${NOT_AFTER_WORD}(?:${part})`;
88
+ try {
89
+ new RegExp(bounded);
90
+ return bounded;
91
+ }
92
+ catch {
93
+ return part;
94
+ }
95
+ }).join('');
96
+ }
97
+ function compileIntentPattern(pattern) {
98
+ if (pattern.length > THRESHOLDS.MAX_PATTERN_LENGTH)
99
+ return { reason: 'oversized', message: OVERSIZED_PATTERN_MESSAGE };
100
+ if (REPEATED_GROUP_SHAPE.test(pattern))
101
+ return { reason: 'unsafe', message: UNSAFE_PATTERN_MESSAGE };
102
+ try {
103
+ // Validates the pattern as written; a per-segment fallback could otherwise hide its error.
104
+ new RegExp(pattern);
105
+ return new RegExp(wordStartSegments(pattern), 'i');
106
+ }
107
+ catch {
108
+ return { reason: 'invalid', message: INVALID_PATTERN_MESSAGE };
109
+ }
110
+ }
111
+ const WORD_CHAR = /\w/;
112
+ /**
113
+ * `keyword` occurs in `prompt` starting a word: "test" matches "tests" but not
114
+ * "latest". The end is left open, as for intent patterns, so plurals still match.
115
+ * Both are lowercased by now. A plain scan, since an untrusted file's keywords
116
+ * still match and must never become a regex.
117
+ */
118
+ export function containsKeyword(prompt, keyword) {
119
+ if (keyword === '')
120
+ return false;
121
+ const opensOnWord = WORD_CHAR.test(keyword[0] ?? '');
122
+ for (let at = prompt.indexOf(keyword); at !== -1; at = prompt.indexOf(keyword, at + 1)) {
123
+ const before = prompt[at - 1];
124
+ if (!opensOnWord || before === undefined || !WORD_CHAR.test(before))
125
+ return true;
126
+ }
127
+ return false;
128
+ }
129
+ function compileTriggers(ctx, triggers, trustPatterns, skippedPatterns) {
130
+ const intentPatterns = [];
131
+ for (const pattern of triggers.intentPatterns ?? []) {
132
+ const compiled = trustPatterns
133
+ ? compileIntentPattern(pattern)
134
+ : { reason: 'untrusted', message: UNTRUSTED_PATTERN_MESSAGE };
135
+ if (compiled instanceof RegExp)
136
+ intentPatterns.push(compiled);
137
+ else
138
+ skippedPatterns.push({ ...ctx, pattern, ...compiled });
139
+ }
140
+ return { keywords: (triggers.keywords ?? []).map((keyword) => keyword.toLowerCase()), intentPatterns };
141
+ }
142
+ function compileRules(file, trustPatterns, source) {
143
+ const skippedSkills = [];
144
+ const skippedPatterns = [];
145
+ const skills = [];
146
+ for (const [name, entry] of Object.entries(file.skills)) {
147
+ const reason = invalidSkillReason(name, entry);
148
+ if (reason) {
149
+ skippedSkills.push({ skill: name, source, reason });
150
+ continue;
151
+ }
152
+ const { promptTriggers, ...rule } = entry;
153
+ skills.push([name, promptTriggers ? { ...rule, promptTriggers: compileTriggers({ skill: name, source }, promptTriggers, trustPatterns, skippedPatterns) } : rule]);
154
+ }
155
+ const version = typeof file.version === 'string' ? file.version : undefined;
156
+ return { rules: { version, skills: Object.fromEntries(skills) }, skippedSkills, skippedPatterns };
157
+ }
158
+ /**
159
+ * Load the first usable candidate. A missing file is not reported, a present
160
+ * unusable one is; a file with no usable skill is skipped so it cannot shadow
161
+ * the home rules. Patterns are vetted once here; an untrusted candidate's are
162
+ * dropped and reported, and its keywords still match.
163
+ */
164
+ export function loadSkillRules(candidates) {
165
+ const skippedFiles = [];
166
+ for (const { path, trustPatterns } of candidates) {
167
+ let text;
168
+ try {
169
+ text = readFileSync(path, 'utf-8');
170
+ }
171
+ catch (error) {
172
+ if (error.code !== 'ENOENT')
173
+ skippedFiles.push({ path, reason: 'unreadable' });
174
+ continue;
175
+ }
176
+ let parsed;
177
+ try {
178
+ parsed = JSON.parse(text);
179
+ }
180
+ catch {
181
+ skippedFiles.push({ path, reason: 'invalid-json' });
182
+ continue;
183
+ }
184
+ if (!isSkillRulesFile(parsed)) {
185
+ skippedFiles.push({ path, reason: 'no-skills-object' });
186
+ continue;
187
+ }
188
+ const compiled = compileRules(parsed, trustPatterns, path);
189
+ if (Object.keys(compiled.rules.skills).length === 0) {
190
+ skippedFiles.push({ path, reason: 'no-usable-skills' });
191
+ continue;
192
+ }
193
+ return { ...compiled, path, skippedFiles };
194
+ }
195
+ return { skippedFiles, skippedSkills: [], skippedPatterns: [] };
196
+ }
@@ -0,0 +1,83 @@
1
+ /** Persists task state to `session-state/<sessionId>/tasks.json` so it survives compaction. */
2
+ import { randomUUID } from 'node:crypto';
3
+ import { join } from 'node:path';
4
+ import { isJsonObject, loadJson, writeJson, withFileLock } from '../core/file-utils.js';
5
+ import { sessionStateDir } from './session-state.js';
6
+ /** One JSON file per session, inside the session's state directory. */
7
+ const TASK_STATE_FILE = 'tasks.json';
8
+ /** Length of the random suffix on an auto-assigned task id. */
9
+ const AUTO_ID_LENGTH = 8;
10
+ /** The status vocabulary, once — the type and the runtime guard cannot drift. */
11
+ const TASK_STATUSES = ['pending', 'in_progress', 'completed', 'deleted'];
12
+ export function isTaskStatus(value) {
13
+ return typeof value === 'string' && TASK_STATUSES.includes(value);
14
+ }
15
+ function getFilePath(sessionId) {
16
+ return join(sessionStateDir(sessionId), TASK_STATE_FILE);
17
+ }
18
+ function saveTaskState(sessionId, tasks) {
19
+ return writeJson(getFilePath(sessionId), {
20
+ sessionId,
21
+ timestamp: Date.now(),
22
+ tasks,
23
+ });
24
+ }
25
+ export function loadTaskState(sessionId) {
26
+ return loadJson(getFilePath(sessionId));
27
+ }
28
+ /** Active (non-deleted) tasks; the one owner of the predicate. */
29
+ export function getActiveTasks(tasks) {
30
+ return tasks.filter(t => t.status !== 'deleted');
31
+ }
32
+ /** Completion ratio over active tasks; an empty set is complete. */
33
+ export function calculateTaskCompletion(tasks) {
34
+ const active = getActiveTasks(tasks);
35
+ if (active.length === 0)
36
+ return 1;
37
+ return active.filter(t => t.status === 'completed').length / active.length;
38
+ }
39
+ /** Active tasks and completion ratio, or null when there are none. */
40
+ export function activeTaskCompletion(sessionId) {
41
+ const taskState = loadTaskState(sessionId);
42
+ if (!taskState)
43
+ return null;
44
+ const active = getActiveTasks(taskState.tasks);
45
+ if (active.length === 0)
46
+ return null;
47
+ return { active, ratio: calculateTaskCompletion(taskState.tasks) };
48
+ }
49
+ /** Auto-assigned task id. */
50
+ export function generateTaskId() {
51
+ return `auto-${randomUUID().slice(0, AUTO_ID_LENGTH)}`;
52
+ }
53
+ function structuredTaskId(toolResponse) {
54
+ if (!isJsonObject(toolResponse))
55
+ return undefined;
56
+ const created = toolResponse.task;
57
+ if (!isJsonObject(created))
58
+ return undefined;
59
+ const id = created.id;
60
+ if (typeof id === 'number')
61
+ return String(id);
62
+ return typeof id === 'string' && id.trim() ? id.trim() : undefined;
63
+ }
64
+ /**
65
+ * The id TaskCreate assigned, the key later TaskUpdate calls use: `tool_response.task.id`
66
+ * as hooks receive it, else "Task #N" in the text form, else auto-generated (PT3, PT15).
67
+ */
68
+ export function createdTaskId(toolResponse, outputText) {
69
+ return structuredTaskId(toolResponse) ?? outputText.match(/Task #(\d+)/)?.[1] ?? generateTaskId();
70
+ }
71
+ /** Upsert one task under the advisory file lock. A known id keeps its creation time, and its name when the write carries none (a TaskUpdate has no subject). */
72
+ export function upsertTask(sessionId, task) {
73
+ return withFileLock(getFilePath(sessionId), () => {
74
+ const tasks = loadTaskState(sessionId)?.tasks ?? [];
75
+ const idx = tasks.findIndex(t => t.id === task.id);
76
+ const existing = tasks[idx];
77
+ if (existing)
78
+ tasks[idx] = { ...task, name: task.name || existing.name, createdAt: existing.createdAt };
79
+ else
80
+ tasks.push(task);
81
+ return saveTaskState(sessionId, tasks);
82
+ });
83
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Which credential a batch ships under (TKR6): a stamped record's own account
3
+ * key, the env credential for an unmapped account, or the signed-in key for
4
+ * unstamped records.
5
+ */
6
+ import { bearerHeaders } from '../core/http-utils.js';
7
+ import { otlpAuthHeaders } from '../otel/otlp-headers.js';
8
+ export function keyRouteOf(record) {
9
+ const ref = record.identityKeyRef;
10
+ return typeof ref === 'string' || ref === null ? ref : undefined;
11
+ }
12
+ /** The signed-in key is a Doppler spawn, fetched at most once and only when an unstamped batch asks. */
13
+ export function createCredentialResolver(opts, overrideHeaders) {
14
+ const envHeaders = (signal) => {
15
+ const headers = otlpAuthHeaders(signal);
16
+ return Object.keys(headers).length > 0 ? headers : undefined;
17
+ };
18
+ let signedInKeyFetch;
19
+ const signedInKey = () => {
20
+ signedInKeyFetch ??= opts.signedInSecretName && opts.keyForRef
21
+ ? opts.keyForRef(opts.signedInSecretName)
22
+ : Promise.resolve(undefined);
23
+ return signedInKeyFetch;
24
+ };
25
+ return async (route, signal) => {
26
+ if (route === undefined) {
27
+ const key = overrideHeaders ? undefined : await signedInKey();
28
+ const headers = overrideHeaders ?? (key ? bearerHeaders(key) : envHeaders(signal));
29
+ return headers ? { headers } : { missing: 'no credential for unstamped records' };
30
+ }
31
+ if (route === null) {
32
+ const headers = envHeaders(signal);
33
+ return headers ? { headers } : { withhold: true };
34
+ }
35
+ const key = await opts.keyForRef?.(route);
36
+ return key ? { headers: bearerHeaders(key) } : { missing: `no key for ${route}` };
37
+ };
38
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * The shipper's cursor and file window without the shipper (HDF2): the spawn
3
+ * guard answers "anything to ship?" without the protobuf import graph, and the
4
+ * shipper reads the same listing so the two cannot disagree.
5
+ */
6
+ import { statSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ import { loadJsonObject, writeJson } from '../core/file-utils.js';
9
+ import { telemetryFileName, telemetryFilePrefix } from '../core/format-utils.js';
10
+ import { TIME_MS } from '../core/units.js';
11
+ import { OTLP_SIGNALS } from '../otel/otlp-signal.js';
12
+ import { SHIPPER_CTX_DIRNAME } from './shipper-status.js';
13
+ const CURSOR_FILENAME = 'cursor.json';
14
+ /** Ship today's and yesterday's files (FileExporter names by UTC date). */
15
+ const SHIP_DAYS = 2;
16
+ export function cursorPath(telemetryDir) {
17
+ return join(telemetryDir, SHIPPER_CTX_DIRNAME, CURSOR_FILENAME);
18
+ }
19
+ /** The signal a telemetry filename belongs to, or null for any other file. */
20
+ function signalForFile(file) {
21
+ const prefix = telemetryFilePrefix(file);
22
+ return OTLP_SIGNALS.find((signal) => signal === prefix) ?? null;
23
+ }
24
+ /** Where reading resumes: the cursor, or 0 once the file was truncated below it, since re-delivering a surviving prefix beats dropping the rest of the day. */
25
+ function resumeOffset(size, offset) {
26
+ return size < offset ? 0 : offset;
27
+ }
28
+ function sizeOf(path) {
29
+ try {
30
+ return statSync(path).size;
31
+ }
32
+ catch {
33
+ return undefined;
34
+ }
35
+ }
36
+ /** The SHIP_DAYS window plus older files with an undelivered backlog, which saveCursor's pruning would otherwise age out. */
37
+ export function candidateFiles(telemetryDir, cursor) {
38
+ const wanted = new Map();
39
+ for (let i = 0; i < SHIP_DAYS; i++) {
40
+ const date = new Date(Date.now() - i * TIME_MS.DAY);
41
+ for (const prefix of OTLP_SIGNALS) {
42
+ wanted.set(telemetryFileName(prefix, date), prefix);
43
+ }
44
+ }
45
+ // Stat known names rather than listing a directory of thousands of files.
46
+ const candidates = [];
47
+ for (const [file, signal] of wanted) {
48
+ const size = sizeOf(join(telemetryDir, file));
49
+ if (size !== undefined)
50
+ candidates.push({ file, signal, size, start: resumeOffset(size, cursor[file] ?? 0) });
51
+ }
52
+ for (const [file, offset] of Object.entries(cursor)) {
53
+ if (wanted.has(file))
54
+ continue;
55
+ const signal = signalForFile(file);
56
+ if (!signal)
57
+ continue;
58
+ const size = sizeOf(join(telemetryDir, file));
59
+ if (size === undefined)
60
+ continue;
61
+ const start = resumeOffset(size, offset);
62
+ if (size > start)
63
+ candidates.push({ file, signal, size, start, aged: true });
64
+ }
65
+ return candidates;
66
+ }
67
+ /** The cursor, empty when missing or unusable, so every listed file reads from 0. */
68
+ export function loadCursor(path) {
69
+ const cursor = {};
70
+ for (const [file, offset] of Object.entries(loadJsonObject(path) ?? {})) {
71
+ if (typeof offset === 'number' && offset >= 0)
72
+ cursor[file] = offset;
73
+ }
74
+ return cursor;
75
+ }
76
+ /** Keeps only the listed files' entries, so a file that leaves the listing loses its cursor. */
77
+ export function saveCursor(path, cursor, listed) {
78
+ const pruned = {};
79
+ for (const { file } of listed) {
80
+ if (cursor[file] !== undefined)
81
+ pruned[file] = cursor[file];
82
+ }
83
+ writeJson(path, pruned, false, { silent: true });
84
+ }
85
+ /** Whether any listed file holds bytes past its resume offset, so first runs and held cursors answer yes. */
86
+ export function hasUnshippedTelemetry(telemetryDir) {
87
+ const cursor = loadCursor(cursorPath(telemetryDir));
88
+ return candidateFiles(telemetryDir, cursor).some(({ size, start }) => size > start);
89
+ }