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,158 @@
1
+ /**
2
+ * On-disk cache of per-cwd git facts at TELEMETRY_DIR/.git-cache/<sha256(cwd)[0..16]>.json,
3
+ * shared by every hook process; pruned from the shipper's detached process.
4
+ */
5
+ import { createHash } from 'node:crypto';
6
+ import * as fs from 'node:fs';
7
+ import * as path from 'node:path';
8
+ import { settledValue } from '../core/child-result.js';
9
+ import { TELEMETRY_DIR, THRESHOLDS, GIT_TIMEOUT_MS } from '../core/constants.js';
10
+ import { loadJson, pruneOldFiles, readTextOrNull, writeJson } from '../core/file-utils.js';
11
+ import { countNonEmptyLines } from '../core/format-utils.js';
12
+ import { DURATION_MS, TIME_MS } from '../core/units.js';
13
+ import { git, gitSync, REMOTE_URL_ARGS } from './git-exec.js';
14
+ /** The remote URL changes only on `git remote set-url`. */
15
+ export const GIT_REMOTE_CACHE_TTL_MS = TIME_MS.WEEK;
16
+ export const GIT_BRANCH_CACHE_TTL_MS = DURATION_MS.FIVE_MINUTES;
17
+ const GIT_CACHE_DIRNAME = '.git-cache';
18
+ const GIT_CACHE_EXTENSION = '.json';
19
+ const CACHE_KEY_HEX_CHARS = 16;
20
+ const GIT_DISK_CACHE_DIR = path.join(TELEMETRY_DIR, GIT_CACHE_DIRNAME);
21
+ export function cwdToCacheKey(cwd) {
22
+ return createHash('sha256').update(cwd).digest('hex').slice(0, CACHE_KEY_HEX_CHARS);
23
+ }
24
+ export function diskGitCachePath(cwd, dir = GIT_DISK_CACHE_DIR) {
25
+ return path.join(dir, `${cwdToCacheKey(cwd)}${GIT_CACHE_EXTENSION}`);
26
+ }
27
+ export function pruneGitCache(telemetryDir) {
28
+ pruneOldFiles(path.join(telemetryDir, GIT_CACHE_DIRNAME), GIT_REMOTE_CACHE_TTL_MS, {
29
+ extension: GIT_CACHE_EXTENSION,
30
+ });
31
+ }
32
+ export function readDiskGitCache(cwd, dir = GIT_DISK_CACHE_DIR) {
33
+ return loadJson(diskGitCachePath(cwd, dir));
34
+ }
35
+ export function writeDiskGitCache(cwd, entry, dir = GIT_DISK_CACHE_DIR) {
36
+ writeJson(diskGitCachePath(cwd, dir), entry, false, { silent: true });
37
+ }
38
+ const HEAD_REF_PREFIX = 'ref: refs/heads/';
39
+ /** `.git` as a file (worktree or submodule) points at the real git dir. */
40
+ const GITDIR_PREFIX = 'gitdir:';
41
+ /** The checkout's git dir, spawn-free: `.git` itself, or the directory its pointer file names. Undefined when `.git` is missing or the pointer is malformed. */
42
+ export function resolveGitDir(repoRoot) {
43
+ const dotGit = path.join(repoRoot, '.git');
44
+ try {
45
+ if (!fs.statSync(dotGit).isFile())
46
+ return dotGit;
47
+ const pointer = fs.readFileSync(dotGit, 'utf8').trim();
48
+ if (!pointer.startsWith(GITDIR_PREFIX))
49
+ return undefined;
50
+ return path.resolve(repoRoot, pointer.slice(GITDIR_PREFIX.length).trim());
51
+ }
52
+ catch {
53
+ return undefined;
54
+ }
55
+ }
56
+ /** Uncached and spawn-free: the GCS2 branch guard needs a fresh read, and a stale hit would manufacture the mismatch it detects. Undefined when detached or not a repo. */
57
+ export function readHeadBranch(dir) {
58
+ const gitDir = resolveGitDir(dir);
59
+ if (!gitDir)
60
+ return undefined;
61
+ const head = readTextOrNull(path.join(gitDir, 'HEAD'))?.trim();
62
+ return head?.startsWith(HEAD_REF_PREFIX) ? head.slice(HEAD_REF_PREFIX.length) : undefined;
63
+ }
64
+ /** `https://host/owner/repo[.git]` or `git@host:owner/repo[.git]`. */
65
+ export function parseRepoFromRemoteUrl(remoteUrl) {
66
+ return remoteUrl.trim().match(/[:/]([^/]+\/[^/]+?)(?:\.git)?$/)?.[1] ?? null;
67
+ }
68
+ /** `vcs.repository.name` must not include the owner. */
69
+ export function splitOwnerRepo(ownerRepo) {
70
+ const slash = ownerRepo.indexOf('/');
71
+ return slash < 0 ? { name: ownerRepo } : { owner: ownerRepo.slice(0, slash), name: ownerRepo.slice(slash + 1) };
72
+ }
73
+ export function freshRepository(disk, now) {
74
+ if (!disk)
75
+ return { hit: false };
76
+ if (disk.repository && now - disk.repository.ts < GIT_REMOTE_CACHE_TTL_MS) {
77
+ return { hit: true, value: disk.repository.value };
78
+ }
79
+ if (disk.repositoryMissing && now - disk.repositoryMissing.ts < THRESHOLDS.GIT_REMOTE_MISS_TTL_MS) {
80
+ return { hit: true, value: null };
81
+ }
82
+ return { hit: false };
83
+ }
84
+ /** Merges into `entry`, which `probeGitStatus` also fills with the branch fields. Writing one repository field clears the other, so a gained or lost remote leaves no stale marker. */
85
+ export function withRepository(entry, value, now) {
86
+ const rest = { ...entry };
87
+ delete rest.repository;
88
+ delete rest.repositoryMissing;
89
+ return value !== null
90
+ ? { ...rest, repository: { value, ts: now } }
91
+ : { ...rest, repositoryMissing: { ts: now } };
92
+ }
93
+ function toGitStatus(branch, uncommitted, repository) {
94
+ return { branch, uncommitted, ...(repository !== null ? { repository } : {}) };
95
+ }
96
+ /** An empty branch is the cached negative (not a repo). */
97
+ function gitStatusFromCache(disk, cachedRepo) {
98
+ const branch = disk.branch?.value;
99
+ if (!branch)
100
+ return null;
101
+ return toGitStatus(branch, disk.uncommitted?.value ?? 0, cachedRepo.hit ? cachedRepo.value : null);
102
+ }
103
+ async function runGitProbe(cwd, fetchRemote, timeoutMs) {
104
+ const [branchResult, statusResult, remoteResult] = await Promise.allSettled([
105
+ git(cwd, ['branch', '--show-current'], timeoutMs),
106
+ git(cwd, ['status', '--porcelain', '--untracked-files=no'], timeoutMs),
107
+ fetchRemote ? git(cwd, REMOTE_URL_ARGS, timeoutMs) : Promise.resolve(undefined),
108
+ ]);
109
+ const remoteUrl = settledValue(remoteResult);
110
+ return {
111
+ branch: settledValue(branchResult)?.trim() || undefined,
112
+ uncommitted: countNonEmptyLines(settledValue(statusResult) ?? ''),
113
+ repository: remoteUrl ? parseRepoFromRemoteUrl(remoteUrl) : null,
114
+ };
115
+ }
116
+ /** Null outside a repo or on a detached HEAD. `uncommitted` counts tracked changes only (HP1). */
117
+ export async function probeGitStatus(cwd, timeoutMs, now = Date.now(), dir = GIT_DISK_CACHE_DIR) {
118
+ const disk = readDiskGitCache(cwd, dir) ?? {};
119
+ const cachedRepo = freshRepository(disk, now);
120
+ if (disk.branch && now - disk.branch.ts < GIT_BRANCH_CACHE_TTL_MS) {
121
+ return gitStatusFromCache(disk, cachedRepo);
122
+ }
123
+ const { branch, uncommitted, repository: probedRepository } = await runGitProbe(cwd, !cachedRepo.hit, timeoutMs);
124
+ if (!branch) {
125
+ writeDiskGitCache(cwd, { ...disk, branch: { value: '', ts: now } }, dir);
126
+ return null;
127
+ }
128
+ const withStatus = {
129
+ ...disk,
130
+ branch: { value: branch, ts: now },
131
+ uncommitted: { value: uncommitted, ts: now },
132
+ };
133
+ const repository = cachedRepo.hit ? cachedRepo.value : probedRepository;
134
+ writeDiskGitCache(cwd, cachedRepo.hit ? withStatus : withRepository(withStatus, repository, now), dir);
135
+ return toGitStatus(branch, uncommitted, repository);
136
+ }
137
+ /** "owner/repo" or null, from the disk cache first: the uncached spawn was ~12% of a hook. Misses are cached too, on the shorter TTL. */
138
+ export function getGitHubRepo(cwd = process.cwd(), now = Date.now(), dir = GIT_DISK_CACHE_DIR) {
139
+ const disk = readDiskGitCache(cwd, dir);
140
+ const cached = freshRepository(disk, now);
141
+ if (cached.hit)
142
+ return cached.value;
143
+ let repo;
144
+ try {
145
+ const remoteUrl = gitSync(cwd, REMOTE_URL_ARGS, GIT_TIMEOUT_MS.REMOTE_PROBE);
146
+ repo = parseRepoFromRemoteUrl(remoteUrl);
147
+ }
148
+ catch {
149
+ repo = null;
150
+ }
151
+ try {
152
+ writeDiskGitCache(cwd, withRepository(disk ?? {}, repo, now), dir);
153
+ }
154
+ catch {
155
+ // A failed cache write costs a re-fetch next event, nothing more.
156
+ }
157
+ return repo;
158
+ }
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Did a Bash `git commit` land, and which files did it touch (HSF11). A quiet
3
+ * commit is detected against the HEAD PreToolUse snapshotted before the command
4
+ * (HSF10): "did this command move HEAD", not "did HEAD move recently".
5
+ */
6
+ import { createHash } from 'node:crypto';
7
+ import { rmSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ import { classifyExecError } from '../core/child-result.js';
10
+ import { GIT_COMMIT_SUBCOMMAND, GIT_TIMEOUT_MS } from '../core/constants.js';
11
+ import { loadJson, writeJsonAtomic } from '../core/file-utils.js';
12
+ import { commandInvocations, isOptionArg, programOf } from '../core/shell-command.js';
13
+ import { getStringField } from '../runtime/tool-input.js';
14
+ import { resolveOutputText } from '../runtime/tool-output.js';
15
+ import { sessionStateDir } from '../session/session-state.js';
16
+ import { git } from './git-exec.js';
17
+ const GIT_PROGRAM = 'git';
18
+ /** Global options whose value is the next word (`git -C <dir> commit`). */
19
+ const GIT_OPTIONS_WITH_VALUE = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--config-env']);
20
+ const HELP_FLAGS = new Set(['-h', '--help']);
21
+ /** Scripts that run `git commit` themselves; their commits are found through the HEAD snapshot. */
22
+ const COMMIT_WRAPPER_SCRIPTS = new Set(['conventional-commit.sh']);
23
+ /** A simple command that is `git [global options] commit` or a wrapper script (HSF18); `echo git commit` does not count. */
24
+ export function isGitCommitCommand(command) {
25
+ if (!command.includes(GIT_COMMIT_SUBCOMMAND))
26
+ return false;
27
+ return commandInvocations(command).some((argv) => {
28
+ const program = programOf(argv);
29
+ if (COMMIT_WRAPPER_SCRIPTS.has(program))
30
+ return true;
31
+ if (program !== GIT_PROGRAM)
32
+ return false;
33
+ let i = 1;
34
+ for (let arg = argv[i]; arg !== undefined && isOptionArg(arg); arg = argv[i])
35
+ i += GIT_OPTIONS_WITH_VALUE.has(arg) ? 2 : 1;
36
+ return argv[i] === GIT_COMMIT_SUBCOMMAND && !argv.slice(i + 1).some((arg) => HELP_FLAGS.has(arg));
37
+ });
38
+ }
39
+ /** git's `[branch sha]` line on a successful commit. */
40
+ const COMMIT_SUCCESS_PATTERN = /\[.+\s[a-f0-9]+\]/;
41
+ const NOTHING_TO_COMMIT = 'nothing to commit';
42
+ export const commandOf = (input) => getStringField(input, 'command') ?? '';
43
+ const eventCwd = (input) => input.cwd || process.cwd();
44
+ /** `commit`, `commit (amend|initial|merge)`; never checkout/reset/rebase. */
45
+ const COMMIT_REFLOG_ACTION = /^commit( \([a-z]+\))?:/;
46
+ const REFLOG_FIELD_SEPARATOR = '\t';
47
+ const HEAD_SNAPSHOT_DIR = 'git-head-snapshots';
48
+ /** Recorded for a repo with no commits yet, so its first commit still reads as a move. */
49
+ export const UNBORN_HEAD = '';
50
+ /** `git rev-parse -q --verify HEAD` exits 1 on an unborn branch, 128 outside a repo. */
51
+ const UNBORN_HEAD_EXIT = 1;
52
+ /** Keyed by the call's `tool_use_id`, so identical commands in flight do not share a snapshot; by command text when the payload has none. */
53
+ function snapshotPath(sessionId, command, toolUseId) {
54
+ const key = createHash('sha1').update(toolUseId || command).digest('hex');
55
+ return join(sessionStateDir(sessionId), HEAD_SNAPSHOT_DIR, `${key}.json`);
56
+ }
57
+ async function readHead(cwd) {
58
+ try {
59
+ return (await git(cwd, ['rev-parse', '-q', '--verify', 'HEAD'], GIT_TIMEOUT_MS.HOOK_PATH)).trim();
60
+ }
61
+ catch (error) {
62
+ return error.code === UNBORN_HEAD_EXIT ? UNBORN_HEAD : undefined;
63
+ }
64
+ }
65
+ /** PreToolUse half (HSF10). Outside a repo nothing is recorded and a stale snapshot is removed. */
66
+ export async function recordCommitHeadSnapshot(input) {
67
+ const command = commandOf(input);
68
+ if (!input.session_id || !isGitCommitCommand(command))
69
+ return;
70
+ const path = snapshotPath(input.session_id, command, input.tool_use_id);
71
+ const head = await readHead(eventCwd(input));
72
+ if (head === undefined) {
73
+ rmSync(path, { force: true });
74
+ return;
75
+ }
76
+ writeJsonAtomic(path, { head }, { silent: true });
77
+ }
78
+ /** PostToolUseFailure half (HSF19): a failed commit never reaches `resolveCommitEvent`. */
79
+ export function discardCommitHeadSnapshot(input) {
80
+ const command = commandOf(input);
81
+ if (!input.session_id || !isGitCommitCommand(command))
82
+ return;
83
+ rmSync(snapshotPath(input.session_id, command, input.tool_use_id), { force: true });
84
+ }
85
+ function takeHeadSnapshot(input, command) {
86
+ if (!input.session_id)
87
+ return undefined;
88
+ const path = snapshotPath(input.session_id, command, input.tool_use_id);
89
+ const snapshot = loadJson(path);
90
+ rmSync(path, { force: true });
91
+ return typeof snapshot?.head === 'string' ? snapshot.head : undefined;
92
+ }
93
+ async function headMovedByCommit(cwd, before) {
94
+ try {
95
+ const stdout = await git(cwd, ['reflog', '-1', `--format=%H${REFLOG_FIELD_SEPARATOR}%gs`, 'HEAD'], GIT_TIMEOUT_MS.HOOK_PATH);
96
+ const [sha = '', subject = ''] = stdout.trim().split(REFLOG_FIELD_SEPARATOR);
97
+ return sha !== '' && sha !== before && COMMIT_REFLOG_ACTION.test(subject);
98
+ }
99
+ catch {
100
+ return false;
101
+ }
102
+ }
103
+ /**
104
+ * Against the first parent, not `git show`: its combined diff drops every file
105
+ * identical to a parent, so a merge whose only conflicts were Markdown read as
106
+ * docs-only and skipped review. `--root` keeps an initial commit's files; `-m`
107
+ * still emits one block per parent, hence the dedupe. The SHA leads the output.
108
+ */
109
+ const COMMIT_FILES_ARGS = [
110
+ 'diff-tree', '-m', '--first-parent', '--root', '--name-only', '-r', 'HEAD',
111
+ ];
112
+ const SHA_RE = /^[0-9a-f]{40}$/;
113
+ /**
114
+ * An empty `files` never means "no changes": git could not answer, and the docs-only
115
+ * skip must fail open into reviewing. Paths come back verbatim (`core.quotePath=false`):
116
+ * git's quoted form of a non-ASCII path matched nothing when joined onto the root.
117
+ */
118
+ export async function getCommittedFiles(cwd) {
119
+ try {
120
+ const stdout = await git(cwd, COMMIT_FILES_ARGS, GIT_TIMEOUT_MS.HOOK_PATH);
121
+ const lines = stdout.split('\n').map(line => line.trim()).filter(Boolean);
122
+ // With -m a merge repeats the SHA line per parent block.
123
+ const commit = lines.find(line => SHA_RE.test(line));
124
+ const files = [...new Set(lines.filter(line => !SHA_RE.test(line)))];
125
+ return { files, outcome: 'ok', commit };
126
+ }
127
+ catch (error) {
128
+ return { files: [], outcome: classifyExecError(error) };
129
+ }
130
+ }
131
+ /** Commit-line marker in `commitsInRange`'s output; no file line starts with it. */
132
+ const COMMIT_LINE_MARKER = '\u0001';
133
+ /** `base..HEAD` (whole history for an unborn base), newest first. Empty on failure. */
134
+ async function commitsInRange(cwd, base) {
135
+ try {
136
+ const range = base === UNBORN_HEAD ? 'HEAD' : `${base}..HEAD`;
137
+ const stdout = await git(cwd, ['log', '-m', '--first-parent', '--name-only', `--format=${COMMIT_LINE_MARKER}%H`, range], GIT_TIMEOUT_MS.HOOK_PATH);
138
+ const lines = stdout.split('\n').map((line) => line.trim()).filter(Boolean);
139
+ const result = [];
140
+ let current = null;
141
+ for (const line of lines) {
142
+ if (line.startsWith(COMMIT_LINE_MARKER)) {
143
+ if (current)
144
+ result.push(current);
145
+ current = { sha: line.slice(1), files: [] };
146
+ }
147
+ else if (current) {
148
+ if (!current.files.includes(line))
149
+ current.files.push(line);
150
+ }
151
+ }
152
+ if (current)
153
+ result.push(current);
154
+ return result;
155
+ }
156
+ catch {
157
+ return [];
158
+ }
159
+ }
160
+ /**
161
+ * The `[branch sha]` output line is the fast path and the only one that sees a commit
162
+ * into another repo; `-q`, a redirect or a pipe drops it silently.
163
+ * The snapshot then decides by reflog. Without a snapshot only the fast
164
+ * path answers. On the quiet path diff-tree starts speculatively alongside the reflog read (HSF14).
165
+ */
166
+ export async function resolveCommitEvent(input) {
167
+ const command = commandOf(input);
168
+ if (!isGitCommitCommand(command))
169
+ return null;
170
+ const before = takeHeadSnapshot(input, command);
171
+ const cwd = eventCwd(input);
172
+ const output = resolveOutputText(input);
173
+ const fastPathLanded = COMMIT_SUCCESS_PATTERN.test(output) && !output.includes(NOTHING_TO_COMMIT);
174
+ const speculativeFiles = (!fastPathLanded && before !== undefined)
175
+ ? getCommittedFiles(cwd)
176
+ : null;
177
+ const landed = fastPathLanded
178
+ || (before !== undefined && await headMovedByCommit(cwd, before));
179
+ if (!landed)
180
+ return null;
181
+ const [head, commits] = await Promise.all([
182
+ speculativeFiles ?? getCommittedFiles(cwd),
183
+ before === undefined ? Promise.resolve([]) : commitsInRange(cwd, before),
184
+ ]);
185
+ if (commits.length <= 1)
186
+ return { ...head, commitCount: 1, commandFiles: head.files };
187
+ const commandFiles = [...new Set(commits.flatMap(commit => commit.files))];
188
+ return { ...head, commitCount: commits.length, commandFiles, base: before };
189
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Thin wrapper around the `git` binary, kept as a leaf module.
3
+ */
4
+ import { execFile, execFileSync } from 'node:child_process';
5
+ import { promisify } from 'node:util';
6
+ import { THRESHOLDS, GIT_TIMEOUT_MS } from '../core/constants.js';
7
+ const execFileAsync = promisify(execFile);
8
+ /** `git remote get-url origin`: the one remote probe, sync or async. */
9
+ export const REMOTE_URL_ARGS = ['remote', 'get-url', 'origin'];
10
+ function gitArgv(repoRoot, args) {
11
+ return ['-C', repoRoot, '-c', 'core.quotePath=false', ...args];
12
+ }
13
+ /** `timeoutMs` lets a detached caller exceed the hook-path default. */
14
+ export async function git(repoRoot, args, timeoutMs = GIT_TIMEOUT_MS.HOOK_PATH) {
15
+ const { stdout } = await execFileAsync('git', gitArgv(repoRoot, args), {
16
+ encoding: 'utf8',
17
+ timeout: timeoutMs,
18
+ maxBuffer: THRESHOLDS.GIT_MAX_BUFFER_BYTES,
19
+ });
20
+ return stdout;
21
+ }
22
+ /** Synchronous `git`, stderr discarded; for the few callers that cannot await. */
23
+ export function gitSync(repoRoot, args, timeoutMs) {
24
+ return execFileSync('git', gitArgv(repoRoot, args), {
25
+ encoding: 'utf8',
26
+ stdio: ['ignore', 'pipe', 'ignore'],
27
+ timeout: timeoutMs,
28
+ maxBuffer: THRESHOLDS.GIT_MAX_BUFFER_BYTES,
29
+ });
30
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Per-session MCP tool invocation counts (append-only JSONL) for detecting incomplete workflows.
3
+ * @internal
4
+ */
5
+ import { join } from 'node:path';
6
+ import { appendLine, readJsonlFile } from '../core/file-utils.js';
7
+ import { sessionStateDir } from '../session/session-state.js';
8
+ /** Append-only JSONL, one file inside the session's state directory. */
9
+ const COMPLETENESS_FILE = 'mcp-invocations.jsonl';
10
+ function getLogPath(sessionId) {
11
+ return join(sessionStateDir(sessionId), COMPLETENESS_FILE);
12
+ }
13
+ /** Append one invocation. */
14
+ export function recordMcpInvocation(sessionId, record) {
15
+ try {
16
+ appendLine(getLogPath(sessionId), `${JSON.stringify(record)}\n`);
17
+ return true;
18
+ }
19
+ catch {
20
+ return false;
21
+ }
22
+ }
23
+ /** All invocations for a session; empty when it recorded none. */
24
+ export function loadInvocations(sessionId) {
25
+ return readJsonlFile(getLogPath(sessionId));
26
+ }
27
+ /** Invocations grouped by server/tool. */
28
+ export function summarizeInvocations(invocations) {
29
+ const summary = {};
30
+ for (const inv of invocations) {
31
+ const key = `${inv.server}/${inv.tool}`;
32
+ const counts = (summary[key] ??= { total: 0, successful: 0, failed: 0 });
33
+ counts.total++;
34
+ if (inv.success)
35
+ counts.successful++;
36
+ else
37
+ counts.failed++;
38
+ }
39
+ return summary;
40
+ }
@@ -0,0 +1,118 @@
1
+ /** MCP config loading and scope detection; per-scope maps hold full server definitions so mcp-status.ts shares the cache. */
2
+ import { createHash } from 'node:crypto';
3
+ import { basename, join, sep } from 'node:path';
4
+ import { CLAUDE_HOME } from '../core/constants.js';
5
+ import { findUp, loadJson, writeJson } from '../core/file-utils.js';
6
+ import { claudeJsonPath } from '../core/identity-key-resolver.js';
7
+ import { sessionStateDir } from '../session/session-state.js';
8
+ const MCP_CONFIG_FILENAME = '.mcp.json';
9
+ /** Directory holding in-repo MCP server checkouts (e.g. observability-toolkit). */
10
+ const MCP_SERVERS_ROOT = join(CLAUDE_HOME, 'mcp-servers');
11
+ let mcpConfigCache = null;
12
+ /** @returns true if the file declared `mcpServers`: the project walk stops on the nearest file that does. */
13
+ function readServers(filePath, into) {
14
+ const config = loadJson(filePath);
15
+ if (!config?.mcpServers)
16
+ return false;
17
+ for (const [name, serverConfig] of Object.entries(config.mcpServers)) {
18
+ into.set(name, serverConfig);
19
+ }
20
+ return true;
21
+ }
22
+ function loadMcpConfigs(cwd) {
23
+ const currentCwd = cwd || process.cwd();
24
+ if (mcpConfigCache?.cwd === currentCwd) {
25
+ return mcpConfigCache;
26
+ }
27
+ const globalServers = new Map();
28
+ const projectServers = new Map();
29
+ const userServers = new Map();
30
+ readServers(join(CLAUDE_HOME, MCP_CONFIG_FILENAME), globalServers);
31
+ // `claudeJsonPath` holds servers from `claude mcp add`, which appear in no `.mcp.json`;
32
+ // read first so mcp_config.json candidates win on a name collision.
33
+ readServers(claudeJsonPath(), userServers);
34
+ const userMcpPaths = [
35
+ join(CLAUDE_HOME, 'mcp_config.json'),
36
+ join(CLAUDE_HOME, 'config', 'mcp_config.json'),
37
+ ];
38
+ for (const userMcpPath of userMcpPaths) {
39
+ readServers(userMcpPath, userServers);
40
+ }
41
+ findUp(currentCwd, dir => readServers(join(dir, MCP_CONFIG_FILENAME), projectServers) ? dir : null);
42
+ mcpConfigCache = {
43
+ global: globalServers,
44
+ project: projectServers,
45
+ user: userServers,
46
+ cwd: currentCwd,
47
+ };
48
+ return mcpConfigCache;
49
+ }
50
+ /** Every configured server keyed by name; project > user > global. Fresh copy. */
51
+ export function getAllMcpServers(cwd) {
52
+ const configs = loadMcpConfigs(cwd);
53
+ return new Map([...configs.global, ...configs.user, ...configs.project]);
54
+ }
55
+ export function clearMcpConfigCache() {
56
+ mcpConfigCache = null;
57
+ }
58
+ const CWD_HASH_HEX_CHARS = 8;
59
+ /** Not a security boundary; it only distinguishes `~/a/web` from `~/b/web` in a filename. */
60
+ function cwdHash(cwd) {
61
+ return createHash('md5').update(cwd).digest('hex').slice(0, CWD_HASH_HEX_CHARS);
62
+ }
63
+ function scopeCachePath(sessionId, cwd) {
64
+ return join(sessionStateDir(sessionId), `mcp-scope-${cwdHash(cwd)}.json`);
65
+ }
66
+ /** Persisted scope map for this (session, cwd), or null on miss. */
67
+ function loadScopeCache(sessionId, cwd) {
68
+ const entry = loadJson(scopeCachePath(sessionId, cwd));
69
+ return entry?.cwd === cwd ? entry.scopes : null;
70
+ }
71
+ /** Compute and persist the scope map; fails open on write error. */
72
+ function buildAndPersistScopeCache(sessionId, cwd) {
73
+ const configs = loadMcpConfigs(cwd);
74
+ const scopes = {};
75
+ for (const name of configs.project.keys())
76
+ scopes[name] = 'project';
77
+ for (const name of configs.user.keys())
78
+ if (!(name in scopes))
79
+ scopes[name] = 'user';
80
+ for (const name of configs.global.keys())
81
+ if (!(name in scopes))
82
+ scopes[name] = 'global';
83
+ writeJson(scopeCachePath(sessionId, cwd), { cwd, scopes });
84
+ return scopes;
85
+ }
86
+ /** Scope lookup backed by the persisted map; falls back to the live walk when unreadable. */
87
+ export function getMcpScopeCached(serverName, sessionId, cwd) {
88
+ const cached = loadScopeCache(sessionId, cwd);
89
+ const scopes = cached ?? buildAndPersistScopeCache(sessionId, cwd);
90
+ return scopes[serverName] ?? 'unknown';
91
+ }
92
+ /** In-repo checkout directory a server runs from; undefined for remote/npx/uvx servers. */
93
+ function serverCheckoutDir(config) {
94
+ for (const part of [config.command, ...(config.args ?? [])]) {
95
+ if (part?.startsWith(MCP_SERVERS_ROOT + sep)) {
96
+ const firstSegment = part.slice(MCP_SERVERS_ROOT.length + 1).split(sep)[0];
97
+ if (firstSegment)
98
+ return join(MCP_SERVERS_ROOT, firstSegment);
99
+ }
100
+ }
101
+ return undefined;
102
+ }
103
+ /**
104
+ * Path→project table for "wrong project activated" errors, derived from configured
105
+ * servers (PT6). Most-specific first: checkout dirs, mcp-servers root, CLAUDE_HOME
106
+ * (bare '/hooks' fragments matched unrelated repos). Project name = checkout basename.
107
+ */
108
+ export function getProjectMismatchPatterns(cwd) {
109
+ const patterns = [];
110
+ for (const config of getAllMcpServers(cwd).values()) {
111
+ const dir = serverCheckoutDir(config);
112
+ if (dir && !patterns.some((p) => p.path === dir)) {
113
+ patterns.push({ path: dir, project: basename(dir) });
114
+ }
115
+ }
116
+ patterns.push({ path: MCP_SERVERS_ROOT, project: '.claude (or specific MCP project)' }, { path: CLAUDE_HOME, project: '.claude' });
117
+ return patterns;
118
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Per-session latch reporting each unavailable MCP server once. On disk because
3
+ * every hook is its own process; reset at session start so a reused id reports afresh.
4
+ */
5
+ import { mkdirSync, rmSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ import { toSafeFilename } from '../core/file-utils.js';
8
+ import { claimOnce, sessionMarkerPath, sessionStateDir, sessionStateRoot } from '../session/session-state.js';
9
+ const MCP_FAILURES_DIRNAME = 'mcp-failures';
10
+ function failuresDir(sessionId, stateRoot) {
11
+ return join(sessionStateDir(sessionId, stateRoot), MCP_FAILURES_DIRNAME);
12
+ }
13
+ /** Atomic per-session claim. `stateRoot` keeps tests out of $HOME. */
14
+ export function claimFailureReport(sessionId, server, stateRoot = sessionStateRoot()) {
15
+ const marker = sessionMarkerPath(sessionId, join(MCP_FAILURES_DIRNAME, toSafeFilename(server)), stateRoot);
16
+ // Uncached mkdir: resetFailureTracking deletes this dir, so the memoized ensureDirExists would hit stale.
17
+ return claimOnce(marker, { mkdir: (dir) => mkdirSync(dir, { recursive: true }) });
18
+ }
19
+ /** Called at session start so a session that reuses an id reports its failures afresh. */
20
+ export function resetFailureTracking(sessionId, stateRoot = sessionStateRoot()) {
21
+ rmSync(failuresDir(sessionId, stateRoot), { recursive: true, force: true });
22
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * `node mcp-identity-launcher.js <server-entry.js> [args...]`: launch a stdio MCP
3
+ * server with the signed-in account's obtool key in `OBTOOL_API_KEY` and
4
+ * `OTEL_EXPORTER_OTLP_HEADERS` (TKR1). Stdio is inherited, signals forwarded,
5
+ * exit code passed through; with no resolvable key both variables stay as inherited.
6
+ */
7
+ import { spawn } from 'node:child_process';
8
+ import { FIRST_CLI_ARG_INDEX } from '../core/constants.js';
9
+ import { writeStderr } from '../core/format-utils.js';
10
+ import { AUTHORIZATION_HEADER, bearerCredential } from '../core/http-utils.js';
11
+ import { resolveOtlpApiKey } from '../core/identity-key-resolver.js';
12
+ import { OTLP_ENV } from '../core/settings-env.js';
13
+ import { formatOtlpHeaders } from '../otel/otlp-headers.js';
14
+ const FORWARDED_SIGNALS = ['SIGTERM', 'SIGINT', 'SIGHUP'];
15
+ const EXIT_USAGE = 64;
16
+ const EXIT_SIGNALLED = 1;
17
+ /** The child's environment: `env` with the credential pair set when a key resolved. */
18
+ export function childEnvWithKey(env, apiKey) {
19
+ if (!apiKey)
20
+ return { ...env };
21
+ return { ...env, [OTLP_ENV.API_KEY]: apiKey, [OTLP_ENV.HEADERS]: formatOtlpHeaders({ [AUTHORIZATION_HEADER]: bearerCredential(apiKey) }) };
22
+ }
23
+ export function main(argv = process.argv.slice(FIRST_CLI_ARG_INDEX)) {
24
+ const [entry, ...rest] = argv;
25
+ if (!entry) {
26
+ writeStderr('usage: mcp-identity-launcher <server-entry.js> [args...]');
27
+ process.exit(EXIT_USAGE);
28
+ }
29
+ const key = resolveOtlpApiKey();
30
+ const child = spawn(process.execPath, [entry, ...rest], {
31
+ stdio: 'inherit',
32
+ env: childEnvWithKey(process.env, key),
33
+ });
34
+ for (const signal of FORWARDED_SIGNALS) {
35
+ process.on(signal, () => child.kill(signal));
36
+ }
37
+ child.on('exit', (code, signal) => {
38
+ process.exit(code ?? (signal ? EXIT_SIGNALLED : 0));
39
+ });
40
+ }
41
+ if (import.meta.main) {
42
+ main();
43
+ }