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,105 @@
1
+ /** MCP PostToolUse; lazy-loaded by the router so builtin events never pay for its imports (HSF27). */
2
+ import { basename } from 'node:path';
3
+ import { CLAUDE_HOME, INPUT_PREVIEW_CHARS, THRESHOLDS } from '../lib/core/constants.js';
4
+ import { truncate, writeStderr } from '../lib/core/format-utils.js';
5
+ import { mcpLabelsOf, parseMcpToolName } from '../lib/core/parsers.js';
6
+ import { BYTES } from '../lib/core/units.js';
7
+ import { recordMcpInvocation } from '../lib/mcp/mcp-completeness.js';
8
+ import { getMcpScopeCached, getProjectMismatchPatterns } from '../lib/mcp/mcp-config.js';
9
+ import { MCP_ATTRS, MCP_METRICS, HOOK_NAMES, HOOK_TYPE_ATTR, UNKNOWN_ERROR_TYPE } from '../lib/otel/attributes.js';
10
+ import { instrumentHook } from '../lib/otel/otel-monitor.js';
11
+ import { analyzeOutput, boundedScanText } from '../lib/runtime/output-analyzer.js';
12
+ import { readString } from '../lib/runtime/tool-input.js';
13
+ import { resolveOutputText } from '../lib/runtime/tool-output.js';
14
+ import { outcomeSpanAttributes, recordOutcome } from './post-tool-outcome.js';
15
+ /** Suggestion when a "not found" error names a path another project owns; every such path is under CLAUDE_HOME, so others skip the config load. */
16
+ function detectProjectContextMismatch(fullOutput, cwd) {
17
+ const output = boundedScanText(fullOutput);
18
+ if (!output.includes('not found') && !output.includes('FileNotFoundError'))
19
+ return undefined;
20
+ if (!output.includes(CLAUDE_HOME))
21
+ return undefined;
22
+ for (const { path, project } of getProjectMismatchPatterns(cwd)) {
23
+ if (output.includes(path)) {
24
+ return `Activate project '${project}' before reading files from ${basename(path)}`;
25
+ }
26
+ }
27
+ return undefined;
28
+ }
29
+ /** Input fields worth echoing into the MCP completeness record, in preference order. */
30
+ const INPUT_SUMMARY_KEYS = ['url', 'path', 'query', 'account', 'handle', 'repo'];
31
+ function extractInputSummary(toolInput) {
32
+ for (const key of INPUT_SUMMARY_KEYS) {
33
+ const value = readString(toolInput, key);
34
+ if (value)
35
+ return truncate(value, INPUT_PREVIEW_CHARS, '');
36
+ }
37
+ return undefined;
38
+ }
39
+ const MCP_OUTCOME_KEYS = {
40
+ successAttr: MCP_ATTRS.SUCCESS,
41
+ outputSizeAttr: MCP_ATTRS.OUTPUT_SIZE,
42
+ hasErrorAttr: MCP_ATTRS.HAS_ERROR,
43
+ errorTypeAttr: MCP_ATTRS.ERROR_TYPE,
44
+ errorCategoryAttr: MCP_ATTRS.ERROR_CATEGORY,
45
+ completionsMetric: MCP_METRICS.COMPLETIONS,
46
+ outputSizeMetric: MCP_METRICS.OUTPUT_SIZE,
47
+ };
48
+ function trackCompleteness(ctx, input, call, success) {
49
+ const recorded = recordMcpInvocation(input.session_id, {
50
+ server: call.info.server,
51
+ tool: call.info.tool,
52
+ success,
53
+ timestamp: new Date().toISOString(),
54
+ params: extractInputSummary(input.tool_input),
55
+ });
56
+ if (!recorded) {
57
+ ctx.logger.error('Failed to record MCP invocation', call.logLabels);
58
+ }
59
+ }
60
+ export async function handleMcpPostTool(input) {
61
+ const mcpInfo = parseMcpToolName(input.tool_name);
62
+ if (!mcpInfo)
63
+ return;
64
+ const sessionId = input.session_id;
65
+ const scope = getMcpScopeCached(mcpInfo.server, sessionId, input.cwd);
66
+ const logLabels = mcpLabelsOf(mcpInfo);
67
+ const call = {
68
+ info: mcpInfo,
69
+ logLabels,
70
+ metricLabels: { ...logLabels, [MCP_ATTRS.SCOPE]: scope },
71
+ };
72
+ await instrumentHook(HOOK_NAMES.MCP_POST_TOOL, (ctx) => {
73
+ const resolvedOutput = resolveOutputText(input);
74
+ const analysis = analyzeOutput(resolvedOutput);
75
+ const suggestion = detectProjectContextMismatch(resolvedOutput, input.cwd);
76
+ const toolLabel = `${mcpInfo.server}/${mcpInfo.tool}`;
77
+ const errorType = analysis.errorType ?? UNKNOWN_ERROR_TYPE;
78
+ ctx.addAttributes({
79
+ ...call.metricLabels,
80
+ [MCP_ATTRS.FULL_NAME]: mcpInfo.fullName,
81
+ ...outcomeSpanAttributes(analysis, MCP_OUTCOME_KEYS),
82
+ ...(suggestion ? { [MCP_ATTRS.CONTEXT_MISMATCH]: true, [MCP_ATTRS.SUGGESTION]: suggestion } : {}),
83
+ });
84
+ recordOutcome(ctx, analysis, MCP_OUTCOME_KEYS, {
85
+ toolName: mcpInfo.fullName,
86
+ sessionId,
87
+ logLabels: call.metricLabels,
88
+ errorLogExtras: suggestion ? { [MCP_ATTRS.SUGGESTION]: suggestion } : undefined,
89
+ metricLabels: call.metricLabels,
90
+ successMessage: 'MCP tool completed',
91
+ errorMessage: 'MCP tool returned error',
92
+ exceptionMessage: suggestion ? `${mcpInfo.fullName}: ${errorType} — Try: ${suggestion}` : `${mcpInfo.fullName}: ${errorType}`,
93
+ });
94
+ writeStderr(analysis.hasError
95
+ ? `[MCP ERROR] ${toolLabel} - ${errorType}`
96
+ : `[MCP] ${toolLabel} (${(analysis.outputSize / BYTES.KB).toFixed(1)}KB)`);
97
+ trackCompleteness(ctx, input, call, !analysis.hasError);
98
+ if (analysis.outputSize > THRESHOLDS.LARGE_OUTPUT_BYTES) {
99
+ ctx.logger.warn('Large MCP output', {
100
+ ...call.logLabels,
101
+ [MCP_ATTRS.OUTPUT_SIZE]: analysis.outputSize,
102
+ });
103
+ }
104
+ }, { [HOOK_TYPE_ATTR]: 'mcp' });
105
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Shared outcome reporting for PostToolUse handlers.
3
+ * Both builtin and MCP run the same sequence — emitToolCorrectness, log, completions
4
+ * metric, output-size metric — keyed on different attribute and metric names.
5
+ * Imported by post-tool.ts and post-tool-mcp.ts; not used elsewhere.
6
+ */
7
+ import { UNITS } from '../lib/core/units.js';
8
+ import { UNKNOWN_ERROR_TYPE } from '../lib/otel/attributes.js';
9
+ import { emitToolCorrectness } from '../lib/quality/quality-signals.js';
10
+ /**
11
+ * Returns the SUCCESS/OUTPUT_SIZE/HAS_ERROR/ERROR_TYPE/ERROR_CATEGORY fragment
12
+ * for the calling handler's key schema. Spread this into ctx.addAttributes alongside
13
+ * handler-specific keys.
14
+ */
15
+ export function outcomeSpanAttributes(analysis, keys) {
16
+ return {
17
+ [keys.successAttr]: !analysis.hasError,
18
+ [keys.outputSizeAttr]: analysis.outputSize,
19
+ [keys.hasErrorAttr]: analysis.hasError,
20
+ ...(analysis.errorType ? { [keys.errorTypeAttr]: analysis.errorType } : {}),
21
+ ...(analysis.errorCategory ? { [keys.errorCategoryAttr]: analysis.errorCategory } : {}),
22
+ };
23
+ }
24
+ /**
25
+ * Runs the shared post-tool outcome sequence: emitToolCorrectness, warn/recordException
26
+ * or info, completions metric, output-size metric. Handler-specific extras (error metrics,
27
+ * completeness records, stderr) run in the caller after this returns.
28
+ */
29
+ export function recordOutcome(ctx, analysis, keys, report) {
30
+ emitToolCorrectness(!analysis.hasError, report.toolName, report.sessionId);
31
+ if (analysis.hasError) {
32
+ const errorType = analysis.errorType ?? UNKNOWN_ERROR_TYPE;
33
+ ctx.logger.warn(report.errorMessage, {
34
+ ...report.logLabels,
35
+ [keys.errorTypeAttr]: errorType,
36
+ ...(report.errorLogExtras ?? {}),
37
+ });
38
+ ctx.span.recordException(new Error(report.exceptionMessage));
39
+ }
40
+ else {
41
+ ctx.logger.info(report.successMessage, { ...report.logLabels, [keys.outputSizeAttr]: analysis.outputSize });
42
+ }
43
+ ctx.recordMetric(keys.completionsMetric, 1, {
44
+ ...report.metricLabels,
45
+ [keys.successAttr]: String(!analysis.hasError),
46
+ }, { unit: UNITS.COMPLETION });
47
+ ctx.recordMetric(keys.outputSizeMetric, analysis.outputSize, report.metricLabels, { unit: UNITS.BYTE });
48
+ }
@@ -0,0 +1,74 @@
1
+ /** TaskCreate / TaskUpdate: status transitions on the span, task state persisted to survive compaction (PT3). */
2
+ import { TASK_TOOLS } from '../lib/core/constants.js';
3
+ import { isJsonObject } from '../lib/core/file-utils.js';
4
+ import { UNITS } from '../lib/core/units.js';
5
+ import { HOOK_NAMES, HOOK_TYPE_ATTR, SESSION_ATTRIBUTES, TASK_ATTRS } from '../lib/otel/attributes.js';
6
+ import { instrumentHook } from '../lib/otel/otel-monitor.js';
7
+ import { getStringField } from '../lib/runtime/tool-input.js';
8
+ import { resolveOutputText } from '../lib/runtime/tool-output.js';
9
+ import { upsertTask, loadTaskState, isTaskStatus, createdTaskId } from '../lib/session/task-tracker.js';
10
+ const PERSISTENCE_FAILURES_METRIC = 'integritystudio.task.persistence_failures';
11
+ const DEFAULT_CREATE_STATUS = 'pending';
12
+ const RESPONSE_SUCCESS_FIELD = 'success';
13
+ function resolveExplicitStatus(input) {
14
+ const status = getStringField(input, 'status');
15
+ if (isTaskStatus(status))
16
+ return status;
17
+ return input.tool_name === TASK_TOOLS.CREATE ? DEFAULT_CREATE_STATUS : undefined;
18
+ }
19
+ function recordTaskStatus(ctx, resolvedStatus, sessionId, taskId) {
20
+ if (resolvedStatus) {
21
+ ctx.addAttribute(TASK_ATTRS.STATUS, resolvedStatus);
22
+ return;
23
+ }
24
+ if (!taskId)
25
+ return;
26
+ const task = loadTaskState(sessionId)?.tasks.find(t => t.id === taskId);
27
+ if (task) {
28
+ ctx.addAttribute(TASK_ATTRS.STATUS, task.status);
29
+ }
30
+ }
31
+ /** A task tool reports its own failure ("Task not found") as `success: false` on PostToolUse, not as PostToolUseFailure. */
32
+ function reportsFailure(toolResponse) {
33
+ return isJsonObject(toolResponse) && toolResponse[RESPONSE_SUCCESS_FIELD] === false;
34
+ }
35
+ function persistTask(ctx, input, taskId, status) {
36
+ // TaskCreate's id is only in its result; later TaskUpdates use it.
37
+ let resolvedId = taskId;
38
+ if (!resolvedId && input.tool_name === TASK_TOOLS.CREATE) {
39
+ resolvedId = createdTaskId(input.tool_response, resolveOutputText(input));
40
+ }
41
+ if (!resolvedId)
42
+ return;
43
+ const subject = getStringField(input, 'subject') ?? '';
44
+ const now = new Date().toISOString();
45
+ const ok = upsertTask(input.session_id, {
46
+ id: resolvedId,
47
+ name: subject,
48
+ status,
49
+ createdAt: now,
50
+ updatedAt: now,
51
+ });
52
+ if (ok)
53
+ return;
54
+ const failureAttributes = {
55
+ [SESSION_ATTRIBUTES.SESSION_ID]: input.session_id,
56
+ [TASK_ATTRS.ID]: resolvedId,
57
+ };
58
+ ctx.logger.error('Failed to persist task state', failureAttributes);
59
+ ctx.recordMetric(PERSISTENCE_FAILURES_METRIC, 1, failureAttributes, { unit: UNITS.FAILURE });
60
+ }
61
+ /** Unguarded: the `post-tool.ts` router calls this only for `TASK_STATE_TOOLS`. */
62
+ export async function handleTaskState(input) {
63
+ await instrumentHook(HOOK_NAMES.TASK_STATE, (ctx) => {
64
+ const taskId = getStringField(input, 'taskId')?.trim() ?? '';
65
+ const resolvedStatus = resolveExplicitStatus(input);
66
+ recordTaskStatus(ctx, resolvedStatus, input.session_id, taskId);
67
+ if (taskId) {
68
+ ctx.addAttribute(TASK_ATTRS.ID, taskId);
69
+ }
70
+ if (resolvedStatus !== undefined && !reportsFailure(input.tool_response)) {
71
+ persistTask(ctx, input, taskId, resolvedStatus);
72
+ }
73
+ }, { [HOOK_TYPE_ATTR]: 'task-state' });
74
+ }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * PostToolUse router. Per-concern handlers are the sibling `post-tool-*.ts`
3
+ * modules, loaded lazily so builtin events never pay for their imports (HSF27).
4
+ */
5
+ import { EDIT_TOOLS, CHANGELOG_DIR_SEGMENT, MCP_RESOURCE_TOOLS, TASK_STATE_TOOLS } from '../lib/core/constants.js';
6
+ import { writeStderr } from '../lib/core/format-utils.js';
7
+ import { parseSkillName, pluginLabelsOf } from '../lib/core/parsers.js';
8
+ import { UNITS } from '../lib/core/units.js';
9
+ import { ERROR_TYPE_ATTR, GENAI_TOOL_NAME_ATTR, HOOK_TYPE_ATTR, TOOL_ATTRS, HOOK_NAMES, FILE_PATH_ATTR, UNKNOWN_ERROR_TYPE } from '../lib/otel/attributes.js';
10
+ import { instrumentHook } from '../lib/otel/otel-monitor.js';
11
+ import { builtinToolLabels } from '../lib/runtime/categorizers.js';
12
+ import { analyzeBuiltinOutput } from '../lib/runtime/output-analyzer.js';
13
+ import { lazy, runHandlers } from '../lib/runtime/run-handlers.js';
14
+ import { getStringField, getTargetPath, mayRunGitCommit, toolWorkingDirectory } from '../lib/runtime/tool-input.js';
15
+ import { resolveOutputText } from '../lib/runtime/tool-output.js';
16
+ import { outcomeSpanAttributes, recordOutcome } from './post-tool-outcome.js';
17
+ import { routeToolEvent } from './tool-event-router.js';
18
+ const handleMcpPostTool = lazy(async () => (await import('./post-tool-mcp.js')).handleMcpPostTool);
19
+ const handleAgentPostTool = lazy(async () => (await import('./post-tool-agent.js')).handleAgentPostTool);
20
+ const handleMcpStatus = lazy(async () => (await import('./mcp-status.js')).handleMcpStatus);
21
+ const handleChangelogVersionBump = lazy(async () => (await import('./post-tool-changelog-sync.js')).handleChangelogVersionBump);
22
+ const handleCodeStructure = lazy(async () => (await import('./post-tool-code-structure.js')).handleCodeStructure);
23
+ const handleTaskState = lazy(async () => (await import('./post-tool-task-state.js')).handleTaskState);
24
+ const handlePostCommitReview = lazy(async () => (await import('./post-tool-git.js')).handlePostCommitReview);
25
+ const handleEditLedger = lazy(async () => (await import('./post-tool-edit-ledger.js')).handleEditLedger);
26
+ // ==================== Plugin Post-Tool ====================
27
+ async function handlePluginPostTool(input) {
28
+ const skillName = getStringField(input, 'skill');
29
+ if (!skillName)
30
+ return;
31
+ await instrumentHook(HOOK_NAMES.PLUGIN_POST_TOOL, (ctx) => {
32
+ const outputSize = resolveOutputText(input).length;
33
+ const labels = pluginLabelsOf(parseSkillName(skillName));
34
+ const attrs = { ...labels, 'integritystudio.plugin.output_size': outputSize };
35
+ ctx.addAttributes(attrs);
36
+ ctx.logger.info('Plugin completed', attrs);
37
+ ctx.recordMetric('integritystudio.plugin.completions', 1, labels, { unit: UNITS.COMPLETION });
38
+ ctx.recordMetric('integritystudio.plugin.output_size', outputSize, labels, { unit: UNITS.BYTE });
39
+ writeStderr(`[Plugin] ${skillName} completed`);
40
+ }, { [HOOK_TYPE_ATTR]: 'plugin' });
41
+ }
42
+ const BUILTIN_OUTCOME_KEYS = {
43
+ successAttr: TOOL_ATTRS.SUCCESS,
44
+ outputSizeAttr: TOOL_ATTRS.OUTPUT_SIZE,
45
+ hasErrorAttr: TOOL_ATTRS.HAS_ERROR,
46
+ errorTypeAttr: TOOL_ATTRS.ERROR_TYPE,
47
+ errorCategoryAttr: TOOL_ATTRS.ERROR_CATEGORY,
48
+ completionsMetric: 'integritystudio.tool.completions',
49
+ outputSizeMetric: TOOL_ATTRS.OUTPUT_SIZE,
50
+ };
51
+ // ==================== Built-in Tool Post-Tool ====================
52
+ async function handleBuiltinPostTool(input) {
53
+ const toolName = input.tool_name;
54
+ await instrumentHook(HOOK_NAMES.BUILTIN_POST_TOOL, (ctx) => {
55
+ const sessionId = input.session_id;
56
+ const outputText = resolveOutputText(input);
57
+ const analysis = analyzeBuiltinOutput(toolName, outputText);
58
+ const labels = builtinToolLabels(toolName);
59
+ const filePath = getTargetPath(input.tool_input);
60
+ const workingDirectory = toolWorkingDirectory(input);
61
+ ctx.addAttributes({
62
+ ...labels,
63
+ ...outcomeSpanAttributes(analysis, BUILTIN_OUTCOME_KEYS),
64
+ ...(filePath ? { [FILE_PATH_ATTR]: filePath } : {}),
65
+ // Where a Bash write landed: its spans name no file, so consumers find its changes from this directory's repo.
66
+ ...(workingDirectory ? { [TOOL_ATTRS.WORKING_DIRECTORY]: workingDirectory } : {}),
67
+ ...(analysis.resultCount !== undefined ? { [TOOL_ATTRS.RESULT_COUNT]: analysis.resultCount } : {}),
68
+ });
69
+ recordOutcome(ctx, analysis, BUILTIN_OUTCOME_KEYS, {
70
+ toolName,
71
+ sessionId,
72
+ logLabels: labels,
73
+ metricLabels: labels,
74
+ successMessage: 'Built-in tool completed',
75
+ errorMessage: 'Built-in tool returned error',
76
+ exceptionMessage: `${toolName}: ${analysis.errorType ?? UNKNOWN_ERROR_TYPE}`,
77
+ });
78
+ if (analysis.hasError) {
79
+ ctx.recordMetric('integritystudio.tool.errors', 1, {
80
+ ...labels,
81
+ [ERROR_TYPE_ATTR]: analysis.errorType ?? UNKNOWN_ERROR_TYPE,
82
+ }, { unit: UNITS.ERROR });
83
+ }
84
+ if (analysis.resultCount !== undefined) {
85
+ ctx.recordMetric(TOOL_ATTRS.RESULT_COUNT, analysis.resultCount, {
86
+ [GENAI_TOOL_NAME_ATTR]: toolName,
87
+ }, { unit: UNITS.RESULT });
88
+ }
89
+ }, { [HOOK_TYPE_ATTR]: 'builtin' });
90
+ }
91
+ /** Resolve the commit once and fan out only when one landed (HSF11); a Bash-group member so its git spawns overlap the builtin handler. */
92
+ async function handlePostCommit(input) {
93
+ if (!mayRunGitCommit(input))
94
+ return;
95
+ const { resolveCommitEvent } = await import('../lib/git/git-commit.js');
96
+ const commit = await resolveCommitEvent(input);
97
+ if (!commit)
98
+ return;
99
+ await handlePostCommitReview(input, commit);
100
+ }
101
+ // ==================== Main Handler ====================
102
+ /** The changelog bump as a spreadable zero- or one-element handler list: both routes need the segment in their path or command, and most events carry neither. */
103
+ function changelogBumpWhen(input, pathOrCommand) {
104
+ return pathOrCommand?.includes(CHANGELOG_DIR_SEGMENT) ? [handleChangelogVersionBump(input)] : [];
105
+ }
106
+ /** The handler group for a builtin tool; the builtin handler alone when no group claims it. */
107
+ async function runBuiltinToolGroup(input, toolName) {
108
+ if (MCP_RESOURCE_TOOLS.has(toolName)) {
109
+ await runHandlers('McpResource', handleBuiltinPostTool(input), handleMcpStatus(input));
110
+ }
111
+ else if (EDIT_TOOLS.has(toolName)) {
112
+ const isWrite = toolName === 'Write';
113
+ await runHandlers(isWrite ? 'Write' : 'Edit', handleBuiltinPostTool(input), handleCodeStructure(input), ...changelogBumpWhen(input, isWrite ? getStringField(input, 'file_path') : undefined), handleEditLedger(input));
114
+ }
115
+ else if (toolName === 'Bash') {
116
+ await runHandlers('Bash', handleBuiltinPostTool(input), handlePostCommit(input), ...changelogBumpWhen(input, getStringField(input, 'command')));
117
+ }
118
+ else if (TASK_STATE_TOOLS.has(toolName)) {
119
+ await runHandlers('Task', handleBuiltinPostTool(input), handleTaskState(input));
120
+ }
121
+ else {
122
+ await handleBuiltinPostTool(input);
123
+ }
124
+ }
125
+ export async function handlePostTool(input, subType) {
126
+ await routeToolEvent(input, subType, {
127
+ mcp: () => runHandlers('Mcp', handleMcpPostTool(input), handleMcpStatus(input)),
128
+ plugin: () => handlePluginPostTool(input),
129
+ agent: () => handleAgentPostTool(input),
130
+ builtin: () => runBuiltinToolGroup(input, input.tool_name),
131
+ });
132
+ }
@@ -0,0 +1,192 @@
1
+ /** Agent PreToolUse: scope guards and invocation instrumentation; lazy-loaded by the router so main-loop builtin events never pay for its imports (HSF27). Subagent events with agent_type still load this module on first call. */
2
+ import { savePendingAgent, generateHex } from '../lib/agent/agent-context.js';
3
+ import { getAgentSourceType, agentInvocationAttributes } from '../lib/agent/agent-sources.js';
4
+ import { AGENT_TOOLS, ELLIPSIS, EDIT_TOOLS, THRESHOLDS, SPAN_ID_BYTES, TRACE_ID_BYTES, } from '../lib/core/constants.js';
5
+ import { truncate, writeStderr } from '../lib/core/format-utils.js';
6
+ import { estimateTokenCount, UNITS } from '../lib/core/units.js';
7
+ import { AGENT_ATTRS, AGENT_LINK_ATTRIBUTES, AGENT_LINK_KIND_DISPATCH, HOOK_NAMES, HOOK_TYPE_ATTR, HOOK_INSTRUMENTATION_ATTR, HOOK_INSTRUMENTATION_INTERNAL, } from '../lib/otel/attributes.js';
8
+ import { instrumentHook } from '../lib/otel/otel-monitor.js';
9
+ import { otelApi } from '../lib/otel/otel.js';
10
+ import { agentTypeLabels } from '../lib/runtime/categorizers.js';
11
+ import { denyToolUse } from '../lib/runtime/hook-output.js';
12
+ import { getStringField, getTargetPath, spawnedAgentType } from '../lib/runtime/tool-input.js';
13
+ // ==================== Agent Scope Guards (AA1d / AA1e / AA1g) ====================
14
+ /** The only subagent web-research-analyst may spawn (AA1e). */
15
+ const WEB_RESEARCH_ALLOWED_SUBAGENT = 'haiku-extractor';
16
+ /** genai-quality-monitor write/publish tools — gated behind explicit user request (AA1e). */
17
+ const GENAI_MONITOR_WRITE_TOOLS = new Set([
18
+ 'mcp__observability-toolkit__obs_manage_datasets',
19
+ 'mcp__observability-toolkit__obs_inject_evaluations',
20
+ 'mcp__observability-toolkit__obs_export_langfuse',
21
+ 'mcp__observability-toolkit__obs_export_phoenix',
22
+ 'mcp__observability-toolkit__obs_export_datadog',
23
+ 'mcp__observability-toolkit__obs_export_confident',
24
+ ]);
25
+ /** agents/*.md, lazy-agents/*.md or skills/*\/agents/*.md, never SKILL.md. */
26
+ function isAgentManifestPath(filePath) {
27
+ return !filePath.endsWith('SKILL.md') && /(?:^|\/)(?:lazy-)?agents\/[^/]+\.md$/.test(filePath);
28
+ }
29
+ /** Per-agent write, MCP and spawn rules (HSF28). Adding a scoped agent is one entry here. */
30
+ const AGENT_SCOPE_RULES = {
31
+ 'telemetry-backfill': {
32
+ check: ({ toolName, isWrite }) => {
33
+ if (!isWrite)
34
+ return undefined;
35
+ return (`[Guard AA1e] telemetry-backfill must write only via the backfill script through Bash. ` +
36
+ `Direct ${toolName} calls are not permitted. Use Bash to invoke the backfill script instead.`);
37
+ },
38
+ },
39
+ 'agent-auditor': {
40
+ check: ({ isWrite, filePath }) => {
41
+ if (!isWrite || !filePath.endsWith('SKILL.md'))
42
+ return undefined;
43
+ return '[Guard AA1e] agent-auditor may not write SKILL.md files — those belong to skill-auditor.';
44
+ },
45
+ },
46
+ 'skill-auditor': {
47
+ check: ({ isWrite, filePath }) => {
48
+ if (!isWrite || !isAgentManifestPath(filePath))
49
+ return undefined;
50
+ return '[Guard AA1e] skill-auditor may not write agent manifests — those belong to agent-auditor.';
51
+ },
52
+ },
53
+ 'genai-quality-monitor': {
54
+ check: ({ toolName }) => {
55
+ if (!GENAI_MONITOR_WRITE_TOOLS.has(toolName))
56
+ return undefined;
57
+ return (`[Guard AA1e] genai-quality-monitor is read-only by default. ` +
58
+ `${toolName} requires an explicit user request naming the destination, ` +
59
+ `not a side effect of analysis. Surface the intended write/export to the user for approval.`);
60
+ },
61
+ },
62
+ 'auto-error-resolver': {
63
+ // AA1g: distinct-file budget per fix; fails open on I/O errors.
64
+ check: async ({ isWrite, filePath, sessionId }) => {
65
+ if (!isWrite || !filePath)
66
+ return undefined;
67
+ const { checkAndRecordFilePath, AUTO_ERROR_RESOLVER_FILE_BUDGET } = await import('../lib/agent/agent-file-budget.js');
68
+ const { allowed, count } = checkAndRecordFilePath(sessionId, 'auto-error-resolver', filePath, AUTO_ERROR_RESOLVER_FILE_BUDGET);
69
+ if (!allowed) {
70
+ return (`[Guard AA1g] auto-error-resolver may write at most ${AUTO_ERROR_RESOLVER_FILE_BUDGET} distinct files per fix. ` +
71
+ `${count} files already written this invocation. ` +
72
+ `Propose remaining changes as a diff and halt for user approval.`);
73
+ }
74
+ return undefined;
75
+ },
76
+ // AA1g: a previous invocation's count must not carry into the next.
77
+ onSpawn: async (sessionId) => {
78
+ const { resetAgentFileBudget } = await import('../lib/agent/agent-file-budget.js');
79
+ resetAgentFileBudget(sessionId, 'auto-error-resolver');
80
+ },
81
+ },
82
+ 'multi-agent-orchestrator': {
83
+ check: ({ spawnTarget }) => {
84
+ if (spawnTarget !== 'multi-agent-orchestrator')
85
+ return undefined;
86
+ return ('[Guard] multi-agent-orchestrator cannot invoke itself recursively (no-recursion rule, AA1d). ' +
87
+ 'Route sub-tasks to a specialist agent or handle them directly.');
88
+ },
89
+ },
90
+ 'web-research-analyst': {
91
+ check: ({ toolName, spawnTarget }) => {
92
+ if (!AGENT_TOOLS.has(toolName) || spawnTarget === WEB_RESEARCH_ALLOWED_SUBAGENT)
93
+ return undefined;
94
+ return (`[Guard AA1e] web-research-analyst may only spawn ${WEB_RESEARCH_ALLOWED_SUBAGENT} (attempted: ${spawnTarget ?? '(none)'}). ` +
95
+ `Route sub-tasks through ${WEB_RESEARCH_ALLOWED_SUBAGENT} or handle them directly (AA1e).`);
96
+ },
97
+ },
98
+ };
99
+ const scopeRuleFor = (agentType) => Object.hasOwn(AGENT_SCOPE_RULES, agentType) ? AGENT_SCOPE_RULES[agentType] : undefined;
100
+ /** Per-agent scope guards (AA1d / AA1e / AA1g). A missing agent_type is the main loop, so no denial can fire. */
101
+ export async function handleAgentScopeGuards(input) {
102
+ const agentType = input.agent_type;
103
+ if (!agentType)
104
+ return;
105
+ const rule = scopeRuleFor(agentType);
106
+ if (!rule)
107
+ return;
108
+ const toolName = input.tool_name;
109
+ const isWrite = EDIT_TOOLS.has(toolName);
110
+ const filePath = getTargetPath(input.tool_input) ?? '';
111
+ const spawnTarget = spawnedAgentType(input);
112
+ const sessionId = input.session_id;
113
+ const call = { toolName, isWrite, filePath, spawnTarget, sessionId };
114
+ const denial = await rule.check?.(call);
115
+ if (denial) {
116
+ denyToolUse(denial);
117
+ }
118
+ }
119
+ // ==================== Agent Pre-Tool ====================
120
+ /** Metric label for an Agent call that names no model override. Never a span attribute. */
121
+ const DEFAULT_MODEL_LABEL = 'default';
122
+ /** Link back to the dispatching span (OBP6); empty when OTel is inactive, since the all-zero context must not become a link target. */
123
+ function dispatchLinkField(spanContext) {
124
+ if (!otelApi.trace.isSpanContextValid(spanContext))
125
+ return {};
126
+ const link = {
127
+ traceId: spanContext.traceId,
128
+ spanId: spanContext.spanId,
129
+ traceFlags: spanContext.traceFlags,
130
+ attributes: { [AGENT_LINK_ATTRIBUTES.LINK_KIND]: AGENT_LINK_KIND_DISPATCH },
131
+ };
132
+ return { dispatchLink: link };
133
+ }
134
+ export async function handleAgentPreTool(input) {
135
+ const agentType = spawnedAgentType(input);
136
+ if (!agentType)
137
+ return;
138
+ await scopeRuleFor(agentType)?.onSpawn?.(input.session_id);
139
+ // Internal instrumentation; the GenAI-conformant span is post-tool-agent's synthetic invoke_agent (OBP6).
140
+ await instrumentHook(HOOK_NAMES.AGENT_PREPARE, (ctx) => {
141
+ const prompt = getStringField(input, 'prompt');
142
+ const agentInfo = getAgentSourceType(agentType);
143
+ const sessionId = input.session_id;
144
+ const promptLength = prompt?.length ?? 0;
145
+ // Shared with the synthetic invoke_agent span; no `gen_ai.operation.name` (OBP6).
146
+ const { attrs: agentAttrs, description, requestedModel, isResume, isBackground } = agentInvocationAttributes(agentType, agentInfo, input.tool_input ?? {});
147
+ const agentLabels = { ...agentTypeLabels(agentType), [AGENT_ATTRS.SOURCE_TYPE]: agentInfo.sourceType };
148
+ ctx.addAttributes({
149
+ ...agentAttrs,
150
+ ...agentLabels,
151
+ 'integritystudio.agent.has_prompt': !!prompt,
152
+ 'integritystudio.agent.prompt_length': promptLength,
153
+ });
154
+ ctx.logger.info('Agent invoked', {
155
+ ...agentLabels,
156
+ [AGENT_ATTRS.IS_RESUME]: isResume,
157
+ [AGENT_ATTRS.IS_BACKGROUND]: isBackground,
158
+ });
159
+ ctx.recordMetric('integritystudio.agent.invocations', 1, {
160
+ ...agentLabels,
161
+ [AGENT_ATTRS.REQUESTED_MODEL]: requestedModel || DEFAULT_MODEL_LABEL,
162
+ [AGENT_ATTRS.IS_RESUME]: String(isResume),
163
+ [AGENT_ATTRS.IS_BACKGROUND]: String(isBackground),
164
+ }, { unit: UNITS.INVOCATION });
165
+ const estimatedInputTokens = estimateTokenCount(promptLength);
166
+ // Not `gen_ai.usage.input_tokens`: a same-named metric shadows real client usage.
167
+ ctx.recordMetric('integritystudio.agent.estimated_input_tokens', estimatedInputTokens, { [AGENT_ATTRS.TYPE]: agentType }, { unit: UNITS.TOKEN });
168
+ // Persisted for the post-tool process, which closes the invocation (agent-context.ts).
169
+ // The store keeps createSpanId only on the agent's first invocation per session.
170
+ const createSpanId = generateHex(SPAN_ID_BYTES);
171
+ const invokeSpanId = generateHex(SPAN_ID_BYTES);
172
+ savePendingAgent({
173
+ sessionId,
174
+ agentName: agentType,
175
+ startTimeMs: Date.now(),
176
+ traceId: generateHex(TRACE_ID_BYTES),
177
+ invokeSpanId,
178
+ createSpanId,
179
+ isBackground,
180
+ ...(input.tool_use_id ? { toolUseId: input.tool_use_id } : {}),
181
+ ...dispatchLinkField(ctx.span.spanContext()),
182
+ });
183
+ ctx.addAttribute(AGENT_ATTRS.INVOCATION_ID, invokeSpanId);
184
+ const modelIndicator = requestedModel ? ` @${requestedModel}` : '';
185
+ const bgIndicator = isBackground ? ' (background)' : '';
186
+ const resumeIndicator = isResume ? ' [resume]' : '';
187
+ writeStderr(`[Agent] ${agentType}${modelIndicator}${bgIndicator}${resumeIndicator} [${agentLabels[AGENT_ATTRS.CATEGORY]}] (${agentInfo.sourceType})`);
188
+ if (description) {
189
+ writeStderr(` ${truncate(description, THRESHOLDS.AGENT_TASK_DESCRIPTION_TRUNCATE, ELLIPSIS)}`);
190
+ }
191
+ }, { [HOOK_TYPE_ATTR]: 'agent', [HOOK_INSTRUMENTATION_ATTR]: HOOK_INSTRUMENTATION_INTERNAL });
192
+ }