observability-toolkit-hooks 0.0.0-stage → 1.0.0

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 (305) hide show
  1. package/CONFIG.md +144 -0
  2. package/README.md +201 -2
  3. package/dist/handlers/compact.js +38 -0
  4. package/dist/handlers/mcp-status.js +66 -0
  5. package/dist/handlers/notification.js +45 -0
  6. package/dist/handlers/post-tool-agent.js +157 -0
  7. package/dist/handlers/post-tool-changelog-sync.js +148 -0
  8. package/dist/handlers/post-tool-code-structure.js +116 -0
  9. package/dist/handlers/post-tool-edit-ledger.js +15 -0
  10. package/dist/handlers/post-tool-failure.js +83 -0
  11. package/dist/handlers/post-tool-git.js +79 -0
  12. package/dist/handlers/post-tool-mcp.js +105 -0
  13. package/dist/handlers/post-tool-outcome.js +48 -0
  14. package/dist/handlers/post-tool-task-state.js +74 -0
  15. package/dist/handlers/post-tool.js +132 -0
  16. package/dist/handlers/pre-tool-agent.js +192 -0
  17. package/dist/handlers/pre-tool.js +218 -0
  18. package/dist/handlers/session-end.js +39 -0
  19. package/dist/handlers/session-start.js +262 -0
  20. package/dist/handlers/stop-error-reminder.js +195 -0
  21. package/dist/handlers/stop-quality-evaluation.js +58 -0
  22. package/dist/handlers/stop-session-summary.js +62 -0
  23. package/dist/handlers/stop-token-metrics.js +83 -0
  24. package/dist/handlers/stop.js +25 -0
  25. package/dist/handlers/subagent.js +105 -0
  26. package/dist/handlers/tool-event-router.js +39 -0
  27. package/dist/handlers/user-prompt.js +218 -0
  28. package/dist/hook-runner.js +10 -0
  29. package/dist/hook-runner.js.map +7 -0
  30. package/dist/lib/agent/agent-context.js +123 -0
  31. package/dist/lib/agent/agent-evaluations.js +155 -0
  32. package/dist/lib/agent/agent-file-budget.js +65 -0
  33. package/dist/lib/agent/agent-sources.js +165 -0
  34. package/dist/lib/agent/synth-spans.js +51 -0
  35. package/dist/lib/core/bounded-label.js +6 -0
  36. package/dist/lib/core/category-rules.js +11 -0
  37. package/dist/lib/core/child-result.js +19 -0
  38. package/dist/lib/core/config-dir-recovery.js +22 -0
  39. package/dist/lib/core/constants.js +171 -0
  40. package/dist/lib/core/detached-runner.js +55 -0
  41. package/dist/lib/core/file-utils.js +353 -0
  42. package/dist/lib/core/format-utils.js +51 -0
  43. package/dist/lib/core/http-utils.js +74 -0
  44. package/dist/lib/core/http1-fetch.js +14 -0
  45. package/dist/lib/core/identity-key-resolver.js +149 -0
  46. package/dist/lib/core/jsonl-tail.js +207 -0
  47. package/dist/lib/core/load-envrc.js +72 -0
  48. package/dist/lib/core/parsers.js +43 -0
  49. package/dist/lib/core/regex.js +27 -0
  50. package/dist/lib/core/settings-env.js +31 -0
  51. package/dist/lib/core/shell-command.js +122 -0
  52. package/dist/lib/core/units.js +97 -0
  53. package/dist/lib/git/git-cache.js +158 -0
  54. package/dist/lib/git/git-commit.js +189 -0
  55. package/dist/lib/git/git-exec.js +30 -0
  56. package/dist/lib/mcp/mcp-completeness.js +40 -0
  57. package/dist/lib/mcp/mcp-config.js +118 -0
  58. package/dist/lib/mcp/mcp-failure-latch.js +22 -0
  59. package/dist/lib/mcp/mcp-identity-launcher.js +43 -0
  60. package/dist/lib/otel/attributes.js +322 -0
  61. package/dist/lib/otel/evaluation-attrs.js +51 -0
  62. package/dist/lib/otel/file-exporters.js +169 -0
  63. package/dist/lib/otel/host-resource.js +61 -0
  64. package/dist/lib/otel/otel-headers-helper.js +26 -0
  65. package/dist/lib/otel/otel-monitor.js +181 -0
  66. package/dist/lib/otel/otel.js +235 -0
  67. package/dist/lib/otel/otlp-headers.js +101 -0
  68. package/dist/lib/otel/otlp-post.js +122 -0
  69. package/dist/lib/otel/otlp-serialize.js +142 -0
  70. package/dist/lib/otel/otlp-signal.js +2 -0
  71. package/dist/lib/otel/remote-spans.js +142 -0
  72. package/dist/lib/otel/service-identity.js +10 -0
  73. package/dist/lib/otel/telemetry-alerts.js +43 -0
  74. package/dist/lib/otel/token-metrics.js +122 -0
  75. package/dist/lib/otel/trace-context.js +81 -0
  76. package/dist/lib/quality/judge-meta-eval.js +70 -0
  77. package/dist/lib/quality/judge-prompts.js +104 -0
  78. package/dist/lib/quality/judge-providers.js +193 -0
  79. package/dist/lib/quality/judge-transport.js +93 -0
  80. package/dist/lib/quality/llm-judge.js +170 -0
  81. package/dist/lib/quality/quality-budget.js +99 -0
  82. package/dist/lib/quality/quality-degradation.js +156 -0
  83. package/dist/lib/quality/quality-eval-handoff.js +74 -0
  84. package/dist/lib/quality/quality-evaluator.js +178 -0
  85. package/dist/lib/quality/quality-sampler.js +43 -0
  86. package/dist/lib/quality/quality-signals.js +150 -0
  87. package/dist/lib/runtime/categorizers.js +101 -0
  88. package/dist/lib/runtime/hook-input.js +16 -0
  89. package/dist/lib/runtime/hook-output.js +50 -0
  90. package/dist/lib/runtime/output-analyzer.js +160 -0
  91. package/dist/lib/runtime/run-handlers.js +32 -0
  92. package/dist/lib/runtime/tool-input.js +111 -0
  93. package/dist/lib/runtime/tool-output.js +44 -0
  94. package/dist/lib/runtime/unknown-tool.js +32 -0
  95. package/dist/lib/session/edit-ledger.js +29 -0
  96. package/dist/lib/session/forked-skill.js +39 -0
  97. package/dist/lib/session/handoffs.js +77 -0
  98. package/dist/lib/session/session-state.js +169 -0
  99. package/dist/lib/session/skill-rules.js +196 -0
  100. package/dist/lib/session/task-tracker.js +83 -0
  101. package/dist/lib/shipper/shipper-credentials.js +38 -0
  102. package/dist/lib/shipper/shipper-cursor.js +89 -0
  103. package/dist/lib/shipper/shipper-status.js +174 -0
  104. package/dist/lib/shipper/span-shipper.js +272 -0
  105. package/dist/lib/shipper/telemetry-shipper.js +39 -0
  106. package/dist/lib/transcript/agent-transcript-metrics.js +34 -0
  107. package/dist/lib/transcript/context-breakdown.js +134 -0
  108. package/dist/lib/transcript/context-history.js +69 -0
  109. package/dist/lib/transcript/context-tracker.js +226 -0
  110. package/dist/lib/transcript/message-count.js +49 -0
  111. package/dist/lib/transcript/model-ids.js +36 -0
  112. package/dist/lib/transcript/model-pricing.js +153 -0
  113. package/dist/lib/transcript/token-metrics-checkpoint.js +152 -0
  114. package/dist/lib/transcript/tool-call-durations.js +64 -0
  115. package/dist/lib/transcript/transcript-entry.js +67 -0
  116. package/dist/lib/transcript/transcript-fold.js +130 -0
  117. package/dist/lib/transcript/transcript-layout.js +39 -0
  118. package/dist/lib/transcript/transcript-parser.js +117 -0
  119. package/dist/runner/agent-context-4XTCLMLZ.js +23 -0
  120. package/dist/runner/agent-context-4XTCLMLZ.js.map +7 -0
  121. package/dist/runner/agent-file-budget-Q33ESBBE.js +68 -0
  122. package/dist/runner/agent-file-budget-Q33ESBBE.js.map +7 -0
  123. package/dist/runner/agent-transcript-metrics-W5CZZFMI.js +39 -0
  124. package/dist/runner/agent-transcript-metrics-W5CZZFMI.js.map +7 -0
  125. package/dist/runner/chunk-2NTNAJZE.js +49 -0
  126. package/dist/runner/chunk-2NTNAJZE.js.map +7 -0
  127. package/dist/runner/chunk-4KWBQTTG.js +78 -0
  128. package/dist/runner/chunk-4KWBQTTG.js.map +7 -0
  129. package/dist/runner/chunk-52RY6LQT.js +699 -0
  130. package/dist/runner/chunk-52RY6LQT.js.map +7 -0
  131. package/dist/runner/chunk-7OM5CYES.js +8695 -0
  132. package/dist/runner/chunk-7OM5CYES.js.map +7 -0
  133. package/dist/runner/chunk-7PEOKGYR.js +1568 -0
  134. package/dist/runner/chunk-7PEOKGYR.js.map +7 -0
  135. package/dist/runner/chunk-AGSGKELQ.js +126 -0
  136. package/dist/runner/chunk-AGSGKELQ.js.map +7 -0
  137. package/dist/runner/chunk-AVM7PJFW.js +12 -0
  138. package/dist/runner/chunk-AVM7PJFW.js.map +7 -0
  139. package/dist/runner/chunk-C3WHUMU5.js +178 -0
  140. package/dist/runner/chunk-C3WHUMU5.js.map +7 -0
  141. package/dist/runner/chunk-DGB4NSSD.js +157 -0
  142. package/dist/runner/chunk-DGB4NSSD.js.map +7 -0
  143. package/dist/runner/chunk-DNSTWC26.js +151 -0
  144. package/dist/runner/chunk-DNSTWC26.js.map +7 -0
  145. package/dist/runner/chunk-FDJJ3TYU.js +449 -0
  146. package/dist/runner/chunk-FDJJ3TYU.js.map +7 -0
  147. package/dist/runner/chunk-FGKYDQHZ.js +137 -0
  148. package/dist/runner/chunk-FGKYDQHZ.js.map +7 -0
  149. package/dist/runner/chunk-GG2I4TGI.js +582 -0
  150. package/dist/runner/chunk-GG2I4TGI.js.map +7 -0
  151. package/dist/runner/chunk-GNNKUMRF.js +60 -0
  152. package/dist/runner/chunk-GNNKUMRF.js.map +7 -0
  153. package/dist/runner/chunk-I7TD2QVR.js +118 -0
  154. package/dist/runner/chunk-I7TD2QVR.js.map +7 -0
  155. package/dist/runner/chunk-IJ4SLUBV.js +78 -0
  156. package/dist/runner/chunk-IJ4SLUBV.js.map +7 -0
  157. package/dist/runner/chunk-IY7AP7NA.js +32 -0
  158. package/dist/runner/chunk-IY7AP7NA.js.map +7 -0
  159. package/dist/runner/chunk-J3F3Z3EQ.js +177 -0
  160. package/dist/runner/chunk-J3F3Z3EQ.js.map +7 -0
  161. package/dist/runner/chunk-JLEO5OHU.js +104 -0
  162. package/dist/runner/chunk-JLEO5OHU.js.map +7 -0
  163. package/dist/runner/chunk-JRNNLOPR.js +168 -0
  164. package/dist/runner/chunk-JRNNLOPR.js.map +7 -0
  165. package/dist/runner/chunk-KGSA5JYP.js +82 -0
  166. package/dist/runner/chunk-KGSA5JYP.js.map +7 -0
  167. package/dist/runner/chunk-LBCZAYFR.js +125 -0
  168. package/dist/runner/chunk-LBCZAYFR.js.map +7 -0
  169. package/dist/runner/chunk-LHWRXY2G.js +41 -0
  170. package/dist/runner/chunk-LHWRXY2G.js.map +7 -0
  171. package/dist/runner/chunk-LQ2LGUYJ.js +41 -0
  172. package/dist/runner/chunk-LQ2LGUYJ.js.map +7 -0
  173. package/dist/runner/chunk-LYY6RCIE.js +158 -0
  174. package/dist/runner/chunk-LYY6RCIE.js.map +7 -0
  175. package/dist/runner/chunk-M4R4QIQH.js +41 -0
  176. package/dist/runner/chunk-M4R4QIQH.js.map +7 -0
  177. package/dist/runner/chunk-MC75VXMX.js +207 -0
  178. package/dist/runner/chunk-MC75VXMX.js.map +7 -0
  179. package/dist/runner/chunk-NKZU4RRG.js +104 -0
  180. package/dist/runner/chunk-NKZU4RRG.js.map +7 -0
  181. package/dist/runner/chunk-PJHWHJ3K.js +56 -0
  182. package/dist/runner/chunk-PJHWHJ3K.js.map +7 -0
  183. package/dist/runner/chunk-RIGVYJ2O.js +114 -0
  184. package/dist/runner/chunk-RIGVYJ2O.js.map +7 -0
  185. package/dist/runner/chunk-RWRGC7ZK.js +93 -0
  186. package/dist/runner/chunk-RWRGC7ZK.js.map +7 -0
  187. package/dist/runner/chunk-SRMAJQMV.js +54 -0
  188. package/dist/runner/chunk-SRMAJQMV.js.map +7 -0
  189. package/dist/runner/chunk-TRMFD36J.js +47 -0
  190. package/dist/runner/chunk-TRMFD36J.js.map +7 -0
  191. package/dist/runner/chunk-U4IOZYQ3.js +21 -0
  192. package/dist/runner/chunk-U4IOZYQ3.js.map +7 -0
  193. package/dist/runner/chunk-UEXDE3WP.js +83 -0
  194. package/dist/runner/chunk-UEXDE3WP.js.map +7 -0
  195. package/dist/runner/chunk-UW3GQZSM.js +50 -0
  196. package/dist/runner/chunk-UW3GQZSM.js.map +7 -0
  197. package/dist/runner/chunk-V2GSP6VR.js +46 -0
  198. package/dist/runner/chunk-V2GSP6VR.js.map +7 -0
  199. package/dist/runner/chunk-VOV4Y5VU.js +81 -0
  200. package/dist/runner/chunk-VOV4Y5VU.js.map +7 -0
  201. package/dist/runner/chunk-VT5T6OEI.js +65 -0
  202. package/dist/runner/chunk-VT5T6OEI.js.map +7 -0
  203. package/dist/runner/chunk-VUYVFWIN.js +12 -0
  204. package/dist/runner/chunk-VUYVFWIN.js.map +7 -0
  205. package/dist/runner/chunk-VVGOPPEN.js +36 -0
  206. package/dist/runner/chunk-VVGOPPEN.js.map +7 -0
  207. package/dist/runner/chunk-VXFSLM6P.js +14 -0
  208. package/dist/runner/chunk-VXFSLM6P.js.map +7 -0
  209. package/dist/runner/chunk-W3EK7JUT.js +26125 -0
  210. package/dist/runner/chunk-W3EK7JUT.js.map +7 -0
  211. package/dist/runner/chunk-WJHNCOUF.js +52 -0
  212. package/dist/runner/chunk-WJHNCOUF.js.map +7 -0
  213. package/dist/runner/chunk-WU7ANGCW.js +269 -0
  214. package/dist/runner/chunk-WU7ANGCW.js.map +7 -0
  215. package/dist/runner/chunk-X7XLMSZX.js +44 -0
  216. package/dist/runner/chunk-X7XLMSZX.js.map +7 -0
  217. package/dist/runner/chunk-XSO3B4QN.js +124 -0
  218. package/dist/runner/chunk-XSO3B4QN.js.map +7 -0
  219. package/dist/runner/chunk-YGFN3LN2.js +174 -0
  220. package/dist/runner/chunk-YGFN3LN2.js.map +7 -0
  221. package/dist/runner/chunk-YHYDBLVB.js +33 -0
  222. package/dist/runner/chunk-YHYDBLVB.js.map +7 -0
  223. package/dist/runner/compact-36NP3PKT.js +60 -0
  224. package/dist/runner/compact-36NP3PKT.js.map +7 -0
  225. package/dist/runner/getMachineId-bsd-AGENNHN6.js +42 -0
  226. package/dist/runner/getMachineId-bsd-AGENNHN6.js.map +7 -0
  227. package/dist/runner/getMachineId-bsd-I5WZGCL4.js +33 -0
  228. package/dist/runner/getMachineId-bsd-I5WZGCL4.js.map +7 -0
  229. package/dist/runner/getMachineId-bsd-ZXK225P7.js +33 -0
  230. package/dist/runner/getMachineId-bsd-ZXK225P7.js.map +7 -0
  231. package/dist/runner/getMachineId-darwin-47GDLEXL.js +42 -0
  232. package/dist/runner/getMachineId-darwin-47GDLEXL.js.map +7 -0
  233. package/dist/runner/getMachineId-darwin-5CRLMDD6.js +33 -0
  234. package/dist/runner/getMachineId-darwin-5CRLMDD6.js.map +7 -0
  235. package/dist/runner/getMachineId-darwin-ADG4I32N.js +33 -0
  236. package/dist/runner/getMachineId-darwin-ADG4I32N.js.map +7 -0
  237. package/dist/runner/getMachineId-linux-5KVS3T2M.js +27 -0
  238. package/dist/runner/getMachineId-linux-5KVS3T2M.js.map +7 -0
  239. package/dist/runner/getMachineId-linux-GDFB5GSO.js +34 -0
  240. package/dist/runner/getMachineId-linux-GDFB5GSO.js.map +7 -0
  241. package/dist/runner/getMachineId-linux-NQMWCRO3.js +27 -0
  242. package/dist/runner/getMachineId-linux-NQMWCRO3.js.map +7 -0
  243. package/dist/runner/getMachineId-unsupported-5PFIGMVX.js +18 -0
  244. package/dist/runner/getMachineId-unsupported-5PFIGMVX.js.map +7 -0
  245. package/dist/runner/getMachineId-unsupported-DW27K3ZX.js +18 -0
  246. package/dist/runner/getMachineId-unsupported-DW27K3ZX.js.map +7 -0
  247. package/dist/runner/getMachineId-unsupported-XV3FHTHD.js +25 -0
  248. package/dist/runner/getMachineId-unsupported-XV3FHTHD.js.map +7 -0
  249. package/dist/runner/getMachineId-win-5JVMW3EI.js +44 -0
  250. package/dist/runner/getMachineId-win-5JVMW3EI.js.map +7 -0
  251. package/dist/runner/getMachineId-win-SNESQF7R.js +35 -0
  252. package/dist/runner/getMachineId-win-SNESQF7R.js.map +7 -0
  253. package/dist/runner/getMachineId-win-UJYHSBM2.js +35 -0
  254. package/dist/runner/getMachineId-win-UJYHSBM2.js.map +7 -0
  255. package/dist/runner/git-commit-BA53DOJQ.js +30 -0
  256. package/dist/runner/git-commit-BA53DOJQ.js.map +7 -0
  257. package/dist/runner/hook-runner-JHH6PGKE.js +220 -0
  258. package/dist/runner/hook-runner-JHH6PGKE.js.map +7 -0
  259. package/dist/runner/judge-transport-R4TF5LEH.js +91 -0
  260. package/dist/runner/judge-transport-R4TF5LEH.js.map +7 -0
  261. package/dist/runner/mcp-status-QEUH2KGX.js +89 -0
  262. package/dist/runner/mcp-status-QEUH2KGX.js.map +7 -0
  263. package/dist/runner/notification-FKMBCSXF.js +69 -0
  264. package/dist/runner/notification-FKMBCSXF.js.map +7 -0
  265. package/dist/runner/post-tool-3MRHTBKH.js +192 -0
  266. package/dist/runner/post-tool-3MRHTBKH.js.map +7 -0
  267. package/dist/runner/post-tool-agent-BB34MNHI.js +370 -0
  268. package/dist/runner/post-tool-agent-BB34MNHI.js.map +7 -0
  269. package/dist/runner/post-tool-changelog-sync-OP2TT2I7.js +147 -0
  270. package/dist/runner/post-tool-changelog-sync-OP2TT2I7.js.map +7 -0
  271. package/dist/runner/post-tool-code-structure-LE7J2SC2.js +130 -0
  272. package/dist/runner/post-tool-code-structure-LE7J2SC2.js.map +7 -0
  273. package/dist/runner/post-tool-edit-ledger-IJMEYHKF.js +30 -0
  274. package/dist/runner/post-tool-edit-ledger-IJMEYHKF.js.map +7 -0
  275. package/dist/runner/post-tool-failure-XTH2I2Z7.js +111 -0
  276. package/dist/runner/post-tool-failure-XTH2I2Z7.js.map +7 -0
  277. package/dist/runner/post-tool-git-E46HZGZO.js +94 -0
  278. package/dist/runner/post-tool-git-E46HZGZO.js.map +7 -0
  279. package/dist/runner/post-tool-mcp-AMCDY5GH.js +144 -0
  280. package/dist/runner/post-tool-mcp-AMCDY5GH.js.map +7 -0
  281. package/dist/runner/post-tool-task-state-TLDOI33H.js +100 -0
  282. package/dist/runner/post-tool-task-state-TLDOI33H.js.map +7 -0
  283. package/dist/runner/pre-tool-SQE2FZQO.js +245 -0
  284. package/dist/runner/pre-tool-SQE2FZQO.js.map +7 -0
  285. package/dist/runner/pre-tool-agent-OZUPVFUI.js +218 -0
  286. package/dist/runner/pre-tool-agent-OZUPVFUI.js.map +7 -0
  287. package/dist/runner/quality-evaluator-XYNDKDRG.js +901 -0
  288. package/dist/runner/quality-evaluator-XYNDKDRG.js.map +7 -0
  289. package/dist/runner/session-end-3MJTDLLA.js +57 -0
  290. package/dist/runner/session-end-3MJTDLLA.js.map +7 -0
  291. package/dist/runner/session-start-5ZMCLKBS.js +352 -0
  292. package/dist/runner/session-start-5ZMCLKBS.js.map +7 -0
  293. package/dist/runner/shipper-status-MADX6SPG.js +37 -0
  294. package/dist/runner/shipper-status-MADX6SPG.js.map +7 -0
  295. package/dist/runner/span-shipper-4HQDHC47.js +3408 -0
  296. package/dist/runner/span-shipper-4HQDHC47.js.map +7 -0
  297. package/dist/runner/stop-RTKSIYJV.js +596 -0
  298. package/dist/runner/stop-RTKSIYJV.js.map +7 -0
  299. package/dist/runner/subagent-CBCG4OLZ.js +116 -0
  300. package/dist/runner/subagent-CBCG4OLZ.js.map +7 -0
  301. package/dist/runner/token-metrics-AD2RAFGM.js +31 -0
  302. package/dist/runner/token-metrics-AD2RAFGM.js.map +7 -0
  303. package/dist/runner/user-prompt-T5NZ2UJD.js +376 -0
  304. package/dist/runner/user-prompt-T5NZ2UJD.js.map +7 -0
  305. package/package.json +68 -5
@@ -0,0 +1,218 @@
1
+ /** UserPromptSubmit: context usage snapshot, prompt-span link, and skill activation suggestions. */
2
+ import { createHash } from 'node:crypto';
3
+ import { join } from 'node:path';
4
+ import { THRESHOLDS, CLAUDE_HOME } from '../lib/core/constants.js';
5
+ import { truncate } from '../lib/core/format-utils.js';
6
+ import { roundTo, UNITS } from '../lib/core/units.js';
7
+ import { CONTEXT_ATTRIBUTES, CONTEXT_METRICS, HOOK_NAMES, HOOK_TYPE_ATTR, SESSION_METRICS } from '../lib/otel/attributes.js';
8
+ import { instrumentHook, persistSpanContext } from '../lib/otel/otel-monitor.js';
9
+ import { cacheHitRate } from '../lib/otel/token-metrics.js';
10
+ import { savePromptContext } from '../lib/otel/trace-context.js';
11
+ import { writePlainContext } from '../lib/runtime/hook-output.js';
12
+ import { claimOnce, sessionMarkerPath } from '../lib/session/session-state.js';
13
+ import { containsKeyword, loadSkillRules, skillRulesCandidates, PRIORITIES, } from '../lib/session/skill-rules.js';
14
+ import { getSessionUsage } from '../lib/transcript/context-tracker.js';
15
+ const ACTIVATION_PREFIX = 'Skills matching this prompt (load with the Skill tool before responding):';
16
+ /** Per-session markers for skills already suggested, so each is suggested once. */
17
+ const SUGGESTED_DIRNAME = 'skill-suggested';
18
+ const MATCH_EVENTS = {
19
+ keyword: 'integritystudio.skill_activation.keyword_match',
20
+ intent: 'integritystudio.skill_activation.intent_match',
21
+ };
22
+ const MATCH_COUNT_METRICS = {
23
+ keyword: 'integritystudio.skill_activation.keyword_matches',
24
+ intent: 'integritystudio.skill_activation.intent_matches',
25
+ };
26
+ /** Ratio span attributes are reported to three decimal places. */
27
+ const RATIO_PRECISION = 1000;
28
+ /** Skill-name key shared by the match events and the pattern-rejection logs. */
29
+ const SKILL_ATTR = 'integritystudio.skill_activation.skill';
30
+ /** Per-session markers for skill-rules warnings already logged (SAH6). */
31
+ const RULE_WARNINGS_DIRNAME = 'skill-rule-warnings';
32
+ const WARNING_KEY_HEX_LENGTH = 16;
33
+ function contextUsageAttributes(usage) {
34
+ const breakdown = Object.entries(usage.breakdown).map(([contextType, tokens]) => [`integritystudio.context.breakdown.${contextType}`, tokens]);
35
+ return {
36
+ 'integritystudio.context.total_tokens': usage.totalContextTokens,
37
+ [CONTEXT_ATTRIBUTES.UTILIZATION_PERCENT]: usage.utilizationPercent,
38
+ [CONTEXT_ATTRIBUTES.FREE_SPACE]: usage.freeSpace,
39
+ 'integritystudio.context.input_tokens': usage.inputTokens,
40
+ 'integritystudio.context.cache_read_tokens': usage.cacheReadTokens,
41
+ [CONTEXT_ATTRIBUTES.MESSAGE_COUNT]: usage.messageCount,
42
+ ...Object.fromEntries(breakdown),
43
+ };
44
+ }
45
+ function ratioOf(numerator, denominator) {
46
+ return denominator > 0 ? numerator / denominator : undefined;
47
+ }
48
+ function recordRatio(ctx, attribute, metric, ratio) {
49
+ if (ratio === undefined)
50
+ return;
51
+ ctx.addAttribute(attribute, roundTo(ratio, RATIO_PRECISION));
52
+ ctx.recordMetric(metric, ratio, undefined, { unit: UNITS.RATIO });
53
+ }
54
+ /** Span attributes only: getSessionUsage() already emitted the session context metrics. */
55
+ function recordContextUsage(ctx, usage) {
56
+ const attributes = contextUsageAttributes(usage);
57
+ ctx.addAttributes(attributes);
58
+ recordRatio(ctx, CONTEXT_ATTRIBUTES.CACHE_HIT_RATE, CONTEXT_METRICS.CACHE_HIT_RATE, cacheHitRate(usage.cacheReadTokens, usage.inputTokens));
59
+ recordRatio(ctx, CONTEXT_ATTRIBUTES.CACHE_EFFICIENCY, SESSION_METRICS.CACHE_EFFICIENCY, ratioOf(usage.cacheReadTokens, usage.totalContextTokens));
60
+ ctx.logger.debug('Context usage tracked', attributes);
61
+ }
62
+ /** Each distinct warning is logged once per session; without a session id, or if the marker cannot be written, it always logs. */
63
+ function warnOncePerSession(ctx, sessionId, { message, attributes, identity }) {
64
+ if (sessionId) {
65
+ const key = createHash('sha256').update(JSON.stringify([message, attributes, identity])).digest('hex').slice(0, WARNING_KEY_HEX_LENGTH);
66
+ const marker = sessionMarkerPath(sessionId, join(RULE_WARNINGS_DIRNAME, key));
67
+ if (!claimOnce(marker, { onWriteError: 'grant' }))
68
+ return;
69
+ }
70
+ ctx.logger.warn(message, attributes);
71
+ }
72
+ function loadRules(ctx, sessionId) {
73
+ const loaded = loadSkillRules(skillRulesCandidates(CLAUDE_HOME, process.env.CLAUDE_PROJECT_DIR, process.env.HOME));
74
+ for (const { path, reason } of loaded.skippedFiles) {
75
+ warnOncePerSession(ctx, sessionId, {
76
+ message: 'Skipped an unusable skill-rules.json',
77
+ attributes: {
78
+ 'integritystudio.skill_activation.rules.path': path,
79
+ 'integritystudio.skill_activation.rules.skip_reason': reason,
80
+ },
81
+ identity: [path],
82
+ });
83
+ }
84
+ for (const { skill, source, reason } of loaded.skippedSkills) {
85
+ warnOncePerSession(ctx, sessionId, {
86
+ message: 'Skipped an invalid skill rule',
87
+ attributes: {
88
+ ...(reason === 'invalid-name'
89
+ ? { 'integritystudio.skill_activation.skill_name_length': skill.length }
90
+ : { [SKILL_ATTR]: skill }),
91
+ 'integritystudio.skill_activation.rule.invalid_reason': reason,
92
+ },
93
+ identity: [skill, source],
94
+ });
95
+ }
96
+ for (const { skill, source, pattern, reason, message } of loaded.skippedPatterns) {
97
+ warnOncePerSession(ctx, sessionId, {
98
+ message,
99
+ attributes: {
100
+ [SKILL_ATTR]: skill,
101
+ ...(reason === 'oversized' || reason === 'untrusted'
102
+ ? { 'integritystudio.skill_activation.pattern_length': pattern.length }
103
+ : { 'integritystudio.skill_activation.pattern': pattern }),
104
+ },
105
+ identity: [skill, pattern, source],
106
+ });
107
+ }
108
+ const { rules } = loaded;
109
+ if (!rules) {
110
+ ctx.logger.debug('No skill-rules.json found');
111
+ ctx.addAttribute('integritystudio.skill_activation.rules.found', false);
112
+ return undefined;
113
+ }
114
+ ctx.addAttribute('integritystudio.skill_activation.rules.found', true);
115
+ if (loaded.path)
116
+ ctx.addAttribute('integritystudio.skill_activation.rules.path', loaded.path);
117
+ if (rules.version)
118
+ ctx.addAttribute('integritystudio.skill_activation.rules.version', rules.version);
119
+ ctx.addAttribute('integritystudio.skill_activation.rules.skill_count', Object.keys(rules.skills).length);
120
+ return rules;
121
+ }
122
+ /** Keywords win over intent patterns, which run against `testPrompt`, the length-capped prompt. */
123
+ function findMatchType(triggers, prompt, testPrompt) {
124
+ if (triggers.keywords.some((keyword) => containsKeyword(prompt, keyword)))
125
+ return 'keyword';
126
+ if (triggers.intentPatterns.some((pattern) => pattern.test(testPrompt)))
127
+ return 'intent';
128
+ return undefined;
129
+ }
130
+ function matchSkills(ctx, rules, prompt) {
131
+ const testPrompt = prompt.slice(0, THRESHOLDS.MAX_PROMPT_TEST_LENGTH);
132
+ const matched = [];
133
+ for (const [name, config] of Object.entries(rules.skills)) {
134
+ // Router-only skills cannot be invoked by the model; suggesting one is a dead end.
135
+ if (config.disableModelInvocation || !config.promptTriggers)
136
+ continue;
137
+ const matchType = findMatchType(config.promptTriggers, prompt, testPrompt);
138
+ if (!matchType)
139
+ continue;
140
+ matched.push({ name, matchType, config });
141
+ ctx.recordEvent(MATCH_EVENTS[matchType], {
142
+ [SKILL_ATTR]: name,
143
+ 'integritystudio.skill_activation.skill_type': config.type,
144
+ });
145
+ }
146
+ return matched;
147
+ }
148
+ function groupByPriority(matched) {
149
+ const byPriority = Object.fromEntries(PRIORITIES.map((priority) => [priority, []]));
150
+ for (const skill of matched)
151
+ byPriority[skill.config.priority].push(skill);
152
+ return byPriority;
153
+ }
154
+ function recordMatchCounts(ctx, matched, byPriority) {
155
+ const byType = { keyword: 0, intent: 0 };
156
+ for (const skill of matched)
157
+ byType[skill.matchType]++;
158
+ ctx.addAttribute('integritystudio.skill_activation.matches.total', matched.length);
159
+ ctx.recordMetric('integritystudio.skill_activation.matches', matched.length, undefined, { unit: UNITS.MATCH });
160
+ const priorityCounts = Object.entries(byPriority).map(([priority, skills]) => [`integritystudio.skill_activation.matches.${priority}`, skills.length]);
161
+ ctx.addAttributes(Object.fromEntries(priorityCounts));
162
+ for (const [matchType, count] of Object.entries(byType)) {
163
+ ctx.recordMetric(MATCH_COUNT_METRICS[matchType], count, undefined, { unit: UNITS.MATCH });
164
+ }
165
+ }
166
+ /** One line, highest priority first. */
167
+ function renderActivationLine(byPriority) {
168
+ const skills = PRIORITIES.flatMap((priority) => byPriority[priority].map((s) => `${s.name} (${priority})`));
169
+ return `${ACTIVATION_PREFIX} ${skills.join(', ')}`;
170
+ }
171
+ /** A skill already suggested this session is not suggested again; without a session id every match is new. */
172
+ function claimSuggestion(sessionId, skill) {
173
+ if (!sessionId)
174
+ return true;
175
+ return claimOnce(sessionMarkerPath(sessionId, join(SUGGESTED_DIRNAME, skill)), { onWriteError: 'grant' });
176
+ }
177
+ function reportMatches(ctx, matched, sessionId) {
178
+ if (matched.length === 0) {
179
+ ctx.logger.debug('No skill matches for prompt');
180
+ return;
181
+ }
182
+ const fresh = matched.filter((skill) => claimSuggestion(sessionId, skill.name));
183
+ ctx.addAttribute('integritystudio.skill_activation.matches.already_suggested', matched.length - fresh.length);
184
+ ctx.logger.info('Skills matched for prompt', {
185
+ 'integritystudio.skill_activation.matches.total': matched.length,
186
+ 'integritystudio.skill_activation.skills': matched.map((s) => s.name).join(', '),
187
+ });
188
+ if (fresh.length === 0)
189
+ return;
190
+ writePlainContext(renderActivationLine(groupByPriority(fresh)));
191
+ }
192
+ export async function handleUserPrompt(input) {
193
+ await instrumentHook(HOOK_NAMES.SKILL_ACTIVATION_PROMPT, (ctx) => {
194
+ ctx.logger.debug('Skill activation check starting');
195
+ const prompt = (input.prompt ?? '').toLowerCase();
196
+ ctx.addAttribute('integritystudio.prompt.length', prompt.length);
197
+ if (prompt) {
198
+ ctx.addAttribute('integritystudio.prompt.preview', truncate(prompt, THRESHOLDS.PROMPT_PREVIEW_LENGTH));
199
+ }
200
+ if (input.session_id) {
201
+ const usage = getSessionUsage(input.session_id, input.transcript_path);
202
+ if (usage)
203
+ recordContextUsage(ctx, usage);
204
+ persistSpanContext(ctx, input.session_id, savePromptContext);
205
+ }
206
+ if (!prompt) {
207
+ ctx.logger.debug('No prompt provided');
208
+ return;
209
+ }
210
+ const rules = loadRules(ctx, input.session_id);
211
+ if (!rules)
212
+ return;
213
+ const matched = matchSkills(ctx, rules, prompt);
214
+ const byPriority = groupByPriority(matched);
215
+ recordMatchCounts(ctx, matched, byPriority);
216
+ reportMatches(ctx, matched, input.session_id);
217
+ }, { [HOOK_TYPE_ATTR]: 'prompt' });
218
+ }
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __hookRunnerCreateRequire } from 'node:module';
3
+ const require = __hookRunnerCreateRequire(import.meta.url);
4
+
5
+ // runner-entry.ts
6
+ import * as nodeModule from "node:module";
7
+ nodeModule.enableCompileCache?.();
8
+ var { main } = await import("./runner/hook-runner-JHH6PGKE.js");
9
+ void main();
10
+ //# sourceMappingURL=hook-runner.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../runner-entry.ts"],
4
+ "sourcesContent": ["#!/usr/bin/env node\n/**\n * Entry point of the bundled `dist/hook-runner.js`. It turns on Node's compile cache before\n * the runner's chunks load, so they are compiled once per build rather than on every spawn,\n * then runs the runner. Built by `scripts/bundle-runner.ts`; settings.json invokes the output.\n */\nimport * as nodeModule from 'node:module';\n\n// Optional: a `node` on PATH older than 22.1 lacks it, and a named import would fail at link time.\n(nodeModule as { enableCompileCache?: () => unknown }).enableCompileCache?.();\n\nconst { main } = await import('./hook-runner.js');\n// Not awaited, as in hook-runner.ts: a rejection reaches the `unhandledRejection` handler main()\n// installs, which exits 0 (L1). Awaiting it here would exit 1 instead, or 13 if it never settles.\nvoid main();\n"],
5
+ "mappings": ";;;;;AAMA,YAAY,gBAAgB;AAG2B,gCAAqB;AAE5E,IAAM,EAAE,KAAK,IAAI,MAAM,OAAO,kCAAkB;AAGhD,KAAK,KAAK;",
6
+ "names": []
7
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Cross-process state for synthesized agent spans: the pre-tool process that opens
3
+ * an invocation and the post-tool process that closes it share no memory, so the
4
+ * record lives in the session-state directory. On disk, not module-level Maps —
5
+ * those passed every test (vitest runs both handlers in one process) and emitted
6
+ * zero spans in production for six months (PT2). Deliberately touched only by
7
+ * agent events, never the builtin hot path.
8
+ */
9
+ import { randomBytes } from 'node:crypto';
10
+ import { rmSync } from 'node:fs';
11
+ import { join } from 'node:path';
12
+ import { loadJson, writeJson, withFileLock } from '../core/file-utils.js';
13
+ import { errorMessage, writeStderr } from '../core/format-utils.js';
14
+ import { DURATION_MS } from '../core/units.js';
15
+ import { sessionStateDir } from '../session/session-state.js';
16
+ // ── Storage ────────────────────────────────────────────────────────
17
+ const STORE_FILE = 'pending-agents.json';
18
+ const LOCK_FILE = 'pending-agents.lock';
19
+ /** An invocation with no post-tool event would otherwise be popped by an unrelated later one. */
20
+ export const PENDING_AGENT_TTL_MS = DURATION_MS.THIRTY_MINUTES;
21
+ function readStore(sessionId) {
22
+ const raw = loadJson(join(sessionStateDir(sessionId), STORE_FILE));
23
+ return { pending: raw?.pending ?? {}, seen: raw?.seen ?? {} };
24
+ }
25
+ /** Not `silent`: a failed write has no other symptom, and is the shape of the PT2 outage. */
26
+ function writeStore(sessionId, store) {
27
+ writeJson(join(sessionStateDir(sessionId), STORE_FILE), store, false);
28
+ }
29
+ /** Under the lock: a background agent's pre-tool can land while another's post-tool writes, and a lost update drops an invocation silently. */
30
+ function mutateStore(sessionId, fn) {
31
+ return withFileLock(join(sessionStateDir(sessionId), LOCK_FILE), () => {
32
+ const store = readStore(sessionId);
33
+ pruneStale(store);
34
+ const result = fn(store);
35
+ writeStore(sessionId, store);
36
+ return result;
37
+ });
38
+ }
39
+ function pruneStale(store) {
40
+ const cutoff = Date.now() - PENDING_AGENT_TTL_MS;
41
+ for (const [name, records] of Object.entries(store.pending)) {
42
+ const live = records.filter((r) => r.startTimeMs >= cutoff);
43
+ if (live.length === 0)
44
+ delete store.pending[name];
45
+ else if (live.length !== records.length)
46
+ store.pending[name] = live;
47
+ }
48
+ }
49
+ // ── Helpers ────────────────────────────────────────────────────────
50
+ export function generateHex(bytes) {
51
+ return randomBytes(bytes).toString('hex');
52
+ }
53
+ /** The dispatching parent of an agent starting now (§12.10); a background agent is not it. */
54
+ function latestForegroundParent(store) {
55
+ let newest;
56
+ for (const records of Object.values(store.pending)) {
57
+ for (const r of records) {
58
+ if (r.isBackground)
59
+ continue;
60
+ if (!newest || r.startTimeMs > newest.startTimeMs)
61
+ newest = r;
62
+ }
63
+ }
64
+ return newest?.invokeSpanId;
65
+ }
66
+ // ── Lifecycle ──────────────────────────────────────────────────────
67
+ export function savePendingAgent(input) {
68
+ return mutateStore(input.sessionId, (store) => {
69
+ const existingCreateSpanId = store.seen[input.agentName];
70
+ const isFirstSeen = existingCreateSpanId === undefined;
71
+ const createSpanId = existingCreateSpanId ?? input.createSpanId;
72
+ if (isFirstSeen)
73
+ store.seen[input.agentName] = createSpanId;
74
+ const record = {
75
+ ...input,
76
+ createSpanId,
77
+ isFirstSeen,
78
+ parentAgentInvokeSpanId: latestForegroundParent(store),
79
+ };
80
+ (store.pending[input.agentName] ??= []).push(record);
81
+ return record;
82
+ });
83
+ }
84
+ /**
85
+ * The record saved under the same `toolUseId`; failing that, the newest record saved without
86
+ * an id (the innermost of overlapping invocations). A record that carries an id goes only to
87
+ * its own call.
88
+ */
89
+ export function popPendingAgent(sessionId, agentName, toolUseId) {
90
+ return mutateStore(sessionId, (store) => {
91
+ const records = store.pending[agentName];
92
+ if (!records)
93
+ return undefined;
94
+ const exact = toolUseId ? records.findIndex((r) => r.toolUseId === toolUseId) : -1;
95
+ const index = exact >= 0 ? exact : records.map((r) => !r.toolUseId).lastIndexOf(true);
96
+ if (index < 0)
97
+ return undefined;
98
+ const [record] = records.splice(index, 1);
99
+ if (records.length === 0)
100
+ delete store.pending[agentName];
101
+ return record;
102
+ });
103
+ }
104
+ /** Reported, not swallowed: a surviving `seen` makes the next session on this id skip every `create_agent` span. */
105
+ export function clearSession(sessionId) {
106
+ const dir = sessionStateDir(sessionId);
107
+ for (const file of [STORE_FILE, LOCK_FILE]) {
108
+ try {
109
+ rmSync(join(dir, file), { force: true, recursive: true });
110
+ }
111
+ catch (error) {
112
+ writeStderr(`[agent-context] failed to clear ${file} for session ${sessionId}:`, errorMessage(error));
113
+ }
114
+ }
115
+ }
116
+ /** For tests and diagnostics. */
117
+ export function getAgentStateSizes(sessionId) {
118
+ const store = readStore(sessionId);
119
+ return {
120
+ pending: Object.values(store.pending).reduce((n, r) => n + r.length, 0),
121
+ seen: Object.keys(store.seen).length,
122
+ };
123
+ }
@@ -0,0 +1,155 @@
1
+ /** Per-agent scorecard parsers; adding a scoring agent is a table entry, not a handler branch (PT4). */
2
+ import { writeStderr } from '../core/format-utils.js';
3
+ import { GENAI_AGENT_ATTRIBUTES } from '../otel/attributes.js';
4
+ import { appendEvaluation, EVALUATOR_KIND, EVALUATION_COHORT } from '../quality/quality-signals.js';
5
+ const MIN_SCORECARD_COLUMNS = 3;
6
+ const AGENT_AUDITOR = 'agent-auditor';
7
+ /** Fixed by the scoring spec, unlike the total's denominator, which has moved and is parsed. */
8
+ const DIMENSION_MAX_SCORE = 10;
9
+ /** Keyed by the scorecard's D-number, fixed by `agent-auditor-scoring-spec.md` (the prose titles have already drifted). */
10
+ const DIMENSION_BY_COLUMN = {
11
+ d1: 'telemetry',
12
+ d2: 'definition',
13
+ d3: 'prompting',
14
+ d4: 'overlap',
15
+ d5: 'alignment',
16
+ d6: 'efficiency',
17
+ d7: 'code_quality',
18
+ d8: 'evolutionary_fitness',
19
+ };
20
+ function tableCells(line) {
21
+ const trimmed = line.trim();
22
+ if (!trimmed.startsWith('|'))
23
+ return [];
24
+ return trimmed
25
+ .slice(1)
26
+ .replace(/\|\s*$/, '')
27
+ .split('|')
28
+ .map(c => c.trim());
29
+ }
30
+ function isSeparatorRow(cells) {
31
+ return cells.length > 0 && cells.every(c => /^:?-{2,}:?$/.test(c));
32
+ }
33
+ /** "8", "8.5", "56/70", "**64/80**" → 8, 8.5, 56, 64. */
34
+ function cellNumber(cell) {
35
+ const digits = cell.replace(/\*/g, '').trim().match(/^([\d.]+)/)?.[1];
36
+ if (!digits)
37
+ return undefined;
38
+ const value = parseFloat(digits);
39
+ return Number.isNaN(value) ? undefined : value;
40
+ }
41
+ function cleanAgentName(cell) {
42
+ return cell.replace(/[`*]/g, '').replace(/\.md$/, '').trim();
43
+ }
44
+ function findScorecardLayout(headerCells) {
45
+ const headers = headerCells.map(h => h.toLowerCase());
46
+ if (headers.length < MIN_SCORECARD_COLUMNS)
47
+ return undefined;
48
+ const agentCol = headers.findIndex(h => h === 'agent');
49
+ const totalCol = headers.findIndex(h => h.startsWith('total'));
50
+ if (agentCol === -1 || totalCol === -1)
51
+ return undefined;
52
+ // agent-auditor.md requires the real denominator in the header ("Total /70").
53
+ const totalHeaderCell = headers[totalCol] ?? '';
54
+ const headerDenom = totalHeaderCell.match(/\/\s*(\d+)/)?.[1];
55
+ const maxTotal = headerDenom ? parseInt(headerDenom, 10) : undefined;
56
+ const dimensionCols = new Map();
57
+ headers.forEach((header, index) => {
58
+ const key = header.replace(/[^a-z0-9]/g, '');
59
+ const canonical = DIMENSION_BY_COLUMN[key];
60
+ if (canonical)
61
+ dimensionCols.set(index, canonical);
62
+ });
63
+ return { agentCol, totalCol, maxTotal, dimensionCols };
64
+ }
65
+ function parseScorecardRows(rows, layout) {
66
+ const { agentCol, totalCol, maxTotal, dimensionCols } = layout;
67
+ const cards = [];
68
+ for (const row of rows) {
69
+ const cells = tableCells(row);
70
+ if (cells.length === 0)
71
+ break;
72
+ if (isSeparatorRow(cells))
73
+ continue;
74
+ const agent = cleanAgentName(cells[agentCol] ?? '');
75
+ if (!agent)
76
+ continue;
77
+ const dimensions = {};
78
+ for (const [index, canonical] of dimensionCols) {
79
+ // A withdrawn dimension renders "—" (AA1a) and is absent, not zero.
80
+ const value = cellNumber(cells[index] ?? '');
81
+ if (value !== undefined)
82
+ dimensions[canonical] = value;
83
+ }
84
+ cards.push({ agent, dimensions, total: cellNumber(cells[totalCol] ?? ''), maxTotal });
85
+ }
86
+ return cards;
87
+ }
88
+ /**
89
+ * The wide Scorecard table: one row per agent, one column per dimension. Identified
90
+ * by having both an `Agent` and a `Total` column, which separates it from the
91
+ * Adaptive Assessment Detail table below it (same columns, depth labels not scores).
92
+ */
93
+ function parseScorecard(output) {
94
+ const lines = output.split('\n');
95
+ for (const [i, line] of lines.entries()) {
96
+ const layout = findScorecardLayout(tableCells(line));
97
+ if (layout)
98
+ return parseScorecardRows(lines.slice(i + 1), layout);
99
+ }
100
+ return [];
101
+ }
102
+ function emitScorecard(card, sessionId) {
103
+ const extras = { [GENAI_AGENT_ATTRIBUTES.AGENT_NAME]: card.agent };
104
+ const record = (name, score) => appendEvaluation({
105
+ name,
106
+ score,
107
+ kind: EVALUATOR_KIND.RULE,
108
+ cohort: EVALUATION_COHORT.NORMAL,
109
+ producer: AGENT_AUDITOR,
110
+ sessionId,
111
+ extraAttributes: extras,
112
+ });
113
+ // Normalised to [0,1] before writing: the consumer treats an absent unit as a
114
+ // ratio, so a raw 0–10 dimension averaged as 8.5 against a [0,1] total (AA1i).
115
+ for (const [dimension, score] of Object.entries(card.dimensions)) {
116
+ if (score < 0 || score > DIMENSION_MAX_SCORE) {
117
+ // Dividing would emit >1 under a unit that promises [0,1].
118
+ writeStderr(`[agent-evaluations] ${card.agent} ${dimension}: score ${score} outside ` +
119
+ `0-${DIMENSION_MAX_SCORE}, not emitted`);
120
+ continue;
121
+ }
122
+ record(`agent.quality.score.${dimension}`, score / DIMENSION_MAX_SCORE);
123
+ }
124
+ // Independent of the dimensions: one bad Total cell must not cost eight real scores.
125
+ // The denominator is parsed, not constant — it has moved 60 → 70 → 80 (AA1h) — and
126
+ // without it the total is skipped loudly: the usual cause is the header template
127
+ // emitted verbatim (`Total /{max_score}`).
128
+ if (card.total !== undefined && card.maxTotal === undefined) {
129
+ writeStderr(`[agent-evaluations] no denominator for ${card.agent}: total ${card.total} not emitted ` +
130
+ `(write the real denominator in the Total header, e.g. "Total /70")`);
131
+ return;
132
+ }
133
+ if (card.total !== undefined && card.maxTotal !== undefined) {
134
+ record('agent.quality.score', card.total / card.maxTotal);
135
+ }
136
+ }
137
+ function injectAuditEvaluations(output, sessionId) {
138
+ for (const card of parseScorecard(output))
139
+ emitScorecard(card, sessionId);
140
+ }
141
+ const AGENT_EVALUATION_PARSERS = {
142
+ [AGENT_AUDITOR]: injectAuditEvaluations,
143
+ };
144
+ /** Silent when no parser is registered or the parser throws. */
145
+ export function tryInjectEvaluations(agentType, output, sessionId) {
146
+ const parser = AGENT_EVALUATION_PARSERS[agentType];
147
+ if (!parser)
148
+ return;
149
+ try {
150
+ parser(output, sessionId);
151
+ }
152
+ catch {
153
+ // Never fails the hook.
154
+ }
155
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Per-invocation file-write budget for scoped agents (AA1g), disk-based to survive
3
+ * spawn-per-event. Callers MUST reset at invocation start (trap 2); any I/O error
4
+ * fails open, never a false denial (trap 1).
5
+ */
6
+ import { join } from 'node:path';
7
+ import { loadJson, writeJsonAtomic, withFileLock } from '../core/file-utils.js';
8
+ import { sessionStateDir } from '../session/session-state.js';
9
+ /** Maximum distinct files auto-error-resolver may write per invocation. */
10
+ export const AUTO_ERROR_RESOLVER_FILE_BUDGET = 3;
11
+ const BUDGET_FILE = 'agent-file-budget.json';
12
+ const LOCK_FILE = 'agent-file-budget.lock';
13
+ function budgetFilePath(sessionId) {
14
+ return join(sessionStateDir(sessionId), BUDGET_FILE);
15
+ }
16
+ function lockFilePath(sessionId) {
17
+ return join(sessionStateDir(sessionId), LOCK_FILE);
18
+ }
19
+ /** Locked load–mutate–save; an unchanged store is not written back. Throws, callers own the fail-open. */
20
+ function mutateBudgetStore(sessionId, fn) {
21
+ return withFileLock(lockFilePath(sessionId), () => {
22
+ const storePath = budgetFilePath(sessionId);
23
+ const store = loadJson(storePath) ?? {};
24
+ const { result, changed } = fn(store);
25
+ if (changed)
26
+ writeJsonAtomic(storePath, store, { silent: true });
27
+ return result;
28
+ });
29
+ }
30
+ /** Reset at spawn so a previous invocation's count cannot carry over; a failed reset is caught by fail-open on the check side. */
31
+ export function resetAgentFileBudget(sessionId, agentType) {
32
+ if (!sessionId || !agentType)
33
+ return;
34
+ try {
35
+ mutateBudgetStore(sessionId, (store) => {
36
+ delete store[agentType];
37
+ return { result: undefined, changed: true };
38
+ });
39
+ }
40
+ catch {
41
+ // best-effort
42
+ }
43
+ }
44
+ /** Record a write attempt; re-editing a tracked path is free. Fails open on I/O error (AA1g trap 1). */
45
+ export function checkAndRecordFilePath(sessionId, agentType, filePath, budget) {
46
+ if (!sessionId || !agentType || !filePath)
47
+ return { allowed: true, count: 0 };
48
+ try {
49
+ return mutateBudgetStore(sessionId, (store) => {
50
+ const entry = store[agentType] ?? { filePaths: [] };
51
+ if (entry.filePaths.includes(filePath)) {
52
+ return { result: { allowed: true, count: entry.filePaths.length }, changed: false };
53
+ }
54
+ if (entry.filePaths.length >= budget) {
55
+ return { result: { allowed: false, count: entry.filePaths.length }, changed: false };
56
+ }
57
+ entry.filePaths = [...entry.filePaths, filePath];
58
+ store[agentType] = entry;
59
+ return { result: { allowed: true, count: entry.filePaths.length }, changed: true };
60
+ });
61
+ }
62
+ catch {
63
+ return { allowed: true, count: 0 };
64
+ }
65
+ }