memory-journal-mcp 7.7.1 → 8.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 (531) hide show
  1. package/README.md +126 -56
  2. package/dist/chunk-6OHRCNYW.js +3231 -0
  3. package/dist/chunk-JFMITANR.js +5168 -0
  4. package/dist/{chunk-6LPTBIB6.js → chunk-MWNLAEHR.js} +309 -4332
  5. package/dist/{chunk-ARLYSFSI.js → chunk-UHSO65A4.js} +4242 -6092
  6. package/dist/cli.js +21 -3
  7. package/dist/index.d.ts +16 -13
  8. package/dist/index.js +4 -2
  9. package/dist/resources-IJVKDFGS.js +2 -0
  10. package/dist/tools-44DGXE3V.js +2 -0
  11. package/dist/worker-script.js +201 -20
  12. package/package.json +6 -4
  13. package/skills/README.md +62 -25
  14. package/skills/adversarial-performance/SKILL.md +139 -0
  15. package/skills/adversarial-performance/references/audit-categories.md +462 -0
  16. package/skills/adversarial-performance/references/copilot-performance-prompts.md +44 -0
  17. package/skills/adversarial-performance/references/copilot-usage.md +16 -0
  18. package/skills/adversarial-performance/references/feedback-loop.md +177 -0
  19. package/skills/adversarial-performance/references/multi-pass-performance-protocol.md +398 -0
  20. package/skills/adversarial-planner/SKILL.md +23 -54
  21. package/skills/adversarial-planner/references/copilot-integration.md +25 -40
  22. package/skills/adversarial-planner/references/copilot-usage.md +16 -0
  23. package/skills/adversarial-planner/references/multi-pass-protocol.md +4 -0
  24. package/skills/adversarial-security/SKILL.md +149 -0
  25. package/skills/adversarial-security/references/adversarial-base-protocol.md +44 -0
  26. package/skills/adversarial-security/references/audit-categories.md +723 -0
  27. package/skills/adversarial-security/references/copilot-security-prompts.md +142 -0
  28. package/skills/adversarial-security/references/copilot-usage.md +16 -0
  29. package/skills/adversarial-security/references/feedback-loop.md +206 -0
  30. package/skills/adversarial-security/references/journal-opt-out.md +7 -0
  31. package/skills/adversarial-security/references/multi-pass-security-protocol.md +403 -0
  32. package/skills/adversarial-skill-audit/SKILL.md +118 -0
  33. package/skills/adversarial-skill-audit/references/audit-categories.md +308 -0
  34. package/skills/adversarial-skill-audit/references/copilot-skill-prompts.md +68 -0
  35. package/skills/adversarial-skill-audit/references/copilot-usage.md +16 -0
  36. package/skills/adversarial-skill-audit/references/feedback-loop.md +155 -0
  37. package/skills/adversarial-skill-audit/references/multi-pass-skill-protocol.md +367 -0
  38. package/skills/adversarial-skill-audit/scripts/check-skills.ps1 +48 -0
  39. package/skills/adversarial-skill-audit/scripts/run-copilot.ps1 +52 -0
  40. package/skills/adversarial-workflow-audit/SKILL.md +82 -0
  41. package/skills/adversarial-workflow-audit/references/audit-categories.md +28 -0
  42. package/skills/adversarial-workflow-audit/references/copilot-usage.md +16 -0
  43. package/skills/adversarial-workflow-audit/scripts/check-workflows.ps1 +24 -0
  44. package/skills/agents-sdk/SKILL.md +220 -0
  45. package/skills/agents-sdk/references/callable.md +92 -0
  46. package/skills/agents-sdk/references/codemode.md +209 -0
  47. package/skills/agents-sdk/references/email.md +144 -0
  48. package/skills/agents-sdk/references/mcp/SKILL.md +65 -0
  49. package/skills/agents-sdk/references/mcp/code-mode-reference.md +245 -0
  50. package/skills/agents-sdk/references/mcp/oauth-reference.md +359 -0
  51. package/skills/agents-sdk/references/mcp/references/architecture-reference.md +208 -0
  52. package/skills/agents-sdk/references/mcp/references/cloudflare-quickstart.md +156 -0
  53. package/skills/agents-sdk/references/mcp/references/error-handling.md +343 -0
  54. package/skills/agents-sdk/references/mcp/references/http-security.md +164 -0
  55. package/skills/agents-sdk/references/mcp/references/implementation-guide.md +507 -0
  56. package/skills/agents-sdk/references/mcp/references/testing-reference.md +171 -0
  57. package/skills/agents-sdk/references/mcp.md +157 -0
  58. package/skills/agents-sdk/references/state-scheduling.md +164 -0
  59. package/skills/agents-sdk/references/streaming-chat.md +168 -0
  60. package/skills/agents-sdk/references/workflows.md +136 -0
  61. package/skills/auth-identity/SKILL.md +48 -0
  62. package/skills/autonomous-dev/SKILL.md +46 -23
  63. package/skills/autonomous-dev/references/workflow_orchestration.md +22 -0
  64. package/skills/aws/SKILL.md +39 -0
  65. package/skills/azure/SKILL.md +38 -0
  66. package/skills/bin/sync.js +7 -1
  67. package/skills/biome/SKILL.md +59 -0
  68. package/skills/bun/SKILL.md +8 -2
  69. package/skills/cloudflare/SKILL.md +37 -0
  70. package/skills/cloudflare/references/agents-sdk/README.md +95 -0
  71. package/skills/cloudflare/references/agents-sdk/api.md +195 -0
  72. package/skills/cloudflare/references/agents-sdk/configuration.md +178 -0
  73. package/skills/cloudflare/references/agents-sdk/gotchas.md +173 -0
  74. package/skills/cloudflare/references/agents-sdk/patterns.md +215 -0
  75. package/skills/cloudflare/references/ai-gateway/README.md +176 -0
  76. package/skills/cloudflare/references/ai-gateway/configuration.md +117 -0
  77. package/skills/cloudflare/references/ai-gateway/dynamic-routing.md +88 -0
  78. package/skills/cloudflare/references/ai-gateway/features.md +96 -0
  79. package/skills/cloudflare/references/ai-gateway/sdk-integration.md +110 -0
  80. package/skills/cloudflare/references/ai-gateway/troubleshooting.md +90 -0
  81. package/skills/cloudflare/references/ai-search/README.md +145 -0
  82. package/skills/cloudflare/references/ai-search/api.md +87 -0
  83. package/skills/cloudflare/references/ai-search/configuration.md +91 -0
  84. package/skills/cloudflare/references/ai-search/gotchas.md +92 -0
  85. package/skills/cloudflare/references/ai-search/patterns.md +87 -0
  86. package/skills/cloudflare/references/analytics-engine/README.md +96 -0
  87. package/skills/cloudflare/references/analytics-engine/api.md +112 -0
  88. package/skills/cloudflare/references/analytics-engine/configuration.md +107 -0
  89. package/skills/cloudflare/references/analytics-engine/gotchas.md +87 -0
  90. package/skills/cloudflare/references/analytics-engine/patterns.md +83 -0
  91. package/skills/cloudflare/references/api/README.md +66 -0
  92. package/skills/cloudflare/references/api/api.md +205 -0
  93. package/skills/cloudflare/references/api/configuration.md +158 -0
  94. package/skills/cloudflare/references/api/gotchas.md +231 -0
  95. package/skills/cloudflare/references/api/patterns.md +208 -0
  96. package/skills/cloudflare/references/api-shield/README.md +44 -0
  97. package/skills/cloudflare/references/api-shield/api.md +153 -0
  98. package/skills/cloudflare/references/api-shield/configuration.md +210 -0
  99. package/skills/cloudflare/references/api-shield/gotchas.md +132 -0
  100. package/skills/cloudflare/references/api-shield/patterns.md +185 -0
  101. package/skills/cloudflare/references/argo-smart-routing/README.md +96 -0
  102. package/skills/cloudflare/references/argo-smart-routing/api.md +253 -0
  103. package/skills/cloudflare/references/argo-smart-routing/configuration.md +205 -0
  104. package/skills/cloudflare/references/argo-smart-routing/gotchas.md +115 -0
  105. package/skills/cloudflare/references/argo-smart-routing/patterns.md +107 -0
  106. package/skills/cloudflare/references/bindings/README.md +127 -0
  107. package/skills/cloudflare/references/bindings/api.md +214 -0
  108. package/skills/cloudflare/references/bindings/configuration.md +200 -0
  109. package/skills/cloudflare/references/bindings/gotchas.md +210 -0
  110. package/skills/cloudflare/references/bindings/patterns.md +205 -0
  111. package/skills/cloudflare/references/bot-management/README.md +95 -0
  112. package/skills/cloudflare/references/bot-management/api.md +175 -0
  113. package/skills/cloudflare/references/bot-management/configuration.md +175 -0
  114. package/skills/cloudflare/references/bot-management/gotchas.md +116 -0
  115. package/skills/cloudflare/references/bot-management/patterns.md +181 -0
  116. package/skills/cloudflare/references/browser-rendering/README.md +84 -0
  117. package/skills/cloudflare/references/browser-rendering/api.md +108 -0
  118. package/skills/cloudflare/references/browser-rendering/configuration.md +78 -0
  119. package/skills/cloudflare/references/browser-rendering/gotchas.md +91 -0
  120. package/skills/cloudflare/references/browser-rendering/patterns.md +93 -0
  121. package/skills/cloudflare/references/c3/README.md +111 -0
  122. package/skills/cloudflare/references/c3/api.md +71 -0
  123. package/skills/cloudflare/references/c3/configuration.md +85 -0
  124. package/skills/cloudflare/references/c3/gotchas.md +97 -0
  125. package/skills/cloudflare/references/c3/patterns.md +84 -0
  126. package/skills/cloudflare/references/cache-reserve/README.md +150 -0
  127. package/skills/cloudflare/references/cache-reserve/api.md +184 -0
  128. package/skills/cloudflare/references/cache-reserve/configuration.md +170 -0
  129. package/skills/cloudflare/references/cache-reserve/gotchas.md +136 -0
  130. package/skills/cloudflare/references/cache-reserve/patterns.md +197 -0
  131. package/skills/cloudflare/references/containers/README.md +87 -0
  132. package/skills/cloudflare/references/containers/api.md +197 -0
  133. package/skills/cloudflare/references/containers/configuration.md +191 -0
  134. package/skills/cloudflare/references/containers/gotchas.md +182 -0
  135. package/skills/cloudflare/references/containers/patterns.md +204 -0
  136. package/skills/cloudflare/references/cron-triggers/README.md +101 -0
  137. package/skills/cloudflare/references/cron-triggers/api.md +224 -0
  138. package/skills/cloudflare/references/cron-triggers/configuration.md +190 -0
  139. package/skills/cloudflare/references/cron-triggers/gotchas.md +207 -0
  140. package/skills/cloudflare/references/cron-triggers/patterns.md +274 -0
  141. package/skills/cloudflare/references/d1/README.md +137 -0
  142. package/skills/cloudflare/references/d1/api.md +213 -0
  143. package/skills/cloudflare/references/d1/configuration.md +198 -0
  144. package/skills/cloudflare/references/d1/gotchas.md +98 -0
  145. package/skills/cloudflare/references/d1/patterns.md +240 -0
  146. package/skills/cloudflare/references/ddos/README.md +42 -0
  147. package/skills/cloudflare/references/ddos/api.md +158 -0
  148. package/skills/cloudflare/references/ddos/configuration.md +94 -0
  149. package/skills/cloudflare/references/ddos/gotchas.md +114 -0
  150. package/skills/cloudflare/references/ddos/patterns.md +220 -0
  151. package/skills/cloudflare/references/decision-trees.md +95 -0
  152. package/skills/cloudflare/references/do-storage/README.md +79 -0
  153. package/skills/cloudflare/references/do-storage/api.md +107 -0
  154. package/skills/cloudflare/references/do-storage/configuration.md +114 -0
  155. package/skills/cloudflare/references/do-storage/gotchas.md +153 -0
  156. package/skills/cloudflare/references/do-storage/patterns.md +210 -0
  157. package/skills/cloudflare/references/do-storage/testing.md +186 -0
  158. package/skills/cloudflare/references/durable-objects/README.md +194 -0
  159. package/skills/cloudflare/references/durable-objects/api.md +205 -0
  160. package/skills/cloudflare/references/durable-objects/configuration.md +160 -0
  161. package/skills/cloudflare/references/durable-objects/gotchas.md +200 -0
  162. package/skills/cloudflare/references/durable-objects/patterns.md +205 -0
  163. package/skills/cloudflare/references/email-routing/README.md +89 -0
  164. package/skills/cloudflare/references/email-routing/api.md +192 -0
  165. package/skills/cloudflare/references/email-routing/configuration.md +187 -0
  166. package/skills/cloudflare/references/email-routing/gotchas.md +203 -0
  167. package/skills/cloudflare/references/email-routing/patterns.md +241 -0
  168. package/skills/cloudflare/references/email-workers/README.md +153 -0
  169. package/skills/cloudflare/references/email-workers/api.md +227 -0
  170. package/skills/cloudflare/references/email-workers/configuration.md +115 -0
  171. package/skills/cloudflare/references/email-workers/gotchas.md +133 -0
  172. package/skills/cloudflare/references/email-workers/patterns.md +108 -0
  173. package/skills/cloudflare/references/graphql-api/README.md +147 -0
  174. package/skills/cloudflare/references/graphql-api/api.md +175 -0
  175. package/skills/cloudflare/references/graphql-api/configuration.md +151 -0
  176. package/skills/cloudflare/references/graphql-api/gotchas.md +111 -0
  177. package/skills/cloudflare/references/graphql-api/patterns.md +276 -0
  178. package/skills/cloudflare/references/hyperdrive/README.md +84 -0
  179. package/skills/cloudflare/references/hyperdrive/api.md +149 -0
  180. package/skills/cloudflare/references/hyperdrive/configuration.md +166 -0
  181. package/skills/cloudflare/references/hyperdrive/gotchas.md +77 -0
  182. package/skills/cloudflare/references/hyperdrive/patterns.md +203 -0
  183. package/skills/cloudflare/references/images/README.md +65 -0
  184. package/skills/cloudflare/references/images/api.md +101 -0
  185. package/skills/cloudflare/references/images/configuration.md +206 -0
  186. package/skills/cloudflare/references/images/gotchas.md +106 -0
  187. package/skills/cloudflare/references/images/patterns.md +126 -0
  188. package/skills/cloudflare/references/kv/README.md +90 -0
  189. package/skills/cloudflare/references/kv/api.md +163 -0
  190. package/skills/cloudflare/references/kv/configuration.md +148 -0
  191. package/skills/cloudflare/references/kv/gotchas.md +133 -0
  192. package/skills/cloudflare/references/kv/patterns.md +195 -0
  193. package/skills/cloudflare/references/miniflare/README.md +113 -0
  194. package/skills/cloudflare/references/miniflare/api.md +204 -0
  195. package/skills/cloudflare/references/miniflare/configuration.md +174 -0
  196. package/skills/cloudflare/references/miniflare/gotchas.md +179 -0
  197. package/skills/cloudflare/references/miniflare/patterns.md +187 -0
  198. package/skills/cloudflare/references/network-interconnect/README.md +104 -0
  199. package/skills/cloudflare/references/network-interconnect/api.md +220 -0
  200. package/skills/cloudflare/references/network-interconnect/configuration.md +123 -0
  201. package/skills/cloudflare/references/network-interconnect/gotchas.md +175 -0
  202. package/skills/cloudflare/references/network-interconnect/patterns.md +174 -0
  203. package/skills/cloudflare/references/observability/README.md +93 -0
  204. package/skills/cloudflare/references/observability/api.md +168 -0
  205. package/skills/cloudflare/references/observability/configuration.md +178 -0
  206. package/skills/cloudflare/references/observability/gotchas.md +125 -0
  207. package/skills/cloudflare/references/observability/patterns.md +105 -0
  208. package/skills/cloudflare/references/pages/README.md +92 -0
  209. package/skills/cloudflare/references/pages/api.md +205 -0
  210. package/skills/cloudflare/references/pages/configuration.md +216 -0
  211. package/skills/cloudflare/references/pages/gotchas.md +218 -0
  212. package/skills/cloudflare/references/pages/patterns.md +215 -0
  213. package/skills/cloudflare/references/pages-functions/README.md +104 -0
  214. package/skills/cloudflare/references/pages-functions/api.md +159 -0
  215. package/skills/cloudflare/references/pages-functions/configuration.md +130 -0
  216. package/skills/cloudflare/references/pages-functions/gotchas.md +102 -0
  217. package/skills/cloudflare/references/pages-functions/patterns.md +148 -0
  218. package/skills/cloudflare/references/pipelines/README.md +109 -0
  219. package/skills/cloudflare/references/pipelines/api.md +214 -0
  220. package/skills/cloudflare/references/pipelines/configuration.md +98 -0
  221. package/skills/cloudflare/references/pipelines/gotchas.md +84 -0
  222. package/skills/cloudflare/references/pipelines/patterns.md +87 -0
  223. package/skills/cloudflare/references/product-index.md +112 -0
  224. package/skills/cloudflare/references/pulumi/README.md +113 -0
  225. package/skills/cloudflare/references/pulumi/api.md +230 -0
  226. package/skills/cloudflare/references/pulumi/configuration.md +213 -0
  227. package/skills/cloudflare/references/pulumi/gotchas.md +205 -0
  228. package/skills/cloudflare/references/pulumi/patterns.md +260 -0
  229. package/skills/cloudflare/references/queues/README.md +99 -0
  230. package/skills/cloudflare/references/queues/api.md +211 -0
  231. package/skills/cloudflare/references/queues/configuration.md +151 -0
  232. package/skills/cloudflare/references/queues/gotchas.md +210 -0
  233. package/skills/cloudflare/references/queues/patterns.md +220 -0
  234. package/skills/cloudflare/references/r2/README.md +97 -0
  235. package/skills/cloudflare/references/r2/api.md +235 -0
  236. package/skills/cloudflare/references/r2/configuration.md +176 -0
  237. package/skills/cloudflare/references/r2/gotchas.md +190 -0
  238. package/skills/cloudflare/references/r2/patterns.md +203 -0
  239. package/skills/cloudflare/references/r2-data-catalog/README.md +157 -0
  240. package/skills/cloudflare/references/r2-data-catalog/api.md +199 -0
  241. package/skills/cloudflare/references/r2-data-catalog/configuration.md +205 -0
  242. package/skills/cloudflare/references/r2-data-catalog/gotchas.md +170 -0
  243. package/skills/cloudflare/references/r2-data-catalog/patterns.md +191 -0
  244. package/skills/cloudflare/references/r2-sql/README.md +138 -0
  245. package/skills/cloudflare/references/r2-sql/SKILL.md.backup +512 -0
  246. package/skills/cloudflare/references/r2-sql/api.md +159 -0
  247. package/skills/cloudflare/references/r2-sql/configuration.md +152 -0
  248. package/skills/cloudflare/references/r2-sql/gotchas.md +228 -0
  249. package/skills/cloudflare/references/r2-sql/patterns.md +230 -0
  250. package/skills/cloudflare/references/realtime-sfu/README.md +66 -0
  251. package/skills/cloudflare/references/realtime-sfu/api.md +164 -0
  252. package/skills/cloudflare/references/realtime-sfu/configuration.md +141 -0
  253. package/skills/cloudflare/references/realtime-sfu/gotchas.md +138 -0
  254. package/skills/cloudflare/references/realtime-sfu/patterns.md +187 -0
  255. package/skills/cloudflare/references/realtimekit/README.md +118 -0
  256. package/skills/cloudflare/references/realtimekit/api.md +234 -0
  257. package/skills/cloudflare/references/realtimekit/configuration.md +226 -0
  258. package/skills/cloudflare/references/realtimekit/gotchas.md +206 -0
  259. package/skills/cloudflare/references/realtimekit/patterns.md +240 -0
  260. package/skills/cloudflare/references/sandbox/README.md +104 -0
  261. package/skills/cloudflare/references/sandbox/api.md +200 -0
  262. package/skills/cloudflare/references/sandbox/configuration.md +154 -0
  263. package/skills/cloudflare/references/sandbox/gotchas.md +201 -0
  264. package/skills/cloudflare/references/sandbox/patterns.md +195 -0
  265. package/skills/cloudflare/references/secrets-store/README.md +77 -0
  266. package/skills/cloudflare/references/secrets-store/api.md +199 -0
  267. package/skills/cloudflare/references/secrets-store/configuration.md +187 -0
  268. package/skills/cloudflare/references/secrets-store/gotchas.md +97 -0
  269. package/skills/cloudflare/references/secrets-store/patterns.md +218 -0
  270. package/skills/cloudflare/references/smart-placement/README.md +143 -0
  271. package/skills/cloudflare/references/smart-placement/api.md +192 -0
  272. package/skills/cloudflare/references/smart-placement/configuration.md +202 -0
  273. package/skills/cloudflare/references/smart-placement/gotchas.md +180 -0
  274. package/skills/cloudflare/references/smart-placement/patterns.md +190 -0
  275. package/skills/cloudflare/references/snippets/README.md +74 -0
  276. package/skills/cloudflare/references/snippets/api.md +214 -0
  277. package/skills/cloudflare/references/snippets/configuration.md +239 -0
  278. package/skills/cloudflare/references/snippets/gotchas.md +104 -0
  279. package/skills/cloudflare/references/snippets/patterns.md +135 -0
  280. package/skills/cloudflare/references/spectrum/README.md +52 -0
  281. package/skills/cloudflare/references/spectrum/api.md +184 -0
  282. package/skills/cloudflare/references/spectrum/configuration.md +203 -0
  283. package/skills/cloudflare/references/spectrum/gotchas.md +155 -0
  284. package/skills/cloudflare/references/spectrum/patterns.md +206 -0
  285. package/skills/cloudflare/references/static-assets/README.md +65 -0
  286. package/skills/cloudflare/references/static-assets/api.md +201 -0
  287. package/skills/cloudflare/references/static-assets/configuration.md +186 -0
  288. package/skills/cloudflare/references/static-assets/gotchas.md +164 -0
  289. package/skills/cloudflare/references/static-assets/patterns.md +189 -0
  290. package/skills/cloudflare/references/stream/README.md +123 -0
  291. package/skills/cloudflare/references/stream/api-live.md +202 -0
  292. package/skills/cloudflare/references/stream/api.md +206 -0
  293. package/skills/cloudflare/references/stream/configuration.md +151 -0
  294. package/skills/cloudflare/references/stream/gotchas.md +139 -0
  295. package/skills/cloudflare/references/stream/patterns.md +217 -0
  296. package/skills/cloudflare/references/tail-workers/README.md +92 -0
  297. package/skills/cloudflare/references/tail-workers/api.md +203 -0
  298. package/skills/cloudflare/references/tail-workers/configuration.md +178 -0
  299. package/skills/cloudflare/references/tail-workers/gotchas.md +206 -0
  300. package/skills/cloudflare/references/tail-workers/patterns.md +190 -0
  301. package/skills/cloudflare/references/terraform/README.md +100 -0
  302. package/skills/cloudflare/references/terraform/api.md +178 -0
  303. package/skills/cloudflare/references/terraform/configuration.md +197 -0
  304. package/skills/cloudflare/references/terraform/gotchas.md +150 -0
  305. package/skills/cloudflare/references/terraform/patterns.md +174 -0
  306. package/skills/cloudflare/references/tunnel/README.md +137 -0
  307. package/skills/cloudflare/references/tunnel/api.md +205 -0
  308. package/skills/cloudflare/references/tunnel/configuration.md +163 -0
  309. package/skills/cloudflare/references/tunnel/gotchas.md +159 -0
  310. package/skills/cloudflare/references/tunnel/networking.md +174 -0
  311. package/skills/cloudflare/references/tunnel/patterns.md +199 -0
  312. package/skills/cloudflare/references/turn/README.md +86 -0
  313. package/skills/cloudflare/references/turn/api.md +236 -0
  314. package/skills/cloudflare/references/turn/configuration.md +181 -0
  315. package/skills/cloudflare/references/turn/gotchas.md +236 -0
  316. package/skills/cloudflare/references/turn/patterns.md +228 -0
  317. package/skills/cloudflare/references/turnstile/README.md +102 -0
  318. package/skills/cloudflare/references/turnstile/api.md +253 -0
  319. package/skills/cloudflare/references/turnstile/configuration.md +242 -0
  320. package/skills/cloudflare/references/turnstile/gotchas.md +253 -0
  321. package/skills/cloudflare/references/turnstile/patterns.md +195 -0
  322. package/skills/cloudflare/references/vectorize/README.md +133 -0
  323. package/skills/cloudflare/references/vectorize/api.md +89 -0
  324. package/skills/cloudflare/references/vectorize/configuration.md +91 -0
  325. package/skills/cloudflare/references/vectorize/gotchas.md +83 -0
  326. package/skills/cloudflare/references/vectorize/patterns.md +92 -0
  327. package/skills/cloudflare/references/waf/README.md +125 -0
  328. package/skills/cloudflare/references/waf/api.md +203 -0
  329. package/skills/cloudflare/references/waf/configuration.md +215 -0
  330. package/skills/cloudflare/references/waf/gotchas.md +208 -0
  331. package/skills/cloudflare/references/waf/patterns.md +236 -0
  332. package/skills/cloudflare/references/web-analytics/README.md +149 -0
  333. package/skills/cloudflare/references/web-analytics/configuration.md +81 -0
  334. package/skills/cloudflare/references/web-analytics/gotchas.md +86 -0
  335. package/skills/cloudflare/references/web-analytics/integration.md +63 -0
  336. package/skills/cloudflare/references/web-analytics/patterns.md +98 -0
  337. package/skills/cloudflare/references/workerd/README.md +85 -0
  338. package/skills/cloudflare/references/workerd/api.md +219 -0
  339. package/skills/cloudflare/references/workerd/configuration.md +200 -0
  340. package/skills/cloudflare/references/workerd/gotchas.md +151 -0
  341. package/skills/cloudflare/references/workerd/patterns.md +205 -0
  342. package/skills/cloudflare/references/workers/README.md +110 -0
  343. package/skills/cloudflare/references/workers/api.md +197 -0
  344. package/skills/cloudflare/references/workers/configuration.md +184 -0
  345. package/skills/cloudflare/references/workers/frameworks.md +200 -0
  346. package/skills/cloudflare/references/workers/gotchas.md +145 -0
  347. package/skills/cloudflare/references/workers/patterns.md +220 -0
  348. package/skills/cloudflare/references/workers-ai/README.md +206 -0
  349. package/skills/cloudflare/references/workers-ai/api.md +115 -0
  350. package/skills/cloudflare/references/workers-ai/configuration.md +98 -0
  351. package/skills/cloudflare/references/workers-ai/gotchas.md +130 -0
  352. package/skills/cloudflare/references/workers-ai/patterns.md +122 -0
  353. package/skills/cloudflare/references/workers-for-platforms/README.md +95 -0
  354. package/skills/cloudflare/references/workers-for-platforms/api.md +212 -0
  355. package/skills/cloudflare/references/workers-for-platforms/configuration.md +178 -0
  356. package/skills/cloudflare/references/workers-for-platforms/gotchas.md +134 -0
  357. package/skills/cloudflare/references/workers-for-platforms/patterns.md +210 -0
  358. package/skills/cloudflare/references/workers-playground/README.md +131 -0
  359. package/skills/cloudflare/references/workers-playground/api.md +101 -0
  360. package/skills/cloudflare/references/workers-playground/configuration.md +169 -0
  361. package/skills/cloudflare/references/workers-playground/gotchas.md +88 -0
  362. package/skills/cloudflare/references/workers-playground/patterns.md +134 -0
  363. package/skills/cloudflare/references/workers-vpc/README.md +130 -0
  364. package/skills/cloudflare/references/workers-vpc/api.md +196 -0
  365. package/skills/cloudflare/references/workers-vpc/configuration.md +151 -0
  366. package/skills/cloudflare/references/workers-vpc/gotchas.md +171 -0
  367. package/skills/cloudflare/references/workers-vpc/patterns.md +235 -0
  368. package/skills/cloudflare/references/workflows/README.md +72 -0
  369. package/skills/cloudflare/references/workflows/api.md +237 -0
  370. package/skills/cloudflare/references/workflows/configuration.md +158 -0
  371. package/skills/cloudflare/references/workflows/gotchas.md +97 -0
  372. package/skills/cloudflare/references/workflows/patterns.md +245 -0
  373. package/skills/cloudflare/references/wrangler/README.md +143 -0
  374. package/skills/cloudflare/references/wrangler/api.md +188 -0
  375. package/skills/cloudflare/references/wrangler/configuration.md +198 -0
  376. package/skills/cloudflare/references/wrangler/gotchas.md +212 -0
  377. package/skills/cloudflare/references/wrangler/patterns.md +211 -0
  378. package/skills/cloudflare/references/zaraz/IMPLEMENTATION_SUMMARY.md +131 -0
  379. package/skills/cloudflare/references/zaraz/README.md +114 -0
  380. package/skills/cloudflare/references/zaraz/api.md +118 -0
  381. package/skills/cloudflare/references/zaraz/configuration.md +94 -0
  382. package/skills/cloudflare/references/zaraz/gotchas.md +88 -0
  383. package/skills/cloudflare/references/zaraz/patterns.md +77 -0
  384. package/skills/docker/SKILL.md +7 -101
  385. package/skills/docker/references/advanced-examples.md +71 -0
  386. package/skills/docker/references/templates.md +34 -0
  387. package/skills/docs-marketer/SKILL.md +178 -0
  388. package/skills/docs-marketer/references/audit-categories.md +328 -0
  389. package/skills/docs-marketer/references/copilot-docs-prompts.md +88 -0
  390. package/skills/docs-marketer/references/copilot-usage.md +16 -0
  391. package/skills/docs-marketer/references/feedback-loop.md +155 -0
  392. package/skills/docs-marketer/references/multi-pass-docs-protocol.md +410 -0
  393. package/skills/drizzle-orm/SKILL.md +82 -0
  394. package/skills/durable-objects/SKILL.md +167 -0
  395. package/skills/durable-objects/references/advanced_features.md +29 -0
  396. package/skills/durable-objects/references/rules.md +300 -0
  397. package/skills/durable-objects/references/testing.md +261 -0
  398. package/skills/durable-objects/references/workers.md +336 -0
  399. package/skills/gcp/SKILL.md +37 -0
  400. package/skills/github-actions/SKILL.md +5 -58
  401. package/skills/github-actions/references/templates.md +65 -0
  402. package/skills/github-commander/SKILL.md +13 -21
  403. package/skills/github-commander/workflows/copilot-audit.md +12 -12
  404. package/skills/github-copilot-cli/SKILL.md +21 -26
  405. package/skills/github-repo-setup/SKILL.md +136 -0
  406. package/skills/github-repo-setup/references/community-standards.md +136 -0
  407. package/skills/github-repo-setup/references/github-automation.md +490 -0
  408. package/skills/github-repo-setup/references/inline-templates.md +205 -0
  409. package/skills/github-repo-setup/references/project-config.md +320 -0
  410. package/skills/gitlab/SKILL.md +7 -2
  411. package/skills/gitlab/package-lock.json +389 -389
  412. package/skills/golang/SKILL.md +8 -1
  413. package/skills/graphql/SKILL.md +30 -0
  414. package/skills/hono/SKILL.md +82 -0
  415. package/skills/journal-optimizer/SKILL.md +206 -0
  416. package/skills/journal-optimizer/references/optimizer-scripts.md +169 -0
  417. package/skills/llm-app-engineering/SKILL.md +18 -0
  418. package/skills/monorepo/SKILL.md +56 -0
  419. package/skills/multi-agent-orchestration/SKILL.md +14 -0
  420. package/skills/mysql/SKILL.md +6 -2
  421. package/skills/next-best-practices/SKILL.md +86 -0
  422. package/skills/next-best-practices/references/cache-components-examples.md +234 -0
  423. package/skills/next-best-practices/references/cache-components.md +210 -0
  424. package/skills/next-best-practices/references/upgrade-decision-tree.md +33 -0
  425. package/skills/next-best-practices/references/upgrade.md +43 -0
  426. package/skills/next-cache-components/SKILL.md +441 -0
  427. package/skills/next-upgrade/SKILL.md +43 -0
  428. package/skills/next-upgrade/references/decision-tree.md +33 -0
  429. package/skills/nodejs/SKILL.md +46 -0
  430. package/skills/opentelemetry/SKILL.md +62 -0
  431. package/skills/package.json +39 -4
  432. package/skills/playwright-standard/SKILL.md +6 -11
  433. package/skills/playwright-standard/references/locators.md +7 -0
  434. package/skills/postgres/SKILL.md +6 -1
  435. package/skills/python/SKILL.md +8 -70
  436. package/skills/python/references/advanced-patterns.md +37 -0
  437. package/skills/python/references/config-templates.md +48 -0
  438. package/skills/rag-pipelines/SKILL.md +14 -0
  439. package/skills/redis/SKILL.md +31 -0
  440. package/skills/render/SKILL.md +35 -0
  441. package/skills/rust/SKILL.md +15 -25
  442. package/skills/rust/references/borrow-checker.md +13 -0
  443. package/skills/rust/references/ecosystem.md +11 -0
  444. package/skills/sandbox-sdk/SKILL.md +186 -0
  445. package/skills/sandbox-sdk/references/api-quick-ref.md +113 -0
  446. package/skills/sandbox-sdk/references/examples.md +52 -0
  447. package/skills/shadcn-ui/SKILL.md +22 -57
  448. package/skills/skill-builder/SKILL.md +23 -424
  449. package/skills/skill-builder/references/tutorial.md +457 -0
  450. package/skills/sqlite/SKILL.md +16 -5
  451. package/skills/table.md +59 -0
  452. package/skills/tailwind-css/SKILL.md +11 -60
  453. package/skills/tailwind-css/references/component-patterns.md +52 -0
  454. package/skills/trpc/SKILL.md +56 -0
  455. package/skills/typescript/SKILL.md +30 -433
  456. package/skills/typescript/references/tutorial.md +453 -0
  457. package/skills/vercel-ai-sdk/SKILL.md +48 -0
  458. package/skills/vitest-standard/SKILL.md +5 -11
  459. package/skills/vitest-standard/references/assertions.md +11 -0
  460. package/skills/web-perf/SKILL.md +207 -0
  461. package/skills/workers-best-practices/SKILL.md +120 -0
  462. package/skills/workers-best-practices/references/anti-patterns.md +18 -0
  463. package/skills/workers-best-practices/references/review.md +174 -0
  464. package/skills/workers-best-practices/references/rules.md +485 -0
  465. package/skills/wrangler/SKILL.md +43 -0
  466. package/skills/wrangler/references/cli-commands.md +861 -0
  467. package/skills/zod/SKILL.md +48 -0
  468. package/dist/tools-P4VGG4FH.js +0 -1
  469. package/skills/react-best-practices/AGENTS.md +0 -2883
  470. package/skills/react-best-practices/SKILL.md +0 -138
  471. /package/skills/{react-best-practices → next-best-practices}/README.md +0 -0
  472. /package/skills/{react-best-practices → next-best-practices}/metadata.json +0 -0
  473. /package/skills/{react-best-practices → next-best-practices}/rules/_sections.md +0 -0
  474. /package/skills/{react-best-practices → next-best-practices}/rules/_template.md +0 -0
  475. /package/skills/{react-best-practices → next-best-practices}/rules/advanced-event-handler-refs.md +0 -0
  476. /package/skills/{react-best-practices → next-best-practices}/rules/advanced-init-once.md +0 -0
  477. /package/skills/{react-best-practices → next-best-practices}/rules/advanced-use-latest.md +0 -0
  478. /package/skills/{react-best-practices → next-best-practices}/rules/async-api-routes.md +0 -0
  479. /package/skills/{react-best-practices → next-best-practices}/rules/async-defer-await.md +0 -0
  480. /package/skills/{react-best-practices → next-best-practices}/rules/async-dependencies.md +0 -0
  481. /package/skills/{react-best-practices → next-best-practices}/rules/async-parallel.md +0 -0
  482. /package/skills/{react-best-practices → next-best-practices}/rules/async-suspense-boundaries.md +0 -0
  483. /package/skills/{react-best-practices → next-best-practices}/rules/bundle-barrel-imports.md +0 -0
  484. /package/skills/{react-best-practices → next-best-practices}/rules/bundle-conditional.md +0 -0
  485. /package/skills/{react-best-practices → next-best-practices}/rules/bundle-defer-third-party.md +0 -0
  486. /package/skills/{react-best-practices → next-best-practices}/rules/bundle-dynamic-imports.md +0 -0
  487. /package/skills/{react-best-practices → next-best-practices}/rules/bundle-preload.md +0 -0
  488. /package/skills/{react-best-practices → next-best-practices}/rules/client-event-listeners.md +0 -0
  489. /package/skills/{react-best-practices → next-best-practices}/rules/client-localstorage-schema.md +0 -0
  490. /package/skills/{react-best-practices → next-best-practices}/rules/client-passive-event-listeners.md +0 -0
  491. /package/skills/{react-best-practices → next-best-practices}/rules/client-swr-dedup.md +0 -0
  492. /package/skills/{react-best-practices → next-best-practices}/rules/js-batch-dom-css.md +0 -0
  493. /package/skills/{react-best-practices → next-best-practices}/rules/js-cache-function-results.md +0 -0
  494. /package/skills/{react-best-practices → next-best-practices}/rules/js-cache-property-access.md +0 -0
  495. /package/skills/{react-best-practices → next-best-practices}/rules/js-cache-storage.md +0 -0
  496. /package/skills/{react-best-practices → next-best-practices}/rules/js-combine-iterations.md +0 -0
  497. /package/skills/{react-best-practices → next-best-practices}/rules/js-early-exit.md +0 -0
  498. /package/skills/{react-best-practices → next-best-practices}/rules/js-hoist-regexp.md +0 -0
  499. /package/skills/{react-best-practices → next-best-practices}/rules/js-index-maps.md +0 -0
  500. /package/skills/{react-best-practices → next-best-practices}/rules/js-length-check-first.md +0 -0
  501. /package/skills/{react-best-practices → next-best-practices}/rules/js-min-max-loop.md +0 -0
  502. /package/skills/{react-best-practices → next-best-practices}/rules/js-set-map-lookups.md +0 -0
  503. /package/skills/{react-best-practices → next-best-practices}/rules/js-tosorted-immutable.md +0 -0
  504. /package/skills/{react-best-practices → next-best-practices}/rules/rendering-activity.md +0 -0
  505. /package/skills/{react-best-practices → next-best-practices}/rules/rendering-animate-svg-wrapper.md +0 -0
  506. /package/skills/{react-best-practices → next-best-practices}/rules/rendering-conditional-render.md +0 -0
  507. /package/skills/{react-best-practices → next-best-practices}/rules/rendering-content-visibility.md +0 -0
  508. /package/skills/{react-best-practices → next-best-practices}/rules/rendering-hoist-jsx.md +0 -0
  509. /package/skills/{react-best-practices → next-best-practices}/rules/rendering-hydration-no-flicker.md +0 -0
  510. /package/skills/{react-best-practices → next-best-practices}/rules/rendering-hydration-suppress-warning.md +0 -0
  511. /package/skills/{react-best-practices → next-best-practices}/rules/rendering-svg-precision.md +0 -0
  512. /package/skills/{react-best-practices → next-best-practices}/rules/rendering-usetransition-loading.md +0 -0
  513. /package/skills/{react-best-practices → next-best-practices}/rules/rerender-defer-reads.md +0 -0
  514. /package/skills/{react-best-practices → next-best-practices}/rules/rerender-dependencies.md +0 -0
  515. /package/skills/{react-best-practices → next-best-practices}/rules/rerender-derived-state-no-effect.md +0 -0
  516. /package/skills/{react-best-practices → next-best-practices}/rules/rerender-derived-state.md +0 -0
  517. /package/skills/{react-best-practices → next-best-practices}/rules/rerender-functional-setstate.md +0 -0
  518. /package/skills/{react-best-practices → next-best-practices}/rules/rerender-lazy-state-init.md +0 -0
  519. /package/skills/{react-best-practices → next-best-practices}/rules/rerender-memo-with-default-value.md +0 -0
  520. /package/skills/{react-best-practices → next-best-practices}/rules/rerender-memo.md +0 -0
  521. /package/skills/{react-best-practices → next-best-practices}/rules/rerender-move-effect-to-event.md +0 -0
  522. /package/skills/{react-best-practices → next-best-practices}/rules/rerender-simple-expression-in-memo.md +0 -0
  523. /package/skills/{react-best-practices → next-best-practices}/rules/rerender-transitions.md +0 -0
  524. /package/skills/{react-best-practices → next-best-practices}/rules/rerender-use-ref-transient-values.md +0 -0
  525. /package/skills/{react-best-practices → next-best-practices}/rules/server-after-nonblocking.md +0 -0
  526. /package/skills/{react-best-practices → next-best-practices}/rules/server-auth-actions.md +0 -0
  527. /package/skills/{react-best-practices → next-best-practices}/rules/server-cache-lru.md +0 -0
  528. /package/skills/{react-best-practices → next-best-practices}/rules/server-cache-react.md +0 -0
  529. /package/skills/{react-best-practices → next-best-practices}/rules/server-dedup-props.md +0 -0
  530. /package/skills/{react-best-practices → next-best-practices}/rules/server-parallel-fetching.md +0 -0
  531. /package/skills/{react-best-practices → next-best-practices}/rules/server-serialization.md +0 -0
@@ -0,0 +1,3231 @@
1
+ import { AsyncLocalStorage } from 'async_hooks';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import { Octokit } from '@octokit/rest';
5
+ import { graphql } from '@octokit/graphql';
6
+ import * as simpleGitImport from 'simple-git';
7
+ import { createHash } from 'crypto';
8
+ import { z } from 'zod';
9
+
10
+ // src/utils/errors/suggestions.ts
11
+ var GENERIC_CODES = /* @__PURE__ */ new Set(["QUERY_FAILED", "INTERNAL_ERROR", "UNKNOWN_ERROR"]);
12
+ var ERROR_SUGGESTIONS = [
13
+ // Resource not found patterns
14
+ {
15
+ pattern: /not found/i,
16
+ suggestion: "Verify the resource identifier and try again",
17
+ code: "RESOURCE_NOT_FOUND"
18
+ },
19
+ {
20
+ pattern: /no such table/i,
21
+ suggestion: "The database table does not exist. Run database initialization.",
22
+ code: "TABLE_NOT_FOUND"
23
+ },
24
+ // Permission / access patterns
25
+ {
26
+ pattern: /permission denied|SQLITE_READONLY/i,
27
+ suggestion: "Check file permissions and database access rights",
28
+ code: "PERMISSION_DENIED"
29
+ },
30
+ // Connection / lock patterns
31
+ {
32
+ pattern: /database is locked/i,
33
+ suggestion: "The database is locked by another process. Retry after a short delay.",
34
+ code: "CONNECTION_FAILED"
35
+ },
36
+ // Constraint patterns
37
+ {
38
+ pattern: /SQLITE_CONSTRAINT|unique constraint/i,
39
+ suggestion: "A uniqueness or integrity constraint was violated. Check input values.",
40
+ code: "VALIDATION_ERROR"
41
+ },
42
+ // Disk / space patterns
43
+ {
44
+ pattern: /disk I\/O|SQLITE_FULL/i,
45
+ suggestion: "The disk may be full or the filesystem is read-only."
46
+ },
47
+ // Malformed input patterns
48
+ {
49
+ pattern: /malformed|invalid json|unexpected token/i,
50
+ suggestion: "The input appears malformed. Check the format and try again.",
51
+ code: "VALIDATION_ERROR"
52
+ },
53
+ // Schema / types patterns
54
+ {
55
+ pattern: /invalid input syntax for type|requires a.*column/i,
56
+ suggestion: "The provided value is not valid for the assigned type.",
57
+ code: "VALIDATION_ERROR"
58
+ },
59
+ {
60
+ pattern: /^Missing required parameters:/i,
61
+ suggestion: "Provide all required parameters in your request.",
62
+ code: "VALIDATION_ERROR"
63
+ },
64
+ // Codemode / Sandbox patterns
65
+ {
66
+ pattern: /execution timed out/i,
67
+ suggestion: "Reduce code complexity or increase timeout (max 30s). Break into smaller operations.",
68
+ code: "QUERY_FAILED"
69
+ },
70
+ {
71
+ pattern: /code validation failed/i,
72
+ suggestion: "Check for blocked patterns. Use mj.* API instead.",
73
+ code: "VALIDATION_ERROR"
74
+ },
75
+ {
76
+ pattern: /sandbox.*not initialized/i,
77
+ suggestion: "Internal sandbox error. Retry the operation.",
78
+ code: "INTERNAL_ERROR"
79
+ },
80
+ // Zod enum validation patterns — return valid values for self-correction
81
+ {
82
+ pattern: /invalid enum value.*significance/i,
83
+ suggestion: "Valid significance_type values: milestone, breakthrough, decision, architecture, lesson_learned, blocker_resolved, release, security",
84
+ code: "VALIDATION_ERROR"
85
+ },
86
+ {
87
+ pattern: /invalid enum value.*entry.?type/i,
88
+ suggestion: "Valid entry_type values: retrospective, bug_fix, project_decision, feature_implementation, technical_note, code_review, planning, research, enhancement, milestone, adversarial_review, development_note, learning, standup, meeting_notes, technical_achievement, plan_draft, plan_refinement, copilot_validation, other, personal_reflection",
89
+ code: "VALIDATION_ERROR"
90
+ }
91
+ ];
92
+ function matchSuggestion(message) {
93
+ for (const entry of ERROR_SUGGESTIONS) {
94
+ if (entry.pattern.test(message)) {
95
+ return { suggestion: entry.suggestion, code: entry.code };
96
+ }
97
+ }
98
+ return void 0;
99
+ }
100
+
101
+ // src/types/errors.ts
102
+ var MemoryJournalMcpError = class extends Error {
103
+ /** Module-prefixed error code */
104
+ code;
105
+ /** Error category for programmatic handling */
106
+ category;
107
+ /** Actionable suggestion for resolving the error */
108
+ suggestion;
109
+ /** Whether the operation can be retried */
110
+ recoverable;
111
+ /** Additional structured context */
112
+ details;
113
+ constructor(message, code, category, options) {
114
+ super(message, options?.cause ? { cause: options.cause } : void 0);
115
+ this.name = "MemoryJournalMcpError";
116
+ this.category = category;
117
+ this.recoverable = options?.recoverable ?? false;
118
+ this.details = options?.details;
119
+ const matched = matchSuggestion(message);
120
+ if (GENERIC_CODES.has(code) && matched?.code) {
121
+ this.code = matched.code;
122
+ } else {
123
+ this.code = code;
124
+ }
125
+ this.suggestion = options?.suggestion ?? matched?.suggestion;
126
+ }
127
+ /**
128
+ * Convert to a structured ErrorResponse for tool responses.
129
+ */
130
+ toResponse() {
131
+ return {
132
+ success: false,
133
+ error: this.message,
134
+ code: this.code,
135
+ category: this.category,
136
+ suggestion: this.suggestion,
137
+ recoverable: this.recoverable,
138
+ ...this.details ? { details: this.details } : {}
139
+ };
140
+ }
141
+ };
142
+ var ConnectionError = class extends MemoryJournalMcpError {
143
+ constructor(message, details) {
144
+ super(message, "CONNECTION_FAILED", "connection" /* CONNECTION */, {
145
+ suggestion: "Check database path and file permissions",
146
+ recoverable: true,
147
+ details
148
+ });
149
+ this.name = "ConnectionError";
150
+ }
151
+ };
152
+ var QueryError = class extends MemoryJournalMcpError {
153
+ constructor(message, details) {
154
+ super(message, "QUERY_FAILED", "query" /* QUERY */, {
155
+ suggestion: "Check query parameters and database state",
156
+ recoverable: false,
157
+ details
158
+ });
159
+ this.name = "QueryError";
160
+ }
161
+ };
162
+ var ValidationError = class extends MemoryJournalMcpError {
163
+ constructor(message, details) {
164
+ super(message, "VALIDATION_ERROR", "validation" /* VALIDATION */, {
165
+ suggestion: "Check input parameters against the tool schema",
166
+ recoverable: false,
167
+ details
168
+ });
169
+ this.name = "ValidationError";
170
+ }
171
+ };
172
+ var ResourceNotFoundError = class extends MemoryJournalMcpError {
173
+ constructor(resourceType, identifier) {
174
+ super(
175
+ `${resourceType} not found: ${identifier}`,
176
+ "RESOURCE_NOT_FOUND",
177
+ "resource" /* RESOURCE */,
178
+ {
179
+ suggestion: `Verify the ${resourceType.toLowerCase()} identifier and try again`,
180
+ recoverable: false,
181
+ details: { resourceType, identifier }
182
+ }
183
+ );
184
+ this.name = "ResourceNotFoundError";
185
+ }
186
+ };
187
+ var ConfigurationError = class extends MemoryJournalMcpError {
188
+ constructor(message, details) {
189
+ super(message, "CONFIGURATION_ERROR", "configuration" /* CONFIGURATION */, {
190
+ suggestion: "Check server configuration and environment variables",
191
+ recoverable: false,
192
+ details
193
+ });
194
+ this.name = "ConfigurationError";
195
+ }
196
+ };
197
+ var PermissionError = class extends MemoryJournalMcpError {
198
+ constructor(message, details) {
199
+ super(message, "PERMISSION_DENIED", "permission" /* PERMISSION */, {
200
+ suggestion: "Check file permissions and database access rights",
201
+ recoverable: false,
202
+ details
203
+ });
204
+ this.name = "PermissionError";
205
+ }
206
+ };
207
+ var authContextStorage = new AsyncLocalStorage();
208
+ function runWithAuthContext(context, fn) {
209
+ return authContextStorage.run(context, fn);
210
+ }
211
+ function getAuthContext() {
212
+ return authContextStorage.getStore();
213
+ }
214
+ var SecurityError = class extends MemoryJournalMcpError {
215
+ constructor(message, code) {
216
+ super(message, code, "validation" /* VALIDATION */, {
217
+ suggestion: "Check input for security violations",
218
+ recoverable: false
219
+ });
220
+ this.name = "SecurityError";
221
+ }
222
+ };
223
+ var InvalidDateFormatError = class extends SecurityError {
224
+ constructor(value) {
225
+ super(`Invalid date format pattern: '${value}'`, "INVALID_DATE_FORMAT");
226
+ this.name = "InvalidDateFormatError";
227
+ }
228
+ };
229
+ var PathTraversalError = class extends SecurityError {
230
+ constructor(path2) {
231
+ super(`Path traversal detected: '${path2}'`, "PATH_TRAVERSAL");
232
+ this.name = "PathTraversalError";
233
+ }
234
+ };
235
+ var ALLOWED_DATE_FORMATS = {
236
+ day: "%Y-%m-%d",
237
+ week: "%Y-W%W",
238
+ month: "%Y-%m"
239
+ };
240
+ function validateDateFormatPattern(groupBy) {
241
+ const format = ALLOWED_DATE_FORMATS[groupBy];
242
+ if (!format) {
243
+ throw new InvalidDateFormatError(groupBy);
244
+ }
245
+ return format;
246
+ }
247
+ function sanitizeSearchQuery(query) {
248
+ return query.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
249
+ }
250
+ function assertNoPathTraversal(filename) {
251
+ if (filename.includes("/") || filename.includes("\\") || filename.includes("..")) {
252
+ throw new PathTraversalError(filename);
253
+ }
254
+ }
255
+ function assertSafeDirectoryPath(dirPath, providedRoots) {
256
+ const normalized = dirPath.replace(/\\/g, "/");
257
+ const segments = normalized.split("/");
258
+ if (segments.some((s) => s === "..")) {
259
+ throw new PathTraversalError(dirPath);
260
+ }
261
+ const resolved = path.resolve(dirPath);
262
+ let currentDir = resolved;
263
+ let existingRealPath = "";
264
+ while (currentDir !== path.parse(currentDir).root) {
265
+ try {
266
+ existingRealPath = fs.realpathSync(currentDir);
267
+ break;
268
+ } catch {
269
+ currentDir = path.dirname(currentDir);
270
+ }
271
+ }
272
+ if (!existingRealPath) {
273
+ try {
274
+ existingRealPath = fs.realpathSync(currentDir);
275
+ } catch {
276
+ existingRealPath = currentDir;
277
+ }
278
+ }
279
+ const remainder = path.relative(currentDir, resolved);
280
+ const targetPath = remainder ? path.join(existingRealPath, remainder) : existingRealPath;
281
+ const rawRoots = providedRoots;
282
+ if (rawRoots.length === 0) {
283
+ throw new PathTraversalError(
284
+ "No allowed input/output roots configured for sandbox boundary. Please configure ALLOWED_IO_ROOTS env variable or pass --allowed-io-roots with absolute paths (e.g. C:\\my\\path) to enable filesystem operations."
285
+ );
286
+ }
287
+ const allowedRoots = [];
288
+ for (const root of rawRoots) {
289
+ try {
290
+ allowedRoots.push(fs.realpathSync(path.resolve(root)));
291
+ } catch {
292
+ allowedRoots.push(path.resolve(root));
293
+ }
294
+ }
295
+ const isAllowed = allowedRoots.some((root) => {
296
+ const rel = path.relative(root, targetPath);
297
+ return rel !== ".." && !rel.startsWith(".." + path.sep) && !path.isAbsolute(rel);
298
+ });
299
+ if (!isAllowed) {
300
+ throw new PathTraversalError(
301
+ `Directory path escapes allowed sandbox boundaries: ${dirPath}`
302
+ );
303
+ }
304
+ }
305
+ function assertSafeFilePath(filePath, providedRoots) {
306
+ assertSafeDirectoryPath(path.dirname(filePath), providedRoots);
307
+ try {
308
+ const stats = fs.lstatSync(filePath);
309
+ if (stats.isSymbolicLink()) {
310
+ throw new PathTraversalError(
311
+ `Symlinks are strictly forbidden for file operations: ${filePath}`
312
+ );
313
+ }
314
+ } catch (err) {
315
+ if (err instanceof PathTraversalError) {
316
+ throw err;
317
+ }
318
+ }
319
+ }
320
+ var TOKEN_PATTERNS = [
321
+ // GitHub personal access tokens (classic and fine-grained)
322
+ /gh[pousr]_[A-Za-z0-9_]{36,}/g,
323
+ /github_pat_[A-Za-z0-9_]{82,}/g,
324
+ // JWT Tokens
325
+ /eyJ[a-zA-Z0-9_-]{2,}\.eyJ[a-zA-Z0-9_-]{2,}\.[a-zA-Z0-9_-]{2,}/g,
326
+ // Slack tokens
327
+ /xox[baprs]-[A-Za-z0-9-]+/g,
328
+ // AWS API Keys
329
+ /(?:AKIA|ABIA|ACCA|ASIA)[0-9A-Z]{16}/g,
330
+ // Authorization headers in error dumps (catch-all for token, Bearer, Basic)
331
+ /Authorization:(?:\s+(?:token|Bearer|Basic))?\s+["']?[A-Za-z0-9._~+/#=-]+["']?/gi,
332
+ // Generic token patterns standalone
333
+ /Bearer\s+["']?[A-Za-z0-9._~+/#=-]+["']?/gi,
334
+ /Basic\s+["']?[A-Za-z0-9._~+/#=-]+["']?/gi
335
+ ];
336
+ function sanitizeErrorForLogging(message) {
337
+ let sanitized = message;
338
+ for (const pattern of TOKEN_PATTERNS) {
339
+ pattern.lastIndex = 0;
340
+ sanitized = sanitized.replace(pattern, "[REDACTED]");
341
+ }
342
+ return sanitized;
343
+ }
344
+ function markUntrustedContent(content) {
345
+ if (!content) return "";
346
+ let trimmed = content.trim();
347
+ if (!trimmed) return "";
348
+ trimmed = trimmed.replace(/<\/?untrusted_remote_content[^>]*>/gi, "");
349
+ trimmed = trimmed.replace(/</g, "&lt;").replace(/>/g, "&gt;");
350
+ return `<untrusted_remote_content>
351
+ ${trimmed}
352
+ </untrusted_remote_content>`;
353
+ }
354
+ function markUntrustedContentInline(content) {
355
+ if (!content) return "";
356
+ let cleaned = content;
357
+ cleaned = cleaned.replace(/<\/?untrusted_remote_content[^>]*>/gi, "");
358
+ cleaned = cleaned.replace(/</g, "&lt;").replace(/>/g, "&gt;");
359
+ return `<untrusted_remote_content>${cleaned}</untrusted_remote_content>`;
360
+ }
361
+ function sanitizeAuthor(raw) {
362
+ return raw.replace(/[\x00-\x1f\x7f]/g, "").slice(0, 100);
363
+ }
364
+ function resolveAuthenticatedAuthor() {
365
+ const authCtx = getAuthContext();
366
+ if (authCtx?.authenticated && authCtx.claims) {
367
+ const claims = authCtx.claims;
368
+ const email = typeof claims["email"] === "string" ? claims["email"] : void 0;
369
+ const prefName = typeof claims["preferred_username"] === "string" ? claims["preferred_username"] : void 0;
370
+ const subject = typeof claims["subject"] === "string" ? claims["subject"] : void 0;
371
+ const claimAuthor = email ?? prefName ?? claims.sub ?? subject;
372
+ if (claimAuthor) {
373
+ return sanitizeAuthor(claimAuthor);
374
+ }
375
+ }
376
+ return resolveAuthor();
377
+ }
378
+ function resolveAuthor() {
379
+ const envAuthor = process.env["TEAM_AUTHOR"]?.trim().replace(/"/g, "");
380
+ if (envAuthor) {
381
+ return sanitizeAuthor(envAuthor);
382
+ }
383
+ const authCtx = getAuthContext();
384
+ if (authCtx?.claims?.sub) {
385
+ return sanitizeAuthor(authCtx.claims.sub);
386
+ }
387
+ return "unknown";
388
+ }
389
+
390
+ // src/utils/logger.ts
391
+ var LOG_LEVELS = {
392
+ debug: 7,
393
+ info: 6,
394
+ notice: 5,
395
+ warning: 4,
396
+ error: 3,
397
+ critical: 2
398
+ };
399
+ var Logger = class {
400
+ minLevel;
401
+ constructor(level = "info") {
402
+ this.minLevel = LOG_LEVELS[level];
403
+ }
404
+ shouldLog(level) {
405
+ return LOG_LEVELS[level] <= this.minLevel;
406
+ }
407
+ log(level, message, context) {
408
+ if (!this.shouldLog(level)) return;
409
+ const safeMessage = message.replace(/\n|\r/g, "");
410
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
411
+ const levelUpper = level.toUpperCase().padEnd(8);
412
+ const mod = context?.module ? `[${context.module.replace(/\n|\r/g, "")}]` : "";
413
+ const op = context?.operation ? `[${context.operation.replace(/\n|\r/g, "")}]` : "";
414
+ let line = `[${timestamp}] [${levelUpper}] ${mod}${op} ${safeMessage}`;
415
+ const extras = { ...context };
416
+ delete extras["module"];
417
+ delete extras["operation"];
418
+ if (extras["error"] != null && typeof extras["error"] === "string") {
419
+ extras["error"] = sanitizeErrorForLogging(extras["error"]);
420
+ }
421
+ if (Object.keys(extras).length > 0) {
422
+ line += ` ${JSON.stringify(extras).replace(/\n|\r/g, "")}`;
423
+ }
424
+ console.error(line);
425
+ }
426
+ debug(message, context) {
427
+ this.log("debug", message, context);
428
+ }
429
+ info(message, context) {
430
+ this.log("info", message, context);
431
+ }
432
+ notice(message, context) {
433
+ this.log("notice", message, context);
434
+ }
435
+ warning(message, context) {
436
+ this.log("warning", message, context);
437
+ }
438
+ error(message, context) {
439
+ this.log("error", message, context);
440
+ }
441
+ critical(message, context) {
442
+ this.log("critical", message, context);
443
+ }
444
+ setLevel(level) {
445
+ if (level in LOG_LEVELS) {
446
+ this.minLevel = LOG_LEVELS[level];
447
+ }
448
+ }
449
+ };
450
+ var rawLevel = process.env["LOG_LEVEL"] ?? "info";
451
+ var envLevel = rawLevel in LOG_LEVELS ? rawLevel : "info";
452
+ var logger = new Logger(envLevel);
453
+
454
+ // src/filtering/tool-filter.ts
455
+ var TOOL_GROUPS = {
456
+ core: [
457
+ "create_entry",
458
+ "get_entry_by_id",
459
+ "get_recent_entries",
460
+ "create_entry_minimal",
461
+ "test_simple",
462
+ "list_tags"
463
+ ],
464
+ search: ["search_entries", "search_by_date_range", "semantic_search", "get_vector_index_stats"],
465
+ analytics: ["get_statistics", "get_cross_project_insights"],
466
+ relationships: ["link_entries", "visualize_relationships"],
467
+ io: ["export_entries", "export_markdown", "import_markdown"],
468
+ admin: [
469
+ "update_entry",
470
+ "delete_entry",
471
+ "rebuild_vector_index",
472
+ "add_to_vector_index",
473
+ "merge_tags"
474
+ ],
475
+ github: [
476
+ "get_github_issues",
477
+ "get_github_prs",
478
+ "get_github_issue",
479
+ "get_github_pr",
480
+ "get_github_context",
481
+ "get_kanban_board",
482
+ "move_kanban_item",
483
+ "add_kanban_item",
484
+ "delete_kanban_item",
485
+ "create_github_issue_with_entry",
486
+ "close_github_issue_with_entry",
487
+ "get_github_milestones",
488
+ "get_github_milestone",
489
+ "create_github_milestone",
490
+ "update_github_milestone",
491
+ "delete_github_milestone",
492
+ "get_repo_insights",
493
+ "get_copilot_reviews"
494
+ ],
495
+ backup: ["backup_journal", "list_backups", "restore_backup", "cleanup_backups"],
496
+ team: [
497
+ "team_create_entry",
498
+ "team_get_entry_by_id",
499
+ "team_get_recent",
500
+ "team_list_tags",
501
+ "team_search",
502
+ "team_search_by_date_range",
503
+ "team_update_entry",
504
+ "team_delete_entry",
505
+ "team_merge_tags",
506
+ "team_get_statistics",
507
+ "team_link_entries",
508
+ "team_visualize_relationships",
509
+ "team_export_entries",
510
+ "team_export_markdown",
511
+ "team_import_markdown",
512
+ "team_backup",
513
+ "team_list_backups",
514
+ "team_semantic_search",
515
+ "team_get_vector_index_stats",
516
+ "team_rebuild_vector_index",
517
+ "team_add_to_vector_index",
518
+ "team_get_cross_project_insights",
519
+ "team_get_collaboration_matrix",
520
+ "team_pass_flag",
521
+ "team_resolve_flag",
522
+ "team_list_flags",
523
+ "team_update_flag",
524
+ "team_get_flag_analytics"
525
+ ],
526
+ codemode: ["mj_execute_code"]
527
+ };
528
+ var META_GROUPS = {
529
+ starter: ["core", "search", "codemode"],
530
+ essential: ["core", "codemode"],
531
+ full: [
532
+ "core",
533
+ "search",
534
+ "analytics",
535
+ "relationships",
536
+ "io",
537
+ "admin",
538
+ "github",
539
+ "backup",
540
+ "team",
541
+ "codemode"
542
+ ],
543
+ readonly: ["core", "search", "analytics", "relationships", "io", "codemode"]
544
+ };
545
+ function getAllToolNames() {
546
+ const allTools = [];
547
+ for (const tools of Object.values(TOOL_GROUPS)) {
548
+ allTools.push(...tools);
549
+ }
550
+ return allTools;
551
+ }
552
+ function getToolGroup(toolName) {
553
+ for (const [group, tools] of Object.entries(TOOL_GROUPS)) {
554
+ if (tools.includes(toolName)) {
555
+ return group;
556
+ }
557
+ }
558
+ return void 0;
559
+ }
560
+ function getEnabledGroups(enabledTools) {
561
+ const groups = /* @__PURE__ */ new Set();
562
+ for (const [group, tools] of Object.entries(TOOL_GROUPS)) {
563
+ if (tools.some((t) => enabledTools.has(t))) {
564
+ groups.add(group);
565
+ }
566
+ }
567
+ return groups;
568
+ }
569
+ var GROUP_ALIASES = { export: "io" };
570
+ function resolveGroupAlias(name) {
571
+ return GROUP_ALIASES[name] ?? name;
572
+ }
573
+ function isGroup(name) {
574
+ return resolveGroupAlias(name) in TOOL_GROUPS;
575
+ }
576
+ function isMetaGroup(name) {
577
+ return name in META_GROUPS;
578
+ }
579
+ function parseToolFilter(filterString) {
580
+ const rules = [];
581
+ const parts = filterString.split(",").map((p) => p.trim()).filter(Boolean);
582
+ let enabledTools = /* @__PURE__ */ new Set();
583
+ let isWhitelistMode = false;
584
+ for (let i = 0; i < parts.length; i++) {
585
+ const part = parts[i];
586
+ if (!part) continue;
587
+ const isAdd = part.startsWith("+");
588
+ const isRemove = part.startsWith("-");
589
+ const name = isAdd || isRemove ? part.slice(1) : part;
590
+ if (i === 0 && !isAdd && !isRemove) {
591
+ isWhitelistMode = true;
592
+ if (isMetaGroup(name)) {
593
+ for (const group of META_GROUPS[name]) {
594
+ enabledTools = /* @__PURE__ */ new Set([...enabledTools, ...TOOL_GROUPS[group]]);
595
+ }
596
+ } else if (isGroup(name)) {
597
+ const resolved = resolveGroupAlias(name);
598
+ enabledTools = /* @__PURE__ */ new Set([...enabledTools, ...TOOL_GROUPS[resolved]]);
599
+ } else {
600
+ enabledTools.add(name);
601
+ }
602
+ rules.push({
603
+ type: "include",
604
+ target: name,
605
+ isGroup: isGroup(name) || isMetaGroup(name)
606
+ });
607
+ } else if (isRemove) {
608
+ if (isGroup(name)) {
609
+ const resolved = resolveGroupAlias(name);
610
+ for (const tool of TOOL_GROUPS[resolved]) {
611
+ enabledTools.delete(tool);
612
+ }
613
+ } else {
614
+ enabledTools.delete(name);
615
+ }
616
+ rules.push({
617
+ type: "exclude",
618
+ target: name,
619
+ isGroup: isGroup(name)
620
+ });
621
+ } else {
622
+ if (isMetaGroup(name)) {
623
+ for (const group of META_GROUPS[name]) {
624
+ enabledTools = /* @__PURE__ */ new Set([...enabledTools, ...TOOL_GROUPS[group]]);
625
+ }
626
+ } else if (isGroup(name)) {
627
+ const resolved = resolveGroupAlias(name);
628
+ enabledTools = /* @__PURE__ */ new Set([...enabledTools, ...TOOL_GROUPS[resolved]]);
629
+ } else {
630
+ enabledTools.add(name);
631
+ }
632
+ rules.push({
633
+ type: "include",
634
+ target: name,
635
+ isGroup: isGroup(name) || isMetaGroup(name)
636
+ });
637
+ }
638
+ }
639
+ if (!isWhitelistMode && rules.length > 0 && rules[0]?.type === "exclude") {
640
+ enabledTools = new Set(getAllToolNames());
641
+ for (const rule of rules) {
642
+ if (rule.type === "exclude") {
643
+ if (isGroup(rule.target)) {
644
+ const resolved = resolveGroupAlias(rule.target);
645
+ for (const tool of TOOL_GROUPS[resolved]) {
646
+ enabledTools.delete(tool);
647
+ }
648
+ } else {
649
+ enabledTools.delete(rule.target);
650
+ }
651
+ }
652
+ }
653
+ }
654
+ return {
655
+ raw: filterString,
656
+ rules,
657
+ enabledTools
658
+ };
659
+ }
660
+ function isToolEnabled(toolName, filterConfig) {
661
+ return filterConfig.enabledTools.has(toolName);
662
+ }
663
+ function filterTools(tools, filterConfig) {
664
+ return tools.filter((tool) => isToolEnabled(tool.name, filterConfig));
665
+ }
666
+ function getToolFilterFromEnv() {
667
+ const filterString = process.env["MEMORY_JOURNAL_MCP_TOOL_FILTER"];
668
+ if (!filterString) return null;
669
+ return parseToolFilter(filterString);
670
+ }
671
+ function calculateTokenSavings(totalTools, enabledTools, avgTokensPerTool = 150) {
672
+ const savedTokens = (totalTools - enabledTools) * avgTokensPerTool;
673
+ const reduction = (totalTools - enabledTools) / totalTools * 100;
674
+ return { reduction, savedTokens };
675
+ }
676
+ function getFilterSummary(filterConfig) {
677
+ const total = getAllToolNames().length;
678
+ const enabled = filterConfig.enabledTools.size;
679
+ const { reduction } = calculateTokenSavings(total, enabled);
680
+ return `${enabled}/${total} tools enabled (${reduction.toFixed(0)}% reduction)`;
681
+ }
682
+
683
+ // src/auth/scopes.ts
684
+ var SCOPES = {
685
+ /** Read-only access */
686
+ READ: "read",
687
+ /** Read and write access */
688
+ WRITE: "write",
689
+ /** Administrative access */
690
+ ADMIN: "admin",
691
+ /** Unrestricted access to all operations */
692
+ FULL: "full",
693
+ /** Team operations access */
694
+ TEAM: "team",
695
+ /** Audit log access */
696
+ AUDIT: "audit"
697
+ };
698
+ var BASE_SCOPES = ["read", "write", "admin", "full", "team", "audit"];
699
+ var SUPPORTED_SCOPES = ["read", "write", "admin", "full", "team", "audit"];
700
+ var TOOL_GROUP_SCOPES = {
701
+ core: SCOPES.READ,
702
+ search: SCOPES.READ,
703
+ analytics: SCOPES.READ,
704
+ relationships: SCOPES.READ,
705
+ io: SCOPES.READ,
706
+ admin: SCOPES.ADMIN,
707
+ github: SCOPES.WRITE,
708
+ backup: SCOPES.ADMIN,
709
+ // SEC-1.3: Team tools require the dedicated `team` scope, not generic `write`.
710
+ // This aligns tool-level enforcement with the resource-level boundary at memory://team/*.
711
+ // Tokens with `admin` or `full` scope still implicitly include `team` via hasScope().
712
+ team: SCOPES.TEAM,
713
+ codemode: SCOPES.ADMIN
714
+ };
715
+ var TOOL_SCOPE_OVERRIDES = {
716
+ import_markdown: SCOPES.WRITE,
717
+ team_import_markdown: SCOPES.TEAM,
718
+ mj_execute_code: SCOPES.ADMIN,
719
+ create_entry: SCOPES.WRITE,
720
+ create_entry_minimal: SCOPES.WRITE,
721
+ link_entries: SCOPES.WRITE,
722
+ export_markdown: SCOPES.WRITE
723
+ };
724
+ var groupsForScope = (maxScope) => {
725
+ const hierarchy = {
726
+ read: 0,
727
+ write: 1,
728
+ team: 1.5,
729
+ audit: 1.5,
730
+ admin: 2,
731
+ full: 3
732
+ };
733
+ const maxLevel = hierarchy[maxScope];
734
+ return Object.entries(TOOL_GROUP_SCOPES).filter(([, scope]) => hierarchy[scope] <= maxLevel).map(([group]) => group);
735
+ };
736
+ groupsForScope(SCOPES.READ);
737
+ groupsForScope(SCOPES.WRITE);
738
+ groupsForScope(SCOPES.ADMIN);
739
+ function parseScopes(scopeString) {
740
+ return scopeString.split(/\s+/).map((s) => s.trim()).filter((s) => s.length > 0);
741
+ }
742
+ function isValidScope(scope) {
743
+ return BASE_SCOPES.includes(scope);
744
+ }
745
+ function hasScope(grantedScopes, requiredScope) {
746
+ if (grantedScopes.includes(SCOPES.FULL)) {
747
+ return true;
748
+ }
749
+ if (grantedScopes.includes(requiredScope)) {
750
+ return true;
751
+ }
752
+ if (requiredScope === SCOPES.READ || requiredScope === SCOPES.WRITE || requiredScope === SCOPES.TEAM || requiredScope === SCOPES.AUDIT) {
753
+ if (grantedScopes.includes(SCOPES.ADMIN)) {
754
+ return true;
755
+ }
756
+ }
757
+ if (requiredScope === SCOPES.READ) {
758
+ if (grantedScopes.includes(SCOPES.WRITE)) {
759
+ return true;
760
+ }
761
+ }
762
+ return false;
763
+ }
764
+
765
+ // src/auth/scope-map.ts
766
+ var toolScopeMap = /* @__PURE__ */ new Map();
767
+ for (const [group, tools] of Object.entries(TOOL_GROUPS)) {
768
+ const scope = TOOL_GROUP_SCOPES[group];
769
+ if (scope) {
770
+ for (const toolName of tools) {
771
+ toolScopeMap.set(toolName, scope);
772
+ }
773
+ }
774
+ }
775
+ for (const [toolName, scope] of Object.entries(TOOL_SCOPE_OVERRIDES)) {
776
+ toolScopeMap.set(toolName, scope);
777
+ }
778
+ function getRequiredScope(toolName) {
779
+ const scope = toolScopeMap.get(toolName);
780
+ if (!scope) {
781
+ throw new Error(
782
+ `CRITICAL SECURITY FAILURE: Tool '${toolName}' is missing from scope mapping`
783
+ );
784
+ }
785
+ return scope;
786
+ }
787
+
788
+ // src/auth/validation.ts
789
+ function enforceAccessBoundary(targetName, targetType, capabilities, auditLogger) {
790
+ const auth = getAuthContext();
791
+ const isTeam = capabilities?.requiresTeamScope ?? (targetType === "resource" ? targetName.startsWith("memory://team/") || targetName.startsWith("memory://flags") : targetName.startsWith("team_"));
792
+ const isAdmin = capabilities?.requiresAdminScope ?? (targetType === "resource" ? targetName === "memory://audit" : false);
793
+ if (isTeam) {
794
+ const envAuthor = process.env["TEAM_AUTHOR"]?.trim();
795
+ const hasAuthClaim = auth?.authenticated === true && auth?.claims !== void 0;
796
+ const bypassCodeMode = process.env["CODEMODE_INTERNAL_FULL_ACCESS"] === "true";
797
+ if (!envAuthor && !hasAuthClaim && !bypassCodeMode) {
798
+ logger.warning(`Access to team ${targetType} denied: unauthenticated`, {
799
+ module: "AUTH",
800
+ operation: "fail-closed",
801
+ entityId: targetName
802
+ });
803
+ throw new PermissionError(
804
+ `Access to team ${targetType} '${targetName}' denied: missing TEAM_AUTHOR or active OAuth session.`
805
+ );
806
+ }
807
+ }
808
+ if (auth) {
809
+ let requiredScope;
810
+ if (targetType === "tool") {
811
+ requiredScope = getRequiredScope(targetName);
812
+ } else {
813
+ requiredScope = SCOPES.READ;
814
+ if (isTeam) {
815
+ requiredScope = SCOPES.TEAM;
816
+ } else if (isAdmin) {
817
+ requiredScope = SCOPES.ADMIN;
818
+ }
819
+ }
820
+ if (!hasScope(auth.claims?.scopes ?? [], requiredScope)) {
821
+ logger.warning(`Insufficient scope for ${targetType}: ${targetName}`, {
822
+ module: "AUTH",
823
+ operation: "scope-check",
824
+ entityId: targetName
825
+ });
826
+ if (auditLogger) {
827
+ const category = requiredScope === SCOPES.TEAM ? "team" : requiredScope === SCOPES.ADMIN || requiredScope === SCOPES.FULL ? "admin" : "read";
828
+ auditLogger.logDenial(targetName, "Insufficient scope", {
829
+ user: auth.claims?.sub,
830
+ scopes: auth.claims?.scopes ?? [],
831
+ category,
832
+ scope: requiredScope
833
+ });
834
+ }
835
+ throw new PermissionError(
836
+ `Access to ${targetType} '${targetName}' denied: insufficient scope.`
837
+ );
838
+ }
839
+ }
840
+ }
841
+ var CACHE_TTL_MS = 5 * 60 * 1e3;
842
+ var TRAFFIC_CACHE_TTL_MS = 10 * 60 * 1e3;
843
+ var simpleGit2 = simpleGitImport.simpleGit;
844
+ var GitHubClient = class {
845
+ octokit = null;
846
+ graphqlWithAuth = null;
847
+ git;
848
+ apiCache = /* @__PURE__ */ new Map();
849
+ totalCacheBytes = 0;
850
+ MAX_CACHE_BYTES = 50 * 1024 * 1024;
851
+ // 50MB global limit
852
+ MAX_ENTRY_BYTES = 10 * 1024 * 1024;
853
+ // 10MB per-item limit
854
+ constructor(workingDir = ".", token) {
855
+ const resolvedToken = token ?? process.env["GITHUB_TOKEN"];
856
+ const effectiveDir = workingDir;
857
+ const resolvedDir = effectiveDir === "." ? process.cwd() : effectiveDir;
858
+ logger.info("GitHub integration using directory", {
859
+ module: "GitHub",
860
+ workingDir,
861
+ effectiveDir,
862
+ resolvedDir,
863
+ cwd: process.cwd()
864
+ });
865
+ this.git = simpleGit2(effectiveDir);
866
+ if (resolvedToken) {
867
+ this.octokit = new Octokit({ auth: resolvedToken });
868
+ this.graphqlWithAuth = graphql.defaults({
869
+ headers: { authorization: `token ${resolvedToken}` }
870
+ });
871
+ logger.info("GitHub integration initialized with token", { module: "GitHub" });
872
+ } else {
873
+ logger.info("GitHub integration initialized without token (limited functionality)", {
874
+ module: "GitHub"
875
+ });
876
+ }
877
+ }
878
+ isApiAvailable() {
879
+ return this.octokit !== null;
880
+ }
881
+ getCached(key) {
882
+ const entry = this.apiCache.get(key);
883
+ if (entry && Date.now() - entry.timestamp < CACHE_TTL_MS) {
884
+ this.apiCache.delete(key);
885
+ this.apiCache.set(key, entry);
886
+ return entry.data;
887
+ }
888
+ if (entry) {
889
+ this.totalCacheBytes -= entry.sizeBytes;
890
+ this.apiCache.delete(key);
891
+ }
892
+ return void 0;
893
+ }
894
+ getCachedWithTtl(key, ttlMs) {
895
+ const entry = this.apiCache.get(key);
896
+ if (entry && Date.now() - entry.timestamp < ttlMs) {
897
+ this.apiCache.delete(key);
898
+ this.apiCache.set(key, entry);
899
+ return entry.data;
900
+ }
901
+ if (entry) {
902
+ this.totalCacheBytes -= entry.sizeBytes;
903
+ this.apiCache.delete(key);
904
+ }
905
+ return void 0;
906
+ }
907
+ setCache(key, data) {
908
+ let sizeBytes;
909
+ try {
910
+ sizeBytes = Buffer.byteLength(JSON.stringify(data) || "", "utf8");
911
+ } catch {
912
+ sizeBytes = 1024;
913
+ }
914
+ if (sizeBytes > this.MAX_ENTRY_BYTES) {
915
+ return;
916
+ }
917
+ const existing = this.apiCache.get(key);
918
+ if (existing) {
919
+ this.totalCacheBytes -= existing.sizeBytes;
920
+ }
921
+ this.apiCache.delete(key);
922
+ this.apiCache.set(key, { data, timestamp: Date.now(), sizeBytes });
923
+ this.totalCacheBytes += sizeBytes;
924
+ while (this.apiCache.size > 1e3 || this.totalCacheBytes > this.MAX_CACHE_BYTES) {
925
+ const oldestKey = this.apiCache.keys().next().value;
926
+ if (oldestKey !== void 0) {
927
+ const oldestEntry = this.apiCache.get(oldestKey);
928
+ if (oldestEntry) {
929
+ this.totalCacheBytes -= oldestEntry.sizeBytes;
930
+ }
931
+ this.apiCache.delete(oldestKey);
932
+ } else {
933
+ break;
934
+ }
935
+ }
936
+ }
937
+ invalidateCache(prefix) {
938
+ for (const [key, entry] of this.apiCache.entries()) {
939
+ if (key.startsWith(prefix)) {
940
+ this.totalCacheBytes -= entry.sizeBytes;
941
+ this.apiCache.delete(key);
942
+ }
943
+ }
944
+ }
945
+ clearCache() {
946
+ this.apiCache.clear();
947
+ this.totalCacheBytes = 0;
948
+ }
949
+ };
950
+
951
+ // src/github/github-integration/issues.ts
952
+ var IssuesManager = class {
953
+ constructor(client) {
954
+ this.client = client;
955
+ }
956
+ client;
957
+ async getIssues(owner, repo, state = "open", limit = 20, abortSignal) {
958
+ if (!this.client.octokit) {
959
+ throw new Error("GitHub API not available");
960
+ }
961
+ const cacheKey = `issues:${owner}:${repo}:${state}:${String(limit)}`;
962
+ const cached = this.client.getCached(cacheKey);
963
+ if (cached) return cached;
964
+ try {
965
+ const response = await this.client.octokit.issues.listForRepo({
966
+ owner,
967
+ repo,
968
+ state,
969
+ per_page: Math.min(limit + 5, 100),
970
+ sort: "updated",
971
+ direction: "desc",
972
+ request: { signal: abortSignal }
973
+ });
974
+ const result = response.data.filter((issue) => !issue.pull_request).slice(0, limit).map((issue) => ({
975
+ number: issue.number,
976
+ title: markUntrustedContentInline(issue.title),
977
+ url: issue.html_url,
978
+ state: issue.state === "open" ? "OPEN" : "CLOSED",
979
+ milestone: issue.milestone ? {
980
+ number: issue.milestone.number,
981
+ title: issue.milestone.title
982
+ } : null
983
+ }));
984
+ this.client.setCache(cacheKey, result);
985
+ return result;
986
+ } catch (error) {
987
+ logger.error("Failed to get issues", {
988
+ module: "GitHub",
989
+ error: error instanceof Error ? error.message : String(error)
990
+ });
991
+ throw error;
992
+ }
993
+ }
994
+ async getIssue(owner, repo, issueNumber) {
995
+ if (!this.client.octokit) {
996
+ throw new Error("GitHub API not available");
997
+ }
998
+ const cacheKey = `issue:${owner}:${repo}:${String(issueNumber)}`;
999
+ const cached = this.client.getCached(cacheKey);
1000
+ if (cached !== void 0) return cached;
1001
+ try {
1002
+ const response = await this.client.octokit.issues.get({
1003
+ owner,
1004
+ repo,
1005
+ issue_number: issueNumber
1006
+ });
1007
+ const issue = response.data;
1008
+ if (issue.pull_request) {
1009
+ return null;
1010
+ }
1011
+ const details = {
1012
+ number: issue.number,
1013
+ title: markUntrustedContentInline(issue.title),
1014
+ url: issue.html_url,
1015
+ state: issue.state === "open" ? "OPEN" : "CLOSED",
1016
+ nodeId: issue.node_id,
1017
+ body: issue.body || "",
1018
+ labels: issue.labels.map((l) => typeof l === "string" ? l : l.name ?? ""),
1019
+ assignees: issue.assignees?.map((a) => a.login) ?? [],
1020
+ createdAt: issue.created_at,
1021
+ updatedAt: issue.updated_at,
1022
+ closedAt: issue.closed_at,
1023
+ commentsCount: issue.comments,
1024
+ milestone: issue.milestone ? { number: issue.milestone.number, title: issue.milestone.title } : null
1025
+ };
1026
+ this.client.setCache(cacheKey, details);
1027
+ return details;
1028
+ } catch (error) {
1029
+ if (error instanceof Error && "status" in error && error.status === 404) {
1030
+ return null;
1031
+ }
1032
+ logger.error("Failed to get issue details", {
1033
+ module: "GitHub",
1034
+ entityId: issueNumber,
1035
+ error: error instanceof Error ? error.message : String(error)
1036
+ });
1037
+ throw error;
1038
+ }
1039
+ }
1040
+ async getIssueComments(owner, repo, issueNumber, limit = 30) {
1041
+ const _limit = Math.min(limit, 100);
1042
+ if (_limit <= 0) return [];
1043
+ if (!this.client.octokit) {
1044
+ throw new Error("GitHub API not available");
1045
+ }
1046
+ const cacheKey = `issue-comments:${owner}:${repo}:${String(issueNumber)}:${String(_limit)}`;
1047
+ const cached = this.client.getCached(cacheKey);
1048
+ if (cached) return cached;
1049
+ try {
1050
+ const response = await this.client.octokit.issues.listComments({
1051
+ owner,
1052
+ repo,
1053
+ issue_number: issueNumber,
1054
+ per_page: _limit,
1055
+ sort: "created",
1056
+ direction: "asc"
1057
+ });
1058
+ const comments = response.data.slice(0, _limit).map((comment) => ({
1059
+ author: comment.user?.login ?? "unknown",
1060
+ body: markUntrustedContent(comment.body),
1061
+ createdAt: comment.created_at
1062
+ }));
1063
+ this.client.setCache(cacheKey, comments);
1064
+ return comments;
1065
+ } catch (error) {
1066
+ logger.error("Failed to get issue comments", {
1067
+ module: "GitHub",
1068
+ entityId: issueNumber,
1069
+ error: error instanceof Error ? error.message : String(error)
1070
+ });
1071
+ throw error;
1072
+ }
1073
+ }
1074
+ async createIssue(owner, repo, title, body, labels, assignees, milestone) {
1075
+ if (!this.client.octokit) {
1076
+ logger.error("Cannot create issue: GitHub API not available", { module: "GitHub" });
1077
+ throw new Error("GitHub API not available");
1078
+ }
1079
+ try {
1080
+ const response = await this.client.octokit.issues.create({
1081
+ owner,
1082
+ repo,
1083
+ title,
1084
+ body,
1085
+ labels,
1086
+ assignees,
1087
+ milestone
1088
+ });
1089
+ logger.info("Created GitHub issue", {
1090
+ module: "GitHub",
1091
+ entityId: response.data.number,
1092
+ context: { title, owner, repo }
1093
+ });
1094
+ return {
1095
+ number: response.data.number,
1096
+ url: response.data.html_url,
1097
+ title: response.data.title,
1098
+ nodeId: response.data.node_id
1099
+ };
1100
+ } catch (error) {
1101
+ logger.error("Failed to create issue", {
1102
+ module: "GitHub",
1103
+ error: error instanceof Error ? error.message : String(error),
1104
+ context: { title, owner, repo }
1105
+ });
1106
+ throw error;
1107
+ } finally {
1108
+ this.client.invalidateCache(`issues:${owner}:${repo}`);
1109
+ this.client.invalidateCache("context:");
1110
+ }
1111
+ }
1112
+ async closeIssue(owner, repo, issueNumber, comment) {
1113
+ if (!this.client.octokit) {
1114
+ logger.error("Cannot close issue: GitHub API not available", { module: "GitHub" });
1115
+ throw new Error("GitHub API not available");
1116
+ }
1117
+ try {
1118
+ if (comment) {
1119
+ await this.client.octokit.issues.createComment({
1120
+ owner,
1121
+ repo,
1122
+ issue_number: issueNumber,
1123
+ body: comment
1124
+ });
1125
+ }
1126
+ const response = await this.client.octokit.issues.update({
1127
+ owner,
1128
+ repo,
1129
+ issue_number: issueNumber,
1130
+ state: "closed"
1131
+ });
1132
+ logger.info("Closed GitHub issue", {
1133
+ module: "GitHub",
1134
+ entityId: issueNumber,
1135
+ context: { owner, repo, hadComment: !!comment }
1136
+ });
1137
+ return {
1138
+ success: true,
1139
+ url: response.data.html_url
1140
+ };
1141
+ } catch (error) {
1142
+ logger.error("Failed to close issue", {
1143
+ module: "GitHub",
1144
+ entityId: issueNumber,
1145
+ error: error instanceof Error ? error.message : String(error)
1146
+ });
1147
+ throw error;
1148
+ } finally {
1149
+ this.client.invalidateCache(`issues:${owner}:${repo}`);
1150
+ this.client.invalidateCache(`issue:${owner}:${repo}:${String(issueNumber)}`);
1151
+ this.client.invalidateCache("context:");
1152
+ }
1153
+ }
1154
+ };
1155
+
1156
+ // src/github/github-integration/pull-requests.ts
1157
+ var PullRequestsManager = class _PullRequestsManager {
1158
+ constructor(client) {
1159
+ this.client = client;
1160
+ }
1161
+ client;
1162
+ /** Known Copilot bot login patterns */
1163
+ static COPILOT_BOT_PATTERNS = [
1164
+ "copilot-pull-request-reviewer[bot]",
1165
+ "github-copilot[bot]",
1166
+ "copilot[bot]"
1167
+ ];
1168
+ async getPullRequests(owner, repo, state = "open", limit = 20, abortSignal) {
1169
+ if (!this.client.octokit) {
1170
+ throw new Error("GitHub API not available");
1171
+ }
1172
+ const cacheKey = `prs:${owner}:${repo}:${state}:${String(limit)}`;
1173
+ const cached = this.client.getCached(cacheKey);
1174
+ if (cached) return cached;
1175
+ try {
1176
+ const response = await this.client.octokit.pulls.list({
1177
+ owner,
1178
+ repo,
1179
+ state,
1180
+ per_page: Math.min(limit, 100),
1181
+ sort: "updated",
1182
+ direction: "desc",
1183
+ request: { signal: abortSignal }
1184
+ });
1185
+ const result = response.data.map((pr) => ({
1186
+ number: pr.number,
1187
+ title: markUntrustedContentInline(pr.title),
1188
+ url: pr.html_url,
1189
+ state: pr.merged_at ? "MERGED" : pr.state === "open" ? "OPEN" : "CLOSED"
1190
+ }));
1191
+ this.client.setCache(cacheKey, result);
1192
+ return result;
1193
+ } catch (error) {
1194
+ logger.error("Failed to get pull requests", {
1195
+ module: "GitHub",
1196
+ error: error instanceof Error ? error.message : String(error)
1197
+ });
1198
+ throw error;
1199
+ }
1200
+ }
1201
+ async getPullRequest(owner, repo, prNumber) {
1202
+ if (!this.client.octokit) {
1203
+ throw new Error("GitHub API not available");
1204
+ }
1205
+ const cacheKey = `pr:${owner}:${repo}:${String(prNumber)}`;
1206
+ const cached = this.client.getCached(cacheKey);
1207
+ if (cached !== void 0) return cached;
1208
+ try {
1209
+ const response = await this.client.octokit.pulls.get({
1210
+ owner,
1211
+ repo,
1212
+ pull_number: prNumber
1213
+ });
1214
+ const pr = response.data;
1215
+ const details = {
1216
+ number: pr.number,
1217
+ title: markUntrustedContentInline(pr.title),
1218
+ url: pr.html_url,
1219
+ state: pr.merged_at ? "MERGED" : pr.state === "open" ? "OPEN" : "CLOSED",
1220
+ body: pr.body || "",
1221
+ draft: pr.draft ?? false,
1222
+ headBranch: pr.head.ref,
1223
+ baseBranch: pr.base.ref,
1224
+ author: pr.user?.login ?? "unknown",
1225
+ createdAt: pr.created_at,
1226
+ updatedAt: pr.updated_at,
1227
+ mergedAt: pr.merged_at,
1228
+ closedAt: pr.closed_at,
1229
+ additions: pr.additions,
1230
+ deletions: pr.deletions,
1231
+ changedFiles: pr.changed_files
1232
+ };
1233
+ this.client.setCache(cacheKey, details);
1234
+ return details;
1235
+ } catch (error) {
1236
+ if (error instanceof Error && "status" in error && error.status === 404) {
1237
+ return null;
1238
+ }
1239
+ logger.error("Failed to get PR details", {
1240
+ module: "GitHub",
1241
+ entityId: prNumber,
1242
+ error: error instanceof Error ? error.message : String(error)
1243
+ });
1244
+ throw error;
1245
+ }
1246
+ }
1247
+ static isCopilotAuthor(login) {
1248
+ const lower = login.toLowerCase();
1249
+ return _PullRequestsManager.COPILOT_BOT_PATTERNS.some(
1250
+ (p) => lower === p || lower.includes("copilot")
1251
+ );
1252
+ }
1253
+ async getReviews(owner, repo, prNumber) {
1254
+ if (!this.client.octokit) throw new Error("GitHub API not available");
1255
+ const cacheKey = `reviews:${owner}:${repo}:${String(prNumber)}`;
1256
+ const cached = this.client.getCached(cacheKey);
1257
+ if (cached) return cached;
1258
+ try {
1259
+ const response = await this.client.octokit.rest.pulls.listReviews({
1260
+ owner,
1261
+ repo,
1262
+ pull_number: prNumber,
1263
+ per_page: 100
1264
+ });
1265
+ const reviews = response.data.map((r) => ({
1266
+ id: r.id,
1267
+ author: r.user?.login ?? "unknown",
1268
+ state: r.state,
1269
+ body: markUntrustedContent(r.body),
1270
+ submittedAt: r.submitted_at ?? r.commit_id ?? (/* @__PURE__ */ new Date()).toISOString(),
1271
+ isCopilot: _PullRequestsManager.isCopilotAuthor(r.user?.login ?? "")
1272
+ }));
1273
+ this.client.setCache(cacheKey, reviews);
1274
+ return reviews;
1275
+ } catch (error) {
1276
+ logger.error("Failed to get PR reviews", {
1277
+ module: "GitHub",
1278
+ entityId: prNumber,
1279
+ error: error instanceof Error ? error.message : String(error)
1280
+ });
1281
+ throw error;
1282
+ }
1283
+ }
1284
+ async getReviewComments(owner, repo, prNumber) {
1285
+ if (!this.client.octokit) throw new Error("GitHub API not available");
1286
+ const cacheKey = `review-comments:${owner}:${repo}:${String(prNumber)}`;
1287
+ const cached = this.client.getCached(cacheKey);
1288
+ if (cached) return cached;
1289
+ try {
1290
+ const response = await this.client.octokit.rest.pulls.listReviewComments({
1291
+ owner,
1292
+ repo,
1293
+ pull_number: prNumber,
1294
+ per_page: 100
1295
+ });
1296
+ const comments = response.data.map((c) => ({
1297
+ id: c.id,
1298
+ author: c.user?.login ?? "unknown",
1299
+ body: markUntrustedContent(c.body),
1300
+ path: c.path,
1301
+ line: c.line ?? c.original_line ?? null,
1302
+ side: c.side ?? "RIGHT",
1303
+ createdAt: c.created_at,
1304
+ isCopilot: _PullRequestsManager.isCopilotAuthor(c.user?.login ?? "")
1305
+ }));
1306
+ this.client.setCache(cacheKey, comments);
1307
+ return comments;
1308
+ } catch (error) {
1309
+ logger.error("Failed to get review comments", {
1310
+ module: "GitHub",
1311
+ entityId: prNumber,
1312
+ error: error instanceof Error ? error.message : String(error)
1313
+ });
1314
+ throw error;
1315
+ }
1316
+ }
1317
+ async getCopilotReviewSummary(owner, repo, prNumber) {
1318
+ const [reviews, comments] = await Promise.all([
1319
+ this.getReviews(owner, repo, prNumber),
1320
+ this.getReviewComments(owner, repo, prNumber)
1321
+ ]);
1322
+ const copilotReviews = reviews.filter((r) => r.isCopilot);
1323
+ const copilotComments = comments.filter((c) => c.isCopilot);
1324
+ let state = "none";
1325
+ if (copilotReviews.length > 0) {
1326
+ const latest = copilotReviews[copilotReviews.length - 1];
1327
+ if (latest !== void 0) {
1328
+ if (latest.state === "APPROVED") state = "approved";
1329
+ else if (latest.state === "CHANGES_REQUESTED") state = "changes_requested";
1330
+ else if (latest.state === "COMMENTED") state = "commented";
1331
+ }
1332
+ }
1333
+ return {
1334
+ prNumber,
1335
+ state,
1336
+ commentCount: copilotComments.length,
1337
+ comments: copilotComments
1338
+ };
1339
+ }
1340
+ };
1341
+
1342
+ // src/github/github-integration/projects.ts
1343
+ var ProjectsManager = class {
1344
+ constructor(client) {
1345
+ this.client = client;
1346
+ }
1347
+ client;
1348
+ async getProjectKanban(owner, projectNumber, repo, abortSignal) {
1349
+ if (!this.client.graphqlWithAuth) {
1350
+ logger.debug("GraphQL not available - no token", { module: "GitHub" });
1351
+ throw new Error("GitHub API not available");
1352
+ }
1353
+ const projectFragment = `
1354
+ fragment ProjectData on ProjectV2 {
1355
+ id
1356
+ title
1357
+ fields(first: 20) {
1358
+ nodes {
1359
+ ... on ProjectV2SingleSelectField {
1360
+ id
1361
+ name
1362
+ options {
1363
+ id
1364
+ name
1365
+ color
1366
+ }
1367
+ }
1368
+ }
1369
+ }
1370
+ items(first: $itemLimit) {
1371
+ pageInfo {
1372
+ hasNextPage
1373
+ }
1374
+ nodes {
1375
+ id
1376
+ type
1377
+ createdAt
1378
+ updatedAt
1379
+ fieldValues(first: 10) {
1380
+ nodes {
1381
+ ... on ProjectV2ItemFieldSingleSelectValue {
1382
+ name
1383
+ field {
1384
+ ... on ProjectV2SingleSelectField {
1385
+ name
1386
+ }
1387
+ }
1388
+ }
1389
+ }
1390
+ }
1391
+ content {
1392
+ ... on Issue {
1393
+ number
1394
+ title
1395
+ url
1396
+ labels(first: 5) {
1397
+ nodes { name }
1398
+ }
1399
+ assignees(first: 5) {
1400
+ nodes { login }
1401
+ }
1402
+ }
1403
+ ... on PullRequest {
1404
+ number
1405
+ title
1406
+ url
1407
+ labels(first: 5) {
1408
+ nodes { name }
1409
+ }
1410
+ assignees(first: 5) {
1411
+ nodes { login }
1412
+ }
1413
+ }
1414
+ ... on DraftIssue {
1415
+ title
1416
+ }
1417
+ }
1418
+ }
1419
+ }
1420
+ }
1421
+ `;
1422
+ const userQuery = `
1423
+ ${projectFragment}
1424
+ query($owner: String!, $number: Int!, $itemLimit: Int!) {
1425
+ user(login: $owner) {
1426
+ projectV2(number: $number) {
1427
+ ...ProjectData
1428
+ }
1429
+ }
1430
+ }
1431
+ `;
1432
+ const repoQuery = `
1433
+ ${projectFragment}
1434
+ query($owner: String!, $repo: String!, $number: Int!, $itemLimit: Int!) {
1435
+ repository(owner: $owner, name: $repo) {
1436
+ projectV2(number: $number) {
1437
+ ...ProjectData
1438
+ }
1439
+ }
1440
+ }
1441
+ `;
1442
+ const orgQuery = `
1443
+ ${projectFragment}
1444
+ query($owner: String!, $number: Int!, $itemLimit: Int!) {
1445
+ organization(login: $owner) {
1446
+ projectV2(number: $number) {
1447
+ ...ProjectData
1448
+ }
1449
+ }
1450
+ }
1451
+ `;
1452
+ let project = null;
1453
+ let source = "";
1454
+ try {
1455
+ const response = await this.client.graphqlWithAuth(userQuery, {
1456
+ owner,
1457
+ number: projectNumber,
1458
+ itemLimit: 100,
1459
+ request: { signal: abortSignal }
1460
+ });
1461
+ if (response.user?.projectV2) {
1462
+ project = response.user.projectV2;
1463
+ source = "user";
1464
+ }
1465
+ } catch {
1466
+ logger.debug("User project not found, trying repository...", { module: "GitHub" });
1467
+ }
1468
+ if (!project && repo) {
1469
+ try {
1470
+ const response = await this.client.graphqlWithAuth(repoQuery, {
1471
+ owner,
1472
+ repo,
1473
+ number: projectNumber,
1474
+ itemLimit: 100,
1475
+ request: { signal: abortSignal }
1476
+ });
1477
+ if (response.repository?.projectV2) {
1478
+ project = response.repository.projectV2;
1479
+ source = "repository";
1480
+ }
1481
+ } catch {
1482
+ logger.debug("Repository project not found, trying organization...", {
1483
+ module: "GitHub"
1484
+ });
1485
+ }
1486
+ }
1487
+ if (!project) {
1488
+ try {
1489
+ const response = await this.client.graphqlWithAuth(orgQuery, {
1490
+ owner,
1491
+ number: projectNumber,
1492
+ itemLimit: 100,
1493
+ request: { signal: abortSignal }
1494
+ });
1495
+ if (response.organization?.projectV2) {
1496
+ project = response.organization.projectV2;
1497
+ source = "organization";
1498
+ }
1499
+ } catch {
1500
+ logger.debug("Organization project not found", { module: "GitHub" });
1501
+ }
1502
+ }
1503
+ if (!project) {
1504
+ logger.warning("Project not found", { module: "GitHub", entityId: projectNumber });
1505
+ return null;
1506
+ }
1507
+ const statusField = project.fields.nodes.find(
1508
+ (f) => f.name === "Status" && f.options !== void 0 && f.options.length > 0
1509
+ );
1510
+ if (!statusField?.id || !statusField.options) {
1511
+ logger.warning("Status field not found in project", {
1512
+ module: "GitHub",
1513
+ entityId: projectNumber
1514
+ });
1515
+ return null;
1516
+ }
1517
+ const statusOptions = statusField.options.map((opt) => ({
1518
+ id: opt.id,
1519
+ name: opt.name,
1520
+ color: opt.color
1521
+ }));
1522
+ const columnMap = /* @__PURE__ */ new Map();
1523
+ for (const opt of statusOptions) {
1524
+ columnMap.set(opt.name, []);
1525
+ }
1526
+ columnMap.set("No Status", []);
1527
+ for (const item of project.items.nodes) {
1528
+ const statusValue = item.fieldValues.nodes.find((fv) => fv.field?.name === "Status");
1529
+ const status = statusValue?.name ?? "No Status";
1530
+ const content = item.content;
1531
+ const projectItem = {
1532
+ id: item.id,
1533
+ title: content?.title ?? "Draft Issue",
1534
+ url: content?.url ?? "",
1535
+ type: item.type,
1536
+ status,
1537
+ number: content?.number,
1538
+ labels: content?.labels?.nodes.map((l) => l.name) ?? [],
1539
+ assignees: content?.assignees?.nodes.map((a) => a.login) ?? [],
1540
+ createdAt: item.createdAt,
1541
+ updatedAt: item.updatedAt
1542
+ };
1543
+ const column = columnMap.get(status);
1544
+ if (column) {
1545
+ column.push(projectItem);
1546
+ } else {
1547
+ columnMap.get("No Status")?.push(projectItem);
1548
+ }
1549
+ }
1550
+ const columns = [];
1551
+ for (const opt of statusOptions) {
1552
+ const items = columnMap.get(opt.name) ?? [];
1553
+ columns.push({
1554
+ status: opt.name,
1555
+ statusOptionId: opt.id,
1556
+ items
1557
+ });
1558
+ }
1559
+ const noStatusItems = columnMap.get("No Status") ?? [];
1560
+ if (noStatusItems.length > 0) {
1561
+ columns.push({
1562
+ status: "No Status",
1563
+ statusOptionId: "",
1564
+ items: noStatusItems
1565
+ });
1566
+ }
1567
+ const totalItems = project.items.nodes.length;
1568
+ const truncated = project.items.pageInfo?.hasNextPage ?? false;
1569
+ logger.info("Fetched Kanban board", {
1570
+ module: "GitHub",
1571
+ entityId: projectNumber,
1572
+ context: { columns: columns.length, items: totalItems, source, truncated }
1573
+ });
1574
+ return {
1575
+ projectId: project.id,
1576
+ projectNumber,
1577
+ projectTitle: project.title,
1578
+ statusFieldId: statusField.id,
1579
+ statusOptions,
1580
+ columns,
1581
+ totalItems,
1582
+ truncated
1583
+ };
1584
+ }
1585
+ async moveProjectItem(projectId, itemId, statusFieldId, statusOptionId) {
1586
+ if (!this.client.graphqlWithAuth) {
1587
+ return { success: false, error: "GraphQL not available - no token" };
1588
+ }
1589
+ try {
1590
+ const mutation = `
1591
+ mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $optionId: String!) {
1592
+ updateProjectV2ItemFieldValue(
1593
+ input: {
1594
+ projectId: $projectId
1595
+ itemId: $itemId
1596
+ fieldId: $fieldId
1597
+ value: { singleSelectOptionId: $optionId }
1598
+ }
1599
+ ) {
1600
+ projectV2Item {
1601
+ id
1602
+ }
1603
+ }
1604
+ }
1605
+ `;
1606
+ if (typeof this.client.invalidateCache === "function") {
1607
+ this.client.invalidateCache("kanban:");
1608
+ }
1609
+ await this.client.graphqlWithAuth(mutation, {
1610
+ projectId,
1611
+ itemId,
1612
+ fieldId: statusFieldId,
1613
+ optionId: statusOptionId
1614
+ });
1615
+ logger.info("Moved project item", {
1616
+ module: "GitHub",
1617
+ entityId: itemId,
1618
+ context: { targetStatus: statusOptionId }
1619
+ });
1620
+ return { success: true };
1621
+ } catch (error) {
1622
+ const errorMessage = error instanceof Error ? error.message : String(error);
1623
+ logger.error("Failed to move project item", {
1624
+ module: "GitHub",
1625
+ entityId: itemId,
1626
+ error: errorMessage
1627
+ });
1628
+ return { success: false, error: errorMessage };
1629
+ } finally {
1630
+ if (typeof this.client.invalidateCache === "function") {
1631
+ this.client.invalidateCache("kanban:");
1632
+ }
1633
+ }
1634
+ }
1635
+ async addProjectItem(projectId, contentId) {
1636
+ if (!this.client.graphqlWithAuth) {
1637
+ return { success: false, error: "GraphQL not available - no token" };
1638
+ }
1639
+ try {
1640
+ const mutation = `
1641
+ mutation($projectId: ID!, $contentId: ID!) {
1642
+ addProjectV2ItemById(input: { projectId: $projectId, contentId: $contentId }) {
1643
+ item {
1644
+ id
1645
+ }
1646
+ }
1647
+ }
1648
+ `;
1649
+ if (typeof this.client.invalidateCache === "function") {
1650
+ this.client.invalidateCache("kanban:");
1651
+ }
1652
+ const response = await this.client.graphqlWithAuth(mutation, {
1653
+ projectId,
1654
+ contentId
1655
+ });
1656
+ const itemId = response.addProjectV2ItemById?.item?.id;
1657
+ logger.info("Added item to project", {
1658
+ module: "GitHub",
1659
+ context: { projectId, contentId, itemId }
1660
+ });
1661
+ return { success: true, itemId };
1662
+ } catch (error) {
1663
+ const errorMessage = error instanceof Error ? error.message : String(error);
1664
+ logger.error("Failed to add item to project", {
1665
+ module: "GitHub",
1666
+ context: { projectId, contentId },
1667
+ error: errorMessage
1668
+ });
1669
+ return { success: false, error: errorMessage };
1670
+ } finally {
1671
+ if (typeof this.client.invalidateCache === "function") {
1672
+ this.client.invalidateCache("kanban:");
1673
+ }
1674
+ }
1675
+ }
1676
+ async deleteProjectItem(projectId, itemId) {
1677
+ if (!this.client.graphqlWithAuth) {
1678
+ return { success: false, error: "GraphQL not available - no token" };
1679
+ }
1680
+ try {
1681
+ const mutation = `
1682
+ mutation($projectId: ID!, $itemId: ID!) {
1683
+ deleteProjectV2Item(input: { projectId: $projectId, itemId: $itemId }) {
1684
+ deletedItemId
1685
+ }
1686
+ }
1687
+ `;
1688
+ if (typeof this.client.invalidateCache === "function") {
1689
+ this.client.invalidateCache("kanban:");
1690
+ }
1691
+ await this.client.graphqlWithAuth(mutation, {
1692
+ projectId,
1693
+ itemId
1694
+ });
1695
+ logger.info("Deleted project item", {
1696
+ module: "GitHub",
1697
+ context: { projectId, itemId }
1698
+ });
1699
+ return { success: true };
1700
+ } catch (error) {
1701
+ const errorMessage = error instanceof Error ? error.message : String(error);
1702
+ logger.error("Failed to delete item from project", {
1703
+ module: "GitHub",
1704
+ context: { projectId, itemId },
1705
+ error: errorMessage
1706
+ });
1707
+ return { success: false, error: errorMessage };
1708
+ } finally {
1709
+ if (typeof this.client.invalidateCache === "function") {
1710
+ this.client.invalidateCache("kanban:");
1711
+ }
1712
+ }
1713
+ }
1714
+ };
1715
+
1716
+ // src/github/github-integration/milestones.ts
1717
+ var MilestonesManager = class {
1718
+ constructor(client) {
1719
+ this.client = client;
1720
+ }
1721
+ client;
1722
+ async getMilestones(owner, repo, state = "open", limit = 20, abortSignal) {
1723
+ if (!this.client.octokit) {
1724
+ throw new Error("GitHub API not available");
1725
+ }
1726
+ const cacheKey = `milestones:${owner}:${repo}:${state}:${String(limit)}`;
1727
+ const cached = this.client.getCached(cacheKey);
1728
+ if (cached) return cached;
1729
+ try {
1730
+ const response = await this.client.octokit.issues.listMilestones({
1731
+ owner,
1732
+ repo,
1733
+ state,
1734
+ per_page: limit,
1735
+ sort: "due_on",
1736
+ direction: "asc",
1737
+ request: { signal: abortSignal }
1738
+ });
1739
+ const result = response.data.map((ms) => ({
1740
+ number: ms.number,
1741
+ title: ms.title,
1742
+ description: ms.description ?? null,
1743
+ state: ms.state === "open" ? "open" : "closed",
1744
+ url: ms.html_url,
1745
+ dueOn: ms.due_on ?? null,
1746
+ openIssues: ms.open_issues,
1747
+ closedIssues: ms.closed_issues,
1748
+ createdAt: ms.created_at,
1749
+ updatedAt: ms.updated_at,
1750
+ creator: ms.creator?.login ?? null
1751
+ }));
1752
+ this.client.setCache(cacheKey, result);
1753
+ return result;
1754
+ } catch (error) {
1755
+ logger.error("Failed to get milestones", {
1756
+ module: "GitHub",
1757
+ error: error instanceof Error ? error.message : String(error)
1758
+ });
1759
+ throw error;
1760
+ }
1761
+ }
1762
+ async getMilestone(owner, repo, milestoneNumber) {
1763
+ if (!this.client.octokit) {
1764
+ throw new Error("GitHub API not available");
1765
+ }
1766
+ const cacheKey = `milestone:${owner}:${repo}:${String(milestoneNumber)}`;
1767
+ const cached = this.client.getCached(cacheKey);
1768
+ if (cached !== void 0) return cached;
1769
+ try {
1770
+ const response = await this.client.octokit.issues.getMilestone({
1771
+ owner,
1772
+ repo,
1773
+ milestone_number: milestoneNumber
1774
+ });
1775
+ const ms = response.data;
1776
+ const milestone = {
1777
+ number: ms.number,
1778
+ title: ms.title,
1779
+ description: ms.description ?? null,
1780
+ state: ms.state === "open" ? "open" : "closed",
1781
+ url: ms.html_url,
1782
+ dueOn: ms.due_on ?? null,
1783
+ openIssues: ms.open_issues,
1784
+ closedIssues: ms.closed_issues,
1785
+ createdAt: ms.created_at,
1786
+ updatedAt: ms.updated_at,
1787
+ creator: ms.creator?.login ?? null
1788
+ };
1789
+ this.client.setCache(cacheKey, milestone);
1790
+ return milestone;
1791
+ } catch (error) {
1792
+ if (error instanceof Error && "status" in error && error.status === 404) {
1793
+ return null;
1794
+ }
1795
+ logger.error("Failed to get milestone", {
1796
+ module: "GitHub",
1797
+ entityId: milestoneNumber,
1798
+ error: error instanceof Error ? error.message : String(error)
1799
+ });
1800
+ throw error;
1801
+ }
1802
+ }
1803
+ async createMilestone(owner, repo, title, description, dueOn) {
1804
+ if (!this.client.octokit) {
1805
+ logger.error("Cannot create milestone: GitHub API not available", {
1806
+ module: "GitHub"
1807
+ });
1808
+ throw new Error("GitHub API not available");
1809
+ }
1810
+ try {
1811
+ const response = await this.client.octokit.issues.createMilestone({
1812
+ owner,
1813
+ repo,
1814
+ title,
1815
+ description,
1816
+ due_on: dueOn
1817
+ });
1818
+ const ms = response.data;
1819
+ logger.info("Created GitHub milestone", {
1820
+ module: "GitHub",
1821
+ entityId: ms.number,
1822
+ context: { title, owner, repo }
1823
+ });
1824
+ return {
1825
+ number: ms.number,
1826
+ title: ms.title,
1827
+ description: ms.description ?? null,
1828
+ state: ms.state === "open" ? "open" : "closed",
1829
+ url: ms.html_url,
1830
+ dueOn: ms.due_on ?? null,
1831
+ openIssues: ms.open_issues,
1832
+ closedIssues: ms.closed_issues,
1833
+ createdAt: ms.created_at,
1834
+ updatedAt: ms.updated_at,
1835
+ creator: ms.creator?.login ?? null
1836
+ };
1837
+ } catch (error) {
1838
+ logger.error("Failed to create milestone", {
1839
+ module: "GitHub",
1840
+ error: error instanceof Error ? error.message : String(error),
1841
+ context: { title, owner, repo }
1842
+ });
1843
+ throw error;
1844
+ } finally {
1845
+ this.client.invalidateCache(`milestones:${owner}:${repo}`);
1846
+ this.client.invalidateCache("context:");
1847
+ }
1848
+ }
1849
+ async updateMilestone(owner, repo, milestoneNumber, updates) {
1850
+ if (!this.client.octokit) {
1851
+ logger.error("Cannot update milestone: GitHub API not available", {
1852
+ module: "GitHub"
1853
+ });
1854
+ throw new Error("GitHub API not available");
1855
+ }
1856
+ try {
1857
+ const response = await this.client.octokit.issues.updateMilestone({
1858
+ owner,
1859
+ repo,
1860
+ milestone_number: milestoneNumber,
1861
+ title: updates.title,
1862
+ description: updates.description,
1863
+ due_on: updates.dueOn === null ? void 0 : updates.dueOn,
1864
+ state: updates.state
1865
+ });
1866
+ const ms = response.data;
1867
+ logger.info("Updated GitHub milestone", {
1868
+ module: "GitHub",
1869
+ entityId: milestoneNumber,
1870
+ context: { owner, repo, updates: Object.keys(updates) }
1871
+ });
1872
+ return {
1873
+ number: ms.number,
1874
+ title: ms.title,
1875
+ description: ms.description ?? null,
1876
+ state: ms.state === "open" ? "open" : "closed",
1877
+ url: ms.html_url,
1878
+ dueOn: ms.due_on ?? null,
1879
+ openIssues: ms.open_issues,
1880
+ closedIssues: ms.closed_issues,
1881
+ createdAt: ms.created_at,
1882
+ updatedAt: ms.updated_at,
1883
+ creator: ms.creator?.login ?? null
1884
+ };
1885
+ } catch (error) {
1886
+ logger.error("Failed to update milestone", {
1887
+ module: "GitHub",
1888
+ entityId: milestoneNumber,
1889
+ error: error instanceof Error ? error.message : String(error)
1890
+ });
1891
+ throw error;
1892
+ } finally {
1893
+ this.client.invalidateCache(`milestones:${owner}:${repo}`);
1894
+ this.client.invalidateCache(`milestone:${owner}:${repo}:${String(milestoneNumber)}`);
1895
+ this.client.invalidateCache("context:");
1896
+ }
1897
+ }
1898
+ async deleteMilestone(owner, repo, milestoneNumber) {
1899
+ if (!this.client.octokit) {
1900
+ return { success: false, error: "GitHub API not available" };
1901
+ }
1902
+ try {
1903
+ await this.client.octokit.issues.deleteMilestone({
1904
+ owner,
1905
+ repo,
1906
+ milestone_number: milestoneNumber
1907
+ });
1908
+ logger.info("Deleted GitHub milestone", {
1909
+ module: "GitHub",
1910
+ entityId: milestoneNumber,
1911
+ context: { owner, repo }
1912
+ });
1913
+ return { success: true };
1914
+ } catch (error) {
1915
+ const errorMessage = error instanceof Error ? error.message : String(error);
1916
+ logger.error("Failed to delete milestone", {
1917
+ module: "GitHub",
1918
+ entityId: milestoneNumber,
1919
+ error: errorMessage
1920
+ });
1921
+ return { success: false, error: errorMessage };
1922
+ } finally {
1923
+ this.client.invalidateCache(`milestones:${owner}:${repo}`);
1924
+ this.client.invalidateCache(`milestone:${owner}:${repo}:${String(milestoneNumber)}`);
1925
+ this.client.invalidateCache("context:");
1926
+ }
1927
+ }
1928
+ };
1929
+
1930
+ // src/github/github-integration/insights.ts
1931
+ var InsightsManager = class {
1932
+ constructor(client) {
1933
+ this.client = client;
1934
+ }
1935
+ client;
1936
+ async getRepoStats(owner, repo) {
1937
+ if (!this.client.octokit) {
1938
+ return null;
1939
+ }
1940
+ const cacheKey = `repostats:${owner}:${repo}`;
1941
+ const cached = this.client.getCachedWithTtl(cacheKey, TRAFFIC_CACHE_TTL_MS);
1942
+ if (cached) return cached;
1943
+ try {
1944
+ const response = await this.client.octokit.repos.get({ owner, repo });
1945
+ const data = response.data;
1946
+ const result = {
1947
+ stars: data.stargazers_count,
1948
+ forks: data.forks_count,
1949
+ watchers: data.subscribers_count,
1950
+ openIssues: data.open_issues_count,
1951
+ size: data.size,
1952
+ defaultBranch: data.default_branch
1953
+ };
1954
+ this.client.setCache(cacheKey, result);
1955
+ return result;
1956
+ } catch (error) {
1957
+ logger.error("Failed to get repo stats", {
1958
+ module: "GitHub",
1959
+ error: error instanceof Error ? error.message : String(error),
1960
+ context: { owner, repo }
1961
+ });
1962
+ return null;
1963
+ }
1964
+ }
1965
+ async getTrafficData(owner, repo) {
1966
+ if (!this.client.octokit) {
1967
+ return null;
1968
+ }
1969
+ const cacheKey = `traffic:${owner}:${repo}`;
1970
+ const cached = this.client.getCachedWithTtl(cacheKey, TRAFFIC_CACHE_TTL_MS);
1971
+ if (cached) return cached;
1972
+ try {
1973
+ const [clonesRes, viewsRes] = await Promise.all([
1974
+ this.client.octokit.rest.repos.getClones({ owner, repo }),
1975
+ this.client.octokit.rest.repos.getViews({ owner, repo })
1976
+ ]);
1977
+ const clonesDays = clonesRes.data.clones?.length ?? 0;
1978
+ const viewsDays = viewsRes.data.views?.length ?? 0;
1979
+ const result = {
1980
+ clones: {
1981
+ total: clonesRes.data.count,
1982
+ unique: clonesRes.data.uniques,
1983
+ dailyAvg: clonesDays > 0 ? Math.round(clonesRes.data.count / clonesDays) : 0
1984
+ },
1985
+ views: {
1986
+ total: viewsRes.data.count,
1987
+ unique: viewsRes.data.uniques,
1988
+ dailyAvg: viewsDays > 0 ? Math.round(viewsRes.data.count / viewsDays) : 0
1989
+ },
1990
+ period: "14 days"
1991
+ };
1992
+ this.client.setCache(cacheKey, result);
1993
+ return result;
1994
+ } catch (error) {
1995
+ logger.error("Failed to get traffic data", {
1996
+ module: "GitHub",
1997
+ error: error instanceof Error ? error.message : String(error),
1998
+ context: { owner, repo }
1999
+ });
2000
+ return null;
2001
+ }
2002
+ }
2003
+ async getTopReferrers(owner, repo, limit = 5) {
2004
+ if (!this.client.octokit) {
2005
+ return [];
2006
+ }
2007
+ const cacheKey = `referrers:${owner}:${repo}`;
2008
+ const cached = this.client.getCachedWithTtl(cacheKey, TRAFFIC_CACHE_TTL_MS);
2009
+ if (cached) return cached.slice(0, limit);
2010
+ try {
2011
+ const response = await this.client.octokit.rest.repos.getTopReferrers({ owner, repo });
2012
+ const result = response.data.map((r) => ({
2013
+ referrer: r.referrer,
2014
+ count: r.count,
2015
+ uniques: r.uniques
2016
+ }));
2017
+ this.client.setCache(cacheKey, result);
2018
+ return result.slice(0, limit);
2019
+ } catch (error) {
2020
+ logger.error("Failed to get top referrers", {
2021
+ module: "GitHub",
2022
+ error: error instanceof Error ? error.message : String(error),
2023
+ context: { owner, repo }
2024
+ });
2025
+ return [];
2026
+ }
2027
+ }
2028
+ async getPopularPaths(owner, repo, limit = 5) {
2029
+ if (!this.client.octokit) {
2030
+ return [];
2031
+ }
2032
+ const cacheKey = `paths:${owner}:${repo}`;
2033
+ const cached = this.client.getCachedWithTtl(cacheKey, TRAFFIC_CACHE_TTL_MS);
2034
+ if (cached) return cached.slice(0, limit);
2035
+ try {
2036
+ const response = await this.client.octokit.rest.repos.getTopPaths({ owner, repo });
2037
+ const result = response.data.map((p) => ({
2038
+ path: p.path,
2039
+ title: p.title,
2040
+ count: p.count,
2041
+ uniques: p.uniques
2042
+ }));
2043
+ this.client.setCache(cacheKey, result);
2044
+ return result.slice(0, limit);
2045
+ } catch (error) {
2046
+ logger.error("Failed to get popular paths", {
2047
+ module: "GitHub",
2048
+ error: error instanceof Error ? error.message : String(error),
2049
+ context: { owner, repo }
2050
+ });
2051
+ return [];
2052
+ }
2053
+ }
2054
+ };
2055
+
2056
+ // src/github/github-integration/repository.ts
2057
+ var RepositoryManager = class {
2058
+ constructor(client) {
2059
+ this.client = client;
2060
+ }
2061
+ client;
2062
+ async getRepoInfo() {
2063
+ const cached = this.getCachedRepoInfo();
2064
+ if (cached) return cached;
2065
+ try {
2066
+ const branchResult = await this.client.git.branch();
2067
+ const branch = branchResult.current || null;
2068
+ const remotes = await this.client.git.getRemotes(true);
2069
+ const origin = remotes.find((r) => r.name === "origin");
2070
+ const remoteUrl = origin?.refs?.fetch || null;
2071
+ const { owner, repo } = this.parseRemoteUrl(remoteUrl);
2072
+ const repoInfo = { owner, repo, branch, remoteUrl };
2073
+ this.client.setCache("repoInfo", repoInfo);
2074
+ return repoInfo;
2075
+ } catch (error) {
2076
+ logger.debug("Failed to get repo info (may not be a git repo)", {
2077
+ module: "GitHub",
2078
+ error: error instanceof Error ? error.message : String(error)
2079
+ });
2080
+ return { owner: null, repo: null, branch: null, remoteUrl: null };
2081
+ }
2082
+ }
2083
+ getCachedRepoInfo() {
2084
+ return this.client.getCached("repoInfo") ?? null;
2085
+ }
2086
+ setCachedRepoInfo(info) {
2087
+ this.client.setCache("repoInfo", info);
2088
+ }
2089
+ parseRemoteUrl(remoteUrl) {
2090
+ if (!remoteUrl) return { owner: null, repo: null };
2091
+ if (remoteUrl.startsWith("git@github.com:")) {
2092
+ const pathPart = remoteUrl.replace("git@github.com:", "").replace(".git", "");
2093
+ const parts = pathPart.split("/");
2094
+ if (parts.length >= 2) {
2095
+ return { owner: parts[0] ?? null, repo: parts[1] ?? null };
2096
+ }
2097
+ }
2098
+ try {
2099
+ const url = new URL(remoteUrl);
2100
+ if (url.hostname === "github.com") {
2101
+ const path2 = url.pathname.replace(".git", "").replace(/^\//, "");
2102
+ const parts = path2.split("/");
2103
+ if (parts.length >= 2) {
2104
+ return { owner: parts[0] ?? null, repo: parts[1] ?? null };
2105
+ }
2106
+ }
2107
+ } catch {
2108
+ }
2109
+ return { owner: null, repo: null };
2110
+ }
2111
+ async getWorkflowRuns(owner, repo, limit = 10, abortSignal) {
2112
+ if (!this.client.octokit) {
2113
+ logger.debug("GitHub API not available - no token", { module: "GitHub" });
2114
+ throw new Error("GitHub API not available");
2115
+ }
2116
+ const cacheKey = `workflows:${owner}:${repo}:${String(limit)}`;
2117
+ const cached = this.client.getCached(cacheKey);
2118
+ if (cached) return cached;
2119
+ try {
2120
+ const response = await this.client.octokit.rest.actions.listWorkflowRunsForRepo({
2121
+ owner,
2122
+ repo,
2123
+ per_page: limit,
2124
+ request: { signal: abortSignal }
2125
+ });
2126
+ const result = response.data.workflow_runs.map((run) => ({
2127
+ id: run.id,
2128
+ name: run.name ?? "Unknown Workflow",
2129
+ status: run.status,
2130
+ conclusion: run.conclusion,
2131
+ url: run.html_url,
2132
+ headBranch: run.head_branch ?? "",
2133
+ headSha: run.head_sha,
2134
+ createdAt: run.created_at,
2135
+ updatedAt: run.updated_at
2136
+ }));
2137
+ this.client.setCache(cacheKey, result);
2138
+ return result;
2139
+ } catch (error) {
2140
+ logger.error("Failed to get workflow runs", {
2141
+ module: "GitHub",
2142
+ error: error instanceof Error ? error.message : String(error)
2143
+ });
2144
+ throw error;
2145
+ }
2146
+ }
2147
+ async getLocalGitStatus() {
2148
+ try {
2149
+ const status = await this.client.git.status();
2150
+ return {
2151
+ modified: status.modified.length,
2152
+ untracked: status.not_added.length,
2153
+ isClean: status.isClean()
2154
+ };
2155
+ } catch (error) {
2156
+ logger.debug("Failed to get local git status", {
2157
+ module: "GitHub",
2158
+ error: error instanceof Error ? error.message : String(error)
2159
+ });
2160
+ return { modified: 0, untracked: 0, isClean: true };
2161
+ }
2162
+ }
2163
+ };
2164
+ function getGitHubIntegration(workingDir = ".", runtime, token) {
2165
+ const resolvedDir = workingDir === "." ? process.cwd() : workingDir;
2166
+ if (runtime) {
2167
+ runtime.githubClientPool ??= /* @__PURE__ */ new Map();
2168
+ const cacheKey = token ? `${resolvedDir}:${createHash("sha256").update(token).digest("hex").substring(0, 12)}` : resolvedDir;
2169
+ let instance = runtime.githubClientPool.get(cacheKey);
2170
+ if (!instance) {
2171
+ instance = new GitHubIntegration(resolvedDir, token);
2172
+ runtime.githubClientPool.set(cacheKey, instance);
2173
+ }
2174
+ return instance;
2175
+ }
2176
+ return new GitHubIntegration(resolvedDir, token);
2177
+ }
2178
+ var GitHubIntegration = class {
2179
+ client;
2180
+ issuesManager;
2181
+ pullRequestsManager;
2182
+ projectsManager;
2183
+ milestonesManager;
2184
+ insightsManager;
2185
+ repositoryManager;
2186
+ constructor(workingDir = ".", token) {
2187
+ this.client = new GitHubClient(workingDir, token);
2188
+ this.issuesManager = new IssuesManager(this.client);
2189
+ this.pullRequestsManager = new PullRequestsManager(this.client);
2190
+ this.projectsManager = new ProjectsManager(this.client);
2191
+ this.milestonesManager = new MilestonesManager(this.client);
2192
+ this.insightsManager = new InsightsManager(this.client);
2193
+ this.repositoryManager = new RepositoryManager(this.client);
2194
+ }
2195
+ isApiAvailable() {
2196
+ return this.client.isApiAvailable();
2197
+ }
2198
+ clearCache() {
2199
+ this.client.clearCache();
2200
+ }
2201
+ async getRepoInfo() {
2202
+ return this.repositoryManager.getRepoInfo();
2203
+ }
2204
+ getCachedRepoInfo() {
2205
+ return this.repositoryManager.getCachedRepoInfo();
2206
+ }
2207
+ setCachedRepoInfo(info) {
2208
+ this.repositoryManager.setCachedRepoInfo(info);
2209
+ }
2210
+ async getLocalGitStatus() {
2211
+ return this.repositoryManager.getLocalGitStatus();
2212
+ }
2213
+ async getIssues(owner, repo, state = "open", limit = 20, abortSignal) {
2214
+ return this.issuesManager.getIssues(owner, repo, state, limit, abortSignal);
2215
+ }
2216
+ async getIssue(owner, repo, issueNumber) {
2217
+ return this.issuesManager.getIssue(owner, repo, issueNumber);
2218
+ }
2219
+ async getIssueComments(owner, repo, issueNumber, limit = 30) {
2220
+ return this.issuesManager.getIssueComments(owner, repo, issueNumber, limit);
2221
+ }
2222
+ async createIssue(owner, repo, title, body, labels, assignees, milestone) {
2223
+ return this.issuesManager.createIssue(
2224
+ owner,
2225
+ repo,
2226
+ title,
2227
+ body,
2228
+ labels,
2229
+ assignees,
2230
+ milestone
2231
+ );
2232
+ }
2233
+ async closeIssue(owner, repo, issueNumber, comment) {
2234
+ return this.issuesManager.closeIssue(owner, repo, issueNumber, comment);
2235
+ }
2236
+ async getPullRequests(owner, repo, state = "open", limit = 20, abortSignal) {
2237
+ return this.pullRequestsManager.getPullRequests(owner, repo, state, limit, abortSignal);
2238
+ }
2239
+ async getPullRequest(owner, repo, prNumber) {
2240
+ return this.pullRequestsManager.getPullRequest(owner, repo, prNumber);
2241
+ }
2242
+ async getReviews(owner, repo, prNumber) {
2243
+ return this.pullRequestsManager.getReviews(owner, repo, prNumber);
2244
+ }
2245
+ async getReviewComments(owner, repo, prNumber) {
2246
+ return this.pullRequestsManager.getReviewComments(owner, repo, prNumber);
2247
+ }
2248
+ async getCopilotReviewSummary(owner, repo, prNumber) {
2249
+ return this.pullRequestsManager.getCopilotReviewSummary(owner, repo, prNumber);
2250
+ }
2251
+ async getWorkflowRuns(owner, repo, limit = 10, abortSignal) {
2252
+ return this.repositoryManager.getWorkflowRuns(owner, repo, limit, abortSignal);
2253
+ }
2254
+ async getRepoContext(abortSignal) {
2255
+ const cached = this.client.getCached("context:repo");
2256
+ if (cached) return cached;
2257
+ const repoInfo = await this.repositoryManager.getRepoInfo();
2258
+ const context = {
2259
+ repoName: repoInfo.repo,
2260
+ branch: repoInfo.branch,
2261
+ commit: null,
2262
+ remoteUrl: repoInfo.remoteUrl,
2263
+ projects: [],
2264
+ issues: [],
2265
+ pullRequests: [],
2266
+ workflowRuns: [],
2267
+ milestones: []
2268
+ };
2269
+ try {
2270
+ const log = await this.client.git.log({ maxCount: 1 });
2271
+ context.commit = log.latest?.hash ?? null;
2272
+ } catch {
2273
+ }
2274
+ const degraded = [];
2275
+ if (repoInfo.owner && repoInfo.repo) {
2276
+ const [issuesResult, prsResult, runsResult, milestonesResult] = await Promise.allSettled([
2277
+ this.issuesManager.getIssues(
2278
+ repoInfo.owner,
2279
+ repoInfo.repo,
2280
+ "open",
2281
+ 10,
2282
+ abortSignal
2283
+ ),
2284
+ this.pullRequestsManager.getPullRequests(
2285
+ repoInfo.owner,
2286
+ repoInfo.repo,
2287
+ "open",
2288
+ 10,
2289
+ abortSignal
2290
+ ),
2291
+ this.repositoryManager.getWorkflowRuns(
2292
+ repoInfo.owner,
2293
+ repoInfo.repo,
2294
+ 10,
2295
+ abortSignal
2296
+ ),
2297
+ this.milestonesManager.getMilestones(
2298
+ repoInfo.owner,
2299
+ repoInfo.repo,
2300
+ "open",
2301
+ 10,
2302
+ abortSignal
2303
+ )
2304
+ ]);
2305
+ context.issues = issuesResult.status === "fulfilled" ? issuesResult.value : [];
2306
+ if (issuesResult.status === "rejected") degraded.push("issues");
2307
+ context.pullRequests = prsResult.status === "fulfilled" ? prsResult.value : [];
2308
+ if (prsResult.status === "rejected") degraded.push("pullRequests");
2309
+ context.workflowRuns = runsResult.status === "fulfilled" ? runsResult.value : [];
2310
+ if (runsResult.status === "rejected") degraded.push("workflowRuns");
2311
+ context.milestones = milestonesResult.status === "fulfilled" ? milestonesResult.value : [];
2312
+ if (milestonesResult.status === "rejected") degraded.push("milestones");
2313
+ }
2314
+ if (degraded.length > 0) {
2315
+ context.degraded = degraded;
2316
+ }
2317
+ this.client.setCache("context:repo", context);
2318
+ return context;
2319
+ }
2320
+ async getProjectKanban(owner, projectNumber, repo, abortSignal) {
2321
+ return this.projectsManager.getProjectKanban(owner, projectNumber, repo, abortSignal);
2322
+ }
2323
+ async moveProjectItem(projectId, itemId, statusFieldId, statusOptionId) {
2324
+ return this.projectsManager.moveProjectItem(
2325
+ projectId,
2326
+ itemId,
2327
+ statusFieldId,
2328
+ statusOptionId
2329
+ );
2330
+ }
2331
+ async addProjectItem(projectId, contentId) {
2332
+ return this.projectsManager.addProjectItem(projectId, contentId);
2333
+ }
2334
+ async deleteProjectItem(projectId, itemId) {
2335
+ return this.projectsManager.deleteProjectItem(projectId, itemId);
2336
+ }
2337
+ async getMilestones(owner, repo, state = "open", limit = 20, abortSignal) {
2338
+ return this.milestonesManager.getMilestones(owner, repo, state, limit, abortSignal);
2339
+ }
2340
+ async getMilestone(owner, repo, milestoneNumber) {
2341
+ return this.milestonesManager.getMilestone(owner, repo, milestoneNumber);
2342
+ }
2343
+ async createMilestone(owner, repo, title, description, dueOn) {
2344
+ return this.milestonesManager.createMilestone(owner, repo, title, description, dueOn);
2345
+ }
2346
+ async updateMilestone(owner, repo, milestoneNumber, updates) {
2347
+ return this.milestonesManager.updateMilestone(owner, repo, milestoneNumber, updates);
2348
+ }
2349
+ async deleteMilestone(owner, repo, milestoneNumber) {
2350
+ return this.milestonesManager.deleteMilestone(owner, repo, milestoneNumber);
2351
+ }
2352
+ async getRepoStats(owner, repo) {
2353
+ return this.insightsManager.getRepoStats(owner, repo);
2354
+ }
2355
+ async getTrafficData(owner, repo) {
2356
+ return this.insightsManager.getTrafficData(owner, repo);
2357
+ }
2358
+ async getTopReferrers(owner, repo, limit = 5) {
2359
+ return this.insightsManager.getTopReferrers(owner, repo, limit);
2360
+ }
2361
+ async getPopularPaths(owner, repo, limit = 5) {
2362
+ return this.insightsManager.getPopularPaths(owner, repo, limit);
2363
+ }
2364
+ };
2365
+ var ErrorFieldsMixin = z.object({
2366
+ error: z.string().optional().describe("Human-readable error message"),
2367
+ code: z.string().optional().describe("Error code (e.g. VALIDATION_ERROR, INTERNAL_ERROR)"),
2368
+ category: z.string().optional().describe("Error category (validation, query, connection, internal)"),
2369
+ recoverable: z.boolean().optional().describe("Whether the error is recoverable"),
2370
+ suggestion: z.string().optional().describe("Suggested fix for the error"),
2371
+ details: z.record(z.string(), z.unknown()).optional().describe("Additional error context")
2372
+ });
2373
+ var ENTRY_TYPES = [
2374
+ "personal_reflection",
2375
+ "project_decision",
2376
+ "technical_achievement",
2377
+ "bug_fix",
2378
+ "feature_implementation",
2379
+ "code_review",
2380
+ "meeting_notes",
2381
+ "learning",
2382
+ "research",
2383
+ "planning",
2384
+ "retrospective",
2385
+ "standup",
2386
+ "technical_note",
2387
+ "development_note",
2388
+ "enhancement",
2389
+ "milestone",
2390
+ "flag",
2391
+ "system_integration_test",
2392
+ "test_entry",
2393
+ "plan_draft",
2394
+ "adversarial_review",
2395
+ "plan_refinement",
2396
+ "copilot_validation",
2397
+ "other"
2398
+ ];
2399
+ var SIGNIFICANCE_TYPES = [
2400
+ "milestone",
2401
+ "breakthrough",
2402
+ "decision",
2403
+ "architecture",
2404
+ "lesson_learned",
2405
+ "blocker_resolved",
2406
+ "release",
2407
+ "security"
2408
+ ];
2409
+ function coerceSignificanceAlias(params) {
2410
+ if (params !== null && params !== void 0 && typeof params === "object") {
2411
+ const obj = params;
2412
+ if (typeof obj["significance_type"] === "string") {
2413
+ const lower = obj["significance_type"].toLowerCase();
2414
+ if (lower === "important") obj["significance_type"] = "milestone";
2415
+ else if (lower === "major") obj["significance_type"] = "breakthrough";
2416
+ else if (lower === "critical") obj["significance_type"] = "security";
2417
+ else if (lower === "learning") obj["significance_type"] = "lesson_learned";
2418
+ else if (lower === "key_decision") obj["significance_type"] = "decision";
2419
+ else if (lower === "resolved") obj["significance_type"] = "blocker_resolved";
2420
+ else if (lower === "maintenance" || lower === "minor") delete obj["significance_type"];
2421
+ }
2422
+ }
2423
+ }
2424
+ var MAX_CONTENT_LENGTH = 5e4;
2425
+ var MAX_QUERY_LIMIT = 500;
2426
+ var DATE_MIN_SENTINEL = "1970-01-01";
2427
+ var DATE_MAX_SENTINEL = "2999-12-31";
2428
+ var DATE_FORMAT_REGEX = /^\d{4}-\d{2}-\d{2}$/;
2429
+ var DATE_FORMAT_MESSAGE = "Date must be YYYY-MM-DD format";
2430
+ var relaxedNumber = () => z.union([z.number(), z.string()]);
2431
+ var StrictProjectNumberSchema = z.number({
2432
+ message: "Missing project_number. You MUST provide a valid project_number (e.g., 1) to associate this action with a specific project context."
2433
+ });
2434
+ var EntryOutputSchema = z.object({
2435
+ id: z.number(),
2436
+ content: z.string().max(MAX_CONTENT_LENGTH),
2437
+ entryType: z.string(),
2438
+ isPersonal: z.boolean(),
2439
+ timestamp: z.string(),
2440
+ tags: z.array(z.string()).optional(),
2441
+ significanceType: z.string().nullable().optional(),
2442
+ autoContext: z.string().nullable().optional().describe("@deprecated Use author and flagMetadata instead"),
2443
+ author: z.string().nullable().optional(),
2444
+ flagMetadata: z.record(z.string(), z.unknown()).nullable().optional(),
2445
+ deletedAt: z.string().nullable().optional(),
2446
+ projectNumber: z.number().nullable().optional(),
2447
+ projectOwner: z.string().nullable().optional(),
2448
+ issueNumber: z.number().nullable().optional(),
2449
+ issueUrl: z.string().nullable().optional(),
2450
+ prNumber: z.number().nullable().optional(),
2451
+ prUrl: z.string().nullable().optional(),
2452
+ prStatus: z.string().nullable().optional(),
2453
+ workflowRunId: z.number().nullable().optional(),
2454
+ workflowName: z.string().nullable().optional(),
2455
+ workflowStatus: z.string().nullable().optional(),
2456
+ source: z.enum(["personal", "team"]).optional(),
2457
+ importanceScore: z.number().optional().describe("Importance score (0.0-1.0), present when sort_by=importance")
2458
+ }).extend(ErrorFieldsMixin.shape);
2459
+ var EntriesListOutputSchema = z.object({
2460
+ entries: z.array(EntryOutputSchema).optional(),
2461
+ count: z.number().optional(),
2462
+ searchMode: z.string().optional(),
2463
+ degraded: z.boolean().optional().describe(
2464
+ "True if the search degraded to a slower fallback method due to infrastructure failure"
2465
+ ),
2466
+ success: z.boolean().optional(),
2467
+ error: z.string().optional()
2468
+ }).extend(ErrorFieldsMixin.shape);
2469
+ var RelationshipOutputSchema = z.object({
2470
+ id: z.number(),
2471
+ fromEntryId: z.number(),
2472
+ toEntryId: z.number(),
2473
+ relationshipType: z.string(),
2474
+ description: z.string().nullable().optional(),
2475
+ createdAt: z.string()
2476
+ }).extend(ErrorFieldsMixin.shape);
2477
+ var ImportanceBreakdownSchema = z.object({
2478
+ significance: z.number(),
2479
+ relationships: z.number(),
2480
+ causal: z.number(),
2481
+ recency: z.number()
2482
+ });
2483
+ var TagOutputSchema = z.object({
2484
+ name: z.string(),
2485
+ count: z.number().nullable()
2486
+ }).extend(ErrorFieldsMixin.shape);
2487
+
2488
+ // src/handlers/resources/shared.ts
2489
+ async function resolveGitHubRepo(github, config, targetRepo, runtime) {
2490
+ const lastModified = (/* @__PURE__ */ new Date()).toISOString();
2491
+ let activeGithub = github;
2492
+ if (targetRepo) {
2493
+ if (!/^[a-zA-Z0-9_.-]+(\/[a-zA-Z0-9_.-]+)?$/.test(targetRepo)) {
2494
+ return {
2495
+ data: { error: "Invalid repository name format" },
2496
+ annotations: { lastModified }
2497
+ };
2498
+ }
2499
+ const registry = config?.projectRegistry;
2500
+ let registryKey = targetRepo;
2501
+ if (registry && !Object.prototype.hasOwnProperty.call(registry, targetRepo)) {
2502
+ const parts = targetRepo.split("/");
2503
+ const repoPart = parts[1];
2504
+ if (parts.length === 2 && repoPart && Object.prototype.hasOwnProperty.call(registry, repoPart)) {
2505
+ registryKey = repoPart;
2506
+ }
2507
+ }
2508
+ if (registry && Object.prototype.hasOwnProperty.call(registry, registryKey)) {
2509
+ const entry = registry[registryKey];
2510
+ if (entry) {
2511
+ activeGithub = getGitHubIntegration(entry.path, runtime);
2512
+ }
2513
+ } else {
2514
+ return {
2515
+ data: { error: `Repository not found in registry: ${targetRepo}` },
2516
+ annotations: { lastModified }
2517
+ };
2518
+ }
2519
+ }
2520
+ if (!activeGithub) {
2521
+ const hasRegistry = config?.projectRegistry && Object.keys(config.projectRegistry).length > 0;
2522
+ return {
2523
+ data: {
2524
+ error: "GitHub integration not available",
2525
+ hint: hasRegistry ? "Set GITHUB_TOKEN, or assure the dynamic repo URI correctly matches a registered project." : "Set GITHUB_TOKEN securely."
2526
+ },
2527
+ annotations: { lastModified }
2528
+ };
2529
+ }
2530
+ const repoInfo = await activeGithub.getRepoInfo();
2531
+ const owner = repoInfo.owner;
2532
+ const repo = repoInfo.repo;
2533
+ if (!owner || !repo) {
2534
+ const registry = config?.projectRegistry;
2535
+ const hasRegistry = registry && Object.keys(registry).length > 0;
2536
+ if (!targetRepo && hasRegistry) {
2537
+ for (const key of Object.keys(registry)) {
2538
+ const project = registry[key];
2539
+ if (project) {
2540
+ const fallbackGithub = getGitHubIntegration(project.path, runtime);
2541
+ const fallbackRepoInfo = await fallbackGithub.getRepoInfo();
2542
+ if (fallbackRepoInfo.owner && fallbackRepoInfo.repo) {
2543
+ return {
2544
+ owner: fallbackRepoInfo.owner,
2545
+ repo: fallbackRepoInfo.repo,
2546
+ branch: fallbackRepoInfo.branch ?? null,
2547
+ lastModified,
2548
+ github: fallbackGithub
2549
+ };
2550
+ }
2551
+ }
2552
+ }
2553
+ }
2554
+ return {
2555
+ data: {
2556
+ error: "Could not detect repository",
2557
+ hint: hasRegistry ? "Use a repository-specific URI suffix (e.g., memory://github/status/{repo}) for multi-project setups, or ensure the fallback project is a valid git repository." : "Run the MCP server from a valid git repository or configure PROJECT_REGISTRY.",
2558
+ ...repoInfo.branch ? { branch: repoInfo.branch } : {}
2559
+ },
2560
+ annotations: { lastModified }
2561
+ };
2562
+ }
2563
+ return { owner, repo, branch: repoInfo.branch ?? null, lastModified, github: activeGithub };
2564
+ }
2565
+ function isResourceError(result) {
2566
+ return "data" in result;
2567
+ }
2568
+ var DEFAULT_BRIEFING_CONFIG = {
2569
+ entryCount: 3,
2570
+ summaryCount: 1,
2571
+ includeTeam: false,
2572
+ issueCount: 0,
2573
+ prCount: 0,
2574
+ prStatusBreakdown: false,
2575
+ milestoneCount: 3,
2576
+ workflowCount: 0,
2577
+ workflowStatusBreakdown: false,
2578
+ copilotReviews: false
2579
+ };
2580
+ function milestoneCompletionPct(openIssues, closedIssues) {
2581
+ const total = openIssues + closedIssues;
2582
+ return total > 0 ? Math.round(closedIssues / total * 100) : 0;
2583
+ }
2584
+ var TeamEntryOutputSchema = EntryOutputSchema.extend({
2585
+ author: z.string().nullable().optional()
2586
+ });
2587
+ var TeamCreateEntrySchema = z.object({
2588
+ content: z.string().min(1).max(MAX_CONTENT_LENGTH),
2589
+ entry_type: z.enum(ENTRY_TYPES).optional().default("personal_reflection"),
2590
+ tags: z.array(z.string()).optional().default([]),
2591
+ significance_type: z.enum(SIGNIFICANCE_TYPES).optional(),
2592
+ project_number: StrictProjectNumberSchema,
2593
+ project_owner: z.string().optional(),
2594
+ issue_number: z.number().optional(),
2595
+ issue_url: z.string().optional(),
2596
+ pr_number: z.number().optional(),
2597
+ pr_url: z.string().optional(),
2598
+ pr_status: z.enum(["draft", "open", "merged", "closed"]).optional(),
2599
+ author: z.string().optional()
2600
+ });
2601
+ var TeamCreateEntrySchemaMcp = z.object({
2602
+ content: z.string().optional(),
2603
+ entry_type: z.string().optional().default("personal_reflection"),
2604
+ tags: z.array(z.string()).optional().default([]),
2605
+ significance_type: z.string().optional(),
2606
+ project_number: relaxedNumber().optional(),
2607
+ project_owner: z.string().optional(),
2608
+ issue_number: relaxedNumber().optional(),
2609
+ issue_url: z.string().optional(),
2610
+ pr_number: relaxedNumber().optional(),
2611
+ pr_url: z.string().optional(),
2612
+ pr_status: z.string().optional(),
2613
+ author: z.string().optional()
2614
+ });
2615
+ var TeamGetRecentSchema = z.object({
2616
+ limit: z.number().min(1).max(500).optional().default(10),
2617
+ project_number: StrictProjectNumberSchema,
2618
+ sort_by: z.enum(["timestamp", "importance"]).optional().default("timestamp").describe("Sort results by timestamp (default) or importance score")
2619
+ });
2620
+ var TeamGetRecentSchemaMcp = z.object({
2621
+ limit: relaxedNumber().optional().default(10),
2622
+ project_number: relaxedNumber().optional(),
2623
+ sort_by: z.string().optional().default("timestamp").describe("Sort results by timestamp (default) or importance score")
2624
+ });
2625
+ var TeamSearchSchema = z.object({
2626
+ query: z.string().optional(),
2627
+ tags: z.array(z.string()).optional(),
2628
+ project_number: StrictProjectNumberSchema,
2629
+ limit: z.number().max(500).optional().default(10),
2630
+ sort_by: z.enum(["timestamp", "importance"]).optional().default("timestamp").describe("Sort results by timestamp (default) or importance score")
2631
+ });
2632
+ var TeamSearchSchemaMcp = z.object({
2633
+ query: z.string().optional(),
2634
+ tags: z.array(z.string()).optional(),
2635
+ project_number: relaxedNumber().optional(),
2636
+ limit: relaxedNumber().optional().default(10),
2637
+ sort_by: z.string().optional().default("timestamp").describe("Sort results by timestamp (default) or importance score")
2638
+ });
2639
+ var TeamGetEntryByIdSchema = z.object({
2640
+ entry_id: z.number(),
2641
+ include_relationships: z.boolean().optional().default(true),
2642
+ project_number: StrictProjectNumberSchema
2643
+ });
2644
+ var TeamGetEntryByIdSchemaMcp = z.object({
2645
+ entry_id: relaxedNumber().optional(),
2646
+ include_relationships: z.boolean().optional().default(true),
2647
+ project_number: relaxedNumber().optional()
2648
+ });
2649
+ var TeamSearchByDateRangeSchema = z.object({
2650
+ start_date: z.string().regex(DATE_FORMAT_REGEX, DATE_FORMAT_MESSAGE),
2651
+ end_date: z.string().regex(DATE_FORMAT_REGEX, DATE_FORMAT_MESSAGE),
2652
+ entry_type: z.enum(ENTRY_TYPES).optional(),
2653
+ tags: z.array(z.string()).optional(),
2654
+ project_number: StrictProjectNumberSchema,
2655
+ limit: z.number().max(500).optional().default(50),
2656
+ sort_by: z.enum(["timestamp", "importance"]).optional().default("timestamp").describe("Sort results by timestamp (default) or importance score")
2657
+ });
2658
+ var TeamSearchByDateRangeSchemaMcp = z.object({
2659
+ start_date: z.string().optional().describe("Start date (YYYY-MM-DD)"),
2660
+ end_date: z.string().optional().describe("End date (YYYY-MM-DD)"),
2661
+ entry_type: z.string().optional(),
2662
+ tags: z.array(z.string()).optional(),
2663
+ project_number: relaxedNumber().optional(),
2664
+ limit: relaxedNumber().optional().default(50),
2665
+ sort_by: z.string().optional().default("timestamp").describe("Sort results by timestamp (default) or importance score")
2666
+ });
2667
+ var TeamUpdateEntrySchema = z.object({
2668
+ entry_id: z.number(),
2669
+ content: z.string().min(1).max(MAX_CONTENT_LENGTH).optional(),
2670
+ entry_type: z.enum(ENTRY_TYPES).optional(),
2671
+ tags: z.array(z.string()).optional(),
2672
+ project_number: StrictProjectNumberSchema,
2673
+ significance_type: z.enum(SIGNIFICANCE_TYPES).nullable().optional(),
2674
+ project_owner: z.string().nullable().optional(),
2675
+ issue_number: z.number().nullable().optional(),
2676
+ issue_url: z.string().nullable().optional(),
2677
+ pr_number: z.number().nullable().optional(),
2678
+ pr_url: z.string().nullable().optional(),
2679
+ pr_status: z.enum(["draft", "open", "merged", "closed"]).nullable().optional(),
2680
+ workflow_run_id: z.number().nullable().optional(),
2681
+ workflow_name: z.string().nullable().optional(),
2682
+ workflow_status: z.enum(["queued", "in_progress", "completed"]).nullable().optional()
2683
+ });
2684
+ var TeamUpdateEntrySchemaMcp = z.object({
2685
+ entry_id: relaxedNumber().optional(),
2686
+ content: z.string().optional(),
2687
+ entry_type: z.string().optional(),
2688
+ tags: z.array(z.string()).optional(),
2689
+ project_number: relaxedNumber().nullable().optional(),
2690
+ significance_type: z.string().nullable().optional(),
2691
+ project_owner: z.string().nullable().optional(),
2692
+ issue_number: relaxedNumber().nullable().optional(),
2693
+ issue_url: z.string().nullable().optional(),
2694
+ pr_number: relaxedNumber().nullable().optional(),
2695
+ pr_url: z.string().nullable().optional(),
2696
+ pr_status: z.string().nullable().optional(),
2697
+ workflow_run_id: relaxedNumber().nullable().optional(),
2698
+ workflow_name: z.string().nullable().optional(),
2699
+ workflow_status: z.string().nullable().optional()
2700
+ });
2701
+ var TeamDeleteEntrySchema = z.object({
2702
+ entry_id: z.number(),
2703
+ project_number: StrictProjectNumberSchema
2704
+ });
2705
+ var TeamDeleteEntrySchemaMcp = z.object({
2706
+ entry_id: relaxedNumber().optional(),
2707
+ project_number: relaxedNumber().optional()
2708
+ });
2709
+ var TeamMergeTagsSchema = z.object({
2710
+ source_tag: z.string().min(1),
2711
+ target_tag: z.string().min(1)
2712
+ });
2713
+ var TeamMergeTagsSchemaMcp = z.object({
2714
+ source_tag: z.string().optional(),
2715
+ target_tag: z.string().optional()
2716
+ });
2717
+ var TeamGetStatisticsSchema = z.object({
2718
+ group_by: z.enum(["day", "week", "month"]).optional().default("week")
2719
+ });
2720
+ var TeamGetStatisticsSchemaMcp = z.object({
2721
+ group_by: z.string().optional().default("week")
2722
+ });
2723
+ var TeamLinkEntriesSchema = z.object({
2724
+ from_entry_id: z.number(),
2725
+ to_entry_id: z.number(),
2726
+ relationship_type: z.enum([
2727
+ "evolves_from",
2728
+ "references",
2729
+ "implements",
2730
+ "clarifies",
2731
+ "response_to",
2732
+ "blocked_by",
2733
+ "resolved",
2734
+ "caused"
2735
+ ]).optional().default("references"),
2736
+ description: z.string().optional(),
2737
+ project_number: StrictProjectNumberSchema
2738
+ });
2739
+ var TeamLinkEntriesSchemaMcp = z.object({
2740
+ from_entry_id: relaxedNumber().optional(),
2741
+ to_entry_id: relaxedNumber().optional(),
2742
+ from: relaxedNumber().optional(),
2743
+ to: relaxedNumber().optional(),
2744
+ from_id: relaxedNumber().optional(),
2745
+ to_id: relaxedNumber().optional(),
2746
+ relationship_type: z.string().optional().default("references"),
2747
+ type: z.string().optional(),
2748
+ description: z.string().optional(),
2749
+ project_number: relaxedNumber().optional()
2750
+ }).transform((data) => ({
2751
+ from_entry_id: data.from_entry_id ?? data.from_id ?? data.from,
2752
+ to_entry_id: data.to_entry_id ?? data.to_id ?? data.to,
2753
+ relationship_type: data.type ?? data.relationship_type,
2754
+ description: data.description,
2755
+ project_number: data.project_number
2756
+ }));
2757
+ var TeamVisualizeRelationshipsSchema = z.object({
2758
+ entry_id: z.number().optional(),
2759
+ tag: z.string().optional(),
2760
+ depth: z.number().min(1).max(5).optional().default(2)
2761
+ });
2762
+ var TeamVisualizeRelationshipsSchemaMcp = z.object({
2763
+ entry_id: relaxedNumber().optional(),
2764
+ tag: z.string().optional(),
2765
+ depth: relaxedNumber().optional().default(2)
2766
+ });
2767
+ var TeamExportEntriesSchema = z.object({
2768
+ format: z.enum(["json", "markdown"]).optional().default("json"),
2769
+ start_date: z.string().regex(DATE_FORMAT_REGEX, DATE_FORMAT_MESSAGE).optional(),
2770
+ end_date: z.string().regex(DATE_FORMAT_REGEX, DATE_FORMAT_MESSAGE).optional(),
2771
+ entry_type: z.enum(ENTRY_TYPES).optional(),
2772
+ tags: z.array(z.string()).optional(),
2773
+ limit: z.number().max(5e3).optional().default(100)
2774
+ });
2775
+ var TeamExportEntriesSchemaMcp = z.object({
2776
+ format: z.string().optional().default("json"),
2777
+ start_date: z.string().optional(),
2778
+ end_date: z.string().optional(),
2779
+ entry_type: z.string().optional(),
2780
+ tags: z.array(z.string()).optional(),
2781
+ limit: relaxedNumber().optional().default(100)
2782
+ });
2783
+ var TeamBackupSchema = z.object({
2784
+ name: z.string().optional()
2785
+ });
2786
+ var TeamCreateOutputSchema = z.object({
2787
+ success: z.boolean().optional(),
2788
+ entry: TeamEntryOutputSchema.optional(),
2789
+ author: z.string().optional(),
2790
+ error: z.string().optional()
2791
+ }).extend(ErrorFieldsMixin.shape);
2792
+ var TeamEntriesListOutputSchema = z.object({
2793
+ entries: z.array(TeamEntryOutputSchema).optional(),
2794
+ count: z.number().optional(),
2795
+ success: z.boolean().optional(),
2796
+ error: z.string().optional()
2797
+ }).extend(ErrorFieldsMixin.shape);
2798
+ var TeamEntryDetailOutputSchema = z.object({
2799
+ success: z.boolean().optional(),
2800
+ entry: TeamEntryOutputSchema.optional(),
2801
+ relationships: z.array(RelationshipOutputSchema).optional(),
2802
+ importance: z.object({
2803
+ score: z.number(),
2804
+ breakdown: z.object({
2805
+ significance: z.number(),
2806
+ relationships: z.number(),
2807
+ causal: z.number(),
2808
+ recency: z.number()
2809
+ }).optional()
2810
+ }).optional(),
2811
+ error: z.string().optional()
2812
+ }).extend(ErrorFieldsMixin.shape);
2813
+ var TeamTagsListOutputSchema = z.object({
2814
+ success: z.boolean().optional(),
2815
+ tags: z.array(TagOutputSchema).optional(),
2816
+ count: z.number().optional(),
2817
+ error: z.string().optional()
2818
+ }).extend(ErrorFieldsMixin.shape);
2819
+ var TeamUpdateOutputSchema = z.object({
2820
+ success: z.boolean().optional(),
2821
+ entry: TeamEntryOutputSchema.optional(),
2822
+ error: z.string().optional()
2823
+ }).extend(ErrorFieldsMixin.shape);
2824
+ var TeamDeleteOutputSchema = z.object({
2825
+ success: z.boolean().optional(),
2826
+ message: z.string().optional(),
2827
+ error: z.string().optional()
2828
+ }).extend(ErrorFieldsMixin.shape);
2829
+ var TeamMergeTagsOutputSchema = z.object({
2830
+ success: z.boolean().optional(),
2831
+ message: z.string().optional(),
2832
+ entriesUpdated: z.number().optional(),
2833
+ sourceDeleted: z.boolean().optional(),
2834
+ error: z.string().optional()
2835
+ }).extend(ErrorFieldsMixin.shape);
2836
+ var TeamStatisticsOutputSchema = z.object({
2837
+ success: z.boolean().optional(),
2838
+ totalEntries: z.number().optional(),
2839
+ periodEntries: z.number().optional(),
2840
+ entryTypes: z.record(z.string(), z.number()).optional(),
2841
+ topTags: z.array(z.object({ name: z.string(), count: z.number() })).optional(),
2842
+ authors: z.array(z.object({ author: z.string(), count: z.number() })).optional(),
2843
+ error: z.string().optional()
2844
+ }).extend(ErrorFieldsMixin.shape);
2845
+ var TeamLinkEntriesOutputSchema = z.object({
2846
+ success: z.boolean().optional(),
2847
+ relationship: RelationshipOutputSchema.optional(),
2848
+ duplicate: z.boolean().optional().describe("True if relationship already existed"),
2849
+ message: z.string().optional(),
2850
+ error: z.string().optional()
2851
+ }).extend(ErrorFieldsMixin.shape);
2852
+ var TeamVisualizeOutputSchema = z.object({
2853
+ success: z.boolean().optional(),
2854
+ mermaid: z.string().optional(),
2855
+ nodeCount: z.number().optional(),
2856
+ edgeCount: z.number().optional(),
2857
+ error: z.string().optional()
2858
+ }).extend(ErrorFieldsMixin.shape);
2859
+ var TeamExportOutputSchema = z.object({
2860
+ success: z.boolean().optional(),
2861
+ format: z.string().optional(),
2862
+ data: z.string().optional(),
2863
+ count: z.number().optional(),
2864
+ truncated: z.boolean().optional(),
2865
+ error: z.string().optional()
2866
+ }).extend(ErrorFieldsMixin.shape);
2867
+ var TeamBackupOutputSchema = z.object({
2868
+ success: z.boolean().optional(),
2869
+ message: z.string().optional(),
2870
+ filename: z.string().optional(),
2871
+ path: z.string().optional(),
2872
+ sizeBytes: z.number().optional(),
2873
+ error: z.string().optional()
2874
+ }).extend(ErrorFieldsMixin.shape);
2875
+ var TeamBackupsListOutputSchema = z.object({
2876
+ success: z.boolean().optional(),
2877
+ backups: z.array(
2878
+ z.object({
2879
+ filename: z.string(),
2880
+ path: z.string(),
2881
+ sizeBytes: z.number(),
2882
+ createdAt: z.string()
2883
+ })
2884
+ ).optional(),
2885
+ total: z.number().optional(),
2886
+ backupsDirectory: z.string().optional(),
2887
+ hint: z.string().optional(),
2888
+ error: z.string().optional()
2889
+ }).extend(ErrorFieldsMixin.shape);
2890
+ var TeamSemanticSearchSchema = z.object({
2891
+ query: z.string().optional(),
2892
+ entry_id: z.number().optional().describe("Find entries related to this entry ID"),
2893
+ limit: z.number().max(500).optional().default(10),
2894
+ similarity_threshold: z.number().optional().default(0.25),
2895
+ tags: z.array(z.string()).optional(),
2896
+ entry_type: z.enum(ENTRY_TYPES).optional(),
2897
+ start_date: z.string().regex(DATE_FORMAT_REGEX, DATE_FORMAT_MESSAGE).optional(),
2898
+ end_date: z.string().regex(DATE_FORMAT_REGEX, DATE_FORMAT_MESSAGE).optional(),
2899
+ hint_on_empty: z.boolean().optional().default(true).describe("Include hint when no results found (default: true)"),
2900
+ project_number: StrictProjectNumberSchema
2901
+ });
2902
+ var TeamSemanticSearchSchemaMcp = z.object({
2903
+ query: z.string().optional(),
2904
+ entry_id: relaxedNumber().optional().describe("Find entries related to this entry ID"),
2905
+ limit: relaxedNumber().optional().default(10),
2906
+ similarity_threshold: relaxedNumber().optional().default(0.25),
2907
+ tags: z.array(z.string()).optional(),
2908
+ entry_type: z.string().optional(),
2909
+ start_date: z.string().optional(),
2910
+ end_date: z.string().optional(),
2911
+ hint_on_empty: z.boolean().optional().default(true).describe("Include hint when no results found (default: true)"),
2912
+ project_number: relaxedNumber().optional()
2913
+ });
2914
+ var TeamAddToVectorIndexSchema = z.object({
2915
+ entry_id: z.number(),
2916
+ project_number: StrictProjectNumberSchema
2917
+ });
2918
+ var TeamAddToVectorIndexSchemaMcp = z.object({
2919
+ entry_id: relaxedNumber().optional(),
2920
+ project_number: relaxedNumber().optional()
2921
+ });
2922
+ var TeamSemanticEntryOutputSchema = TeamEntryOutputSchema.extend({
2923
+ similarity: z.number()
2924
+ });
2925
+ var TeamSemanticSearchOutputSchema = z.object({
2926
+ query: z.string().optional(),
2927
+ entryId: z.number().optional(),
2928
+ entries: z.array(TeamSemanticEntryOutputSchema).optional(),
2929
+ count: z.number().optional(),
2930
+ hint: z.string().optional(),
2931
+ success: z.boolean().optional(),
2932
+ error: z.string().optional()
2933
+ }).extend(ErrorFieldsMixin.shape);
2934
+ var TeamVectorStatsOutputSchema = z.object({
2935
+ available: z.boolean(),
2936
+ error: z.string().optional(),
2937
+ itemCount: z.number().optional(),
2938
+ modelName: z.string().optional(),
2939
+ dimensions: z.number().optional(),
2940
+ success: z.boolean().optional()
2941
+ }).extend(ErrorFieldsMixin.shape);
2942
+ var TeamRebuildVectorIndexOutputSchema = z.object({
2943
+ success: z.boolean().optional(),
2944
+ partial: z.boolean().optional(),
2945
+ entriesIndexed: z.number().optional(),
2946
+ failedEntries: z.number().optional(),
2947
+ error: z.string().optional()
2948
+ }).extend(ErrorFieldsMixin.shape);
2949
+ var TeamAddToVectorIndexOutputSchema = z.object({
2950
+ success: z.boolean().optional(),
2951
+ entryId: z.number().optional(),
2952
+ error: z.string().optional()
2953
+ }).extend(ErrorFieldsMixin.shape);
2954
+ var TeamCrossProjectInsightsSchema = z.object({
2955
+ start_date: z.string().regex(DATE_FORMAT_REGEX, DATE_FORMAT_MESSAGE).optional().describe("Start date (YYYY-MM-DD)"),
2956
+ end_date: z.string().regex(DATE_FORMAT_REGEX, DATE_FORMAT_MESSAGE).optional().describe("End date (YYYY-MM-DD)"),
2957
+ min_entries: z.number().optional().default(3).describe("Minimum entries to include project"),
2958
+ limit: z.number().max(500).optional().default(100).describe("Max projects to return")
2959
+ });
2960
+ var TeamCrossProjectInsightsSchemaMcp = z.object({
2961
+ start_date: z.string().optional().describe("Start date (YYYY-MM-DD)"),
2962
+ end_date: z.string().optional().describe("End date (YYYY-MM-DD)"),
2963
+ min_entries: relaxedNumber().optional().default(3).describe("Minimum entries to include project"),
2964
+ limit: relaxedNumber().optional().default(100).describe("Max projects to return")
2965
+ });
2966
+ var TeamProjectSummaryOutputSchema = z.object({
2967
+ project_number: z.number(),
2968
+ entry_count: z.number(),
2969
+ first_entry: z.string(),
2970
+ last_entry: z.string(),
2971
+ active_days: z.number(),
2972
+ top_tags: z.array(z.object({ name: z.string(), count: z.number() }))
2973
+ }).extend(ErrorFieldsMixin.shape);
2974
+ var TeamCrossProjectInsightsOutputSchema = z.object({
2975
+ project_count: z.number().optional(),
2976
+ total_entries: z.number().optional(),
2977
+ projects: z.array(TeamProjectSummaryOutputSchema).optional(),
2978
+ inactive_projects: z.array(
2979
+ z.object({
2980
+ project_number: z.number(),
2981
+ last_entry_date: z.string()
2982
+ })
2983
+ ).optional(),
2984
+ inactiveThresholdDays: z.number().optional(),
2985
+ time_distribution: z.array(
2986
+ z.object({
2987
+ project_number: z.number(),
2988
+ percentage: z.string()
2989
+ })
2990
+ ).optional(),
2991
+ message: z.string().optional(),
2992
+ success: z.boolean().optional(),
2993
+ error: z.string().optional()
2994
+ }).extend(ErrorFieldsMixin.shape);
2995
+ var TeamCollaborationMatrixSchema = z.object({
2996
+ period: z.enum(["week", "month", "quarter"]).optional().default("month").describe("Time granularity for the activity heatmap"),
2997
+ limit: z.number().max(100).optional().default(20).describe("Max authors to include")
2998
+ });
2999
+ var TeamCollaborationMatrixSchemaMcp = z.object({
3000
+ period: z.string().optional().default("month"),
3001
+ limit: relaxedNumber().optional().default(20)
3002
+ });
3003
+ var TeamCollaborationMatrixOutputSchema = z.object({
3004
+ success: z.boolean().optional(),
3005
+ totalAuthors: z.number().optional(),
3006
+ totalEntries: z.number().optional(),
3007
+ authorActivity: z.array(
3008
+ z.object({
3009
+ author: z.string(),
3010
+ period: z.string(),
3011
+ entryCount: z.number()
3012
+ })
3013
+ ).optional(),
3014
+ crossAuthorLinks: z.array(
3015
+ z.object({
3016
+ fromAuthor: z.string(),
3017
+ toAuthor: z.string(),
3018
+ linkCount: z.number()
3019
+ })
3020
+ ).optional(),
3021
+ impactFactor: z.array(
3022
+ z.object({
3023
+ author: z.string(),
3024
+ inboundLinks: z.number()
3025
+ })
3026
+ ).optional(),
3027
+ error: z.string().optional()
3028
+ }).extend(ErrorFieldsMixin.shape);
3029
+ var DEFAULT_FLAG_VOCABULARY = ["blocker", "needs_review", "help_requested", "fyi"];
3030
+ var PassTeamFlagSchema = z.object({
3031
+ flag_type: z.string().min(1).describe("Flag type from vocabulary (e.g., blocker, needs_review)"),
3032
+ message: z.string().min(1).max(49e3).describe("Flag message describing the issue or request"),
3033
+ target_user: z.string().optional().describe("Target user to flag (e.g., @sarah)"),
3034
+ link: z.string().optional().describe("Related file path, URL, or reference"),
3035
+ project_number: StrictProjectNumberSchema,
3036
+ issue_number: z.number().optional(),
3037
+ author: z.string().optional()
3038
+ });
3039
+ var PassTeamFlagSchemaMcp = z.object({
3040
+ flag_type: z.string().optional(),
3041
+ message: z.string().optional(),
3042
+ target_user: z.string().optional(),
3043
+ link: z.string().optional(),
3044
+ project_number: relaxedNumber().optional(),
3045
+ issue_number: relaxedNumber().optional(),
3046
+ author: z.string().optional()
3047
+ });
3048
+ var ResolveTeamFlagSchema = z.object({
3049
+ flag_id: z.number().describe("Entry ID of the flag to resolve"),
3050
+ resolution: z.string().optional().describe("Optional resolution comment")
3051
+ });
3052
+ var ResolveTeamFlagSchemaMcp = z.object({
3053
+ flag_id: relaxedNumber().optional(),
3054
+ resolution: z.string().optional()
3055
+ });
3056
+ var FlagOutputSchema = z.object({
3057
+ success: z.boolean().optional(),
3058
+ entry: TeamEntryOutputSchema.optional(),
3059
+ flag_type: z.string().optional(),
3060
+ target_user: z.string().nullable().optional(),
3061
+ resolved: z.boolean().optional(),
3062
+ author: z.string().optional(),
3063
+ error: z.string().optional()
3064
+ }).extend(ErrorFieldsMixin.shape);
3065
+ var ResolveFlagOutputSchema = z.object({
3066
+ success: z.boolean().optional(),
3067
+ entry: TeamEntryOutputSchema.optional(),
3068
+ flag_type: z.string().optional(),
3069
+ resolved: z.boolean().optional(),
3070
+ resolution: z.string().nullable().optional(),
3071
+ error: z.string().optional()
3072
+ }).extend(ErrorFieldsMixin.shape);
3073
+ var ListTeamFlagsSchema = z.object({
3074
+ status: z.enum(["active", "resolved", "all"]).optional().default("active"),
3075
+ flag_type: z.string().optional().describe("Filter by flag type from vocabulary"),
3076
+ target_user: z.string().optional().describe("Filter by target user"),
3077
+ author: z.string().optional().describe("Filter by flag creator"),
3078
+ limit: z.number().min(1).max(500).optional().default(20),
3079
+ project_number: StrictProjectNumberSchema,
3080
+ sort_by: z.enum(["timestamp", "priority"]).optional().default("priority")
3081
+ });
3082
+ var ListTeamFlagsSchemaMcp = z.object({
3083
+ status: z.string().optional().default("active"),
3084
+ flag_type: z.string().optional(),
3085
+ target_user: z.string().optional(),
3086
+ author: z.string().optional(),
3087
+ limit: relaxedNumber().optional().default(20),
3088
+ project_number: relaxedNumber().optional(),
3089
+ sort_by: z.string().optional().default("priority")
3090
+ });
3091
+ var UpdateTeamFlagSchema = z.object({
3092
+ flag_id: z.number().describe("Entry ID of the flag to update"),
3093
+ flag_type: z.string().optional().describe("New flag type"),
3094
+ target_user: z.string().nullable().optional().describe("New target user (null to clear)"),
3095
+ message: z.string().min(1).max(49e3).optional().describe("Updated flag message"),
3096
+ link: z.string().nullable().optional().describe("Updated link (null to clear)"),
3097
+ reopen: z.boolean().optional().describe("If true, reopen a resolved flag")
3098
+ });
3099
+ var UpdateTeamFlagSchemaMcp = z.object({
3100
+ flag_id: relaxedNumber().optional(),
3101
+ flag_type: z.string().optional(),
3102
+ target_user: z.string().nullable().optional(),
3103
+ message: z.string().optional(),
3104
+ link: z.string().nullable().optional(),
3105
+ reopen: z.boolean().optional()
3106
+ });
3107
+ var FlagAnalyticsSchema = z.object({
3108
+ period: z.enum(["day", "week", "month"]).optional().default("week"),
3109
+ project_number: StrictProjectNumberSchema
3110
+ });
3111
+ var FlagAnalyticsSchemaMcp = z.object({
3112
+ period: z.string().optional().default("week"),
3113
+ project_number: relaxedNumber().optional()
3114
+ });
3115
+ var ListFlagsOutputSchema = z.object({
3116
+ success: z.boolean().optional(),
3117
+ flags: z.array(
3118
+ z.object({
3119
+ id: z.number(),
3120
+ flag_type: z.string(),
3121
+ target_user: z.string().nullable().optional(),
3122
+ author: z.string().nullable().optional(),
3123
+ message: z.string(),
3124
+ link: z.string().nullable().optional(),
3125
+ resolved: z.boolean(),
3126
+ resolved_at: z.string().nullable().optional(),
3127
+ resolution: z.string().nullable().optional(),
3128
+ timestamp: z.string(),
3129
+ age_hours: z.number(),
3130
+ is_stale: z.boolean(),
3131
+ tags: z.array(z.string()).optional(),
3132
+ project_number: z.number().nullable().optional()
3133
+ })
3134
+ ).optional(),
3135
+ count: z.number().optional(),
3136
+ active_count: z.number().optional(),
3137
+ resolved_count: z.number().optional(),
3138
+ error: z.string().optional()
3139
+ }).extend(ErrorFieldsMixin.shape);
3140
+ var UpdateFlagOutputSchema = z.object({
3141
+ success: z.boolean().optional(),
3142
+ entry: TeamEntryOutputSchema.optional(),
3143
+ flag_type: z.string().optional(),
3144
+ target_user: z.string().nullable().optional(),
3145
+ resolved: z.boolean().optional(),
3146
+ author: z.string().optional(),
3147
+ changes: z.array(z.string()).optional(),
3148
+ error: z.string().optional()
3149
+ }).extend(ErrorFieldsMixin.shape);
3150
+ var FlagAnalyticsOutputSchema = z.object({
3151
+ success: z.boolean().optional(),
3152
+ summary: z.object({
3153
+ total_flags: z.number(),
3154
+ active_flags: z.number(),
3155
+ resolved_flags: z.number(),
3156
+ avg_resolution_hours: z.number().nullable(),
3157
+ median_resolution_hours: z.number().nullable(),
3158
+ stale_count: z.number()
3159
+ }).optional(),
3160
+ by_type: z.record(
3161
+ z.string(),
3162
+ z.object({
3163
+ total: z.number(),
3164
+ active: z.number(),
3165
+ avg_resolution_hours: z.number().nullable()
3166
+ })
3167
+ ).optional(),
3168
+ by_target: z.array(
3169
+ z.object({
3170
+ user: z.string(),
3171
+ received: z.number(),
3172
+ active: z.number()
3173
+ })
3174
+ ).optional(),
3175
+ trend: z.object({
3176
+ current_period: z.number(),
3177
+ previous_period: z.number(),
3178
+ change_pct: z.number().nullable()
3179
+ }).optional(),
3180
+ error: z.string().optional()
3181
+ }).extend(ErrorFieldsMixin.shape);
3182
+ var FlagContextSchema = z.object({
3183
+ flag_type: z.string(),
3184
+ target_user: z.string().nullable().optional(),
3185
+ link: z.string().nullable().optional(),
3186
+ resolved: z.boolean(),
3187
+ resolved_at: z.string().nullable().optional(),
3188
+ resolution: z.string().nullable().optional(),
3189
+ author: z.string().optional()
3190
+ });
3191
+ var VersionedEnvelopeSchema = z.object({
3192
+ version: z.string(),
3193
+ data: z.unknown()
3194
+ });
3195
+ var AutoContextSchema = z.union([FlagContextSchema, VersionedEnvelopeSchema]);
3196
+ function parseAutoContext(autoContext) {
3197
+ if (!autoContext) return null;
3198
+ try {
3199
+ const parsed = JSON.parse(autoContext);
3200
+ if (typeof parsed !== "object" || parsed === null) {
3201
+ return null;
3202
+ }
3203
+ const result = AutoContextSchema.safeParse(parsed);
3204
+ if (result.success) {
3205
+ return result.data;
3206
+ }
3207
+ logger.debug("AutoContext schema miss", {
3208
+ module: "Validator",
3209
+ issues: result.error.issues
3210
+ });
3211
+ return parsed;
3212
+ } catch (error) {
3213
+ logger.warning("Failed to parse auto_context JSON", {
3214
+ module: "Validator",
3215
+ error: error instanceof Error ? error.message : "Unknown error"
3216
+ });
3217
+ return null;
3218
+ }
3219
+ }
3220
+ function parseFlagContext(autoContext) {
3221
+ const parsed = parseAutoContext(autoContext);
3222
+ if (parsed === null) return null;
3223
+ const result = FlagContextSchema.safeParse(parsed);
3224
+ return result.success ? result.data : null;
3225
+ }
3226
+ var requestContextStorage = new AsyncLocalStorage();
3227
+ function getRequestContext() {
3228
+ return requestContextStorage.getStore();
3229
+ }
3230
+
3231
+ export { BASE_SCOPES, ConfigurationError, ConnectionError, DATE_FORMAT_MESSAGE, DATE_FORMAT_REGEX, DATE_MAX_SENTINEL, DATE_MIN_SENTINEL, DEFAULT_BRIEFING_CONFIG, DEFAULT_FLAG_VOCABULARY, ENTRY_TYPES, EntriesListOutputSchema, EntryOutputSchema, ErrorFieldsMixin, FlagAnalyticsOutputSchema, FlagAnalyticsSchema, FlagAnalyticsSchemaMcp, FlagOutputSchema, ImportanceBreakdownSchema, ListFlagsOutputSchema, ListTeamFlagsSchema, ListTeamFlagsSchemaMcp, MAX_CONTENT_LENGTH, MAX_QUERY_LIMIT, META_GROUPS, MemoryJournalMcpError, PassTeamFlagSchema, PassTeamFlagSchemaMcp, QueryError, RelationshipOutputSchema, ResolveFlagOutputSchema, ResolveTeamFlagSchema, ResolveTeamFlagSchemaMcp, ResourceNotFoundError, SCOPES, SIGNIFICANCE_TYPES, SUPPORTED_SCOPES, StrictProjectNumberSchema, TOOL_GROUPS, TagOutputSchema, TeamAddToVectorIndexOutputSchema, TeamAddToVectorIndexSchema, TeamAddToVectorIndexSchemaMcp, TeamBackupOutputSchema, TeamBackupSchema, TeamBackupsListOutputSchema, TeamCollaborationMatrixOutputSchema, TeamCollaborationMatrixSchema, TeamCollaborationMatrixSchemaMcp, TeamCreateEntrySchema, TeamCreateEntrySchemaMcp, TeamCreateOutputSchema, TeamCrossProjectInsightsOutputSchema, TeamCrossProjectInsightsSchema, TeamCrossProjectInsightsSchemaMcp, TeamDeleteEntrySchema, TeamDeleteEntrySchemaMcp, TeamDeleteOutputSchema, TeamEntriesListOutputSchema, TeamEntryDetailOutputSchema, TeamExportEntriesSchema, TeamExportEntriesSchemaMcp, TeamExportOutputSchema, TeamGetEntryByIdSchema, TeamGetEntryByIdSchemaMcp, TeamGetRecentSchema, TeamGetRecentSchemaMcp, TeamGetStatisticsSchema, TeamGetStatisticsSchemaMcp, TeamLinkEntriesOutputSchema, TeamLinkEntriesSchema, TeamLinkEntriesSchemaMcp, TeamMergeTagsOutputSchema, TeamMergeTagsSchema, TeamMergeTagsSchemaMcp, TeamRebuildVectorIndexOutputSchema, TeamSearchByDateRangeSchema, TeamSearchByDateRangeSchemaMcp, TeamSearchSchema, TeamSearchSchemaMcp, TeamSemanticSearchOutputSchema, TeamSemanticSearchSchema, TeamSemanticSearchSchemaMcp, TeamStatisticsOutputSchema, TeamTagsListOutputSchema, TeamUpdateEntrySchema, TeamUpdateEntrySchemaMcp, TeamUpdateOutputSchema, TeamVectorStatsOutputSchema, TeamVisualizeOutputSchema, TeamVisualizeRelationshipsSchema, TeamVisualizeRelationshipsSchemaMcp, UpdateFlagOutputSchema, UpdateTeamFlagSchema, UpdateTeamFlagSchemaMcp, ValidationError, assertNoPathTraversal, assertSafeDirectoryPath, assertSafeFilePath, calculateTokenSavings, coerceSignificanceAlias, enforceAccessBoundary, filterTools, getAllToolNames, getAuthContext, getEnabledGroups, getFilterSummary, getGitHubIntegration, getRequestContext, getRequiredScope, getToolFilterFromEnv, getToolGroup, hasScope, isResourceError, isToolEnabled, isValidScope, logger, markUntrustedContent, markUntrustedContentInline, matchSuggestion, milestoneCompletionPct, parseFlagContext, parseScopes, parseToolFilter, relaxedNumber, requestContextStorage, resolveAuthenticatedAuthor, resolveAuthor, resolveGitHubRepo, runWithAuthContext, sanitizeAuthor, sanitizeSearchQuery, validateDateFormatPattern };