@rulemetric/cli 0.14.1 → 0.15.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 (246) hide show
  1. package/dist/base-command.js +1 -1
  2. package/dist/{chunk-HNYHZO2J.js → chunk-3H44B6PB.js} +1 -1
  3. package/dist/chunk-4DA6L7KL.js +1 -0
  4. package/dist/chunk-4GOXEEXZ.js +1 -0
  5. package/dist/{chunk-RMRVUI7B.js → chunk-5PMTNNA6.js} +1 -1
  6. package/dist/{chunk-EMLLGASZ.js → chunk-5TM7AOH2.js} +1 -1
  7. package/dist/{chunk-GKVHFXUQ.js → chunk-5Z6XXOJL.js} +1 -1
  8. package/dist/{chunk-Q36QSFSB.js → chunk-6QMIDH6X.js} +1 -1
  9. package/dist/{chunk-3FNTV2TW.js → chunk-6T6YFPBW.js} +1 -1
  10. package/dist/{chunk-FYZ6HHCV.js → chunk-74KE4VOX.js} +1 -1
  11. package/dist/chunk-77FH6UZP.js +111 -0
  12. package/dist/{chunk-XGMOVQ5G.js → chunk-7LFCZI64.js} +1 -1
  13. package/dist/{chunk-7H4HJ2RV.js → chunk-AFEJYDUK.js} +1 -1
  14. package/dist/{chunk-WWQWHC4K.js → chunk-BDQTVYYF.js} +1 -1
  15. package/dist/{chunk-EUHRTEVJ.js → chunk-CIKQXFQ2.js} +1 -1
  16. package/dist/chunk-CMDOLJ23.js +1 -0
  17. package/dist/chunk-CQD2R3BA.js +3 -0
  18. package/dist/{chunk-I6ZQOMZS.js → chunk-CVPAKEEZ.js} +1 -1
  19. package/dist/{chunk-QRIJ3AHP.js → chunk-CYCH2EQC.js} +1 -1
  20. package/dist/{chunk-AGEZAKCC.js → chunk-CZBO3A6B.js} +1 -1
  21. package/dist/{chunk-JTYVBR5H.js → chunk-DANMUHNW.js} +1 -1
  22. package/dist/{chunk-4FJYVYCU.js → chunk-DX6IPDED.js} +1 -1
  23. package/dist/chunk-DYET4EYU.js +1 -0
  24. package/dist/{chunk-MXHAXY66.js → chunk-EJY5GK6A.js} +1 -1
  25. package/dist/{chunk-H6FVXVGG.js → chunk-FADINV4H.js} +1 -1
  26. package/dist/{chunk-DVU5PHPM.js → chunk-FG343JM3.js} +1 -1
  27. package/dist/{chunk-RXZLBSDO.js → chunk-FXQS7AEZ.js} +1 -1
  28. package/dist/{chunk-LJRJ2RAC.js → chunk-FZMO7XSN.js} +3 -3
  29. package/dist/{chunk-XMTKP74H.js → chunk-GDLQNY4V.js} +1 -1
  30. package/dist/{chunk-76UKAFNM.js → chunk-GIXHG5FK.js} +1 -1
  31. package/dist/{chunk-XJ25HFIT.js → chunk-GLBWNB2N.js} +1 -1
  32. package/dist/chunk-HT6R6KR3.js +3 -0
  33. package/dist/{chunk-OP4U3XBZ.js → chunk-HXOQUYG3.js} +1 -1
  34. package/dist/{chunk-V55ROUNP.js → chunk-IFIWDL7G.js} +1 -1
  35. package/dist/{chunk-B5X6HCBK.js → chunk-ISYU5BMU.js} +1 -1
  36. package/dist/chunk-JNLDISBA.js +4 -0
  37. package/dist/{chunk-MMLRWCBW.js → chunk-JOXTWLLK.js} +1 -1
  38. package/dist/{chunk-QAMHZY2P.js → chunk-JSGXFD42.js} +1 -1
  39. package/dist/chunk-JU5ZNXPK.js +1 -0
  40. package/dist/{chunk-6ANODRDT.js → chunk-JUBXWTJA.js} +1 -1
  41. package/dist/{chunk-YK2IEHLB.js → chunk-KE5K3F7J.js} +1 -1
  42. package/dist/{chunk-VIFOLTZT.js → chunk-KEVDLLHT.js} +1 -1
  43. package/dist/{chunk-7MTYUTUN.js → chunk-KR36ZDGN.js} +1 -1
  44. package/dist/{chunk-OVS7ZDJ4.js → chunk-L562Y4RN.js} +1 -1
  45. package/dist/{chunk-43VKTVM3.js → chunk-LJE5J3EW.js} +1 -1
  46. package/dist/{chunk-XMA6SWOT.js → chunk-LLXC5SRC.js} +1 -1
  47. package/dist/chunk-MOJY6S5J.js +1 -0
  48. package/dist/{chunk-IQEZ3T5A.js → chunk-MYGVN6X4.js} +1 -1
  49. package/dist/chunk-N2PP2A7M.js +1 -0
  50. package/dist/{chunk-44TYRMIS.js → chunk-NWV66NMA.js} +1 -1
  51. package/dist/{chunk-KOYHJFB3.js → chunk-PDXHRF4E.js} +1 -1
  52. package/dist/{chunk-5Z3H5JHK.js → chunk-PJ4RIUI3.js} +1 -1
  53. package/dist/{chunk-NYNHX7OX.js → chunk-Q7IDLOSP.js} +1 -1
  54. package/dist/{chunk-IO46ICZY.js → chunk-QFTAU33Y.js} +1 -1
  55. package/dist/{chunk-5BT375C7.js → chunk-QNSIBPWG.js} +1 -1
  56. package/dist/{chunk-3IMRLHJJ.js → chunk-QPAOX7P2.js} +1 -1
  57. package/dist/{chunk-RG3R4EAB.js → chunk-QPVUGTDP.js} +1 -1
  58. package/dist/{chunk-BMT5WMEV.js → chunk-RDL4HXFL.js} +1 -1
  59. package/dist/{chunk-2UK4DZFW.js → chunk-RE7RAZQ5.js} +1 -1
  60. package/dist/{chunk-35YVHBLL.js → chunk-RYCVPQYK.js} +1 -1
  61. package/dist/{chunk-VU24IH5S.js → chunk-SFZPFNC6.js} +1 -1
  62. package/dist/{chunk-ZK3ACE4T.js → chunk-T7HZZ4DJ.js} +1 -1
  63. package/dist/{chunk-LB24UKHZ.js → chunk-TWPD3ICV.js} +1 -1
  64. package/dist/{chunk-BFQVAU6N.js → chunk-UVCVJKEN.js} +1 -1
  65. package/dist/chunk-V576KKH6.js +1 -0
  66. package/dist/{chunk-CT6GJQIR.js → chunk-VUNJGZPP.js} +1 -1
  67. package/dist/{chunk-AIYFT4P6.js → chunk-W6MMJRFZ.js} +1 -1
  68. package/dist/{chunk-FKTT7A4H.js → chunk-WL5ZWQAS.js} +1 -1
  69. package/dist/chunk-WQFR2LOY.js +15 -0
  70. package/dist/{chunk-MU7KKU3O.js → chunk-WUCACPGC.js} +1 -1
  71. package/dist/{chunk-42A4PUW7.js → chunk-X6CF5KTW.js} +4 -4
  72. package/dist/{chunk-N4YPDZJF.js → chunk-XCH4HPEZ.js} +1 -1
  73. package/dist/{chunk-VXL5H3VZ.js → chunk-XIOYV5A7.js} +1 -1
  74. package/dist/{chunk-W23OYQXI.js → chunk-XXPWPKTD.js} +1 -1
  75. package/dist/{chunk-SCQK52SL.js → chunk-YXMAGC53.js} +1 -1
  76. package/dist/commands/antigravity/backfill.js +1 -1
  77. package/dist/commands/auth/create-key.js +1 -1
  78. package/dist/commands/auth/login.js +1 -1
  79. package/dist/commands/auth/logout.js +1 -1
  80. package/dist/commands/auth/revoke-key.js +1 -1
  81. package/dist/commands/auth/signup.js +1 -1
  82. package/dist/commands/auth/status.js +1 -1
  83. package/dist/commands/capture/scope.js +1 -1
  84. package/dist/commands/catalog/index.js +1 -1
  85. package/dist/commands/catalog/recommend.js +1 -1
  86. package/dist/commands/crons/list.js +1 -1
  87. package/dist/commands/crons/run.js +1 -1
  88. package/dist/commands/dashboard.js +1 -1
  89. package/dist/commands/diagnostics.js +1 -1
  90. package/dist/commands/eval-targets/create.js +1 -1
  91. package/dist/commands/eval-targets/list.js +1 -1
  92. package/dist/commands/evals/agent.js +1 -1
  93. package/dist/commands/evals/auto-run.js +1 -1
  94. package/dist/commands/evals/benchmark.js +1 -1
  95. package/dist/commands/evals/compare.js +1 -1
  96. package/dist/commands/evals/create.js +1 -1
  97. package/dist/commands/evals/optimize-description.js +1 -1
  98. package/dist/commands/evals/optimize.js +1 -1
  99. package/dist/commands/evals/refine-cases.js +1 -1
  100. package/dist/commands/evals/run.js +1 -1
  101. package/dist/commands/evals/validate-judge.js +1 -1
  102. package/dist/commands/experiments/list.js +1 -1
  103. package/dist/commands/gateway/ensure.js +1 -1
  104. package/dist/commands/hooks/install.js +1 -1
  105. package/dist/commands/hooks/run.js +1 -1
  106. package/dist/commands/hooks/uninstall.js +1 -1
  107. package/dist/commands/instructions/create.js +1 -1
  108. package/dist/commands/instructions/dedupe.js +1 -1
  109. package/dist/commands/instructions/delete.js +1 -1
  110. package/dist/commands/instructions/fork.js +1 -1
  111. package/dist/commands/instructions/get.js +1 -1
  112. package/dist/commands/instructions/list.js +1 -1
  113. package/dist/commands/instructions/promote.js +1 -1
  114. package/dist/commands/instructions/pull.js +1 -1
  115. package/dist/commands/instructions/restore.js +1 -1
  116. package/dist/commands/instructions/retract.js +1 -1
  117. package/dist/commands/instructions/upstream.js +1 -1
  118. package/dist/commands/instructions/versions.js +1 -1
  119. package/dist/commands/launcher.js +1 -1
  120. package/dist/commands/local/down.js +1 -1
  121. package/dist/commands/local/up.js +1 -1
  122. package/dist/commands/org/current.js +1 -1
  123. package/dist/commands/org/list.js +1 -1
  124. package/dist/commands/org/switch.js +1 -1
  125. package/dist/commands/packs/add-instruction.js +1 -1
  126. package/dist/commands/packs/apply.js +1 -1
  127. package/dist/commands/packs/create.js +1 -1
  128. package/dist/commands/packs/fork.js +1 -1
  129. package/dist/commands/packs/get.js +1 -1
  130. package/dist/commands/packs/list.js +1 -1
  131. package/dist/commands/packs/remove-instruction.js +1 -1
  132. package/dist/commands/proxy/env.js +1 -1
  133. package/dist/commands/proxy/logs.js +1 -1
  134. package/dist/commands/proxy/restart.js +1 -1
  135. package/dist/commands/proxy/setup.js +1 -1
  136. package/dist/commands/proxy/start.js +1 -1
  137. package/dist/commands/proxy/status.js +1 -1
  138. package/dist/commands/proxy/stop.js +1 -1
  139. package/dist/commands/research/backfill.js +1 -1
  140. package/dist/commands/research/tail-transcript.js +1 -1
  141. package/dist/commands/service/install.js +1 -1
  142. package/dist/commands/service/status.js +1 -1
  143. package/dist/commands/service/uninstall.js +1 -1
  144. package/dist/commands/sessions/analyze.js +1 -1
  145. package/dist/commands/sessions/delete.js +1 -1
  146. package/dist/commands/sessions/end.js +1 -1
  147. package/dist/commands/sessions/import.js +1 -1
  148. package/dist/commands/sessions/list.js +1 -1
  149. package/dist/commands/sessions/start.js +1 -1
  150. package/dist/commands/setup.js +1 -1
  151. package/dist/commands/skills/export-approved.js +1 -1
  152. package/dist/commands/skills/install.js +1 -1
  153. package/dist/commands/skills/list.js +1 -1
  154. package/dist/commands/skills/publish.js +1 -1
  155. package/dist/commands/skills/search.js +1 -1
  156. package/dist/commands/skills/update.js +1 -1
  157. package/dist/commands/suggestions/accept.js +1 -1
  158. package/dist/commands/suggestions/auto.js +1 -1
  159. package/dist/commands/suggestions/dismiss.js +1 -1
  160. package/dist/commands/suggestions/list.js +1 -1
  161. package/dist/commands/suggestions/refresh.js +1 -1
  162. package/dist/commands/suggestions/undo.js +1 -1
  163. package/dist/dashboard/Dashboard.js +1 -1
  164. package/dist/dashboard/data.js +1 -1
  165. package/dist/dashboard/launcher/LauncherOverlay.js +1 -1
  166. package/dist/dashboard/launcher/api.js +1 -1
  167. package/dist/dashboard/launcher/useLaunchJobs.js +1 -1
  168. package/dist/dashboard/panels/measurement.js +1 -1
  169. package/dist/lib/active-org-refresh.js +1 -1
  170. package/dist/lib/agent-loop.js +1 -1
  171. package/dist/lib/antigravity-transcript.js +1 -1
  172. package/dist/lib/api-client.js +1 -1
  173. package/dist/lib/codex-exec.js +1 -1
  174. package/dist/lib/ensure-api-key.js +1 -1
  175. package/dist/lib/ensure-fresh-token.js +1 -1
  176. package/dist/lib/eval-analyzer.js +1 -1
  177. package/dist/lib/eval-benchmark.js +1 -1
  178. package/dist/lib/eval-candidate-run.js +1 -1
  179. package/dist/lib/eval-case-generator.js +1 -1
  180. package/dist/lib/eval-conversation-handler.js +1 -1
  181. package/dist/lib/eval-executor.js +1 -1
  182. package/dist/lib/eval-grader.js +1 -1
  183. package/dist/lib/eval-meta-judge.js +1 -1
  184. package/dist/lib/eval-resume.js +1 -1
  185. package/dist/lib/eval-run-batch.js +1 -1
  186. package/dist/lib/eval-trigger-tester.js +1 -1
  187. package/dist/lib/evolution-cost.js +1 -1
  188. package/dist/lib/evolution-enrolment.js +1 -1
  189. package/dist/lib/insights/generation/installed-asks.js +1 -1
  190. package/dist/lib/insights/generation/project-evidence.js +1 -0
  191. package/dist/lib/insights/generation/prompts.js +1 -1
  192. package/dist/lib/insights/nomination/nominate.js +1 -1
  193. package/dist/lib/instruction-proposer.js +1 -1
  194. package/dist/lib/instruction-restoration.js +1 -0
  195. package/dist/lib/instructions/acceptance/accept-events.js +1 -1
  196. package/dist/lib/instructions/acceptance/accept-hook.js +1 -1
  197. package/dist/lib/instructions/acceptance/hook-install.js +1 -1
  198. package/dist/lib/instructions/acceptance/reverse-applications.js +1 -1
  199. package/dist/lib/instructions/acceptance/suggestion-accept.js +1 -1
  200. package/dist/lib/jobs/handlers/cron-auto-accept-suggestions.js +1 -1
  201. package/dist/lib/jobs/handlers/cron-eval-autorun.js +1 -1
  202. package/dist/lib/jobs/handlers/cron-instruction-evolution.js +1 -1
  203. package/dist/lib/jobs/handlers/cron-instruction-training.js +1 -1
  204. package/dist/lib/jobs/handlers/cron-reconcile-attribution.js +1 -1
  205. package/dist/lib/jobs/handlers/cron-refine-cases.js +1 -1
  206. package/dist/lib/jobs/handlers/cron-refresh-pricing.js +1 -1
  207. package/dist/lib/jobs/handlers/cron-retire-unused-skills.js +1 -1
  208. package/dist/lib/jobs/handlers/cron-suggest-instructions.js +1 -1
  209. package/dist/lib/jobs/handlers/distill-memories.js +1 -1
  210. package/dist/lib/jobs/handlers/harbor-ab-verdict.js +1 -1
  211. package/dist/lib/jobs/handlers/harbor-ab.js +1 -1
  212. package/dist/lib/jobs/handlers/process-changelog.js +1 -1
  213. package/dist/lib/jobs/handlers/process-conversation.js +1 -1
  214. package/dist/lib/jobs/handlers/process-eval.js +1 -1
  215. package/dist/lib/jobs/handlers/process-insights.js +1 -1
  216. package/dist/lib/jobs/handlers/process-judge-review.js +1 -1
  217. package/dist/lib/jobs/handlers/process-launch.js +1 -1
  218. package/dist/lib/jobs/handlers/process-memory-ab.js +1 -1
  219. package/dist/lib/jobs/handlers/process-run-cleanup.js +1 -1
  220. package/dist/lib/jobs/handlers/process-session-goal.js +1 -1
  221. package/dist/lib/jobs/shed-retry.js +1 -1
  222. package/dist/lib/judge-review-runner.js +1 -1
  223. package/dist/lib/llm-client.js +1 -1
  224. package/dist/lib/manual-tasks.js +1 -1
  225. package/dist/lib/measurement-llm.js +1 -1
  226. package/dist/lib/optimize-compare.js +1 -1
  227. package/dist/lib/refine-cases.js +1 -1
  228. package/dist/lib/research-client.js +1 -1
  229. package/dist/lib/retraction.js +1 -1
  230. package/dist/lib/setup-steps.js +1 -1
  231. package/dist/lib/study-fixture.js +1 -0
  232. package/dist/lib/telemetry.js +1 -1
  233. package/dist/lib/terminal-target-heartbeat.js +1 -1
  234. package/dist/lib/work-report.js +1 -1
  235. package/oclif.manifest.json +1 -1
  236. package/package.json +6 -6
  237. package/dist/chunk-BAITMD76.js +0 -1
  238. package/dist/chunk-DHX4U6EC.js +0 -13
  239. package/dist/chunk-E7GQJML3.js +0 -1
  240. package/dist/chunk-FBSZ6KCM.js +0 -1
  241. package/dist/chunk-POEMCITL.js +0 -1
  242. package/dist/chunk-Q776YUBD.js +0 -1
  243. package/dist/chunk-RAQLVO2X.js +0 -1
  244. package/dist/chunk-SG4UDDHB.js +0 -4
  245. package/dist/chunk-SJKS3PYX.js +0 -109
  246. package/dist/chunk-VBXL7XO7.js +0 -1
@@ -0,0 +1 @@
1
+ import{a as m,c as Ds}from"./chunk-ZLLER3HP.js";import{boolean as sn,date as js,index as Qt,integer as zs,jsonb as Rs,pgTable as Yt,text as D,timestamp as G,uniqueIndex as ks,uuid as me}from"drizzle-orm/pg-core";var an=Yt("announcements",{id:me("id").primaryKey().defaultRandom(),version:D("version").notNull().unique(),releaseDate:js("release_date").notNull(),subject:D("subject").notNull(),htmlBody:D("html_body").notNull(),textBody:D("text_body").notNull(),sections:Rs("sections").notNull().default({}),status:D("status").notNull().default("draft"),recipientCount:zs("recipient_count"),sentAt:G("sent_at",{withTimezone:!0}),sentBy:me("sent_by"),error:D("error"),createdAt:G("created_at",{withTimezone:!0}).notNull().defaultNow(),updatedAt:G("updated_at",{withTimezone:!0}).notNull().defaultNow()},e=>[Qt("idx_announcements_status").on(e.status),Qt("idx_announcements_created").on(e.createdAt)]),dn=Yt("announcement_deliveries",{id:me("id").primaryKey().defaultRandom(),announcementId:me("announcement_id").notNull(),userId:me("user_id").notNull(),email:D("email").notNull(),status:D("status").notNull().default("pending"),providerId:D("provider_id"),error:D("error"),sentAt:G("sent_at",{withTimezone:!0}),createdAt:G("created_at",{withTimezone:!0}).notNull().defaultNow()},e=>[ks("uniq_announcement_deliveries_announcement_user").on(e.announcementId,e.userId),Qt("idx_announcement_deliveries_user").on(e.userId,e.createdAt)]),un=Yt("notification_preferences",{userId:me("user_id").primaryKey(),productAnnouncements:sn("product_announcements").notNull().default(!0),weeklyDigest:sn("weekly_digest").notNull().default(!0),unsubscribeToken:D("unsubscribe_token").notNull().unique(),unsubscribedAt:G("unsubscribed_at",{withTimezone:!0}),createdAt:G("created_at",{withTimezone:!0}).notNull().defaultNow(),updatedAt:G("updated_at",{withTimezone:!0}).notNull().defaultNow()});import{boolean as lt,integer as qe,jsonb as Es,pgTable as Ss,real as pn,text as Oe,timestamp as Wt,uuid as _n}from"drizzle-orm/pg-core";import{pgTable as ut,text as fe,timestamp as Ce,jsonb as ln,uuid as ne,primaryKey as cn}from"drizzle-orm/pg-core";var l=ut("organizations",{id:ne("id").primaryKey().defaultRandom(),name:fe("name").unique().notNull(),slug:fe("slug").unique().notNull(),metadata:ln("metadata"),createdAt:Ce("created_at",{withTimezone:!0}).defaultNow(),updatedAt:Ce("updated_at",{withTimezone:!0}).defaultNow()}),v=ut("teams",{id:ne("id").primaryKey().defaultRandom(),orgId:ne("org_id").references(()=>l.id,{onDelete:"cascade"}),name:fe("name").notNull(),slug:fe("slug").notNull(),metadata:ln("metadata"),createdAt:Ce("created_at",{withTimezone:!0}).defaultNow()}),Ne=ut("user_organizations",{userId:ne("user_id").notNull(),orgId:ne("org_id").references(()=>l.id,{onDelete:"cascade"}).notNull(),role:fe("role").notNull().default("member"),createdAt:Ce("created_at",{withTimezone:!0}).defaultNow()},e=>[cn({columns:[e.userId,e.orgId]})]),xe=ut("user_teams",{userId:ne("user_id").notNull(),teamId:ne("team_id").references(()=>v.id,{onDelete:"cascade"}).notNull(),role:fe("role").notNull().default("member"),createdAt:Ce("created_at",{withTimezone:!0}).defaultNow()},e=>[cn({columns:[e.userId,e.teamId]})]);var o=Ss("profiles",{id:_n("id").primaryKey(),email:Oe("email"),measurementPreferences:Es("measurement_preferences"),displayName:Oe("display_name"),activeOrgId:_n("active_org_id").references(()=>l.id,{onDelete:"set null"}),isSuperadmin:lt("is_superadmin").notNull().default(!1),claudeCodePlan:Oe("claude_code_plan"),planSource:Oe("plan_source").notNull().default("detected"),setupCompletedAt:Wt("setup_completed_at",{withTimezone:!0}),liveSendSkipped:lt("live_send_skipped").notNull().default(!1),autoAcceptSuggestions:lt("auto_accept_suggestions").notNull().default(!0),evolutionPaused:lt("evolution_paused").notNull().default(!1),suggestionConfidenceThreshold:pn("suggestion_confidence_threshold").notNull().default(.7),autoAcceptMinScore:pn("auto_accept_min_score"),autoAcceptMaxPerRun:qe("auto_accept_max_per_run"),autoAcceptMaxPerWindow:qe("auto_accept_max_per_window"),autoAcceptWindowDays:qe("auto_accept_window_days"),trialMaxConcurrent:qe("trial_max_concurrent"),trialMaxPerRun:qe("trial_max_per_run"),harborAbCadence:Oe("harbor_ab_cadence").notNull().default("off"),createdAt:Wt("created_at",{withTimezone:!0}).defaultNow(),updatedAt:Wt("updated_at",{withTimezone:!0}).defaultNow()});import{pgTable as bs,text as Xt,timestamp as ct,uuid as pt,index as mn}from"drizzle-orm/pg-core";var P=bs("org_invitations",{id:pt("id").primaryKey().defaultRandom(),orgId:pt("org_id").notNull().references(()=>l.id,{onDelete:"cascade"}),email:Xt("email").notNull(),role:Xt("role").notNull().default("member"),teamId:pt("team_id").references(()=>v.id,{onDelete:"set null"}),invitedBy:pt("invited_by").notNull().references(()=>o.id,{onDelete:"cascade"}),token:Xt("token").notNull().unique(),expiresAt:ct("expires_at",{withTimezone:!0}).notNull(),acceptedAt:ct("accepted_at",{withTimezone:!0}),revokedAt:ct("revoked_at",{withTimezone:!0}),createdAt:ct("created_at",{withTimezone:!0}).notNull().defaultNow()},e=>[mn("idx_org_invitations_token").on(e.token),mn("idx_org_invitations_org").on(e.orgId)]);import{pgTable as Zt,text as N,timestamp as V,jsonb as _t,uuid as z,integer as mt,boolean as Ps,uniqueIndex as ft,index as Me}from"drizzle-orm/pg-core";var n=Zt("instructions",{id:z("id").primaryKey().defaultRandom(),name:N("name").notNull(),description:N("description").notNull(),type:N("type").notNull().default("instruction"),scope:N("scope").notNull(),scopeRef:z("scope_ref"),version:N("version").notNull(),content:N("content").notNull(),frontmatter:_t("frontmatter").notNull(),slots:_t("slots"),tags:N("tags").array(),compatibility:N("compatibility").array(),createdBy:z("created_by"),createdAt:V("created_at",{withTimezone:!0}).defaultNow(),updatedAt:V("updated_at",{withTimezone:!0}).defaultNow(),archived:Ps("archived").default(!1),archivedAt:V("archived_at",{withTimezone:!0}),archivedBy:z("archived_by"),forkedFromId:z("forked_from_id").references(()=>n.id,{onDelete:"set null"}),upstreamVersion:N("upstream_version"),badge:N("badge"),contentHash:N("content_hash"),contextIdentity:N("context_identity"),scanScore:mt("scan_score"),scanFindings:_t("scan_findings"),popularityScore:mt("popularity_score"),sourceUpdatedAt:V("source_updated_at",{withTimezone:!0})},e=>[ft("instructions_name_scope_ref_idx").on(e.name,e.scope,e.scopeRef),Me("idx_instructions_scope").on(e.scope,e.scopeRef),Me("idx_instructions_created_by").on(e.createdBy),Me("idx_instructions_context_identity").on(e.createdBy,e.contextIdentity),Me("idx_instructions_public_recency").on(e.scope,e.sourceUpdatedAt.desc())]),fn=Zt("instruction_version_identities",{id:z("id").primaryKey().defaultRandom(),instructionId:z("instruction_id").notNull().references(()=>n.id,{onDelete:"cascade"}),contentHash:N("content_hash").notNull(),versionOrdinal:mt("version_ordinal").notNull(),content:N("content"),firstSeenAt:V("first_seen_at",{withTimezone:!0}).notNull().defaultNow(),lastSeenAt:V("last_seen_at",{withTimezone:!0}).notNull().defaultNow(),createdAt:V("created_at",{withTimezone:!0}).notNull().defaultNow()},e=>[ft("instruction_version_identities_hash_unique").on(e.instructionId,e.contentHash),ft("instruction_version_identities_ordinal_unique").on(e.instructionId,e.versionOrdinal),Me("idx_ivi_instruction").on(e.instructionId)]),he=Zt("instruction_versions",{id:z("id").primaryKey().defaultRandom(),instructionId:z("instruction_id").references(()=>n.id,{onDelete:"cascade"}),versionNumber:mt("version_number").notNull(),content:N("content").notNull(),frontmatter:_t("frontmatter").notNull(),changeSummary:N("change_summary"),createdBy:z("created_by"),createdAt:V("created_at",{withTimezone:!0}).defaultNow()},e=>[ft("instruction_versions_instruction_version_idx").on(e.instructionId,e.versionNumber)]);import{pgTable as Ks,text as Cs,timestamp as qs,jsonb as Os,uuid as eo,index as Nn}from"drizzle-orm/pg-core";var ge=Ks("instruction_events",{id:eo("id").primaryKey().defaultRandom(),instructionId:eo("instruction_id").notNull().references(()=>n.id,{onDelete:"cascade"}),eventType:Cs("event_type").notNull(),actorId:eo("actor_id").notNull(),metadata:Os("metadata"),createdAt:qs("created_at",{withTimezone:!0}).defaultNow()},e=>[Nn("idx_instruction_events_instruction").on(e.instructionId),Nn("idx_instruction_events_type").on(e.eventType)]);import{boolean as Ms,jsonb as Hs,pgTable as oo,primaryKey as xn,text as re,timestamp as He,uniqueIndex as to,uuid as se}from"drizzle-orm/pg-core";import{sql as Ls}from"drizzle-orm";var s=oo("projects",{id:se("id").primaryKey().defaultRandom(),orgId:se("org_id").references(()=>l.id,{onDelete:"cascade"}),name:re("name").notNull(),description:re("description"),githubRepo:re("github_repo"),gitRemoteUrl:re("git_remote_url"),gitRootCommit:re("git_root_commit"),gitRemoteAliases:re("git_remote_aliases").array().notNull().default([]),metadata:Hs("metadata"),createdBy:se("created_by"),createdAt:He("created_at",{withTimezone:!0}).defaultNow(),updatedAt:He("updated_at",{withTimezone:!0}).defaultNow()},e=>[to("projects_org_name_idx").on(e.orgId,e.name),to("projects_git_remote_url_unique").on(e.gitRemoteUrl).where(Ls`${e.gitRemoteUrl} IS NOT NULL`)]),F=oo("project_instructions",{projectId:se("project_id").references(()=>s.id,{onDelete:"cascade"}).notNull(),instructionId:se("instruction_id").references(()=>n.id,{onDelete:"cascade"}).notNull(),addedAt:He("added_at",{withTimezone:!0}).defaultNow(),addedBy:se("added_by")},e=>[xn({columns:[e.projectId,e.instructionId]})]),hn=oo("project_checkouts",{projectId:se("project_id").references(()=>s.id,{onDelete:"cascade"}).notNull(),path:re("path").notNull(),isWorktree:Ms("is_worktree").notNull().default(!1),firstSeen:He("first_seen",{withTimezone:!0}).notNull().defaultNow(),lastSeen:He("last_seen",{withTimezone:!0}).notNull().defaultNow()},e=>[xn({columns:[e.projectId,e.path]}),to("project_checkouts_path_unique").on(e.path)]);import{pgTable as so,text as I,timestamp as Le,jsonb as ie,uuid as K,integer as xt,uniqueIndex as vn,index as R}from"drizzle-orm/pg-core";import{pgTable as Us,text as ve,timestamp as no,jsonb as gn,uuid as Nt,integer as Bs,boolean as Gs,index as ro}from"drizzle-orm/pg-core";var h=Us("agent_runs",{id:Nt("id").primaryKey().defaultRandom(),userId:Nt("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),orgId:Nt("org_id").references(()=>l.id,{onDelete:"set null"}),projectId:Nt("project_id").references(()=>s.id,{onDelete:"set null"}),projectPath:ve("project_path"),gitRemote:ve("git_remote"),baseBranch:ve("base_branch"),title:ve("title"),prompt:ve("prompt"),toolSpec:gn("tool_spec").notNull().default([]),autoWorktree:Gs("auto_worktree").notNull().default(!0),status:ve("status").notNull().default("pending"),sessionCount:Bs("session_count").notNull().default(0),metadata:gn("metadata").notNull().default({}),createdAt:no("created_at",{withTimezone:!0}).notNull().defaultNow(),updatedAt:no("updated_at",{withTimezone:!0}).notNull().defaultNow(),completedAt:no("completed_at",{withTimezone:!0})},e=>[ro("idx_agent_runs_user").on(e.userId),ro("idx_agent_runs_org_created").on(e.orgId,e.createdAt),ro("idx_agent_runs_project").on(e.projectId)]);var a=so("sessions",{id:K("id").primaryKey().defaultRandom(),userId:K("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),externalSessionId:I("external_session_id"),projectId:K("project_id").references(()=>s.id,{onDelete:"set null"}),orgId:K("org_id").references(()=>l.id,{onDelete:"set null"}),tool:I("tool").notNull(),projectPath:I("project_path"),gitBranch:I("git_branch"),startedAt:Le("started_at",{withTimezone:!0}).notNull(),endedAt:Le("ended_at",{withTimezone:!0}),eventCount:xt("event_count").default(0),tokenUsage:ie("token_usage"),analysis:ie("analysis"),analyzedAt:Le("analyzed_at",{withTimezone:!0}),analyzedEventCount:xt("analyzed_event_count"),analyzedTurnCount:xt("analyzed_turn_count"),metadata:ie("metadata").default({}),origin:I("origin").notNull().default("unknown"),runId:K("run_id").references(()=>h.id,{onDelete:"set null"}),model:I("model"),harnessVersion:I("harness_version"),createdAt:Le("created_at",{withTimezone:!0}).defaultNow()},e=>[R("idx_sessions_user").on(e.userId),R("idx_sessions_tool").on(e.tool),R("idx_sessions_started_at").on(e.startedAt),R("idx_sessions_project").on(e.projectId),R("idx_sessions_org_started_at").on(e.orgId,e.startedAt),R("idx_sessions_run").on(e.runId),vn("idx_sessions_user_external").on(e.userId,e.externalSessionId)]),Ie=so("session_events",{id:K("id").primaryKey().defaultRandom(),sessionId:K("session_id").notNull().references(()=>a.id,{onDelete:"cascade"}),sequence:xt("sequence").notNull(),eventType:I("event_type").notNull(),content:I("content"),toolName:I("tool_name"),toolInput:ie("tool_input"),toolOutput:ie("tool_output"),tokenUsage:ie("token_usage"),model:I("model"),timestamp:Le("timestamp",{withTimezone:!0}).notNull(),metadata:ie("metadata").default({})},e=>[vn("session_events_session_sequence_idx").on(e.sessionId,e.sequence),R("idx_session_events_session_id").on(e.sessionId),R("idx_session_events_event_type").on(e.eventType),R("idx_session_events_model").on(e.model)]),$=so("session_instructions",{sessionId:K("session_id").notNull().references(()=>a.id,{onDelete:"cascade"}),instructionId:K("instruction_id").notNull().references(()=>n.id,{onDelete:"cascade"}),linkMethod:I("link_method").notNull(),contentHash:I("content_hash")},e=>[R("idx_session_instructions_instruction_id").on(e.instructionId)]);import{pgTable as In,text as ht,timestamp as yn,uuid as k,integer as wn,index as ye,unique as Vs}from"drizzle-orm/pg-core";var C=In("treatment_assignments",{id:k("id").primaryKey().defaultRandom(),userId:k("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),treatmentType:ht("treatment_type").notNull(),treatmentId:k("treatment_id").notNull(),treatmentVersion:wn("treatment_version").notNull().default(1),projectId:k("project_id").references(()=>s.id,{onDelete:"set null"}),assignedBy:k("assigned_by").references(()=>o.id,{onDelete:"set null"}),method:ht("method").notNull(),assignedAt:yn("assigned_at",{withTimezone:!0}).notNull().defaultNow()},e=>[ye("idx_treatment_assignments_user").on(e.userId),ye("idx_treatment_assignments_treatment").on(e.treatmentType,e.treatmentId),ye("idx_treatment_assignments_project").on(e.projectId)]),q=In("treatment_exposures",{id:k("id").primaryKey().defaultRandom(),sessionId:k("session_id").notNull().references(()=>a.id,{onDelete:"cascade"}),userId:k("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),treatmentType:ht("treatment_type").notNull(),treatmentId:k("treatment_id").notNull(),treatmentVersion:wn("treatment_version").notNull().default(1),assignmentId:k("assignment_id").references(()=>C.id,{onDelete:"set null"}),method:ht("method").notNull(),exposedAt:yn("exposed_at",{withTimezone:!0}).notNull().defaultNow()},e=>[Vs("treatment_exposures_unique").on(e.sessionId,e.treatmentType,e.treatmentId,e.treatmentVersion),ye("idx_treatment_exposures_treatment").on(e.treatmentType,e.treatmentId),ye("idx_treatment_exposures_user").on(e.userId),ye("idx_treatment_exposures_session").on(e.sessionId)]);import{pgTable as Fs,text as io,timestamp as $s,uuid as gt,integer as Js,index as Tn,uniqueIndex as Qs}from"drizzle-orm/pg-core";var An=Fs("pending_treatment_exposures",{id:gt("id").primaryKey().defaultRandom(),userId:gt("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),externalSessionId:io("external_session_id").notNull(),treatmentType:io("treatment_type").notNull(),treatmentId:gt("treatment_id").notNull(),treatmentVersion:Js("treatment_version").notNull().default(1),method:io("method").notNull().default("injected"),projectId:gt("project_id").references(()=>s.id,{onDelete:"set null"}),createdAt:$s("created_at",{withTimezone:!0}).notNull().defaultNow()},e=>[Qs("pending_treatment_exposures_unique").on(e.externalSessionId,e.treatmentType,e.treatmentId,e.treatmentVersion),Tn("idx_pending_treatment_exposures_ext").on(e.externalSessionId),Tn("idx_pending_treatment_exposures_user").on(e.userId)]);import{pgTable as Dn,text as J,timestamp as jn,uuid as we,numeric as Ys,index as ao,unique as Ws}from"drizzle-orm/pg-core";var Ue=Dn("instruction_experiments",{id:we("id").primaryKey().defaultRandom(),userId:we("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),instructionId:we("instruction_id").notNull().references(()=>n.id,{onDelete:"cascade"}),projectPath:J("project_path").notNull(),status:J("status").notNull().default("running"),treatedShare:Ys("treated_share").notNull().default("0.5"),salt:J("salt").notNull(),contentHash:J("content_hash"),source:J("source").notNull().default("manual"),stoppedReason:J("stopped_reason"),createdAt:jn("created_at",{withTimezone:!0}).notNull().defaultNow()},e=>[ao("idx_instruction_experiments_lookup").on(e.userId,e.projectPath)]),zn=Dn("instruction_experiment_arms",{id:we("id").primaryKey().defaultRandom(),experimentId:we("experiment_id").notNull().references(()=>Ue.id,{onDelete:"cascade"}),userId:we("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),externalSessionId:J("external_session_id").notNull(),arm:J("arm").notNull(),assignedAt:jn("assigned_at",{withTimezone:!0}).notNull().defaultNow()},e=>[Ws("instruction_experiment_arms_unique").on(e.experimentId,e.externalSessionId),ao("idx_instruction_experiment_arms_experiment").on(e.experimentId,e.arm),ao("idx_instruction_experiment_arms_session").on(e.externalSessionId)]);import{pgTable as Xs,text as uo,timestamp as Zs,uuid as vt,numeric as lo,integer as Rn,jsonb as ei,index as ti,unique as oi}from"drizzle-orm/pg-core";var kn=Xs("instruction_verdicts",{id:vt("id").primaryKey().defaultRandom(),userId:vt("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),instructionId:vt("instruction_id").notNull().references(()=>n.id,{onDelete:"cascade"}),contentHash:uo("content_hash").notNull(),projectPath:uo("project_path").notNull(),segment:ei("segment").notNull().default({}),decision:uo("decision").notNull(),delta:lo("delta").notNull(),ciLower:lo("ci_lower").notNull(),ciUpper:lo("ci_upper").notNull(),nTreated:Rn("n_treated").notNull(),nControl:Rn("n_control").notNull(),experimentId:vt("experiment_id").references(()=>Ue.id,{onDelete:"set null"}),decidedAt:Zs("decided_at",{withTimezone:!0}).notNull().defaultNow()},e=>[oi("instruction_verdicts_unique").on(e.instructionId,e.contentHash,e.projectPath),ti("idx_instruction_verdicts_render").on(e.userId,e.projectPath)]);import{pgTable as ni,text as It,timestamp as co,uuid as po,integer as ri,unique as si,index as ii}from"drizzle-orm/pg-core";var En=ni("insight_recommendation_log",{id:po("id").primaryKey().defaultRandom(),userId:po("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),projectPath:It("project_path").notNull().default(""),category:It("category").notNull(),contentHash:It("content_hash").notNull(),label:It("label").notNull().default(""),firstSeenAt:co("first_seen_at",{withTimezone:!0}).notNull().defaultNow(),lastSeenAt:co("last_seen_at",{withTimezone:!0}).notNull().defaultNow(),timesGenerated:ri("times_generated").notNull().default(1),lastJobId:po("last_job_id"),dismissedAt:co("dismissed_at",{withTimezone:!0})},e=>[si("insight_recommendation_log_unique").on(e.userId,e.projectPath,e.contentHash),ii("idx_insight_recommendation_log_read").on(e.userId,e.projectPath)]);import{pgTable as ai,text as Te,timestamp as _o,uuid as Be,integer as Sn,index as yt}from"drizzle-orm/pg-core";var w=ai("memories",{id:Be("id").primaryKey().defaultRandom(),userId:Be("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),orgId:Be("org_id"),projectId:Be("project_id").references(()=>s.id,{onDelete:"set null"}),version:Sn("version").notNull().default(1),parentId:Be("parent_id").references(()=>w.id,{onDelete:"set null"}),kind:Te("kind").notNull(),title:Te("title").notNull(),body:Te("body").notNull(),source:Te("source").notNull(),status:Te("status").notNull().default("active"),trustClass:Te("trust_class"),trustVersion:Sn("trust_version"),trustComputedAt:_o("trust_computed_at",{withTimezone:!0}),createdAt:_o("created_at",{withTimezone:!0}).notNull().defaultNow(),updatedAt:_o("updated_at",{withTimezone:!0}).notNull().defaultNow()},e=>[yt("idx_memories_user").on(e.userId),yt("idx_memories_project").on(e.projectId),yt("idx_memories_parent").on(e.parentId),yt("idx_memories_user_status").on(e.userId,e.status)]);import{pgTable as di,text as ae,timestamp as mo,uuid as fo,integer as bn,jsonb as ui,index as Pn}from"drizzle-orm/pg-core";var Kn=di("memory_experiments",{id:fo("id").primaryKey().defaultRandom(),memoryId:fo("memory_id").notNull().references(()=>w.id,{onDelete:"cascade"}),userId:fo("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),memoryVersion:bn("memory_version").notNull().default(1),memoryBody:ae("memory_body"),taskPrompt:ae("task_prompt").notNull(),expectations:ae("expectations").array().notNull().default([]),trials:bn("trials").notNull().default(10),model:ae("model"),engine:ae("engine").$type().notNull().default("claude"),status:ae("status").notNull().default("pending"),result:ui("result").$type(),error:ae("error"),createdAt:mo("created_at",{withTimezone:!0}).notNull().defaultNow(),startedAt:mo("started_at",{withTimezone:!0}),completedAt:mo("completed_at",{withTimezone:!0})},e=>[Pn("idx_memory_experiments_memory").on(e.memoryId),Pn("idx_memory_experiments_user").on(e.userId)]);import{pgTable as li,text as Ae,timestamp as No,uuid as xo,jsonb as ci,uniqueIndex as pi,index as Cn}from"drizzle-orm/pg-core";var wt=li("session_terminal_targets",{id:xo("id").primaryKey().defaultRandom(),userId:xo("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),sessionId:xo("session_id").references(()=>a.id,{onDelete:"set null"}),externalSessionId:Ae("external_session_id"),kind:Ae("kind").notNull(),target:Ae("target").notNull(),status:Ae("status").notNull().default("active"),attachCommand:Ae("attach_command").notNull(),projectPath:Ae("project_path"),metadata:ci("metadata").notNull().default({}),lastSeenAt:No("last_seen_at",{withTimezone:!0}).defaultNow(),createdAt:No("created_at",{withTimezone:!0}).defaultNow(),updatedAt:No("updated_at",{withTimezone:!0}).defaultNow()},e=>[pi("idx_session_terminal_targets_user_target").on(e.userId,e.target),Cn("idx_session_terminal_targets_session").on(e.sessionId),Cn("idx_session_terminal_targets_user_status").on(e.userId,e.status)]);import{boolean as _i,index as Tt,jsonb as qn,pgTable as mi,text as de,timestamp as Ge,uuid as At,integer as ho}from"drizzle-orm/pg-core";var On=mi("session_send_jobs",{id:At("id").primaryKey().defaultRandom(),userId:At("user_id").notNull(),sessionId:At("session_id").notNull().references(()=>a.id,{onDelete:"cascade"}),terminalTargetId:At("terminal_target_id").references(()=>wt.id,{onDelete:"set null"}),target:de("target").notNull(),message:de("message").notNull(),submit:_i("submit").notNull().default(!0),delivery:de("delivery").notNull().default("live"),status:de("status").notNull().default("pending"),result:qn("result"),error:de("error"),attempts:ho("attempts").notNull().default(0),taskKind:de("task_kind"),payload:qn("payload"),claimedBy:de("claimed_by"),claimedAt:Ge("claimed_at",{withTimezone:!0}),leaseExpiresAt:Ge("lease_expires_at",{withTimezone:!0}),leaseRecoveries:ho("lease_recoveries").notNull().default(0),hostSuspendRecoveries:ho("host_suspend_recoveries").notNull().default(0),createdAt:Ge("created_at",{withTimezone:!0}).defaultNow(),updatedAt:Ge("updated_at",{withTimezone:!0}).defaultNow(),completedAt:Ge("completed_at",{withTimezone:!0})},e=>[Tt("idx_session_send_jobs_user").on(e.userId),Tt("idx_session_send_jobs_session").on(e.sessionId),Tt("idx_session_send_jobs_status").on(e.status),Tt("idx_session_send_jobs_pending").on(e.userId,e.status)]);import{pgTable as Hn,text as ue,timestamp as Dt,jsonb as Ln,uuid as Q,integer as fi,boolean as Ni,uniqueIndex as xi,index as Mn,primaryKey as hi}from"drizzle-orm/pg-core";var j=Hn("packs",{id:Q("id").primaryKey().defaultRandom(),name:ue("name").notNull(),description:ue("description").notNull(),scope:ue("scope").notNull(),scopeRef:Q("scope_ref"),version:ue("version").notNull().default("1.0.0"),tags:ue("tags").array(),badge:ue("badge"),metadata:Ln("metadata"),createdBy:Q("created_by"),createdAt:Dt("created_at",{withTimezone:!0}).defaultNow(),updatedAt:Dt("updated_at",{withTimezone:!0}).defaultNow(),archived:Ni("archived").default(!1),archivedAt:Dt("archived_at",{withTimezone:!0}),archivedBy:Q("archived_by"),forkedFromId:Q("forked_from_id").references(()=>j.id,{onDelete:"set null"}),upstreamVersion:ue("upstream_version")},e=>[xi("packs_name_scope_ref_idx").on(e.name,e.scope,e.scopeRef),Mn("idx_packs_scope").on(e.scope,e.scopeRef),Mn("idx_packs_created_by").on(e.createdBy)]),Y=Hn("pack_instructions",{packId:Q("pack_id").references(()=>j.id,{onDelete:"cascade"}).notNull(),instructionId:Q("instruction_id").references(()=>n.id,{onDelete:"cascade"}).notNull(),position:fi("position").notNull().default(0),slotOverrides:Ln("slot_overrides"),addedAt:Dt("added_at",{withTimezone:!0}).defaultNow(),addedBy:Q("added_by")},e=>[hi({columns:[e.packId,e.instructionId]})]);import{pgTable as gi,text as go,timestamp as vi,jsonb as Ii,uuid as vo,index as De}from"drizzle-orm/pg-core";var je=gi("instruction_usage_events",{id:vo("id").primaryKey().defaultRandom(),instructionId:vo("instruction_id").references(()=>n.id,{onDelete:"set null"}),userId:vo("user_id").notNull(),surface:go("surface").notNull(),action:go("action").notNull(),metadata:Ii("metadata"),traceId:go("trace_id"),createdAt:vi("created_at",{withTimezone:!0}).defaultNow()},e=>[De("idx_usage_events_instruction").on(e.instructionId),De("idx_usage_events_user").on(e.userId),De("idx_usage_events_surface").on(e.surface),De("idx_usage_events_action").on(e.action),De("idx_usage_events_created_at").on(e.createdAt),De("idx_usage_events_user_created").on(e.userId,e.createdAt)]);import{pgTable as yi,text as jt,timestamp as zt,jsonb as wi,uuid as Un,index as Io}from"drizzle-orm/pg-core";var Bn=yi("worker_connections",{id:Un("id").primaryKey().defaultRandom(),userId:Un("user_id").notNull(),workerType:jt("worker_type").notNull().default("mcp"),clientName:jt("client_name").notNull(),clientVersion:jt("client_version"),workerVersion:jt("worker_version"),lastHeartbeat:zt("last_heartbeat",{withTimezone:!0}).notNull().defaultNow(),presenceGapStartedAt:zt("presence_gap_started_at",{withTimezone:!0}),presenceGapEndedAt:zt("presence_gap_ended_at",{withTimezone:!0}),connectedAt:zt("connected_at",{withTimezone:!0}).notNull().defaultNow(),metadata:wi("metadata")},e=>[Io("idx_worker_connections_user").on(e.userId),Io("idx_worker_connections_heartbeat").on(e.userId,e.lastHeartbeat),Io("idx_worker_connections_type").on(e.userId,e.workerType)]);import{pgTable as Ti,text as Rt,timestamp as Ai,jsonb as Di,uuid as Gn,index as Vn}from"drizzle-orm/pg-core";var Fn=Ti("cli_setup_events",{id:Gn("id").primaryKey().defaultRandom(),userId:Gn("user_id").notNull(),deviceId:Rt("device_id").notNull(),event:Rt("event").notNull(),cliVersion:Rt("cli_version"),os:Rt("os"),props:Di("props").notNull().default({}),createdAt:Ai("created_at",{withTimezone:!0}).notNull().defaultNow()},e=>[Vn("idx_cli_setup_events_user").on(e.userId,e.createdAt),Vn("idx_cli_setup_events_device").on(e.deviceId,e.createdAt)]);import{pgTable as ji,text as le,integer as zi,boolean as Ri,timestamp as ki,jsonb as Ei,uuid as Si,index as $n}from"drizzle-orm/pg-core";var Jn=ji("cli_error_events",{id:Si("id").primaryKey().defaultRandom(),deviceId:le("device_id"),event:le("event").notNull(),command:le("command"),statusCode:zi("status_code"),message:le("message"),cliVersion:le("cli_version"),os:le("os"),nodeVersion:le("node_version"),proxied:Ri("proxied"),props:Ei("props").notNull().default({}),createdAt:ki("created_at",{withTimezone:!0}).notNull().defaultNow()},e=>[$n("idx_cli_error_events_created").on(e.createdAt),$n("idx_cli_error_events_device").on(e.deviceId,e.createdAt)]);import{sql as yo}from"drizzle-orm";import{pgTable as ce,text as p,timestamp as g,jsonb as T,uuid as c,integer as O,boolean as Ve,index as f,unique as Qn}from"drizzle-orm/pg-core";var r=ce("eval_targets",{id:c("id").primaryKey().defaultRandom(),userId:c("user_id").notNull(),name:p("name").notNull(),type:p("type").notNull(),content:p("content").notNull(),description:p("description").notNull().default(""),metadata:T("metadata").notNull().default({}),version:O("version").notNull().default(1),parentId:c("parent_id").references(()=>r.id,{onDelete:"set null"}),instructionId:c("instruction_id").references(()=>n.id,{onDelete:"set null"}),projectPath:p("project_path"),createdAt:g("created_at",{withTimezone:!0}).defaultNow(),updatedAt:g("updated_at",{withTimezone:!0}).defaultNow()},e=>[f("eval_targets_name_user_idx").on(e.name,e.userId),f("idx_eval_targets_user").on(e.userId),f("idx_eval_targets_type").on(e.type),f("idx_eval_targets_parent").on(e.parentId),f("idx_eval_targets_instruction").on(e.instructionId).where(yo`${e.instructionId} IS NOT NULL`),f("idx_eval_targets_project").on(e.projectPath).where(yo`${e.projectPath} IS NOT NULL`)]),M=ce("evals",{id:c("id").primaryKey().defaultRandom(),evalTargetId:c("eval_target_id").notNull().references(()=>r.id,{onDelete:"cascade"}),name:p("name").notNull(),prompt:p("prompt").notNull(),expectedOutput:p("expected_output").notNull().default(""),files:T("files").notNull().default([]),expectations:T("expectations").notNull().default([]),retiredAt:g("retired_at",{withTimezone:!0}),retiredReason:p("retired_reason"),createdAt:g("created_at",{withTimezone:!0}).defaultNow(),updatedAt:g("updated_at",{withTimezone:!0}).defaultNow(),contentUpdatedAt:g("content_updated_at",{withTimezone:!0}).notNull().defaultNow()},e=>[f("idx_evals_target").on(e.evalTargetId),f("idx_evals_target_active").on(e.evalTargetId).where(yo`${e.retiredAt} IS NULL`)]),E=ce("eval_runs",{id:c("id").primaryKey().defaultRandom(),jobId:c("job_id"),evalId:c("eval_id").notNull().references(()=>M.id,{onDelete:"cascade"}),evalTargetId:c("eval_target_id").notNull().references(()=>r.id,{onDelete:"cascade"}),evalTargetVersion:O("eval_target_version").notNull(),configuration:p("configuration").notNull(),runNumber:O("run_number").notNull().default(1),iteration:O("iteration").notNull().default(1),status:p("status").notNull().default("completed"),outputs:T("outputs").notNull().default({}),timing:T("timing").notNull().default({}),grading:T("grading").notNull().default({}),comparison:T("comparison"),createdAt:g("created_at",{withTimezone:!0}).defaultNow()},e=>[f("idx_eval_runs_eval").on(e.evalId),f("idx_eval_runs_target").on(e.evalTargetId),f("idx_eval_runs_iteration").on(e.evalTargetId,e.iteration)]),Yn=ce("eval_comparisons",{id:c("id").primaryKey().defaultRandom(),userId:c("user_id").notNull(),targetAId:c("target_a_id").notNull().references(()=>r.id,{onDelete:"cascade"}),targetBId:c("target_b_id").notNull().references(()=>r.id,{onDelete:"cascade"}),targetAVersion:O("target_a_version").notNull(),targetBVersion:O("target_b_version").notNull(),isSwapped:Ve("is_swapped").notNull().default(!1),winnerTargetId:c("winner_target_id").references(()=>r.id,{onDelete:"set null"}),perEval:T("per_eval").notNull().default([]),overall:T("overall").notNull().default({}),rawOutput:p("raw_output"),model:p("model"),status:p("status").notNull().default("completed"),createdAt:g("created_at",{withTimezone:!0}).defaultNow()},e=>[f("idx_eval_comparisons_target_a").on(e.targetAId),f("idx_eval_comparisons_target_b").on(e.targetBId),f("idx_eval_comparisons_user").on(e.userId)]),Wn=ce("eval_grade_annotations",{id:c("id").primaryKey().defaultRandom(),userId:c("user_id").notNull(),evalRunId:c("eval_run_id").notNull().references(()=>E.id,{onDelete:"cascade"}),evalTargetId:c("eval_target_id").notNull().references(()=>r.id,{onDelete:"cascade"}),expectationIndex:O("expectation_index").notNull(),expectationText:p("expectation_text").notNull(),judgePassed:Ve("judge_passed").notNull(),judgeMethod:p("judge_method").notNull(),judgeModel:p("judge_model"),verdict:p("verdict").notNull(),flag:p("flag"),note:p("note"),createdAt:g("created_at",{withTimezone:!0}).defaultNow(),updatedAt:g("updated_at",{withTimezone:!0}).defaultNow()},e=>[f("idx_eval_grade_annotations_target").on(e.evalTargetId),f("idx_eval_grade_annotations_run").on(e.evalRunId),Qn("eval_grade_annotations_eval_run_id_expectation_index_key").on(e.evalRunId,e.expectationIndex)]),Xn=ce("judge_reviewer_verdicts",{id:c("id").primaryKey().defaultRandom(),userId:c("user_id").notNull(),evalTargetId:c("eval_target_id").notNull().references(()=>r.id,{onDelete:"cascade"}),evalRunId:c("eval_run_id").notNull().references(()=>E.id,{onDelete:"cascade"}),expectationIndex:O("expectation_index").notNull(),expectationText:p("expectation_text").notNull(),judgePassed:Ve("judge_passed").notNull(),humanPassed:Ve("human_passed").notNull(),reviewerEngine:p("reviewer_engine").notNull(),reviewerModel:p("reviewer_model").notNull(),reviewerPassed:Ve("reviewer_passed").notNull(),resolvedAt:g("resolved_at",{withTimezone:!0}),resolution:p("resolution"),createdAt:g("created_at",{withTimezone:!0}).defaultNow(),updatedAt:g("updated_at",{withTimezone:!0}).defaultNow()},e=>[f("idx_jrv_target").on(e.evalTargetId),Qn("judge_reviewer_verdicts_eval_run_id_expectation_index_review_key").on(e.evalRunId,e.expectationIndex,e.reviewerModel)]),ze=ce("benchmarks",{id:c("id").primaryKey().defaultRandom(),evalTargetId:c("eval_target_id").notNull().references(()=>r.id,{onDelete:"cascade"}),iteration:O("iteration").notNull().default(1),runSummary:T("run_summary").notNull().default({}),notes:T("notes").notNull().default([]),feedback:T("feedback"),createdAt:g("created_at",{withTimezone:!0}).defaultNow()},e=>[f("idx_benchmarks_target").on(e.evalTargetId)]);import{sql as wo}from"drizzle-orm";import{pgTable as bi,text as H,timestamp as Pi,jsonb as kt,uuid as Et,boolean as Ki,index as Fe,uniqueIndex as Ci}from"drizzle-orm/pg-core";var Zn=bi("instruction_promotions",{id:Et("id").primaryKey().defaultRandom(),userId:Et("user_id").notNull(),evalTargetId:Et("eval_target_id").notNull().references(()=>r.id,{onDelete:"cascade"}),instructionId:Et("instruction_id").references(()=>n.id,{onDelete:"set null"}),fromContentHash:H("from_content_hash").notNull(),toContentHash:H("to_content_hash").notNull(),fromContent:H("from_content").notNull(),toContent:H("to_content").notNull(),proposalSource:H("proposal_source").notNull(),proposalRationale:H("proposal_rationale").notNull().default(""),decision:H("decision").notNull(),applied:Ki("applied").notNull().default(!1),refusals:kt("refusals").notNull().default([]),rationale:H("rationale").notNull().default(""),effectClass:H("effect_class").notNull(),verdict:kt("verdict").notNull().default({}),gates:kt("gates").notNull().default({}),touchedSections:kt("touched_sections").notNull().default([]),createdAt:Pi("created_at",{withTimezone:!0}).notNull().defaultNow()},e=>[Fe("idx_instruction_promotions_budget").on(e.evalTargetId,e.createdAt.desc()).where(wo`${e.applied}`),Fe("idx_instruction_promotions_target").on(e.evalTargetId,e.createdAt.desc()),Fe("idx_instruction_promotions_user").on(e.userId,e.createdAt.desc()),Fe("idx_instruction_promotions_to_hash").on(e.toContentHash),Ci("uq_instruction_promotions_applied").on(e.evalTargetId,e.fromContentHash,e.toContentHash).where(wo`${e.applied}`),Fe("idx_instruction_promotions_applied_hash").on(e.toContentHash,e.createdAt.desc()).where(wo`${e.applied}`)]);import{index as $e,integer as qi,jsonb as Oi,pgTable as Mi,text as y,timestamp as Re,uniqueIndex as Hi,uuid as Je}from"drizzle-orm/pg-core";var er=Mi("recommendation_applications",{id:Je("id").primaryKey().defaultRandom(),userId:Je("user_id").notNull(),instructionId:Je("instruction_id").notNull().references(()=>n.id,{onDelete:"cascade"}),projectId:Je("project_id").references(()=>s.id,{onDelete:"set null"}),projectPath:y("project_path").notNull(),harness:y("harness").notNull(),targetPath:y("target_path").notNull(),status:y("status").notNull().default("proposed"),applyMode:y("apply_mode").notNull(),beforeHash:y("before_hash"),appliedHash:y("applied_hash"),appliedAt:Re("applied_at",{withTimezone:!0}),measurementStartedAt:Re("measurement_started_at",{withTimezone:!0}),measurementEndedAt:Re("measurement_ended_at",{withTimezone:!0}),verdict:y("verdict"),verdictDetail:y("verdict_detail"),revertedAt:Re("reverted_at",{withTimezone:!0}),boundaryClass:y("boundary_class"),targets:y("targets").array().notNull().default([]),inverse:Oi("inverse"),requires:y("requires").array().notNull().default([]),provides:y("provides").array().notNull().default([]),applyBatchId:Je("apply_batch_id"),applySeq:qi("apply_seq"),createdAt:Re("created_at",{withTimezone:!0}).notNull().defaultNow(),updatedAt:Re("updated_at",{withTimezone:!0}).notNull().defaultNow()},e=>[Hi("uq_recommendation_applications_target").on(e.userId,e.instructionId,e.projectPath,e.harness,e.targetPath),$e("idx_recommendation_applications_user_status").on(e.userId,e.status,e.updatedAt.desc()),$e("idx_recommendation_applications_user_harness").on(e.userId,e.harness,e.updatedAt.desc()),$e("idx_recommendation_applications_project").on(e.projectId,e.updatedAt.desc()),$e("idx_recommendation_applications_batch").on(e.userId,e.applyBatchId,e.applySeq.desc()),$e("idx_recommendation_applications_requires").using("gin",e.requires)]);import{pgTable as Li,text as S,timestamp as tr,jsonb as Qe,uuid as To,integer as ke,real as Ui,index as W,uniqueIndex as or}from"drizzle-orm/pg-core";import{sql as Ao}from"drizzle-orm";var X=Li("context_snapshots",{id:To("id").primaryKey().defaultRandom(),sessionId:To("session_id").references(()=>a.id,{onDelete:"cascade"}),userId:To("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),sequence:ke("sequence").notNull().default(0),provider:S("provider").notNull(),model:S("model").notNull(),systemPrompt:S("system_prompt").notNull(),injectedInstructions:Qe("injected_instructions").notNull().default([]),messagesSummary:Qe("messages_summary").notNull(),tools:Qe("tools").notNull().default([]),systemHash:S("system_hash").notNull(),requestHash:S("request_hash").notNull().default(""),toolsHash:S("tools_hash"),injectedHash:S("injected_hash"),messagesDelta:Qe("messages_delta").default([]),messagesDeltaRef:S("messages_delta_ref"),messagesBaseLength:ke("messages_base_length"),payloadPrunedAt:tr("payload_pruned_at",{withTimezone:!0}),deltaOffloadState:S("delta_offload_state").notNull().default("inline"),deltaGzipBytes:ke("delta_gzip_bytes"),deltaOffloadError:S("delta_offload_error"),deltaOffloadAttempts:ke("delta_offload_attempts").notNull().default(0),maxTokens:ke("max_tokens"),temperature:Ui("temperature"),estimatedTokens:ke("estimated_tokens"),capturedAt:tr("captured_at",{withTimezone:!0}).notNull().defaultNow(),metadata:Qe("metadata").default({})},e=>[W("idx_context_snapshots_session").on(e.sessionId),W("idx_context_snapshots_user").on(e.userId),W("idx_context_snapshots_hash").on(e.systemHash),W("idx_context_snapshots_request_hash").on(e.requestHash),or("idx_snapshots_session_request").on(e.sessionId,e.requestHash),or("idx_snapshots_session_sequence").on(e.sessionId,e.sequence),W("idx_context_snapshots_user_session_captured").on(e.userId,e.sessionId,e.capturedAt.desc()),W("idx_snapshots_unpruned_captured").on(e.capturedAt,e.id).where(Ao`${e.payloadPrunedAt} is null`),W("idx_snapshots_pending_offload").on(e.deltaOffloadState,e.capturedAt,e.id).where(Ao`${e.deltaOffloadState} = 'pending'`),W("idx_snapshots_delta_ref").on(e.messagesDeltaRef).where(Ao`${e.messagesDeltaRef} is not null`)]);import{pgTable as Bi,text as nr,timestamp as rr,jsonb as Gi,integer as Vi,index as Fi}from"drizzle-orm/pg-core";var sr=Bi("content_blobs",{hash:nr("hash").primaryKey(),contentType:nr("content_type").notNull(),content:Gi("content").notNull(),sizeBytes:Vi("size_bytes").notNull().default(0),createdAt:rr("created_at",{withTimezone:!0}).defaultNow(),lastReferencedAt:rr("last_referenced_at",{withTimezone:!0}).notNull().defaultNow()},e=>[Fi("idx_content_blobs_type").on(e.contentType)]);import{integer as ir,jsonb as $i,pgTable as Ji,timestamp as Qi,uuid as Yi}from"drizzle-orm/pg-core";var ar=Ji("session_capture_heads",{sessionId:Yi("session_id").primaryKey().references(()=>a.id,{onDelete:"cascade"}),sequence:ir("sequence").notNull(),rawMessageHashes:$i("raw_message_hashes").notNull().$type(),version:ir("version").notNull(),updatedAt:Qi("updated_at",{withTimezone:!0}).notNull().defaultNow()});import{index as Wi,integer as dr,pgTable as Xi,text as Do,timestamp as ur,uniqueIndex as Zi,uuid as ea}from"drizzle-orm/pg-core";import{sql as ta}from"drizzle-orm";var lr=Xi("snapshot_delta_objects",{ref:Do("ref").primaryKey(),snapshotId:ea("snapshot_id"),compressedBytes:dr("compressed_bytes").notNull(),state:Do("state").notNull(),createdAt:ur("created_at",{withTimezone:!0}).notNull().defaultNow(),lastAttemptAt:ur("last_attempt_at",{withTimezone:!0}),attempts:dr("attempts").notNull().default(0),lastError:Do("last_error")},e=>[Wi("idx_snapshot_delta_objects_state_created").on(e.state,e.createdAt),Zi("snapshot_delta_objects_snapshot_id_unique").on(e.snapshotId).where(ta`${e.snapshotId} is not null`)]);import{pgTable as oa,text as St,timestamp as Ye,jsonb as bt,uuid as jo,index as Pt,integer as zo}from"drizzle-orm/pg-core";var b=oa("eval_jobs",{id:jo("id").primaryKey().defaultRandom(),userId:jo("user_id").notNull(),evalTargetId:jo("eval_target_id").notNull().references(()=>r.id,{onDelete:"cascade"}),status:St("status").notNull().default("pending"),config:bt("config").notNull().default({}),progress:bt("progress").notNull().default({}),result:bt("result"),error:St("error"),attempts:zo("attempts").notNull().default(0),taskKind:St("task_kind"),payload:bt("payload"),claimedBy:St("claimed_by"),claimedAt:Ye("claimed_at",{withTimezone:!0}),leaseExpiresAt:Ye("lease_expires_at",{withTimezone:!0}),leaseRecoveries:zo("lease_recoveries").notNull().default(0),hostSuspendRecoveries:zo("host_suspend_recoveries").notNull().default(0),createdAt:Ye("created_at",{withTimezone:!0}).defaultNow(),updatedAt:Ye("updated_at",{withTimezone:!0}).defaultNow(),completedAt:Ye("completed_at",{withTimezone:!0})},e=>[Pt("idx_eval_jobs_user").on(e.userId),Pt("idx_eval_jobs_target").on(e.evalTargetId),Pt("idx_eval_jobs_status").on(e.status),Pt("idx_eval_jobs_pending").on(e.userId,e.status)]);import{pgTable as na,text as We,timestamp as Xe,jsonb as cr,uuid as pr,integer as Ro,index as _r}from"drizzle-orm/pg-core";var mr=na("agent_jobs",{id:pr("id").primaryKey().defaultRandom(),userId:pr("user_id").notNull(),taskKind:We("task_kind").notNull(),status:We("status").notNull().default("pending"),payload:cr("payload").notNull(),dedupeKey:We("dedupe_key"),result:cr("result"),error:We("error"),attempts:Ro("attempts").notNull().default(0),claimedBy:We("claimed_by"),claimedAt:Xe("claimed_at",{withTimezone:!0}),leaseExpiresAt:Xe("lease_expires_at",{withTimezone:!0}),leaseRecoveries:Ro("lease_recoveries").notNull().default(0),hostSuspendRecoveries:Ro("host_suspend_recoveries").notNull().default(0),createdAt:Xe("created_at",{withTimezone:!0}).notNull().defaultNow(),updatedAt:Xe("updated_at",{withTimezone:!0}).notNull().defaultNow(),completedAt:Xe("completed_at",{withTimezone:!0})},e=>[_r("idx_agent_jobs_claim").on(e.userId,e.status,e.taskKind,e.createdAt),_r("idx_agent_jobs_dedupe").on(e.userId,e.taskKind,e.dedupeKey)]);import{pgTable as ra,text as Ze,timestamp as et,jsonb as Kt,uuid as ko,index as Ct,integer as Eo}from"drizzle-orm/pg-core";var fr=ra("insights_jobs",{id:ko("id").primaryKey().defaultRandom(),userId:ko("user_id").notNull(),status:Ze("status").notNull().default("pending"),projectPath:Ze("project_path"),projectId:ko("project_id").references(()=>s.id,{onDelete:"set null"}),config:Kt("config").notNull().default({}),progress:Kt("progress").notNull().default({}),result:Kt("result"),error:Ze("error"),attempts:Eo("attempts").notNull().default(0),taskKind:Ze("task_kind"),payload:Kt("payload"),claimedBy:Ze("claimed_by"),claimedAt:et("claimed_at",{withTimezone:!0}),leaseExpiresAt:et("lease_expires_at",{withTimezone:!0}),leaseRecoveries:Eo("lease_recoveries").notNull().default(0),hostSuspendRecoveries:Eo("host_suspend_recoveries").notNull().default(0),createdAt:et("created_at",{withTimezone:!0}).defaultNow(),updatedAt:et("updated_at",{withTimezone:!0}).defaultNow(),completedAt:et("completed_at",{withTimezone:!0})},e=>[Ct("idx_insights_jobs_user").on(e.userId),Ct("idx_insights_jobs_status").on(e.status),Ct("idx_insights_jobs_pending").on(e.userId,e.status),Ct("idx_insights_jobs_project").on(e.projectId)]);import{pgTable as sa,text as So,timestamp as qt,uuid as Nr,index as ia,uniqueIndex as aa}from"drizzle-orm/pg-core";var Ee=sa("api_keys",{id:Nr("id").primaryKey().defaultRandom(),userId:Nr("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),name:So("name").notNull(),keyHash:So("key_hash").notNull(),keyPrefix:So("key_prefix").notNull(),lastUsedAt:qt("last_used_at",{withTimezone:!0}),expiresAt:qt("expires_at",{withTimezone:!0}),revokedAt:qt("revoked_at",{withTimezone:!0}),createdAt:qt("created_at",{withTimezone:!0}).defaultNow()},e=>[ia("idx_api_keys_user").on(e.userId),aa("idx_api_keys_hash").on(e.keyHash)]);import{pgTable as da,text as bo,timestamp as xr,uuid as ua,index as la}from"drizzle-orm/pg-core";var hr=da("extension_auth_codes",{code:bo("code").primaryKey(),userId:ua("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),editor:bo("editor"),email:bo("email"),expiresAt:xr("expires_at",{withTimezone:!0}).notNull(),createdAt:xr("created_at",{withTimezone:!0}).defaultNow()},e=>[la("idx_ext_auth_codes_expiry").on(e.expiresAt)]);import{pgTable as ca,text as pa,timestamp as gr,jsonb as _a,uuid as Po,index as vr}from"drizzle-orm/pg-core";var Se=ca("eval_conversations",{id:Po("id").primaryKey().defaultRandom(),evalTargetId:Po("eval_target_id").notNull().references(()=>r.id,{onDelete:"cascade"}),userId:Po("user_id").notNull(),messages:_a("messages").notNull().default([]),status:pa("status").notNull().default("active"),createdAt:gr("created_at",{withTimezone:!0}).defaultNow(),updatedAt:gr("updated_at",{withTimezone:!0}).defaultNow()},e=>[vr("idx_eval_conversations_target").on(e.evalTargetId),vr("idx_eval_conversations_user").on(e.userId)]);import{pgTable as ma,text as L,timestamp as Ir,jsonb as fa,uuid as Ko}from"drizzle-orm/pg-core";var yr=ma("skill_submissions",{id:Ko("id").primaryKey().defaultRandom(),skillId:L("skill_id").notNull(),name:L("name").notNull(),description:L("description").notNull(),category:L("category").notNull(),tools:L("tools").array().notNull(),tags:L("tags").array().default([]),content:L("content").notNull(),status:L("status").notNull().default("pending"),submittedBy:Ko("submitted_by").notNull(),reviewedBy:Ko("reviewed_by"),reviewNote:L("review_note"),metadata:fa("metadata"),createdAt:Ir("created_at",{withTimezone:!0}).defaultNow(),updatedAt:Ir("updated_at",{withTimezone:!0}).defaultNow()});import{pgTable as Na,text as tt,timestamp as wr,jsonb as xa,uuid as ha,uniqueIndex as ga,index as Tr}from"drizzle-orm/pg-core";var Ar=Na("harness_releases",{id:ha("id").primaryKey().defaultRandom(),harness:tt("harness").notNull(),version:tt("version").notNull(),publishedAt:wr("published_at",{withTimezone:!0}).notNull(),title:tt("title"),body:tt("body"),categories:xa("categories").default({}),url:tt("url"),createdAt:wr("created_at",{withTimezone:!0}).defaultNow()},e=>[ga("idx_harness_releases_unique").on(e.harness,e.version),Tr("idx_harness_releases_harness").on(e.harness),Tr("idx_harness_releases_published").on(e.publishedAt)]);import{pgTable as va,text as be,timestamp as Dr,jsonb as Ia,uuid as jr,index as zr,uniqueIndex as ya}from"drizzle-orm/pg-core";var Co=va("notifications",{id:jr("id").primaryKey().defaultRandom(),userId:jr("user_id").notNull(),type:be("type").notNull(),title:be("title").notNull(),body:be("body"),url:be("url"),sourceTable:be("source_table"),sourceId:be("source_id"),metadata:Ia("metadata").notNull().default({}),readAt:Dr("read_at",{withTimezone:!0}),createdAt:Dr("created_at",{withTimezone:!0}).notNull().defaultNow()},e=>[zr("idx_notifications_user_created").on(e.userId,e.createdAt),zr("idx_notifications_user_unread").on(e.userId),ya("idx_notifications_source_dedup").on(e.userId,e.sourceTable,e.sourceId)]);import{pgTable as wa,text as ot,timestamp as nt,jsonb as qo,uuid as Oo,index as Ot,integer as Mo}from"drizzle-orm/pg-core";var Pe=wa("launch_jobs",{id:Oo("id").primaryKey().defaultRandom(),userId:Oo("user_id").notNull(),tool:ot("tool").notNull(),status:ot("status").notNull().default("pending"),config:qo("config").notNull().default({}),result:qo("result"),error:ot("error"),attempts:Mo("attempts").notNull().default(0),taskKind:ot("task_kind"),payload:qo("payload"),claimedBy:ot("claimed_by"),claimedAt:nt("claimed_at",{withTimezone:!0}),leaseExpiresAt:nt("lease_expires_at",{withTimezone:!0}),leaseRecoveries:Mo("lease_recoveries").notNull().default(0),hostSuspendRecoveries:Mo("host_suspend_recoveries").notNull().default(0),createdAt:nt("created_at",{withTimezone:!0}).defaultNow(),updatedAt:nt("updated_at",{withTimezone:!0}).defaultNow(),completedAt:nt("completed_at",{withTimezone:!0}),runId:Oo("run_id").references(()=>h.id,{onDelete:"set null"})},e=>[Ot("idx_launch_jobs_user").on(e.userId),Ot("idx_launch_jobs_status").on(e.status),Ot("idx_launch_jobs_pending").on(e.userId,e.status),Ot("idx_launch_jobs_run").on(e.runId)]);import{pgTable as Rr,uuid as U,text as Z,real as Ta,timestamp as rt,boolean as Aa,uniqueIndex as Da,index as st}from"drizzle-orm/pg-core";var kr=["add","remove","trim"],Ho=Rr("instruction_suggestions",{id:U("id").primaryKey().defaultRandom(),userId:U("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),instructionId:U("instruction_id").notNull().references(()=>n.id,{onDelete:"cascade"}),projectPath:Z("project_path").notNull(),projectId:U("project_id").references(()=>s.id,{onDelete:"set null"}),score:Ta("score").notNull(),reason:Z("reason").notNull(),kind:Z("kind").$type().notNull().default("add"),generatedAt:rt("generated_at",{withTimezone:!0}).notNull().defaultNow(),isStale:Aa("is_stale").notNull().default(!1),dismissedAt:rt("dismissed_at",{withTimezone:!0}),acceptedAt:rt("accepted_at",{withTimezone:!0}),declinedAt:rt("declined_at",{withTimezone:!0}),declinedReason:Z("declined_reason"),promotedToInstructionId:U("promoted_to_instruction_id").references(()=>n.id,{onDelete:"set null"})},e=>[Da("idx_instruction_suggestions_user_project_instruction_kind").on(e.userId,e.projectPath,e.instructionId,e.kind),st("idx_instruction_suggestions_user_project").on(e.userId,e.projectPath),st("idx_instruction_suggestions_user_proj_id").on(e.userId,e.projectId),st("idx_instruction_suggestions_generated_at").on(e.generatedAt)]),Er=Rr("instruction_suggestion_events",{id:U("id").primaryKey().defaultRandom(),suggestionId:U("suggestion_id").notNull().references(()=>Ho.id,{onDelete:"cascade"}),userId:U("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),eventType:Z("event_type").notNull(),tool:Z("tool"),sessionId:U("session_id"),projectPath:Z("project_path").notNull(),actor:Z("actor"),createdAt:rt("created_at",{withTimezone:!0}).notNull().defaultNow()},e=>[st("idx_instruction_suggestion_events_suggestion_id").on(e.suggestionId),st("idx_instruction_suggestion_events_user_id").on(e.userId)]);import{pgTable as ja,text as Lo,integer as za,numeric as it,timestamp as Uo,index as Ra,primaryKey as ka}from"drizzle-orm/pg-core";var Sr=ja("model_pricing",{provider:Lo("provider").notNull(),modelId:Lo("model_id").notNull(),inputPerM:it("input_per_m").notNull(),outputPerM:it("output_per_m").notNull(),cacheReadPerM:it("cache_read_per_m").notNull(),cacheWrite5mPerM:it("cache_write_5m_per_m").notNull(),cacheWrite1hPerM:it("cache_write_1h_per_m").notNull(),contextWindow:za("context_window"),effectiveFrom:Uo("effective_from",{withTimezone:!0}).notNull(),effectiveUntil:Uo("effective_until",{withTimezone:!0}),source:Lo("source").notNull(),verifiedAt:Uo("verified_at",{withTimezone:!0})},e=>[ka({columns:[e.provider,e.modelId,e.effectiveFrom]}),Ra("idx_model_pricing_active").on(e.provider,e.modelId,e.effectiveFrom.desc())]);import{pgTable as Ea,text as pe,numeric as br,timestamp as Pr,uuid as Kr,jsonb as Sa,index as Cr}from"drizzle-orm/pg-core";var qr=Ea("limit_observations",{id:Kr("id").primaryKey().defaultRandom(),observedAt:Pr("observed_at",{withTimezone:!0}).notNull().defaultNow(),provider:pe("provider").notNull(),plan:pe("plan").notNull(),limitType:pe("limit_type").notNull(),value:br("value").notNull(),unit:pe("unit").notNull(),comparator:pe("comparator").notNull().default("="),resetsAt:Pr("resets_at",{withTimezone:!0}),sourceType:pe("source_type").notNull(),sourceUrl:pe("source_url"),sourceEvidence:Sa("source_evidence"),confidence:br("confidence").notNull(),userId:Kr("user_id")},e=>[Cr("idx_limit_obs_lookup").on(e.provider,e.plan,e.limitType,e.observedAt.desc()),Cr("idx_limit_obs_user").on(e.userId,e.observedAt.desc())]);import{pgTable as ba,text as Mt,timestamp as Pa,uuid as Ka,jsonb as Ca,boolean as qa,uniqueIndex as Oa}from"drizzle-orm/pg-core";var Or=ba("provider_docs_snapshots",{id:Ka("id").primaryKey().defaultRandom(),fetchedAt:Pa("fetched_at",{withTimezone:!0}).notNull().defaultNow(),provider:Mt("provider").notNull(),docUrl:Mt("doc_url").notNull(),contentHash:Mt("content_hash").notNull(),content:Mt("content").notNull(),parseSuccess:qa("parse_success").notNull(),parseErrors:Ca("parse_errors")},e=>[Oa("idx_docs_dedup").on(e.provider,e.docUrl,e.contentHash)]);import{pgTable as Ma,text as Ht,numeric as Mr,timestamp as Hr,uuid as Ha,primaryKey as La,index as Ua}from"drizzle-orm/pg-core";var Lr=Ma("plan_limits_active",{provider:Ht("provider").notNull(),plan:Ht("plan").notNull(),limitType:Ht("limit_type").notNull(),value:Mr("value").notNull(),unit:Ht("unit").notNull(),effectiveFrom:Hr("effective_from",{withTimezone:!0}).notNull(),effectiveUntil:Hr("effective_until",{withTimezone:!0}),confidence:Mr("confidence").notNull(),sourceObservationIds:Ha("source_observation_ids").array().notNull()},e=>[La({columns:[e.provider,e.plan,e.limitType,e.effectiveFrom]}),Ua("idx_plan_limits_lookup").on(e.provider,e.plan,e.limitType,e.effectiveFrom.desc())]);import{pgTable as Ba,text as Bo,timestamp as Ga,uuid as Ur,jsonb as Va,index as Fa}from"drizzle-orm/pg-core";var Br=Ba("alert_dispatches",{id:Ur("id").primaryKey().defaultRandom(),userId:Ur("user_id").notNull(),alertKey:Bo("alert_key").notNull(),severity:Bo("severity").notNull(),lastDispatchedAt:Ga("last_dispatched_at",{withTimezone:!0}).notNull().defaultNow(),lastState:Va("last_state").notNull(),channel:Bo("channel").notNull()},e=>[Fa("idx_alert_user_key").on(e.userId,e.alertKey,e.lastDispatchedAt.desc())]);import{date as Gr,integer as Go,pgTable as Vr,primaryKey as $a,text as Ja,timestamp as Vo,uuid as Qa}from"drizzle-orm/pg-core";var Fr=Vr("weekly_digest_deliveries",{userId:Qa("user_id").notNull().references(()=>o.id,{onDelete:"cascade"}),weekStart:Gr("week_start").notNull(),sentAt:Vo("sent_at",{withTimezone:!0}).notNull().defaultNow(),providerMessageId:Ja("provider_message_id")},e=>[$a({columns:[e.userId,e.weekStart]})]),$r=Vr("weekly_digest_runs",{weekStart:Gr("week_start").primaryKey(),startedAt:Vo("started_at",{withTimezone:!0}).notNull().defaultNow(),finishedAt:Vo("finished_at",{withTimezone:!0}),sent:Go("sent"),skipped:Go("skipped"),failed:Go("failed")});import{pgTable as Ya,text as Fo,timestamp as Jr,uuid as $o,integer as Wa,index as Xa,unique as Za}from"drizzle-orm/pg-core";var Qr=Ya("scaffolding_fingerprints",{id:$o("id").primaryKey().defaultRandom(),userId:$o("user_id").notNull(),harness:Fo("harness").notNull(),model:Fo("model").notNull(),toolsHash:Fo("tools_hash").notNull(),firstSeenAt:Jr("first_seen_at",{withTimezone:!0}).notNull().defaultNow(),lastSeenAt:Jr("last_seen_at",{withTimezone:!0}).notNull().defaultNow(),snapshotCount:Wa("snapshot_count").notNull().default(1),firstSessionId:$o("first_session_id")},e=>[Za("scaffolding_fingerprints_user_id_harness_model_tools_hash_key").on(e.userId,e.harness,e.model,e.toolsHash),Xa("idx_scaffolding_fp_segment").on(e.userId,e.harness,e.model)]);import{pgTable as ed,text as Jo,timestamp as td,jsonb as od,uuid as Yr,integer as nd,unique as rd}from"drizzle-orm/pg-core";var Wr=ed("scaffolding_segments",{id:Yr("id").primaryKey().defaultRandom(),userId:Yr("user_id").notNull(),harness:Jo("harness").notNull(),model:Jo("model").notNull(),coreNames:od("core_names").notNull(),coreHash:Jo("core_hash").notNull(),activeFingerprints:nd("active_fingerprints").notNull(),computedAt:td("computed_at",{withTimezone:!0}).notNull().defaultNow()},e=>[rd("scaffolding_segments_user_id_harness_model_key").on(e.userId,e.harness,e.model)]);import{pgTable as sd,text as ee,timestamp as Xr,uuid as Qo,uniqueIndex as id,index as ad}from"drizzle-orm/pg-core";var Zr=["blog","docs","changelog"],Yo=sd("vendor_guidance_snapshots",{id:Qo("id").primaryKey().defaultRandom(),fetchedAt:Xr("fetched_at",{withTimezone:!0}).notNull().defaultNow(),sourceId:ee("source_id").notNull(),harness:ee("harness").notNull(),vendor:ee("vendor").notNull(),kind:ee("kind").$type().notNull(),url:ee("url").notNull(),title:ee("title").notNull(),contentHash:ee("content_hash").notNull(),text:ee("text").notNull(),previousSnapshotId:Qo("previous_snapshot_id").references(()=>Yo.id,{onDelete:"set null"}),pitchedAt:Xr("pitched_at",{withTimezone:!0}),pitchInstructionId:Qo("pitch_instruction_id").references(()=>n.id,{onDelete:"set null"})},e=>[id("idx_vendor_guidance_dedup").on(e.sourceId,e.contentHash),ad("idx_vendor_guidance_source_fetched").on(e.sourceId,e.fetchedAt)]);import{pgTable as ts,uuid as Ke,text as Lt,jsonb as es,timestamp as Wo,uniqueIndex as dd,integer as ud,unique as ld}from"drizzle-orm/pg-core";var te=ts("performance_studies",{id:Ke("id").primaryKey().defaultRandom(),userId:Ke("user_id").notNull(),evalTargetId:Ke("eval_target_id").notNull().references(()=>r.id,{onDelete:"cascade"}),projectPath:Lt("project_path").notNull(),protocol:es("protocol").notNull(),protocolHash:Lt("protocol_hash").notNull(),result:es("result"),finalizedAt:Wo("finalized_at",{withTimezone:!0}),createdAt:Wo("created_at",{withTimezone:!0}).defaultNow().notNull()},e=>[dd("performance_studies_protocol_unique").on(e.userId,e.evalTargetId,e.protocolHash)]),_e=ts("performance_study_calls",{id:Ke("id").primaryKey().defaultRandom(),studyId:Ke("study_id").notNull().references(()=>te.id,{onDelete:"cascade"}),jobId:Ke("job_id").notNull().references(()=>b.id,{onDelete:"cascade"}),taskId:Lt("task_id").notNull(),arm:Lt("arm").notNull(),repetition:ud("repetition").notNull(),reservedAt:Wo("reserved_at",{withTimezone:!0}).defaultNow().notNull()},e=>[ld("performance_study_calls_study_id_task_id_arm_repetition_key").on(e.studyId,e.taskId,e.arm,e.repetition)]);import{drizzle as is}from"drizzle-orm/postgres-js";import as from"postgres";var Ut={};Ds(Ut,{GUIDANCE_KINDS:()=>Zr,SUGGESTION_KINDS:()=>kr,agentJobs:()=>mr,agentRuns:()=>h,agentRunsRelations:()=>Ad,alertDispatches:()=>Br,announcementDeliveries:()=>dn,announcements:()=>an,apiKeys:()=>Ee,apiKeysRelations:()=>pd,benchmarks:()=>ze,benchmarksRelations:()=>qd,cliErrorEvents:()=>Jn,cliSetupEvents:()=>Fn,contentBlobs:()=>sr,contextSnapshots:()=>X,contextSnapshotsRelations:()=>Hd,evalComparisons:()=>Yn,evalConversations:()=>Se,evalConversationsRelations:()=>Md,evalGradeAnnotations:()=>Wn,evalJobs:()=>b,evalJobsRelations:()=>Od,evalRuns:()=>E,evalRunsRelations:()=>Cd,evalTargets:()=>r,evalTargetsRelations:()=>Pd,evals:()=>M,evalsRelations:()=>Kd,extensionAuthCodes:()=>hr,harnessReleases:()=>Ar,insightRecommendationLog:()=>En,insightsJobs:()=>fr,instructionEvents:()=>ge,instructionEventsRelations:()=>gd,instructionExperimentArms:()=>zn,instructionExperiments:()=>Ue,instructionPromotions:()=>Zn,instructionSuggestionEvents:()=>Er,instructionSuggestions:()=>Ho,instructionUsageEvents:()=>je,instructionUsageEventsRelations:()=>bd,instructionVerdicts:()=>kn,instructionVersionIdentities:()=>fn,instructionVersions:()=>he,instructionVersionsRelations:()=>Id,instructions:()=>n,instructionsRelations:()=>hd,judgeReviewerVerdicts:()=>Xn,launchJobs:()=>Pe,launchJobsRelations:()=>Dd,limitObservations:()=>qr,memories:()=>w,memoriesRelations:()=>vd,memoryExperiments:()=>Kn,modelPricing:()=>Sr,notificationPreferences:()=>un,notifications:()=>Co,orgInvitations:()=>P,orgInvitationsRelations:()=>fd,organizations:()=>l,organizationsRelations:()=>_d,packInstructions:()=>Y,packInstructionsRelations:()=>Sd,packs:()=>j,packsRelations:()=>Ed,pendingTreatmentExposures:()=>An,performanceStudies:()=>te,performanceStudiesRelations:()=>Ld,performanceStudyCalls:()=>_e,performanceStudyCallsRelations:()=>Ud,planLimitsActive:()=>Lr,profiles:()=>o,profilesRelations:()=>cd,projectCheckouts:()=>hn,projectInstructions:()=>F,projectInstructionsRelations:()=>wd,projects:()=>s,projectsRelations:()=>yd,providerDocsSnapshots:()=>Or,recommendationApplications:()=>er,scaffoldingFingerprints:()=>Qr,scaffoldingSegments:()=>Wr,sessionCaptureHeads:()=>ar,sessionEvents:()=>Ie,sessionEventsRelations:()=>jd,sessionInstructions:()=>$,sessionInstructionsRelations:()=>zd,sessionSendJobs:()=>On,sessionTerminalTargets:()=>wt,sessions:()=>a,sessionsRelations:()=>Td,skillSubmissions:()=>yr,snapshotDeltaObjects:()=>lr,teams:()=>v,teamsRelations:()=>md,treatmentAssignments:()=>C,treatmentAssignmentsRelations:()=>Rd,treatmentExposures:()=>q,treatmentExposuresRelations:()=>kd,userOrganizations:()=>Ne,userOrganizationsRelations:()=>Nd,userTeams:()=>xe,userTeamsRelations:()=>xd,vendorGuidanceSnapshots:()=>Yo,weeklyDigestDeliveries:()=>Fr,weeklyDigestRuns:()=>$r,workerConnections:()=>Bn});import{relations as i}from"drizzle-orm";var cd=i(o,({many:e})=>({sessions:e(a),contextSnapshots:e(X),apiKeys:e(Ee)})),pd=i(Ee,({one:e})=>({profile:e(o,{fields:[Ee.userId],references:[o.id]})})),_d=i(l,({many:e})=>({teams:e(v),userOrganizations:e(Ne),projects:e(s),invitations:e(P)})),md=i(v,({one:e,many:t})=>({organization:e(l,{fields:[v.orgId],references:[l.id]}),userTeams:t(xe),invitations:t(P)})),fd=i(P,({one:e})=>({organization:e(l,{fields:[P.orgId],references:[l.id]}),team:e(v,{fields:[P.teamId],references:[v.id]}),inviter:e(o,{fields:[P.invitedBy],references:[o.id]})})),Nd=i(Ne,({one:e})=>({organization:e(l,{fields:[Ne.orgId],references:[l.id]})})),xd=i(xe,({one:e})=>({team:e(v,{fields:[xe.teamId],references:[v.id]})})),hd=i(n,({one:e,many:t})=>({versions:t(he),projectInstructions:t(F),events:t(ge),usageEvents:t(je),sessionInstructions:t($),packInstructions:t(Y),forkedFrom:e(n,{fields:[n.forkedFromId],references:[n.id]})})),gd=i(ge,({one:e})=>({instruction:e(n,{fields:[ge.instructionId],references:[n.id]})})),vd=i(w,({one:e,many:t})=>({project:e(s,{fields:[w.projectId],references:[s.id]}),parent:e(w,{fields:[w.parentId],references:[w.id]}),versions:t(w)})),Id=i(he,({one:e})=>({instruction:e(n,{fields:[he.instructionId],references:[n.id]})})),yd=i(s,({one:e,many:t})=>({organization:e(l,{fields:[s.orgId],references:[l.id]}),projectInstructions:t(F),sessions:t(a)})),wd=i(F,({one:e})=>({project:e(s,{fields:[F.projectId],references:[s.id]}),instruction:e(n,{fields:[F.instructionId],references:[n.id]})})),Td=i(a,({one:e,many:t})=>({profile:e(o,{fields:[a.userId],references:[o.id]}),project:e(s,{fields:[a.projectId],references:[s.id]}),run:e(h,{fields:[a.runId],references:[h.id]}),events:t(Ie),sessionInstructions:t($),treatmentExposures:t(q),contextSnapshots:t(X)})),Ad=i(h,({one:e,many:t})=>({profile:e(o,{fields:[h.userId],references:[o.id]}),organization:e(l,{fields:[h.orgId],references:[l.id]}),project:e(s,{fields:[h.projectId],references:[s.id]}),sessions:t(a),launchJobs:t(Pe)})),Dd=i(Pe,({one:e})=>({run:e(h,{fields:[Pe.runId],references:[h.id]})})),jd=i(Ie,({one:e})=>({session:e(a,{fields:[Ie.sessionId],references:[a.id]})})),zd=i($,({one:e})=>({session:e(a,{fields:[$.sessionId],references:[a.id]}),instruction:e(n,{fields:[$.instructionId],references:[n.id]})})),Rd=i(C,({one:e,many:t})=>({owner:e(o,{fields:[C.userId],references:[o.id]}),project:e(s,{fields:[C.projectId],references:[s.id]}),exposures:t(q)})),kd=i(q,({one:e})=>({session:e(a,{fields:[q.sessionId],references:[a.id]}),owner:e(o,{fields:[q.userId],references:[o.id]}),assignment:e(C,{fields:[q.assignmentId],references:[C.id]})})),Ed=i(j,({one:e,many:t})=>({packInstructions:t(Y),forkedFrom:e(j,{fields:[j.forkedFromId],references:[j.id]})})),Sd=i(Y,({one:e})=>({pack:e(j,{fields:[Y.packId],references:[j.id]}),instruction:e(n,{fields:[Y.instructionId],references:[n.id]})})),bd=i(je,({one:e})=>({instruction:e(n,{fields:[je.instructionId],references:[n.id]})})),Pd=i(r,({one:e,many:t})=>({parent:e(r,{fields:[r.parentId],references:[r.id]}),evals:t(M),evalRuns:t(E),benchmarks:t(ze),evalJobs:t(b),evalConversations:t(Se)})),Kd=i(M,({one:e,many:t})=>({evalTarget:e(r,{fields:[M.evalTargetId],references:[r.id]}),runs:t(E)})),Cd=i(E,({one:e})=>({eval:e(M,{fields:[E.evalId],references:[M.id]}),evalTarget:e(r,{fields:[E.evalTargetId],references:[r.id]})})),qd=i(ze,({one:e})=>({evalTarget:e(r,{fields:[ze.evalTargetId],references:[r.id]})})),Od=i(b,({one:e})=>({evalTarget:e(r,{fields:[b.evalTargetId],references:[r.id]})})),Md=i(Se,({one:e})=>({evalTarget:e(r,{fields:[Se.evalTargetId],references:[r.id]})})),Hd=i(X,({one:e})=>({session:e(a,{fields:[X.sessionId],references:[a.id]}),profile:e(o,{fields:[X.userId],references:[o.id]})})),Ld=i(te,({one:e,many:t})=>({target:e(r,{fields:[te.evalTargetId],references:[r.id]}),calls:t(_e)})),Ud=i(_e,({one:e})=>({study:e(te,{fields:[_e.studyId],references:[te.id]}),job:e(b,{fields:[_e.jobId],references:[b.id]})}));var at=0,os=0,dt=0,ns=0;var Bd=0;function Xo(){at++,at>os&&(os=at)}m(Xo,"trackDbOpStart");function Zo(){at>0&&at--}m(Zo,"trackDbOpEnd");function en(){dt++,dt>ns&&(ns=dt)}m(en,"trackHeavyDbOpStart");function tn(){dt>0&&dt--}m(tn,"trackHeavyDbOpEnd");function rs(){Bd++}m(rs,"recordQueryDeadline");var Gt,Ft,on=!1,Bt;var ss,$t,Vt;function ds(e){let t=process.env[e];if(!t)throw new Error(`Missing required env var: ${e}`);return t}m(ds,"getEnv");function us(){if(on)throw new Error("getDb() called after closeDb(): the connection pool is closed for shutdown. Stop issuing queries (timers/requests) before draining the pool.");if(!Gt){let e=process.env.PG_APPLICATION_NAME||"rulemetric",t=Number(process.env.PG_POOL_MAX)||3,d=Number(process.env.PG_CONNECT_TIMEOUT_S)||10,u=Number(process.env.PG_STATEMENT_TIMEOUT_MS)||0,_=Number(process.env.PG_IDLE_TIMEOUT)||5,x=Number(process.env.PG_KEEP_ALIVE_S)||60;Ft=as(ds("DATABASE_URL"),{prepare:!1,max:t,connect_timeout:d,idle_timeout:_,keep_alive:x,max_lifetime:300,connection:{application_name:e,...u>0?{statement_timeout:u}:{}}}),Gt=is(Ft,{schema:Ut})}return Gt}m(us,"getDb");function ls(){if(on)throw new Error("getHeavyDb() called after closeDb(): the connection pool is closed for shutdown. Stop issuing queries (timers/requests) before draining the pool.");if(!Vt){let e=(process.env.PG_APPLICATION_NAME||"rulemetric")+":heavy",t=Number(process.env.PG_HEAVY_POOL_MAX)||2;$t=as(ds("DATABASE_URL"),{prepare:!1,max:t,connect_timeout:Number(process.env.PG_CONNECT_TIMEOUT_S)||10,idle_timeout:Number(process.env.PG_IDLE_TIMEOUT)||5,keep_alive:Number(process.env.PG_KEEP_ALIVE_S)||60,max_lifetime:300,connection:{application_name:e}}),Vt=is($t,{schema:Ut})}return Vt}m(ls,"getHeavyDb");async function Gd(){if(Bt)return Bt;on=!0;let e=Ft,t=ss,d=$t;return Ft=void 0,Gt=void 0,ss=void 0,$t=void 0,Vt=void 0,Bt=Promise.allSettled([e?e.end({timeout:5}):Promise.resolve(),t?t.end({timeout:5}):Promise.resolve(),d?d.end({timeout:5}):Promise.resolve()]).then(()=>{}),Bt}m(Gd,"closeDb");var Vd=new Set(["CONNECT_TIMEOUT","ETIMEDOUT","ENOTFOUND","ECONNREFUSED","EAI_AGAIN"]);function cs(e){let t=e,d=t?.code??t?.cause?.code??t?.errno;return d!==void 0&&Vd.has(d)}m(cs,"isRetryableConnectError");var Fd=new Set(["CONNECTION_CLOSED","ECONNRESET","EPIPE"]);function ps(e){let t=e,d=t?.code??t?.cause?.code??t?.errno;return d!==void 0&&Fd.has(d)}m(ps,"isRetryableResetError");async function _s(e,t={}){let d=t.attempts??3,u=t.baseMs??100,_;for(let x=0;x<d;x++)try{return await e()}catch(A){_=A;let B=cs(A)||t.retryResets===!0&&ps(A);if(x===d-1||!B)throw A;await new Promise(oe=>setTimeout(oe,u*2**x))}throw _}m(_s,"withDbRetry");var Jt=class extends Error{static{m(this,"QueryDeadlineError")}code="QUERY_DEADLINE";constructor(t){super(`Query exceeded the client-side deadline of ${t}ms \u2014 the DB pool is likely saturated (acquire-wait) or holding a dead socket; failing fast to avoid pinning the caller. See client.ts.`),this.name="QueryDeadlineError"}};function ms(){let e=Number(process.env.PG_QUERY_DEADLINE_MS);return Number.isFinite(e)&&e>=0?e:2e4}m(ms,"queryDeadlineMs");function fs(){let e=Number(process.env.PG_HEAVY_QUERY_DEADLINE_MS);return Number.isFinite(e)&&e>=0?e:6e4}m(fs,"heavyQueryDeadlineMs");function $d(e,t,d=!0){let u,_=new Promise((x,A)=>{u=setTimeout(()=>{d&&rs(),A(new Jt(t))},t);let B=u;typeof B.unref=="function"&&B.unref()});return Promise.race([e,_]).finally(()=>clearTimeout(u))}m($d,"raceWithDeadline");var Ns=new Set(["select","selectDistinct","selectDistinctOn","insert","update","delete","execute","with","$count","refreshMaterializedView"]),xs=new Set(["select","selectDistinct","selectDistinctOn","$count"]);function nn(e,t=!1,d=0,u=!1){return e===null||typeof e!="object"&&typeof e!="function"?e:new Proxy(e,{get(_,x,A){if(x==="then"){let oe=Reflect.get(_,x,A);return typeof oe!="function"?oe:(vs,Is)=>{let ys=u?en:Xo,ws=u?tn:Zo;ys();let rn=_s(()=>new Promise((Ts,As)=>oe.call(_,Ts,As)),{retryResets:t});return(d>0?$d(rn,d,!u):rn).finally(ws).then(vs,Is)}}let B=Reflect.get(_,x,A);return typeof B=="function"?(...oe)=>nn(B.apply(_,oe),t,d,u):B}})}m(nn,"wrapBuilder");function hs(e,t=!1){let d=t?en:Xo,u=t?tn:Zo;d();try{return Promise.resolve(e()).finally(u)}catch(_){throw u(),_}}m(hs,"gaugeTransaction");var gs=new Proxy({},{get(e,t){let d=us(),u=d[t];if(typeof t=="string"&&Ns.has(t)&&typeof u=="function"){let _=xs.has(t),x=ms();return(...A)=>nn(u.apply(d,A),_,x)}return t==="transaction"&&typeof u=="function"?(..._)=>hs(()=>u.apply(d,_)):u}}),Jd=new Proxy({},{get(e,t){let d=ls(),u=d[t];if(typeof t=="string"&&Ns.has(t)&&typeof u=="function"){let _=xs.has(t);return(...x)=>nn(u.apply(d,x),_,fs(),!0)}return t==="transaction"&&typeof u=="function"?(..._)=>hs(()=>u.apply(d,_),!0):u}});export{an as a,us as b,Gd as c};
@@ -1 +1 @@
1
- import{a as E}from"./chunk-DQYYHX6K.js";import{a as I}from"./chunk-RBSEE2Z6.js";import{a as w}from"./chunk-M7QSC64D.js";import{c as v,e as h}from"./chunk-H6FVXVGG.js";import{b as R}from"./chunk-SWSOEYC7.js";import{e as m}from"./chunk-76UKAFNM.js";import{a as d}from"./chunk-ZLLER3HP.js";var T=6e5;async function P(e,$){let i=d(n=>$?.logger?.info?.(n)??console.log(n),"log"),{evalTargetId:r}=e,k=e.measurement?v(e):{},o=await m(`/api/eval-targets/${r}/judge-calibration`),l=!e.measurement||o.methodology?.measurement?.engine===e.measurement.engine&&o.methodology.measurement.model===e.measurement.model&&o.methodology.current===R(e.measurement.engine),a=I({powered:l&&o.powerCheck.powered,mde:l?o.powerCheck.mde??Number.POSITIVE_INFINITY:Number.POSITIVE_INFINITY},(l?o.caseDiscrimination:void 0)??{total:0,discriminating:0,nonDiscriminating:0,unpaired:0},{runsCompleted:0,maxRuns:e.maxRuns??24,batchesRun:0,maxBatches:1});if(a.action==="stop")return i(`[cron_eval_autorun] ${r}: ${a.reason}`),{skipped:a.code,reason:a.reason};let t=await m(`/api/eval-targets/${r}`);if(t.metadata?.autoRunEnabled===!1)return{skipped:"paused",reason:"Nightly measurement is off for this target."};let c=w(t);if(c)return i(`[cron_eval_autorun] ${r}: ${c.reason}`),c;let p=(await m(`/api/eval-targets/${r}/evals`)).filter(n=>!n.retiredAt);if(p.length===0)return{skipped:"no-live-cases"};let{completed:f,failed:b,results:N}=await h({cases:E(p,e.maxRuns??12),targetContent:t.content,concurrency:2,runNumber:Math.floor(Date.now()/1e3),opts:{targetId:r,targetVersion:t.version??1,iteration:1,timeout:e.timeout??T,model:e.model,graderModel:e.graderModel,graderEngine:e.graderEngine,...k,skipGrading:!1,targetType:t.type,targetName:t.name},onLog:i}),g={};for(let n of N){if(n.status!=="failed")continue;let s=n.failure?.kind??"unknown";g[s]=(g[s]??0)+1}let u=Object.entries(g).sort(([,n],[,s])=>s-n).map(([n,s])=>`${n}x${s}`).join(", ");return i(`[cron_eval_autorun] ${t.name}: ${f} completed, ${b} failed`+(u===""?"":` (${u})`)),{ranRuns:f,failedRuns:b,...u===""?{}:{failures:u},reason:a.reason}}d(P,"cronEvalAutorun");export{P as a};
1
+ import{a as E}from"./chunk-DQYYHX6K.js";import{a as I}from"./chunk-RBSEE2Z6.js";import{a as w}from"./chunk-M7QSC64D.js";import{c as v,e as h}from"./chunk-FADINV4H.js";import{b as R}from"./chunk-SWSOEYC7.js";import{e as m}from"./chunk-GIXHG5FK.js";import{a as d}from"./chunk-ZLLER3HP.js";var T=6e5;async function P(e,$){let i=d(n=>$?.logger?.info?.(n)??console.log(n),"log"),{evalTargetId:r}=e,k=e.measurement?v(e):{},o=await m(`/api/eval-targets/${r}/judge-calibration`),l=!e.measurement||o.methodology?.measurement?.engine===e.measurement.engine&&o.methodology.measurement.model===e.measurement.model&&o.methodology.current===R(e.measurement.engine),a=I({powered:l&&o.powerCheck.powered,mde:l?o.powerCheck.mde??Number.POSITIVE_INFINITY:Number.POSITIVE_INFINITY},(l?o.caseDiscrimination:void 0)??{total:0,discriminating:0,nonDiscriminating:0,unpaired:0},{runsCompleted:0,maxRuns:e.maxRuns??24,batchesRun:0,maxBatches:1});if(a.action==="stop")return i(`[cron_eval_autorun] ${r}: ${a.reason}`),{skipped:a.code,reason:a.reason};let t=await m(`/api/eval-targets/${r}`);if(t.metadata?.autoRunEnabled===!1)return{skipped:"paused",reason:"Nightly measurement is off for this target."};let c=w(t);if(c)return i(`[cron_eval_autorun] ${r}: ${c.reason}`),c;let p=(await m(`/api/eval-targets/${r}/evals`)).filter(n=>!n.retiredAt);if(p.length===0)return{skipped:"no-live-cases"};let{completed:f,failed:b,results:N}=await h({cases:E(p,e.maxRuns??12),targetContent:t.content,concurrency:2,runNumber:Math.floor(Date.now()/1e3),opts:{targetId:r,targetVersion:t.version??1,iteration:1,timeout:e.timeout??T,model:e.model,graderModel:e.graderModel,graderEngine:e.graderEngine,...k,skipGrading:!1,targetType:t.type,targetName:t.name},onLog:i}),g={};for(let n of N){if(n.status!=="failed")continue;let s=n.failure?.kind??"unknown";g[s]=(g[s]??0)+1}let u=Object.entries(g).sort(([,n],[,s])=>s-n).map(([n,s])=>`${n}x${s}`).join(", ");return i(`[cron_eval_autorun] ${t.name}: ${f} completed, ${b} failed`+(u===""?"":` (${u})`)),{ranRuns:f,failedRuns:b,...u===""?{}:{failures:u},reason:a.reason}}d(P,"cronEvalAutorun");export{P as a};
@@ -1,4 +1,4 @@
1
- import{e as b,g as y}from"./chunk-N4YPDZJF.js";import{e as M,f as w}from"./chunk-76UKAFNM.js";import{a as u}from"./chunk-ZLLER3HP.js";var $={anthropic:["https://platform.claude.com/docs/en/about-claude/pricing.md"],openai:["https://platform.openai.com/docs/pricing"]},R=.7,v=16e3,x=["You extract LLM API pricing from a provider pricing page.","You will be given the page text in <data> tags and, in this system prompt,","a list of model ids to find. For EACH requested model id, return its","published USD price per 1,000,000 tokens.","","Rules:","- Only report a model if you can find its rate ON THE PAGE. If it is not on"," the page, set found=false and omit the numbers \u2014 never guess from memory.","- inputPerM and outputPerM are the standard (non-batch, non-priority) rates.","- cacheReadPerM: the cached/discounted-input rate if published, else omit.","- For Anthropic models ONLY, if cache-write rates are not explicitly listed,"," compute them as cacheWrite5mPerM = inputPerM * 1.25 and"," cacheWrite1hPerM = inputPerM * 2.0. For all other providers, omit them.","- confidence is 0..1: how sure you are the numbers are correct for THIS id.","- contextWindow in tokens if stated, else omit.","","Respond with ONLY a JSON object of the form:",'{"rates":[{"modelId":"...","found":true,"confidence":0.9,"inputPerM":5,"outputPerM":25,"cacheReadPerM":0.5,"contextWindow":1000000}]}'].join(`
1
+ import{e as b,g as y}from"./chunk-XCH4HPEZ.js";import{e as M,f as w}from"./chunk-GIXHG5FK.js";import{a as u}from"./chunk-ZLLER3HP.js";var $={anthropic:["https://platform.claude.com/docs/en/about-claude/pricing.md"],openai:["https://platform.openai.com/docs/pricing"]},R=.7,v=16e3,x=["You extract LLM API pricing from a provider pricing page.","You will be given the page text in <data> tags and, in this system prompt,","a list of model ids to find. For EACH requested model id, return its","published USD price per 1,000,000 tokens.","","Rules:","- Only report a model if you can find its rate ON THE PAGE. If it is not on"," the page, set found=false and omit the numbers \u2014 never guess from memory.","- inputPerM and outputPerM are the standard (non-batch, non-priority) rates.","- cacheReadPerM: the cached/discounted-input rate if published, else omit.","- For Anthropic models ONLY, if cache-write rates are not explicitly listed,"," compute them as cacheWrite5mPerM = inputPerM * 1.25 and"," cacheWrite1hPerM = inputPerM * 2.0. For all other providers, omit them.","- confidence is 0..1: how sure you are the numbers are correct for THIS id.","- contextWindow in tokens if stated, else omit.","","Respond with ONLY a JSON object of the form:",'{"rates":[{"modelId":"...","found":true,"confidence":0.9,"inputPerM":5,"outputPerM":25,"cacheReadPerM":0.5,"contextWindow":1000000}]}'].join(`
2
2
  `);async function C(f){try{let n=await fetch(f,{headers:{accept:"text/plain, text/markdown, text/html"}});if(!n.ok)return null;let i=await n.text();return i.length>v?i.slice(0,v):i}catch{return null}}u(C,"fetchPage");var L=u(async(f,n)=>{let i=await M("/api/pricing/coverage"),I=[...i.unpriced,...i.stale],m=new Map;for(let r of I)m.set(`${r.provider}::${r.modelId}`,r);let a=[...m.values()];if(a.length===0)return n.logger.info("[cron-refresh-pricing] coverage clean \u2014 nothing unpriced or stale"),{status:"clean",checked:i.unpriced.length+i.stale.length};if(b()==="none")return n.logger.warn(`[cron-refresh-pricing] ${a.length} model(s) need pricing but no LLM backend (install the claude CLI or set ANTHROPIC_API_KEY) \u2014 skipping`),{status:"no-llm",pending:a.length};let d=new Map;for(let r of a){let o=d.get(r.provider)??[];o.push(r.modelId),d.set(r.provider,o)}let t={written:0,unchanged:0,flagged:0,rejected:0,skipped:0},c=[];for(let[r,o]of d){let h=$[r];if(!h){n.logger.warn(`[cron-refresh-pricing] no pricing source configured for provider '${r}' (${o.length} model(s)) \u2014 skipping`),t.skipped+=o.length;continue}let p="",l="";for(let e of h){let s=await C(e);s&&(p+=`
3
3
 
4
4
  === ${e} ===
@@ -1 +1 @@
1
- import{a as d,d as m}from"./chunk-76UKAFNM.js";import{a as c,l as a}from"./chunk-PZNWH4VQ.js";import{a as o}from"./chunk-ZLLER3HP.js";import{createHash as g,randomUUID as v}from"node:crypto";import{hostname as y,platform as p}from"node:os";import{existsSync as P,mkdirSync as _,readFileSync as h,writeFileSync as R}from"node:fs";import{join as E}from"node:path";var O="device-id";function u(){let e=o(t=>t==="1"||t==="true","off");return e(process.env.RULEMETRIC_NO_TELEMETRY)||e(process.env.DO_NOT_TRACK)}o(u,"telemetryDisabled");function l(){let e=a(),t=E(e,O);try{if(P(t)){let r=h(t,"utf-8").trim();if(r)return r}}catch{}let n=g("sha256").update(`${v()}:${y()}`).digest("hex").slice(0,32);try{_(e,{recursive:!0}),R(t,n,{mode:384})}catch{}return n}o(l,"getDeviceId");async function U(e,t={},n){if(!u())try{await m("/api/telemetry/cli-events",{method:"POST",body:{event:e,deviceId:l(),cliVersion:n,os:p(),props:t},timeoutMs:5e3})}catch{}}o(U,"emitSetupEvent");async function w(e){if(u())return;let n=`${process.env.RULEMETRIC_API_URL??c().apiUrl??d}/api/telemetry/cli-error`,r=process.env.HTTPS_PROXY,s=process.env.HTTP_PROXY,T=r!==void 0||s!==void 0;delete process.env.HTTPS_PROXY,delete process.env.HTTP_PROXY;let i=new AbortController,f=setTimeout(()=>i.abort(),4e3);try{await globalThis.fetch(n,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":`rulemetric-cli/${e.cliVersion??"unknown"}`},body:JSON.stringify({event:e.event??"onboarding_error",deviceId:l(),command:e.command,statusCode:e.statusCode,message:e.message?e.message.slice(0,500):void 0,cliVersion:e.cliVersion,os:p(),nodeVersion:process.version,proxied:T,props:e.props}),signal:i.signal})}catch{}finally{clearTimeout(f),r!==void 0&&(process.env.HTTPS_PROXY=r),s!==void 0&&(process.env.HTTP_PROXY=s)}}o(w,"emitErrorBeacon");export{u as a,l as b,U as c,w as d};
1
+ import{a as d,d as m}from"./chunk-GIXHG5FK.js";import{a as c,l as a}from"./chunk-PZNWH4VQ.js";import{a as o}from"./chunk-ZLLER3HP.js";import{createHash as g,randomUUID as v}from"node:crypto";import{hostname as y,platform as p}from"node:os";import{existsSync as P,mkdirSync as _,readFileSync as h,writeFileSync as R}from"node:fs";import{join as E}from"node:path";var O="device-id";function u(){let e=o(t=>t==="1"||t==="true","off");return e(process.env.RULEMETRIC_NO_TELEMETRY)||e(process.env.DO_NOT_TRACK)}o(u,"telemetryDisabled");function l(){let e=a(),t=E(e,O);try{if(P(t)){let r=h(t,"utf-8").trim();if(r)return r}}catch{}let n=g("sha256").update(`${v()}:${y()}`).digest("hex").slice(0,32);try{_(e,{recursive:!0}),R(t,n,{mode:384})}catch{}return n}o(l,"getDeviceId");async function U(e,t={},n){if(!u())try{await m("/api/telemetry/cli-events",{method:"POST",body:{event:e,deviceId:l(),cliVersion:n,os:p(),props:t},timeoutMs:5e3})}catch{}}o(U,"emitSetupEvent");async function w(e){if(u())return;let n=`${process.env.RULEMETRIC_API_URL??c().apiUrl??d}/api/telemetry/cli-error`,r=process.env.HTTPS_PROXY,s=process.env.HTTP_PROXY,T=r!==void 0||s!==void 0;delete process.env.HTTPS_PROXY,delete process.env.HTTP_PROXY;let i=new AbortController,f=setTimeout(()=>i.abort(),4e3);try{await globalThis.fetch(n,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":`rulemetric-cli/${e.cliVersion??"unknown"}`},body:JSON.stringify({event:e.event??"onboarding_error",deviceId:l(),command:e.command,statusCode:e.statusCode,message:e.message?e.message.slice(0,500):void 0,cliVersion:e.cliVersion,os:p(),nodeVersion:process.version,proxied:T,props:e.props}),signal:i.signal})}catch{}finally{clearTimeout(f),r!==void 0&&(process.env.HTTPS_PROXY=r),s!==void 0&&(process.env.HTTP_PROXY=s)}}o(w,"emitErrorBeacon");export{u as a,l as b,U as c,w as d};
@@ -0,0 +1,15 @@
1
+ import{a as M}from"./chunk-5RBLIVBF.js";import{c as q}from"./chunk-GLBWNB2N.js";import{a as K,b as Y}from"./chunk-CQD2R3BA.js";import{a as A,d as N}from"./chunk-3UKZJAFS.js";import{a as j,b as k,c as V,d as D}from"./chunk-77FH6UZP.js";import{a as Z}from"./chunk-KE5K3F7J.js";import{b as W,e as B,g as T}from"./chunk-XCH4HPEZ.js";import{e as h,f as U,h as m}from"./chunk-GIXHG5FK.js";import{a as L,b as H}from"./chunk-X6CF5KTW.js";import{a as f}from"./chunk-ZLLER3HP.js";var Q=f((l,{limit:a,sort:n,eventTypes:s})=>h(`/api/sessions/${l}/events?limit=${a}&sort=${n}&eventType=${encodeURIComponent(s.join(","))}&hasContent=true`),"fetchTranscriptTurns");async function ms(l,a){let{mirrorId:n,projectPath:s,projectId:r,config:u}=l,e=f(t=>a.logger.info(t),"log");if(u?.sessionId)return es({mirrorId:n,sessionId:u.sessionId},e);e(`Processing insights job ${n}...`),await m(`/api/insights-jobs/${n}/progress`,{status:"running",progress:{step:"reading_data"}});try{let{repaired:t}=await U("/api/sessions/repair-analyzed-at",{});t>0&&e(` Repaired analyzed_at on ${t} orphan session(s).`)}catch(t){e(` Warning: analyzed_at repair failed: ${t instanceof Error?t.message:String(t)}`)}let p=20,C=200,z=15*6e4,F=3,E=Date.now()+z,I=B()==="none"?"no-llm-backend":null;if(I&&a.logger.warn?.("[process-insights] no LLM backend (no claude/codex CLI and no ANTHROPIC_API_KEY) \u2014 facet grading SKIPPED for this run; the summary below is computed from already-graded sessions only"),!I){let t=0,i=0;try{for(;t<C&&Date.now()<E;){let c=await h(`/api/sessions?needsFacets=true&graderVersion=${2}&limit=${p}&offset=${i}`);if(c.length===0)break;e(` Generating facets for ${c.length} un-analyzed sessions (drained ${t} so far)...`);for(let b=0;b<c.length&&!(t>=C||Date.now()>=E);b+=F){let R=c.slice(b,b+F);await Promise.all(R.map(async g=>{if(!(t>=C||Date.now()>=E))try{let d=await N(ss=>Q(g.id,ss));if(d.turnCount<2){t++,i++;return}let O=await T(D,d.text,4096);O&&typeof O.outcome=="string"?(await m(`/api/sessions/${g.id}/enrich`,{analysis:{source:"generated_facets",...O,graderVersion:2},...g.eventCount!=null?{analyzedEventCount:g.eventCount}:{},analyzedTurnCount:d.turnCount}),e(` Generated facets for session ${g.id} (${g.tool}, ${d.turnCount} turns)`)):i++,t++}catch(d){e(` Failed to generate facets for session ${g.id}: ${d instanceof Error?d.message:String(d)}`),t++,i++}}))}if(c.length<p)break}}catch(c){e(` Warning: facet generation failed after ${t} sessions: ${c instanceof Error?c.message:String(c)}`)}if(t>0){let c=Date.now()>=E?`time budget (${Math.round(z/6e4)}m)`:t>=C?`hard cap (${C})`:"queue empty";e(` Facet drain stopped on ${c} after ${t} session(s); the rest resume next run.`)}}let _=await ns(s,r);if(!_)throw new M("No session data found \u2014 ensure sessions are captured and enriched.");e(` Found ${_.stats.sessions} sessions, generating recommendations...`);let y=await Y({projectId:r,projectPath:s},h);_.summary+=`
2
+
3
+ ${y.text}`,e(` Session evidence: ${y.sessionIds.length} usable, ${y.failedSessionIds.length} unavailable`);let S=await ts(s,e);S&&e(` Generator memory: ${S.split(`
4
+ `).length} lines of prior-advice context`);let o={},$=[],w=k.length+1;for(let t=0;t<k.length;t++){let i=k[t];e(` [${t+1}/${w}] Generating ${i.name}...`);try{await m(`/api/insights-jobs/${n}/progress`,{status:"running",progress:{step:i.name,current:t+1,total:w,partial:{...o}}})}catch(d){e(` Warning: progress update failed for ${i.name}: ${d instanceof Error?d.message:String(d)}`)}e(` Running LLM prompt for ${i.name}...`);let c=i.usesGeneratorMemory&&S?`${_.summary}
5
+ ${S}`:_.summary,b=Date.now(),R=await T(i.prompt,c,i.maxTokens,{timeoutMs:i.timeoutMs}),g=Date.now()-b;R?(o[i.name]=R,e(` Got result for ${i.name} (${Math.round(g/1e3)}s)`)):($.push(i.name),e(` No result for ${i.name} after ${Math.round(g/1e3)}s (budget ${Math.round((i.timeoutMs??12e4)/1e3)}s) \u2014 section DROPPED`))}e(` [${w}/${w}] Generating at_a_glance...`),await m(`/api/insights-jobs/${n}/progress`,{status:"running",progress:{step:"at_a_glance",current:w,total:w,partial:{...o}}});let X=[_.summary,o.what_works?`
6
+ ## What Works
7
+ ${JSON.stringify(o.what_works)}`:"",o.friction_analysis?`
8
+ ## Friction
9
+ ${JSON.stringify(o.friction_analysis)}`:"",o.suggestions?`
10
+ ## Suggestions
11
+ ${JSON.stringify(o.suggestions)}`:"",o.on_the_horizon?`
12
+ ## On the Horizon
13
+ ${JSON.stringify(o.on_the_horizon)}`:""].join(`
14
+ `),x=await T(V,X,8192);x&&(o.at_a_glance=x),e(" Uploading results..."),e(` Done! Recommendations generated for job ${n}`),H(o);let v=K(o.recommendation_candidates,y.sessionIds);o.recommendation_candidates=v.candidates;let P=o.suggestions;if(P&&typeof P=="object"&&!Array.isArray(P)){let t=P;t.recommendation_candidates=v.candidates,t.claude_md_additions=[],t.features_to_try=[]}L(o);let J={recommendations:o,sessionEvidence:{sessionIds:y.sessionIds,failedSessionIds:y.failedSessionIds,emptySessionIds:y.emptySessionIds,selection:"recent-8-head-tail",rejectedCandidateTitles:v.rejected},...$.length>0?{sectionsFailed:$}:{},...I?{facetsSkipped:I}:{}};return $.length>0&&e(` \u26A0 ${$.length} section(s) produced nothing: ${$.join(", ")}`),await m(`/api/insights-jobs/${n}/state`,{result:J}).catch(t=>{e(`result persist failed: ${t instanceof Error?t.message:String(t)}`)}),await Z(o,s,e),J}f(ms,"processInsights");async function es(l,a){let{mirrorId:n,sessionId:s}=l;a(`Analyzing session ${s} via tool CLI...`),await m(`/api/insights-jobs/${n}/progress`,{status:"running",progress:{step:"fetching_session"}});let r=await h(`/api/sessions/${s}`);if(r.analysis&&r.analysis.source==="session_analysis")return a(` Session ${s} already analyzed \u2014 skipping (idempotency guard)`),{sessionId:s,skipped:!0,reason:"already_analyzed"};let u=await N(p=>Q(s,p));if(u.turnCount<2)throw new M("Session has too few conversation turns to analyze");await m(`/api/insights-jobs/${n}/progress`,{status:"running",progress:{step:"running_analysis",tool:r.tool}});let e=await W(r.tool,D,u.text);if(!e.ok)throw new Error(`Analysis failed \u2014 ${e.reason}`);return await m(`/api/sessions/${s}/enrich`,{analysis:{source:"session_analysis",tool:r.tool,...e.value,graderVersion:2},...r.eventCount!=null?{analyzedEventCount:r.eventCount}:{},analyzedTurnCount:u.turnCount}),a(` Session ${s} analyzed via ${r.tool}`),{sessionId:s,tool:r.tool,facets:e.value}}f(es,"processSessionAnalysisInline");async function ts(l,a,n=h,s=q){let{asks:r,omitted:u}=s(l);try{let e=await n(`/api/insights/recommendations/history?projectPath=${encodeURIComponent(l??"")}`);return!e||!Array.isArray(e.dismissed)||!Array.isArray(e.repeated)?j({dismissed:[],repeated:[],installed:r,installedOmitted:u}):j({...e,installed:r,installedOmitted:u})}catch(e){return a(` Warning: generator memory unavailable (${e instanceof Error?e.message:String(e)}) \u2014 generating without it`),j({dismissed:[],repeated:[],installed:r,installedOmitted:u})}}f(ts,"fetchGeneratorMemory");async function ns(l,a){try{let n=new URLSearchParams;a?n.set("projectId",a):l&&n.set("projectPath",l);let s=await h(`/api/insights/compute?${n}`);if(!s||s.total_sessions===0)return null;let r=Object.entries(s.tool_counts??{}).sort((e,p)=>p[1]-e[1]).slice(0,10).map(([e,p])=>`${e}: ${p}`).join(", ");return{summary:[`Sessions: ${s.total_sessions}, Messages: ${s.total_messages}, Session-hours: ${Math.round(s.total_duration_hours)} (sum of per-session spans across ${s.sessions_with_meta} measured sessions; concurrent sessions counted separately, so this exceeds elapsed time)`,`Top tools: ${r}`,s.goal_categories&&Object.keys(s.goal_categories).length>0?`Goals: ${JSON.stringify(s.goal_categories)}`:"",s.friction&&Object.keys(s.friction).length>0?`Friction: ${JSON.stringify(s.friction)}`:"",s.outcomes&&Object.keys(s.outcomes).length>0?`Outcomes: ${JSON.stringify(s.outcomes)}`:"",s.projects&&Object.keys(s.projects).length>0?`Projects: ${JSON.stringify(s.projects)}`:""].filter(Boolean).join(`
15
+ `),stats:{sessions:s.total_sessions,totalMessages:s.total_messages,totalSessionHours:s.total_duration_hours,measuredSessions:s.sessions_with_meta,toolCounts:s.tool_counts,goalCounts:s.goal_categories,frictionCounts:s.friction}}}catch(n){throw new G(n instanceof Error?n.message:String(n))}}f(ns,"buildDataSummaryFromApi");var G=class extends Error{static{f(this,"InsightsSummaryUnavailableError")}constructor(a){super(`Could not read session summary (retryable): ${a}`),this.name="InsightsSummaryUnavailableError"}};export{ms as a,ts as b};
@@ -1,4 +1,4 @@
1
- import{a as c,c as d}from"./chunk-IZTIYR5Q.js";import{d as u}from"./chunk-FKTT7A4H.js";import{a}from"./chunk-VIFOLTZT.js";import{a as n}from"./chunk-4FJYVYCU.js";import{b as i}from"./chunk-76UKAFNM.js";import{g as r}from"./chunk-PZNWH4VQ.js";import{a as s}from"./chunk-ZLLER3HP.js";import{Command as f,Flags as h}from"@oclif/core";function p(t){return t instanceof i?t.statusCode>=500||t.statusCode===408||t.statusCode===0:/fetch failed|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|bad gateway|timed out/i.test(t.message??"")}s(p,"isAvailabilityError");var m=class extends f{static{s(this,"BaseCommand")}static baseFlags={"api-url":h.string({description:"Override API base URL",env:"RULEMETRIC_API_URL",hidden:!0})};async init(){await super.init();let{flags:e}=await this.parse(this.constructor);e["api-url"]&&(process.env.RULEMETRIC_API_URL=e["api-url"]);let o=d(this.config.version);o&&!this.argv.includes("--quiet")&&!process.env.RULEMETRIC_QUIET&&process.stderr.write(`
1
+ import{a as c,c as d}from"./chunk-IZTIYR5Q.js";import{d as u}from"./chunk-WL5ZWQAS.js";import{a}from"./chunk-KEVDLLHT.js";import{a as n}from"./chunk-DX6IPDED.js";import{b as i}from"./chunk-GIXHG5FK.js";import{g as r}from"./chunk-PZNWH4VQ.js";import{a as s}from"./chunk-ZLLER3HP.js";import{Command as f,Flags as h}from"@oclif/core";function p(t){return t instanceof i?t.statusCode>=500||t.statusCode===408||t.statusCode===0:/fetch failed|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|bad gateway|timed out/i.test(t.message??"")}s(p,"isAvailabilityError");var m=class extends f{static{s(this,"BaseCommand")}static baseFlags={"api-url":h.string({description:"Override API base URL",env:"RULEMETRIC_API_URL",hidden:!0})};async init(){await super.init();let{flags:e}=await this.parse(this.constructor);e["api-url"]&&(process.env.RULEMETRIC_API_URL=e["api-url"]);let o=d(this.config.version);o&&!this.argv.includes("--quiet")&&!process.env.RULEMETRIC_QUIET&&process.stderr.write(`
2
2
  ${o}
3
3
 
4
4
  `),c();try{await a()}catch{}}requireAuth(){r()||this.error("Not logged in. Run `rulemetric auth login` to authenticate."),n()}async catch(e){throw p(e)&&await u({command:this.id,statusCode:e instanceof i?e.statusCode:void 0,message:e.message,cliVersion:this.config.version}),e instanceof i&&(e.statusCode===401&&this.error("Session expired. Run `rulemetric auth login` to re-authenticate."),this.error(e.message)),(e.message?.includes("fetch failed")||e.message?.includes("ECONNREFUSED"))&&this.error("Could not connect to the API server. Is it running?"),e}};export{m as a};
@@ -36,13 +36,13 @@ Only include instructions with a relevance score >= ${.5}. Order by score descen
36
36
  Name: ${e.name}
37
37
  Description: ${e.description}
38
38
  Tags: ${e.tags.join(", ")}
39
- Preview: ${e.contentPreview}`.length+2}i(le,"renderedSize");var H=["Added","Changed","Fixed","Removed","Deprecated","Security"],ue=/^##\s+\[([^\]]+)\](?:\s*[-–]\s*(\d{4}-\d{2}-\d{2}))?\s*$/,me=/^###\s+(.+?)\s*$/,de=/^[-*]\s+(.*\S)\s*$/,pe=/^ {2,}(\S.*)$/;function fe(e){let t=e.split(/\r?\n/),n=[],o=null,r=null,s=null;for(let a of t){let c=a.match(ue);if(c){o&&n.push(o);let m=c[1].trim();o={version:m,date:c[2]??null,unreleased:m.toLowerCase()==="unreleased",sections:{}},r=null,s=null;continue}if(!o)continue;let l=a.match(me);if(l){let m=l[1].trim();H.includes(m)?(r=m,o.sections[r]||(o.sections[r]=[]),s=o.sections[r]):(r=null,s=null);continue}if(!r||!s)continue;let u=a.match(de);if(u){s.push(u[1]);continue}let f=a.match(pe);if(f&&s.length>0){s[s.length-1]+=" "+f[1].trim();continue}}return o&&n.push(o),{entries:n}}i(fe,"parseChangelog");function he(e){return e.entries.filter(t=>t.unreleased?!1:Object.values(t.sections).some(n=>n&&n.length>0))}i(he,"announceableEntries");function S(e){let t=/^(#{1,6})\s+/.exec(e);return t?t[1].length:0}i(S,"headingLevel");function B(e){return e.replace(/^#{1,6}\s+/,"").replace(/[`*_~]/g,"").trim().toLowerCase()}i(B,"normaliseHeading");function ge(e,t){let n=B(t);if(n.length===0)return{content:e,removed:!1,removedText:null,reason:"not-found"};let o=e.split(`
40
- `),r=[];for(let m=0;m<o.length;m+=1)S(o[m])>0&&B(o[m])===n&&r.push(m);if(r.length===0)return{content:e,removed:!1,removedText:null,reason:"not-found"};if(r.length>1)return{content:e,removed:!1,removedText:null,reason:"ambiguous"};let s=r[0],a=S(o[s]),c=o.length;for(let m=s+1;m<o.length;m+=1){let E=S(o[m]);if(E>0&&E<=a){c=m;break}}let l=o.slice(s,c).join(`
39
+ Preview: ${e.contentPreview}`.length+2}i(le,"renderedSize");var H=["Added","Changed","Fixed","Removed","Deprecated","Security"],ue=/^##\s+\[([^\]]+)\](?:\s*[-–]\s*(\d{4}-\d{2}-\d{2}))?\s*$/,me=/^###\s+(.+?)\s*$/,de=/^[-*]\s+(.*\S)\s*$/,pe=/^ {2,}(\S.*)$/;function fe(e){let t=e.split(/\r?\n/),n=[],o=null,r=null,s=null;for(let a of t){let c=a.match(ue);if(c){o&&n.push(o);let m=c[1].trim();o={version:m,date:c[2]??null,unreleased:m.toLowerCase()==="unreleased",sections:{}},r=null,s=null;continue}if(!o)continue;let l=a.match(me);if(l){let m=l[1].trim();H.includes(m)?(r=m,o.sections[r]||(o.sections[r]=[]),s=o.sections[r]):(r=null,s=null);continue}if(!r||!s)continue;let u=a.match(de);if(u){s.push(u[1]);continue}let f=a.match(pe);if(f&&s.length>0){s[s.length-1]+=" "+f[1].trim();continue}}return o&&n.push(o),{entries:n}}i(fe,"parseChangelog");function he(e){return e.entries.filter(t=>t.unreleased?!1:Object.values(t.sections).some(n=>n&&n.length>0))}i(he,"announceableEntries");function E(e){let t=/^(#{1,6})\s+/.exec(e);return t?t[1].length:0}i(E,"headingLevel");function B(e){return e.replace(/^#{1,6}\s+/,"").replace(/[`*_~]/g,"").trim().toLowerCase()}i(B,"normaliseHeading");function ge(e,t){let n=B(t);if(n.length===0)return{content:e,removed:!1,removedText:null,reason:"not-found"};let o=e.split(`
40
+ `),r=[];for(let m=0;m<o.length;m+=1)E(o[m])>0&&B(o[m])===n&&r.push(m);if(r.length===0)return{content:e,removed:!1,removedText:null,reason:"not-found"};if(r.length>1)return{content:e,removed:!1,removedText:null,reason:"ambiguous"};let s=r[0],a=E(o[s]),c=o.length;for(let m=s+1;m<o.length;m+=1){let v=E(o[m]);if(v>0&&v<=a){c=m;break}}let l=o.slice(s,c).join(`
41
41
  `),u=[...o.slice(0,s),...o.slice(c)];return u.join("").trim().length===0?{content:e,removed:!1,removedText:null,reason:"would-empty-file"}:{content:u.join(`
42
42
  `).replace(/\n{3,}/g,`
43
43
 
44
44
  `),removed:!0,removedText:l}}i(ge,"removeMarkdownSection");function ye(e,t){let n=t.trim();if(n.length===0)return{content:e,removed:!1,removedText:null,reason:"not-found"};let o=e.indexOf(n);if(o===-1)return{content:e,removed:!1,removedText:null,reason:"not-found"};if(e.indexOf(n,o+1)!==-1)return{content:e,removed:!1,removedText:null,reason:"ambiguous"};let r=(e.slice(0,o)+e.slice(o+n.length)).replace(/\n{3,}/g,`
45
45
 
46
- `);return r.trim().length===0?{content:e,removed:!1,removedText:null,reason:"would-empty-file"}:{content:r,removed:!0,removedText:n}}i(ye,"removeExactBlock");var U=["HTTPS_PROXY","HTTP_PROXY","NODE_EXTRA_CA_CERTS"];function xe(e,t){if(!e||typeof e!="object")return{value:e,removed:!1,removedDescriptions:[],reason:"not-found"};let n=structuredClone(e);if(!n.hooks)return{value:n,removed:!1,removedDescriptions:[],reason:"not-found"};let o=[];for(let[r,s]of Object.entries(n.hooks)){if(!Array.isArray(s))continue;let a=s.filter(c=>{let l=(c.hooks??[]).some(u=>typeof u.command=="string"&&u.command.includes(t));return l&&o.push(`${r}: ${c.matcher??"*"} \u2192 ${(c.hooks??[]).map(u=>u.command).join(", ")}`),!l});a.length===0?delete n.hooks[r]:n.hooks[r]=a}return Object.keys(n.hooks).length===0&&delete n.hooks,{value:n,removed:o.length>0,removedDescriptions:o,...o.length===0?{reason:"not-found"}:{}}}i(xe,"removeHookByCommand");function _e(e,t){if(!e||typeof e!="object")return{value:e,removed:!1,removedDescriptions:[],reason:"not-found"};let n=structuredClone(e);return!n.mcpServers||!(t in n.mcpServers)?{value:n,removed:!1,removedDescriptions:[],reason:"not-found"}:(delete n.mcpServers[t],Object.keys(n.mcpServers).length===0&&delete n.mcpServers,{value:n,removed:!0,removedDescriptions:[`mcpServers.${t}`]})}i(_e,"removeMcpServer");function v(e){if(!e||typeof e!="object")return[];let t=e.env;return t?U.filter(n=>n in t):[]}i(v,"protectedEnvKeysPresent");function Ee(e,t){let n=v(e),o=new Set(v(t));return n.filter(r=>!o.has(r))}i(Ee,"lostProtectedEnvKeys");function Se(e,t){let n=`HTTP ${e}`;if(!t||typeof t!="object")return{message:n};let o=t,r=typeof o.error=="string"&&o.error?o.error:o.error?JSON.stringify(o.error):n,s=typeof o.code=="string"&&o.code?o.code:void 0;return s?{message:r,code:s}:{message:r}}i(Se,"parseApiError");var T=["inside","outside"];function y(e){return e.trim().toLowerCase()}i(y,"normalizeDependencyKey");function ve(e){let t=[];if(T.includes(e.boundaryClass)||t.push({field:"boundaryClass",message:`must be one of ${T.join(" | ")}`}),!Array.isArray(e.targets)||e.targets.length===0)t.push({field:"targets",message:"a proposal that cannot name the paths it writes cannot be applied"});else{for(let r of e.targets)if(typeof r!="string"||r.trim().length===0){t.push({field:"targets",message:"target paths must be non-empty"});break}let n=e.targets.filter(r=>typeof r=="string"&&(r.startsWith("/")||/^[A-Za-z]:[\\/]/.test(r)));n.length>0&&t.push({field:"targets",message:`targets must be project-relative (absolute: ${n.join(", ")})`});let o=e.targets.filter(r=>typeof r=="string"&&r.split(/[\\/]/).includes(".."));o.length>0&&t.push({field:"targets",message:`targets must not traverse outside the project (${o.join(", ")})`})}for(let n of["requires","provides"]){let o=e[n];if(!Array.isArray(o)){t.push({field:n,message:"must be an array of dependency keys"});continue}o.some(r=>typeof r!="string"||r.trim().length===0)&&t.push({field:n,message:"dependency keys must be non-empty strings"})}return t}i(ve,"validateArtifactSpec");function Ae(e,t){let n=[],o=new Set(e.targets??[]);if(t.kind==="delete-paths"){e.boundaryClass!=="inside"&&n.push({field:"inverse",message:"deleting paths is only an inverse for `inside` artifacts; an `outside` path may hold text we did not write"}),t.paths.length===0&&n.push({field:"inverse.paths",message:"nothing to delete \u2014 this is not an inverse"});let r=t.paths.filter(s=>!o.has(s));return r.length>0&&n.push({field:"inverse.paths",message:`would delete paths the spec never declared: ${r.join(", ")}`}),n}return e.boundaryClass!=="outside"&&n.push({field:"inverse",message:"a compensation is only an inverse for `outside` artifacts; an `inside` path owes an exact undo"}),(!t.backupPath||t.backupPath.trim().length===0)&&n.push({field:"inverse.backupPath",message:"an `outside` write owes a backup"}),(!t.hashAtWrite||t.hashAtWrite.trim().length===0)&&n.push({field:"inverse.hashAtWrite",message:"without the post-write hash the undo cannot tell a drifted file from an untouched one"}),o.has(t.file)||n.push({field:"inverse.file",message:`wrote ${t.file}, which the spec did not declare as a target`}),t.kind==="remove-marked-region"?(!t.startMarker||!t.endMarker)&&n.push({field:"inverse",message:"an `outside` region needs both markers, or the undo cannot tell where our text ends"}):t.command.trim().length===0&&n.push({field:"inverse.command",message:"the exact command written is the identity of the entry; without it the undo is a search"}),n}i(Ae,"validateArtifactInverse");var z="artifact";function A(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}i(A,"stringArray");function Te(e){if(!e||typeof e!="object")return null;let t=e[z];if(!t||typeof t!="object")return null;let n=t;return{boundaryClass:n.boundaryClass,targets:A(n.targets),requires:A(n.requires),provides:A(n.provides)}}i(Te,"parseArtifactSpec");var be=["applied","measuring","improved","inconclusive","harmful","rollback_ready"];function K(e){return e.appliedAt?e.appliedAt instanceof Date?e.appliedAt.getTime():new Date(e.appliedAt).getTime():0}i(K,"appliedAtMs");function ke(e){return[...e].sort((t,n)=>{let o=K(n)-K(t);return o!==0?o:(n.applySeq??0)-(t.applySeq??0)})}i(ke,"orderForReversal");var Y=["SessionStart","SessionEnd","UserPromptSubmit","PreToolUse","PostToolUse","PreCompact","Notification","Stop","SubagentStop"],b=".claude/settings.local.json";function G(e){return`# rm-artifact:${e}`}i(G,"hookTag");function Ce(e,t){return`${e.trim()} ${G(t)}`}i(Ce,"taggedHookCommand");var Oe=new Set(["if","then","else","elif","fi","for","while","until","do","done","case","esac","function","return","exit","cd","echo","test","true","false"]);function k(e){let t=e.trim().split(/\s+/)[0]??"";return!/^[a-z][a-z0-9_-]*$/.test(t)||Oe.has(t)?null:y(`cmd:${t}`)}i(k,"inferredCommandRequirement");function we(e,t){let n=new Set((t?.requires??[]).map(y).filter(Boolean)),o=k(e.command);return o&&n.add(o),{boundaryClass:"outside",targets:[b],requires:[...n],provides:(t?.provides??[]).map(y).filter(Boolean)}}i(we,"hookArtifactSpec");function x(e){let t=[];Y.includes(e.event)||t.push({field:"event",message:`unknown hook event ${JSON.stringify(e.event)} \u2014 a hook on an event that never fires is indistinguishable from one that was never installed`});let n=(e.command??"").trim();return n.length===0?t.push({field:"command",message:"a hook with no command installs nothing"}):(/[\r\n]/.test(n)&&t.push({field:"command",message:"multi-line commands are refused: the identity tag is a trailing shell comment, which would silence only the final line, and a human reviewing an install should read one line"}),n.includes("\0")&&t.push({field:"command",message:"command contains a NUL byte"}),n.includes("rulemetric")&&t.push({field:"command",message:'refused: `rulemetric hooks uninstall` deletes every hook whose command contains "rulemetric", so installing one here would make this hook collateral damage of an unrelated command'}),n.includes("rm-artifact:")&&t.push({field:"command",message:"command already carries an artifact tag \u2014 installing it would produce two identities for one entry"})),e.matcher!==void 0&&(typeof e.matcher!="string"||e.matcher.trim().length===0)&&t.push({field:"matcher",message:"matcher must be a non-empty string when present"}),t}i(x,"validateHookSpec");function Re(e){let t=[`runs on: ${e.event}${e.matcher?` (tools matching ${e.matcher})`:""}`,`spawns: ${e.command.trim()}`,`writes: ${b} (one entry, tagged with this artifact's id)`],n=k(e.command);return n&&t.push(`needs: ${n} on PATH`),t}i(Re,"describeHookCapability");var q="hook";function h(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}i(h,"asRecord");function F(e){let t=e.event,n=e.command;if(typeof t!="string"||typeof n!="string")return null;let o=typeof e.matcher=="string"?e.matcher:void 0;return{event:t,matcher:o,command:n}}i(F,"readBareSpec");function W(e){let t=h(e.hooks)??e,n=[];for(let[o,r]of Object.entries(t))if(Array.isArray(r))for(let s of r){let a=h(s);if(!a)continue;let c=typeof a.matcher=="string"&&a.matcher.length>0?a.matcher:void 0,l=Array.isArray(a.hooks)?a.hooks:[];for(let u of l){let f=h(u)?.command;typeof f=="string"&&n.push({event:o,matcher:c,command:f})}}return n.length===0?{spec:null,problems:[]}:n.length>1?{spec:null,problems:[{field:"hook",message:`proposal describes ${n.length} hook entries; one proposal installs exactly one hook, so its inverse stays exact and its review stays readable`}]}:{spec:n[0],problems:[]}}i(W,"readSettingsFragment");function Le(e){let t=[],n=/```[a-zA-Z]*\n([\s\S]*?)```/g,o;for(;(o=n.exec(e))!==null;)t.push(o[1]);return t}i(Le,"fencedBlocks");function Ie(e){let t=h(h(e.frontmatter)?.artifact),n=t?h(t[q]):null;if(n){let o=F(n);if(o)return{spec:o,problems:x(o),source:"envelope"};let r=W(n);if(r.spec)return{spec:r.spec,problems:x(r.spec),source:"envelope"};if(r.problems.length>0)return{spec:null,problems:r.problems,source:"envelope"}}for(let o of Le(e.content??"")){let r;try{r=JSON.parse(o)}catch{continue}let s=h(r);if(!s)continue;let a=F(s);if(a)return{spec:a,problems:x(a),source:"content-fragment"};let c=W(s);if(c.spec)return{spec:c.spec,problems:x(c.spec),source:"content-fragment"};if(c.problems.length>0)return{spec:null,problems:c.problems,source:"content-fragment"}}return{spec:null,problems:[{field:"hook",message:"no hook spec found \u2014 a hook proposal must carry {event, command} in its artifact envelope or a JSON settings fragment in its body"}],source:"none"}}i(Ie,"parseHookSpec");var V=25,C=N,X=[{task:"rm-batch-task",instructions:"rm-batch-task/inject.md",class:"proven",axis:"reward",measured:"2026-09-02 n=25/arm Haiku 4.5: 0/25 \u2192 25/25, delta +1.000, 95% CI [+0.734, +1.000]"},{task:"rm-locality-task",instructions:"rm-locality-task/inject.md",class:"proven",axis:"cost",measured:"2026-09-02 n=25/arm Haiku 4.5: 25/25 both arms, cost \u221225.6%/trial, 95% CI [\u22120.0171, \u22120.0107]"},{task:"rm-migrations-task",instructions:"rm-migrations-task/inject.md",class:"negative",axis:"reward",measured:"2026-08-31 Haiku 4.5: flat after two reworks \u2014 redundant with the model's priors on this shape"},{task:"rm-pagination-task",instructions:"rm-pagination-task/inject.md",class:"negative",axis:"reward",measured:"2026-09-02 n=25/arm Haiku 4.5: 25/25 baseline under --allowedTools Bash; the rule costs +8.0%/trial and buys nothing"}];function Ne(e){return X.filter(t=>t.class===e)}i(Ne,"harborTasksOfClass");function J(e,t){return t?.engine==="pi"?"Pi is supported for eval trials, not Harbor tasks":t?.engine==="codex"&&e.axis==="cost"?`${e.task}: dollar-cost telemetry is unavailable for Codex; reward calibration remains supported`:null}i(J,"harborTaskSupport");function Pe(e,t,n=null){let o=n?I.parse(n):null,r=J(e,o);if(r)throw new Error(r);let s=!o||o.engine==="claude"&&o.model===C;return{task:e.task,instructions:e.instructions,class:s?e.class:"unvalidated",axis:e.axis,model:o?.model??C,...o?{measurement:o}:{},nTrials:V,lane:t}}i(Pe,"harborPayloadFor");var De=/[\p{L}\p{N}]+/gu;function O(e){let t=new Set;for(let n of e.toLowerCase().matchAll(De)){let o=` ${n[0]} `;for(let r=0;r+3<=o.length;r+=1)t.add(o.slice(r,r+3))}return t}i(O,"trigrams");function g(e,t){let n=O(e),o=O(t);if(n.size===0||o.size===0)return 0;let r=0,[s,a]=n.size<=o.size?[n,o]:[o,n];for(let l of s)a.has(l)&&(r+=1);let c=n.size+o.size-r;return c===0?0:r/c}i(g,"trigramSimilarity");var R=.3,je=15;function w(e){let n=e.replace(/<!--[\s\S]*?-->/g," ").replace(/```[\s\S]*?```/g," "),o=[];for(let r of n.split(`
46
+ `);return r.trim().length===0?{content:e,removed:!1,removedText:null,reason:"would-empty-file"}:{content:r,removed:!0,removedText:n}}i(ye,"removeExactBlock");var U=["HTTPS_PROXY","HTTP_PROXY","NODE_EXTRA_CA_CERTS"];function xe(e,t){if(!e||typeof e!="object")return{value:e,removed:!1,removedDescriptions:[],reason:"not-found"};let n=structuredClone(e);if(!n.hooks)return{value:n,removed:!1,removedDescriptions:[],reason:"not-found"};let o=[];for(let[r,s]of Object.entries(n.hooks)){if(!Array.isArray(s))continue;let a=s.filter(c=>{let l=(c.hooks??[]).some(u=>typeof u.command=="string"&&u.command.includes(t));return l&&o.push(`${r}: ${c.matcher??"*"} \u2192 ${(c.hooks??[]).map(u=>u.command).join(", ")}`),!l});a.length===0?delete n.hooks[r]:n.hooks[r]=a}return Object.keys(n.hooks).length===0&&delete n.hooks,{value:n,removed:o.length>0,removedDescriptions:o,...o.length===0?{reason:"not-found"}:{}}}i(xe,"removeHookByCommand");function _e(e,t){if(!e||typeof e!="object")return{value:e,removed:!1,removedDescriptions:[],reason:"not-found"};let n=structuredClone(e);return!n.mcpServers||!(t in n.mcpServers)?{value:n,removed:!1,removedDescriptions:[],reason:"not-found"}:(delete n.mcpServers[t],Object.keys(n.mcpServers).length===0&&delete n.mcpServers,{value:n,removed:!0,removedDescriptions:[`mcpServers.${t}`]})}i(_e,"removeMcpServer");function S(e){if(!e||typeof e!="object")return[];let t=e.env;return t?U.filter(n=>n in t):[]}i(S,"protectedEnvKeysPresent");function ve(e,t){let n=S(e),o=new Set(S(t));return n.filter(r=>!o.has(r))}i(ve,"lostProtectedEnvKeys");function Ee(e,t){let n=`HTTP ${e}`;if(!t||typeof t!="object")return{message:n};let o=t,r=typeof o.error=="string"&&o.error?o.error:o.error?JSON.stringify(o.error):n,s=typeof o.code=="string"&&o.code?o.code:void 0;return s?{message:r,code:s}:{message:r}}i(Ee,"parseApiError");var T=["inside","outside"];function y(e){return e.trim().toLowerCase()}i(y,"normalizeDependencyKey");function Se(e){let t=[];if(T.includes(e.boundaryClass)||t.push({field:"boundaryClass",message:`must be one of ${T.join(" | ")}`}),!Array.isArray(e.targets)||e.targets.length===0)t.push({field:"targets",message:"a proposal that cannot name the paths it writes cannot be applied"});else{for(let r of e.targets)if(typeof r!="string"||r.trim().length===0){t.push({field:"targets",message:"target paths must be non-empty"});break}let n=e.targets.filter(r=>typeof r=="string"&&(r.startsWith("/")||/^[A-Za-z]:[\\/]/.test(r)));n.length>0&&t.push({field:"targets",message:`targets must be project-relative (absolute: ${n.join(", ")})`});let o=e.targets.filter(r=>typeof r=="string"&&r.split(/[\\/]/).includes(".."));o.length>0&&t.push({field:"targets",message:`targets must not traverse outside the project (${o.join(", ")})`})}for(let n of["requires","provides"]){let o=e[n];if(!Array.isArray(o)){t.push({field:n,message:"must be an array of dependency keys"});continue}o.some(r=>typeof r!="string"||r.trim().length===0)&&t.push({field:n,message:"dependency keys must be non-empty strings"})}return t}i(Se,"validateArtifactSpec");function Ae(e,t){let n=[],o=new Set(e.targets??[]);if(t.kind==="delete-paths"){e.boundaryClass!=="inside"&&n.push({field:"inverse",message:"deleting paths is only an inverse for `inside` artifacts; an `outside` path may hold text we did not write"}),t.paths.length===0&&n.push({field:"inverse.paths",message:"nothing to delete \u2014 this is not an inverse"});let r=t.paths.filter(s=>!o.has(s));return r.length>0&&n.push({field:"inverse.paths",message:`would delete paths the spec never declared: ${r.join(", ")}`}),n}return e.boundaryClass!=="outside"&&n.push({field:"inverse",message:"a compensation is only an inverse for `outside` artifacts; an `inside` path owes an exact undo"}),(!t.backupPath||t.backupPath.trim().length===0)&&n.push({field:"inverse.backupPath",message:"an `outside` write owes a backup"}),(!t.hashAtWrite||t.hashAtWrite.trim().length===0)&&n.push({field:"inverse.hashAtWrite",message:"without the post-write hash the undo cannot tell a drifted file from an untouched one"}),o.has(t.file)||n.push({field:"inverse.file",message:`wrote ${t.file}, which the spec did not declare as a target`}),t.kind==="remove-marked-region"?(!t.startMarker||!t.endMarker)&&n.push({field:"inverse",message:"an `outside` region needs both markers, or the undo cannot tell where our text ends"}):t.command.trim().length===0&&n.push({field:"inverse.command",message:"the exact command written is the identity of the entry; without it the undo is a search"}),n}i(Ae,"validateArtifactInverse");var z="artifact";function A(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}i(A,"stringArray");function Te(e){if(!e||typeof e!="object")return null;let t=e[z];if(!t||typeof t!="object")return null;let n=t;return{boundaryClass:n.boundaryClass,targets:A(n.targets),requires:A(n.requires),provides:A(n.provides)}}i(Te,"parseArtifactSpec");var be=["applied","measuring","improved","inconclusive","harmful","rollback_ready"];function K(e){return e.appliedAt?e.appliedAt instanceof Date?e.appliedAt.getTime():new Date(e.appliedAt).getTime():0}i(K,"appliedAtMs");function ke(e){return[...e].sort((t,n)=>{let o=K(n)-K(t);return o!==0?o:(n.applySeq??0)-(t.applySeq??0)})}i(ke,"orderForReversal");var Y=["SessionStart","SessionEnd","UserPromptSubmit","PreToolUse","PostToolUse","PreCompact","Notification","Stop","SubagentStop"],b=".claude/settings.local.json";function G(e){return`# rm-artifact:${e}`}i(G,"hookTag");function Ce(e,t){return`${e.trim()} ${G(t)}`}i(Ce,"taggedHookCommand");var Oe=new Set(["if","then","else","elif","fi","for","while","until","do","done","case","esac","function","return","exit","cd","echo","test","true","false"]);function k(e){let t=e.trim().split(/\s+/)[0]??"";return!/^[a-z][a-z0-9_-]*$/.test(t)||Oe.has(t)?null:y(`cmd:${t}`)}i(k,"inferredCommandRequirement");function we(e,t){let n=new Set((t?.requires??[]).map(y).filter(Boolean)),o=k(e.command);return o&&n.add(o),{boundaryClass:"outside",targets:[b],requires:[...n],provides:(t?.provides??[]).map(y).filter(Boolean)}}i(we,"hookArtifactSpec");function x(e){let t=[];Y.includes(e.event)||t.push({field:"event",message:`unknown hook event ${JSON.stringify(e.event)} \u2014 a hook on an event that never fires is indistinguishable from one that was never installed`});let n=(e.command??"").trim();return n.length===0?t.push({field:"command",message:"a hook with no command installs nothing"}):(/[\r\n]/.test(n)&&t.push({field:"command",message:"multi-line commands are refused: the identity tag is a trailing shell comment, which would silence only the final line, and a human reviewing an install should read one line"}),n.includes("\0")&&t.push({field:"command",message:"command contains a NUL byte"}),n.includes("rulemetric")&&t.push({field:"command",message:'refused: `rulemetric hooks uninstall` deletes every hook whose command contains "rulemetric", so installing one here would make this hook collateral damage of an unrelated command'}),n.includes("rm-artifact:")&&t.push({field:"command",message:"command already carries an artifact tag \u2014 installing it would produce two identities for one entry"})),e.matcher!==void 0&&(typeof e.matcher!="string"||e.matcher.trim().length===0)&&t.push({field:"matcher",message:"matcher must be a non-empty string when present"}),t}i(x,"validateHookSpec");function Re(e){let t=[`runs on: ${e.event}${e.matcher?` (tools matching ${e.matcher})`:""}`,`spawns: ${e.command.trim()}`,`writes: ${b} (one entry, tagged with this artifact's id)`],n=k(e.command);return n&&t.push(`needs: ${n} on PATH`),t}i(Re,"describeHookCapability");var q="hook";function h(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}i(h,"asRecord");function F(e){let t=e.event,n=e.command;if(typeof t!="string"||typeof n!="string")return null;let o=typeof e.matcher=="string"?e.matcher:void 0;return{event:t,matcher:o,command:n}}i(F,"readBareSpec");function W(e){let t=h(e.hooks)??e,n=[];for(let[o,r]of Object.entries(t))if(Array.isArray(r))for(let s of r){let a=h(s);if(!a)continue;let c=typeof a.matcher=="string"&&a.matcher.length>0?a.matcher:void 0,l=Array.isArray(a.hooks)?a.hooks:[];for(let u of l){let f=h(u)?.command;typeof f=="string"&&n.push({event:o,matcher:c,command:f})}}return n.length===0?{spec:null,problems:[]}:n.length>1?{spec:null,problems:[{field:"hook",message:`proposal describes ${n.length} hook entries; one proposal installs exactly one hook, so its inverse stays exact and its review stays readable`}]}:{spec:n[0],problems:[]}}i(W,"readSettingsFragment");function Le(e){let t=[],n=/```[a-zA-Z]*\n([\s\S]*?)```/g,o;for(;(o=n.exec(e))!==null;)t.push(o[1]);return t}i(Le,"fencedBlocks");function Ie(e){let t=h(h(e.frontmatter)?.artifact),n=t?h(t[q]):null;if(n){let o=F(n);if(o)return{spec:o,problems:x(o),source:"envelope"};let r=W(n);if(r.spec)return{spec:r.spec,problems:x(r.spec),source:"envelope"};if(r.problems.length>0)return{spec:null,problems:r.problems,source:"envelope"}}for(let o of Le(e.content??"")){let r;try{r=JSON.parse(o)}catch{continue}let s=h(r);if(!s)continue;let a=F(s);if(a)return{spec:a,problems:x(a),source:"content-fragment"};let c=W(s);if(c.spec)return{spec:c.spec,problems:x(c.spec),source:"content-fragment"};if(c.problems.length>0)return{spec:null,problems:c.problems,source:"content-fragment"}}return{spec:null,problems:[{field:"hook",message:"no hook spec found \u2014 a hook proposal must carry {event, command} in its artifact envelope or a JSON settings fragment in its body"}],source:"none"}}i(Ie,"parseHookSpec");var V=25,C=N,X=[{task:"rm-batch-task",instructions:"rm-batch-task/inject.md",class:"proven",axis:"reward",measured:"2026-09-02 n=25/arm Haiku 4.5: 0/25 \u2192 25/25, delta +1.000, 95% CI [+0.734, +1.000]"},{task:"rm-locality-task",instructions:"rm-locality-task/inject.md",class:"proven",axis:"cost",measured:"2026-09-02 n=25/arm Haiku 4.5: 25/25 both arms, cost \u221225.6%/trial, 95% CI [\u22120.0171, \u22120.0107]"},{task:"rm-migrations-task",instructions:"rm-migrations-task/inject.md",class:"negative",axis:"reward",measured:"2026-08-31 Haiku 4.5: inconclusive after two exploratory reworks; redundancy unestablished"},{task:"rm-pagination-task",instructions:"rm-pagination-task/inject.md",class:"negative",axis:"reward",measured:"2026-09-02 n=25/arm Haiku 4.5: 25/25 baseline under --allowedTools Bash; observed cost +8.0%/trial; reward equivalence unestablished"}];function Ne(e){return X.filter(t=>t.class===e)}i(Ne,"harborTasksOfClass");function J(e,t){return t?.engine==="pi"?"Pi is supported for eval trials, not Harbor tasks":t?.engine==="codex"&&e.axis==="cost"?`${e.task}: dollar-cost telemetry is unavailable for Codex; reward calibration remains supported`:null}i(J,"harborTaskSupport");function Pe(e,t,n=null){let o=n?I.parse(n):null,r=J(e,o);if(r)throw new Error(r);let s=!o||o.engine==="claude"&&o.model===C;return{task:e.task,instructions:e.instructions,class:s?e.class:"unvalidated",axis:e.axis,model:o?.model??C,...o?{measurement:o}:{},nTrials:V,lane:t}}i(Pe,"harborPayloadFor");var De=/[\p{L}\p{N}]+/gu;function O(e){let t=new Set;for(let n of e.toLowerCase().matchAll(De)){let o=` ${n[0]} `;for(let r=0;r+3<=o.length;r+=1)t.add(o.slice(r,r+3))}return t}i(O,"trigrams");function g(e,t){let n=O(e),o=O(t);if(n.size===0||o.size===0)return 0;let r=0,[s,a]=n.size<=o.size?[n,o]:[o,n];for(let l of s)a.has(l)&&(r+=1);let c=n.size+o.size-r;return c===0?0:r/c}i(g,"trigramSimilarity");var R=.3,je=15;function w(e){let n=e.replace(/<!--[\s\S]*?-->/g," ").replace(/```[\s\S]*?```/g," "),o=[];for(let r of n.split(`
47
47
  `)){let s=r.trim();if(s.length===0||s.startsWith("#"))continue;let a=s.replace(/^(?:[-*+]|\d+[.)])\s+/,"").trim();if(a.length!==0)for(let c of a.split(/(?<=[.!?])\s+(?=[A-Z(`"'*])/)){let l=c.trim();l.length>=je&&o.push(l)}}return o}i(w,"splitDirectives");function Z(e,t,n=R){let o=w(e);if(o.length===0)return{redundant:!1,coverage:0,matches:[],novel:[]};let r=t.flatMap(c=>w(c.content).map(l=>({text:l,id:c.id,source:c.source}))),s=[],a=[];for(let c of o){let l=null;for(let u of r){let f=g(c,u.text);f<n||(l===null||f>l.similarity)&&(l={directive:c,matchedDirective:u.text,matchedId:u.id,matchedSource:u.source,similarity:f})}l?s.push(l):a.push(c)}return{redundant:a.length===0,coverage:s.length/o.length,matches:s,novel:a}}i(Z,"assessRedundancy");function $e(e,t=R){let n=[];for(let o=0;o<e.length;o+=1){let r=Z(e[o].content,e.slice(0,o),t);r.matches.length>0&&n.push({instruction:e[o],verdict:r})}return n}i($e,"findInternalRedundancy");var Q=.5,Me=/-(?=[0-9a-f]{6}$)[0-9a-f]*[0-9][0-9a-f]*$/;function L(e){return e.trim().toLowerCase().replace(/^skills--/,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").replace(Me,"").replace(/-+$/,"")}i(L,"skillNameStem");function He(e,t,n=Q){let o=L(e.name);for(let s of t)if(o.length>0&&L(s.name)===o)return{name:s.name,similarity:g(e.content,s.content),reason:"name-stem"};let r=null;for(let s of t){let a=g(e.content,s.content);a<n||(r===null||a>r.similarity)&&(r={name:s.name,similarity:a,reason:"body"})}return r}i(He,"assessSkillDuplication");var Be=new Set(["sh","bash","zsh","fish"]),Ue=new Set(["mjs","cjs","js","ts","py","rb","pl"]),Ke=/(?:^|[\s(`'"])(?:sudo\s+)?(?:node|npx|pnpm|npm|yarn|bun|deno|tsx|ts-node|vitest|jest|python3?|python|ruby|perl|bash|sh|zsh|exec|run|dlx)\s+(?:[-\w=@./]+\s+)*$/,ze=/(?:\.\/)?(?:[\w.@-]+\/)+[\w.@-]+\.\w+/g;function Fe(e){return e.replace(/```[\w-]*\n?/g," ").replace(/`/g," ")}i(Fe,"stripCodeMarkers");function We(e){let t=e.trim();return t=t.replace(/[.,;:)\]]+$/,""),t.startsWith("./")&&(t=t.slice(2)),t.length===0||t.startsWith("/")||t.startsWith("~")||t.startsWith("..")||/[<>{}*?]/.test(t)?null:t}i(We,"normalise");function ee(e){let t=Fe(e),n=new Set,o=[];for(let r of t.matchAll(ze)){let s=r[0],a=r.index??0,c=t.slice(Math.max(0,a-1),a);if(c.length>0&&!/[\s(['"=]/.test(c))continue;let l=We(s);if(!l)continue;let u=l.slice(l.lastIndexOf(".")+1).toLowerCase();(Be.has(u)||Ue.has(u)&&(s.startsWith("./")||Ke.test(t.slice(t.lastIndexOf(`
48
- `,Math.max(0,a-1))+1,a))))&&(n.has(l)||(n.add(l),o.push({reference:s,path:l})))}return o}i(ee,"extractCommandReferences");function Ye(e,t){return ee(e).filter(n=>!t(n.path))}i(Ye,"findUnresolvableReferences");import Yt from"gray-matter";import{z as te}from"zod";var Xt=te.object({type:te.enum(["instruction","prompt"])});export{se as a,ie as b,_ as c,M as d,fe as e,he as f,ge as g,ye as h,xe as i,_e as j,Ee as k,Se as l,y as m,ve as n,Ae as o,Te as p,be as q,ke as r,b as s,G as t,Ce as u,we as v,Re as w,Ie as x,C as y,Ne as z,J as A,Pe as B,w as C,Z as D,$e as E,He as F,Ye as G};
48
+ `,Math.max(0,a-1))+1,a))))&&(n.has(l)||(n.add(l),o.push({reference:s,path:l})))}return o}i(ee,"extractCommandReferences");function Ye(e,t){return ee(e).filter(n=>!t(n.path))}i(Ye,"findUnresolvableReferences");import Yt from"gray-matter";import{z as te}from"zod";var Xt=te.object({type:te.enum(["instruction","prompt"])});export{se as a,ie as b,_ as c,M as d,fe as e,he as f,ge as g,ye as h,xe as i,_e as j,ve as k,Ee as l,y as m,Se as n,Ae as o,Te as p,be as q,ke as r,b as s,G as t,Ce as u,we as v,Re as w,Ie as x,C as y,Ne as z,J as A,Pe as B,w as C,Z as D,$e as E,He as F,Ye as G};
@@ -1,4 +1,4 @@
1
- import{a as S,b as P}from"./chunk-PPAHIVG5.js";import{a as V,b as v,c as T}from"./chunk-5MXZJWQS.js";import{a as E,b as C,c as _}from"./chunk-CT7FWSIU.js";import{a as b}from"./chunk-N7ODX6PO.js";import{d as K}from"./chunk-SG4UDDHB.js";import{c as z,d as H}from"./chunk-GPBN4ROE.js";import{a as g,b as U}from"./chunk-6XTLP2G7.js";import{a as c}from"./chunk-ZLLER3HP.js";import{execSync as M,spawn as ee}from"node:child_process";import{tmpdir as B}from"node:os";import{mkdtempSync as te,rmSync as ne,writeFileSync as re}from"node:fs";import{join as Y}from"node:path";function oe(t,o){let{available:r,backend:n}=o??{available:c(l=>g(l)!==null,"available"),backend:A()},e=P(t);if(r(e.bin))return{bin:e.bin,args:e.args,delivery:e.delivery??"stdin",substitutedFrom:null};let i=n==="codex-cli"?S.codex:n==="claude-cli"?S.claude_code:n==="copilot-cli"?S.copilot:null;return!i||!r(i.bin)?null:{bin:i.bin,args:i.args,delivery:i.delivery??"stdin",substitutedFrom:e.bin}}c(oe,"planToolExecution");function X(t,o=300){let r=t.trim().replace(/\s+/g," ");return r.length>o?`${r.slice(0,o)}\u2026`:r}c(X,"excerpt");async function ye(t,o,r){let n=oe(t);if(!n){let s=`no engine can run ${t}'s prompt: ${P(t).bin} is not installed and no substitutable backend was detected`;return console.warn(`[llm-client] ${s}`),{ok:!1,reason:s}}let{bin:e,args:i,delivery:l}=n;n.substitutedFrom&&console.warn(`[llm-client] ${n.substitutedFrom} is not installed \u2014 running ${t}'s analysis prompt on ${e} instead`);let a=g(e);if(!a){let s=`${e} not found on PATH, well-known dirs, or the node bin dir`;return console.warn(`[llm-client] ${s}`),{ok:!1,reason:s}}let u=`${o}
1
+ import{a as S,b as P}from"./chunk-PPAHIVG5.js";import{a as E,b as C,c as _}from"./chunk-CT7FWSIU.js";import{a as V,b as v,c as T}from"./chunk-5MXZJWQS.js";import{a as b}from"./chunk-N7ODX6PO.js";import{d as K}from"./chunk-JNLDISBA.js";import{c as z,d as H}from"./chunk-GPBN4ROE.js";import{a as g,b as U}from"./chunk-6XTLP2G7.js";import{a as c}from"./chunk-ZLLER3HP.js";import{execSync as M,spawn as ee}from"node:child_process";import{tmpdir as B}from"node:os";import{mkdtempSync as te,rmSync as ne,writeFileSync as re}from"node:fs";import{join as Y}from"node:path";function oe(t,o){let{available:r,backend:n}=o??{available:c(l=>g(l)!==null,"available"),backend:A()},e=P(t);if(r(e.bin))return{bin:e.bin,args:e.args,delivery:e.delivery??"stdin",substitutedFrom:null};let i=n==="codex-cli"?S.codex:n==="claude-cli"?S.claude_code:n==="copilot-cli"?S.copilot:null;return!i||!r(i.bin)?null:{bin:i.bin,args:i.args,delivery:i.delivery??"stdin",substitutedFrom:e.bin}}c(oe,"planToolExecution");function X(t,o=300){let r=t.trim().replace(/\s+/g," ");return r.length>o?`${r.slice(0,o)}\u2026`:r}c(X,"excerpt");async function ye(t,o,r){let n=oe(t);if(!n){let s=`no engine can run ${t}'s prompt: ${P(t).bin} is not installed and no substitutable backend was detected`;return console.warn(`[llm-client] ${s}`),{ok:!1,reason:s}}let{bin:e,args:i,delivery:l}=n;n.substitutedFrom&&console.warn(`[llm-client] ${n.substitutedFrom} is not installed \u2014 running ${t}'s analysis prompt on ${e} instead`);let a=g(e);if(!a){let s=`${e} not found on PATH, well-known dirs, or the node bin dir`;return console.warn(`[llm-client] ${s}`),{ok:!1,reason:s}}let u=`${o}
2
2
 
3
3
  SESSION DATA:
4
4
  ${r}`,m={...b()};delete m.HTTPS_PROXY;let p=null,y=i,$=u;if(l==="argv-file"){p=te(Y(B(),"rulemetric-tool-prompt-"));let s=Y(p,"session-data.txt");re(s,r),y=[...i,`@${s}`,`${o}
@@ -1 +1 @@
1
- import{b as l}from"./chunk-ISFPPDDB.js";import{a as p}from"./chunk-5RBLIVBF.js";import{h}from"./chunk-76UKAFNM.js";import{a as c}from"./chunk-ZLLER3HP.js";async function g(t){if(!t.worktree?.create)return t;let{branch:e,baseRef:s}=t.worktree,n=await l({repoRoot:t.projectPath,branch:e,baseRef:s});return{...t,projectPath:n.path,gitBranch:n.branch}}c(g,"resolveWorktreeForLaunch");async function L(t,e){let{mirrorId:s,tool:n}=t,{config:r}=t,a=c(o=>e.logger.info(o),"log");if(e.job.attempts>1)throw new p(`process_launch is not safe to retry (attempt ${e.job.attempts}). Re-launch manually.`);r=await g(r),r.worktree?.create&&a(`Worktree resolved: ${r.projectPath} (branch ${r.gitBranch})`),a(`Launching ${n}...`);let{getLauncher:f}=await import("./dist-GSHUC7UU.js"),i=await f(n).launch(r);a(`Launch completed: sessionId=${i.sessionId}`);let u={...i,worktreePath:r.worktree?.create?r.projectPath:void 0,runId:r.runId};return await h(`/api/launch-jobs/${s}/state`,{result:u}).catch(o=>{a(`result persist failed: ${o instanceof Error?o.message:String(o)}`)}),u}c(L,"processLaunch");export{g as a,L as b};
1
+ import{b as l}from"./chunk-ISFPPDDB.js";import{a as p}from"./chunk-5RBLIVBF.js";import{h}from"./chunk-GIXHG5FK.js";import{a as c}from"./chunk-ZLLER3HP.js";async function g(t){if(!t.worktree?.create)return t;let{branch:e,baseRef:s}=t.worktree,n=await l({repoRoot:t.projectPath,branch:e,baseRef:s});return{...t,projectPath:n.path,gitBranch:n.branch}}c(g,"resolveWorktreeForLaunch");async function L(t,e){let{mirrorId:s,tool:n}=t,{config:r}=t,a=c(o=>e.logger.info(o),"log");if(e.job.attempts>1)throw new p(`process_launch is not safe to retry (attempt ${e.job.attempts}). Re-launch manually.`);r=await g(r),r.worktree?.create&&a(`Worktree resolved: ${r.projectPath} (branch ${r.gitBranch})`),a(`Launching ${n}...`);let{getLauncher:f}=await import("./dist-GSHUC7UU.js"),i=await f(n).launch(r);a(`Launch completed: sessionId=${i.sessionId}`);let u={...i,worktreePath:r.worktree?.create?r.projectPath:void 0,runId:r.runId};return await h(`/api/launch-jobs/${s}/state`,{result:u}).catch(o=>{a(`result persist failed: ${o instanceof Error?o.message:String(o)}`)}),u}c(L,"processLaunch");export{g as a,L as b};
@@ -1 +1 @@
1
- import{b as c,f as m}from"./chunk-76UKAFNM.js";import{a as s}from"./chunk-ZLLER3HP.js";var R=new Set([408,429,502,503,504]),_=12e4,T=2e4,b=1e3,l=15e3;function p(t,e){try{t(JSON.stringify({ts:new Date().toISOString(),...e}))}catch{t(`[agent-loop] log_error event=${e.event}`)}}s(p,"structuredLog");function f(t,e){return e.aborted?Promise.resolve(!1):t<=0?Promise.resolve(!0):new Promise(r=>{let a=setTimeout(()=>{e.removeEventListener("abort",o),r(!0)},t),o=s(()=>{clearTimeout(a),e.removeEventListener("abort",o),r(!1)},"onAbort");e.addEventListener("abort",o,{once:!0})})}s(f,"abortableSleep");function g(t){return t instanceof c?R.has(t.statusCode):!0}s(g,"isRetryableReportError");async function S(t,e,r){let a=Date.now()+r.budgetMs,o=b;for(let i=1;;i++)try{return await m(t,e),{ok:!0,attempts:i}}catch(n){let u=a-Date.now();if(!g(n)||u<=0||r.signal.aborted)return{ok:!1,attempts:i,error:n};if(p(r.log,{event:`${r.event}_retry`,jobId:r.jobId,attempt:i,status:n instanceof c?n.statusCode:void 0,error:n instanceof Error?n.message:String(n),retryInMs:Math.min(o,u)}),!await f(Math.min(o,u),r.signal))return{ok:!1,attempts:i,error:n};o=Math.min(o*2,l)}}s(S,"postReportWithRetry");export{R as a,_ as b,T as c,b as d,l as e,p as f,f as g,g as h,S as i};
1
+ import{b as c,f as m}from"./chunk-GIXHG5FK.js";import{a as s}from"./chunk-ZLLER3HP.js";var R=new Set([408,429,502,503,504]),_=12e4,T=2e4,b=1e3,l=15e3;function p(t,e){try{t(JSON.stringify({ts:new Date().toISOString(),...e}))}catch{t(`[agent-loop] log_error event=${e.event}`)}}s(p,"structuredLog");function f(t,e){return e.aborted?Promise.resolve(!1):t<=0?Promise.resolve(!0):new Promise(r=>{let a=setTimeout(()=>{e.removeEventListener("abort",o),r(!0)},t),o=s(()=>{clearTimeout(a),e.removeEventListener("abort",o),r(!1)},"onAbort");e.addEventListener("abort",o,{once:!0})})}s(f,"abortableSleep");function g(t){return t instanceof c?R.has(t.statusCode):!0}s(g,"isRetryableReportError");async function S(t,e,r){let a=Date.now()+r.budgetMs,o=b;for(let i=1;;i++)try{return await m(t,e),{ok:!0,attempts:i}}catch(n){let u=a-Date.now();if(!g(n)||u<=0||r.signal.aborted)return{ok:!1,attempts:i,error:n};if(p(r.log,{event:`${r.event}_retry`,jobId:r.jobId,attempt:i,status:n instanceof c?n.statusCode:void 0,error:n instanceof Error?n.message:String(n),retryInMs:Math.min(o,u)}),!await f(Math.min(o,u),r.signal))return{ok:!1,attempts:i,error:n};o=Math.min(o*2,l)}}s(S,"postReportWithRetry");export{R as a,_ as b,T as c,b as d,l as e,p as f,f as g,g as h,S as i};
@@ -1 +1 @@
1
- import{d as E}from"./chunk-H6FVXVGG.js";import{b as F,c as x}from"./chunk-KGURGIZ2.js";import{f as R}from"./chunk-76UKAFNM.js";import{a}from"./chunk-ZLLER3HP.js";var _="with_candidate",w="with_prior_version";function S(e){return JSON.stringify([e.outputs.engine??null,e.outputs.model??null,e.outputs.methodology??null,e.outputs.deliveryRegime??null,e.grading.judge_engine??null,e.grading.judge_model??null])}a(S,"observedExecutionKey");function I(e){let r=e.filter(n=>n.status==="completed"),i=new Set(r.map(n=>JSON.stringify([n.outputs.engine??null,n.outputs.model??null,n.outputs.methodology??null,n.outputs.deliveryRegime??null]))),t=new Set(r.filter(n=>n.grading.judge_model!=null).map(n=>JSON.stringify([n.grading.judge_engine??"claude",n.grading.judge_model])));return i.size===1&&t.size<=1?JSON.stringify([[...i][0],[...t][0]??null]):null}a(I,"measurementBatchKey");function A(e){let r=e.filter(t=>t.configuration===_),i=[];for(let t of r){let n=e.find(s=>s.configuration===w&&s.evalId===t.evalId&&s.runNumber===t.runNumber);if(!n||S(n)!==S(t))continue;let l=h(t),m=h(n);l==null||m==null||i.push({withScore:l,withoutScore:m})}return i}a(A,"pairCandidateRuns");function h(e){return e.status!=="completed"?null:e.grading?.summary?.pass_rate??null}a(h,"evidenceOf");function $(e){let r=[],i=0;for(let t of e){if(t.status==="failed"){r.push(t.failure??{kind:"unknown",class:"infrastructure"});continue}h(t)==null&&(i+=1)}return{infrastructureFailed:r.length,ungradeable:i,summary:F(r)}}a($,"accountForFailures");function Q(e){let{pairs:r,minPairs:i,accounting:t}=e;return r>=i?{kind:"proceed"}:t.infrastructureFailed<=0?{kind:"proceed"}:{kind:"infrastructure-incomplete",reason:`${r}/${i} pair(s) \u2014 ${t.infrastructureFailed} run(s) never executed (${t.summary.describe()}). Retry when the environment recovers; this is not a statement about the target.`}}a(Q,"attributeShortfall");function k(e,r,i,t){let n=[];for(let l of e)n.push({eval_:l,configuration:_,targetContent:r,runNumber:t}),n.push({eval_:l,configuration:w,targetContent:i,runNumber:t});return n}a(k,"buildCandidateQueue");async function j(e){let{cases:r,candidateContent:i,priorVersionContent:t,concurrency:n,runNumber:l,opts:m,onLog:s=a(()=>{},"onLog")}=e,g=k(r,i,t,l),o=[],y=Math.max(1,n),p=null;for(let u=0;u<g.length;u+=y){let d=g.slice(u,u+y);o.push(...await Promise.all(d.map(c=>E(c,m,s))));let C=o.find(c=>c.failure&&x(c.failure.kind));if(C?.failure){p=C.failure.kind;let c=g.length-o.length;s(` \u26D4 aborting batch \u2014 ${p}: the account is out of quota. Skipped ${c} remaining run(s) that would certainly have failed.`);break}}for(let u of o)try{await R("/api/eval-runs",u)}catch(d){s(` \u26A0 failed to post a run result: ${d instanceof Error?d.message:String(d)}`)}let b=A(o),f=$(o),v=r.length-b.length;if(v>0){let u=f.infrastructureFailed?` \u2014 ${f.infrastructureFailed} run(s) never executed (${f.summary.describe()})`:"";s(` \u26A0 ${v}/${r.length} case(s) produced no usable pair (failed or ungradeable arm)${u}`)}return{completed:o.filter(u=>u.status==="completed").length,failed:o.filter(u=>u.status==="failed").length,results:o,pairs:b,accounting:f,abortedForQuota:p}}a(j,"runCandidateBatchAndPost");export{_ as a,w as b,S as c,I as d,A as e,$ as f,Q as g,k as h,j as i};
1
+ import{d as E}from"./chunk-FADINV4H.js";import{b as F,c as x}from"./chunk-KGURGIZ2.js";import{f as R}from"./chunk-GIXHG5FK.js";import{a}from"./chunk-ZLLER3HP.js";var _="with_candidate",w="with_prior_version";function S(e){return JSON.stringify([e.outputs.engine??null,e.outputs.model??null,e.outputs.methodology??null,e.outputs.deliveryRegime??null,e.grading.judge_engine??null,e.grading.judge_model??null])}a(S,"observedExecutionKey");function I(e){let r=e.filter(n=>n.status==="completed"),i=new Set(r.map(n=>JSON.stringify([n.outputs.engine??null,n.outputs.model??null,n.outputs.methodology??null,n.outputs.deliveryRegime??null]))),t=new Set(r.filter(n=>n.grading.judge_model!=null).map(n=>JSON.stringify([n.grading.judge_engine??"claude",n.grading.judge_model])));return i.size===1&&t.size<=1?JSON.stringify([[...i][0],[...t][0]??null]):null}a(I,"measurementBatchKey");function A(e){let r=e.filter(t=>t.configuration===_),i=[];for(let t of r){let n=e.find(s=>s.configuration===w&&s.evalId===t.evalId&&s.runNumber===t.runNumber);if(!n||S(n)!==S(t))continue;let l=h(t),m=h(n);l==null||m==null||i.push({withScore:l,withoutScore:m})}return i}a(A,"pairCandidateRuns");function h(e){return e.status!=="completed"?null:e.grading?.summary?.pass_rate??null}a(h,"evidenceOf");function $(e){let r=[],i=0;for(let t of e){if(t.status==="failed"){r.push(t.failure??{kind:"unknown",class:"infrastructure"});continue}h(t)==null&&(i+=1)}return{infrastructureFailed:r.length,ungradeable:i,summary:F(r)}}a($,"accountForFailures");function Q(e){let{pairs:r,minPairs:i,accounting:t}=e;return r>=i?{kind:"proceed"}:t.infrastructureFailed<=0?{kind:"proceed"}:{kind:"infrastructure-incomplete",reason:`${r}/${i} pair(s) \u2014 ${t.infrastructureFailed} run(s) never executed (${t.summary.describe()}). Retry when the environment recovers; this is not a statement about the target.`}}a(Q,"attributeShortfall");function k(e,r,i,t){let n=[];for(let l of e)n.push({eval_:l,configuration:_,targetContent:r,runNumber:t}),n.push({eval_:l,configuration:w,targetContent:i,runNumber:t});return n}a(k,"buildCandidateQueue");async function j(e){let{cases:r,candidateContent:i,priorVersionContent:t,concurrency:n,runNumber:l,opts:m,onLog:s=a(()=>{},"onLog")}=e,g=k(r,i,t,l),o=[],y=Math.max(1,n),p=null;for(let u=0;u<g.length;u+=y){let d=g.slice(u,u+y);o.push(...await Promise.all(d.map(c=>E(c,m,s))));let C=o.find(c=>c.failure&&x(c.failure.kind));if(C?.failure){p=C.failure.kind;let c=g.length-o.length;s(` \u26D4 aborting batch \u2014 ${p}: the account is out of quota. Skipped ${c} remaining run(s) that would certainly have failed.`);break}}for(let u of o)try{await R("/api/eval-runs",u)}catch(d){s(` \u26A0 failed to post a run result: ${d instanceof Error?d.message:String(d)}`)}let b=A(o),f=$(o),v=r.length-b.length;if(v>0){let u=f.infrastructureFailed?` \u2014 ${f.infrastructureFailed} run(s) never executed (${f.summary.describe()})`:"";s(` \u26A0 ${v}/${r.length} case(s) produced no usable pair (failed or ungradeable arm)${u}`)}return{completed:o.filter(u=>u.status==="completed").length,failed:o.filter(u=>u.status==="failed").length,results:o,pairs:b,accounting:f,abortedForQuota:p}}a(j,"runCandidateBatchAndPost");export{_ as a,w as b,S as c,I as d,A as e,$ as f,Q as g,k as h,j as i};
@@ -1,2 +1,2 @@
1
- import{a as v,b as u,e as y,g as d}from"../../chunk-WWQWHC4K.js";import{a as h}from"../../chunk-MU7KKU3O.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-FKTT7A4H.js";import"../../chunk-VIFOLTZT.js";import"../../chunk-4FJYVYCU.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-76UKAFNM.js";import"../../chunk-42A4PUW7.js";import"../../chunk-XQYAVSUQ.js";import"../../chunk-PZNWH4VQ.js";import{a as p}from"../../chunk-ZLLER3HP.js";import{Args as k,Flags as o}from"@oclif/core";import{existsSync as T}from"node:fs";import{homedir as P}from"node:os";import{join as I}from"node:path";var A=I(P(),".gemini","antigravity-ide","brain"),g=class x extends h{static{p(this,"AntigravityBackfill")}static description="Backfill historical events from an Antigravity conversation transcript into a RuleMetric session. Useful for seeding a conversation that existed before hooks were installed \u2014 the live hook intentionally only captures forward.";static examples=["<%= config.bin %> antigravity backfill 26fd215d-f43b-4ea5-b177-dc2c0e696f97 --session 158db9aa-68ee-43fc-961b-f3a180578694","<%= config.bin %> antigravity backfill 26fd215d-f43b-4ea5-b177-dc2c0e696f97 --dry-run"];static args={conversationId:k.string({description:"Antigravity conversationId (UUID) \u2014 the directory name under ~/.gemini/antigravity-ide/brain/",required:!0})};static flags={session:o.string({char:"s",description:"RuleMetric session UUID to POST events into. If omitted, resolved from the hook tmp file ($TMPDIR/rulemetric/<conversationId>) \u2014 fails if neither is present."}),transcript:o.string({description:"Path to the transcript.jsonl file. Defaults to ~/.gemini/antigravity-ide/brain/<conversationId>/.system_generated/logs/transcript.jsonl"}),"after-step":o.integer({description:"Only emit records with step_index > this value. Default: read from existing state file, else -1 (everything)."}),limit:o.integer({description:"Cap on the number of records to process this run."}),"dry-run":o.boolean({default:!1,description:"Classify records without POSTing. Reports counts only."}),"save-state":o.boolean({default:!0,allowNo:!0,description:"After backfill, persist the highest step_index so the live hook resumes from there."})};async run(){let{args:b,flags:e}=await this.parse(x),t=b.conversationId;d.loadEnvFile(),process.env.RULEMETRIC_API_URL||this.error("RULEMETRIC_API_URL is not set. Configure it via env or ~/.config/rulemetric/env.");let l=e.transcript??I(A,t,".system_generated","logs","transcript.jsonl");T(l)||this.error(`Transcript not found: ${l}`);let m=e.session??d.resolveRwSessionId(t);m||this.error(`No RuleMetric session resolved. Pass --session <uuid>, or run the Antigravity hook at least once so $TMPDIR/rulemetric/${t} is populated.`);let n=e["after-step"];n===void 0&&(n=d.load(t)?.lastStepIdx??-1);let i=v(l,n);e.limit!==void 0&&i.length>e.limit&&(i=i.slice(0,e.limit));let R=u(l);if(this.log(`Conversation ${t}: transcript max step = ${R}, after-step = ${n}, records to process = ${i.length}`),i.length===0){this.log("Nothing to backfill.");return}if(e["dry-run"]){let r=0,a=0,c={};for(let S of i){let f=(await import("../../lib/antigravity-transcript.js")).classifyRecord(S,0);f?(r++,c[f.eventType]=(c[f.eventType]??0)+1):a++}this.log(`Dry run: would emit ${r}, skip ${a}. By eventType: ${JSON.stringify(c)}`);return}let w=Date.now(),s=await y(i,m,t,n,{onProgress:p(({attempted:r,total:a})=>{(r%100===0||r===a)&&process.stderr.write(` \u2026${r}/${a}
1
+ import{a as v,b as u,e as y,g as d}from"../../chunk-BDQTVYYF.js";import{a as h}from"../../chunk-WUCACPGC.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-WL5ZWQAS.js";import"../../chunk-KEVDLLHT.js";import"../../chunk-DX6IPDED.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-GIXHG5FK.js";import"../../chunk-X6CF5KTW.js";import"../../chunk-XQYAVSUQ.js";import"../../chunk-PZNWH4VQ.js";import{a as p}from"../../chunk-ZLLER3HP.js";import{Args as k,Flags as o}from"@oclif/core";import{existsSync as T}from"node:fs";import{homedir as P}from"node:os";import{join as I}from"node:path";var A=I(P(),".gemini","antigravity-ide","brain"),g=class x extends h{static{p(this,"AntigravityBackfill")}static description="Backfill historical events from an Antigravity conversation transcript into a RuleMetric session. Useful for seeding a conversation that existed before hooks were installed \u2014 the live hook intentionally only captures forward.";static examples=["<%= config.bin %> antigravity backfill 26fd215d-f43b-4ea5-b177-dc2c0e696f97 --session 158db9aa-68ee-43fc-961b-f3a180578694","<%= config.bin %> antigravity backfill 26fd215d-f43b-4ea5-b177-dc2c0e696f97 --dry-run"];static args={conversationId:k.string({description:"Antigravity conversationId (UUID) \u2014 the directory name under ~/.gemini/antigravity-ide/brain/",required:!0})};static flags={session:o.string({char:"s",description:"RuleMetric session UUID to POST events into. If omitted, resolved from the hook tmp file ($TMPDIR/rulemetric/<conversationId>) \u2014 fails if neither is present."}),transcript:o.string({description:"Path to the transcript.jsonl file. Defaults to ~/.gemini/antigravity-ide/brain/<conversationId>/.system_generated/logs/transcript.jsonl"}),"after-step":o.integer({description:"Only emit records with step_index > this value. Default: read from existing state file, else -1 (everything)."}),limit:o.integer({description:"Cap on the number of records to process this run."}),"dry-run":o.boolean({default:!1,description:"Classify records without POSTing. Reports counts only."}),"save-state":o.boolean({default:!0,allowNo:!0,description:"After backfill, persist the highest step_index so the live hook resumes from there."})};async run(){let{args:b,flags:e}=await this.parse(x),t=b.conversationId;d.loadEnvFile(),process.env.RULEMETRIC_API_URL||this.error("RULEMETRIC_API_URL is not set. Configure it via env or ~/.config/rulemetric/env.");let l=e.transcript??I(A,t,".system_generated","logs","transcript.jsonl");T(l)||this.error(`Transcript not found: ${l}`);let m=e.session??d.resolveRwSessionId(t);m||this.error(`No RuleMetric session resolved. Pass --session <uuid>, or run the Antigravity hook at least once so $TMPDIR/rulemetric/${t} is populated.`);let n=e["after-step"];n===void 0&&(n=d.load(t)?.lastStepIdx??-1);let i=v(l,n);e.limit!==void 0&&i.length>e.limit&&(i=i.slice(0,e.limit));let R=u(l);if(this.log(`Conversation ${t}: transcript max step = ${R}, after-step = ${n}, records to process = ${i.length}`),i.length===0){this.log("Nothing to backfill.");return}if(e["dry-run"]){let r=0,a=0,c={};for(let S of i){let f=(await import("../../lib/antigravity-transcript.js")).classifyRecord(S,0);f?(r++,c[f.eventType]=(c[f.eventType]??0)+1):a++}this.log(`Dry run: would emit ${r}, skip ${a}. By eventType: ${JSON.stringify(c)}`);return}let w=Date.now(),s=await y(i,m,t,n,{onProgress:p(({attempted:r,total:a})=>{(r%100===0||r===a)&&process.stderr.write(` \u2026${r}/${a}
2
2
  `)},"onProgress")}),$=((Date.now()-w)/1e3).toFixed(1);this.log(`Backfill complete in ${$}s. attempted=${s.attempted} emitted=${s.emitted} skipped=${s.skipped} failed=${s.failed} highestStepIdx=${s.highestStepIdx}`),e["save-state"]?(d.save(t,{lastStepIdx:s.highestStepIdx}),this.log(`State saved \u2192 live hook will resume from step_index > ${s.highestStepIdx}.`)):this.log("State NOT saved (--no-save-state). Live hook will re-emit any new records from after-step.")}};export{g as default};
@@ -1 +1 @@
1
- import{a as n}from"../../chunk-MU7KKU3O.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-FKTT7A4H.js";import"../../chunk-VIFOLTZT.js";import"../../chunk-4FJYVYCU.js";import"../../chunk-3AV3GTMP.js";import{f as r}from"../../chunk-76UKAFNM.js";import"../../chunk-42A4PUW7.js";import"../../chunk-XQYAVSUQ.js";import{i as o,l as s}from"../../chunk-PZNWH4VQ.js";import{a}from"../../chunk-ZLLER3HP.js";import*as c from"node:path";import{Flags as l}from"@oclif/core";var t=class g extends n{static{a(this,"AuthCreateKey")}static description="Create a long-lived API key for CLI and proxy authentication";static examples=['<%= config.bin %> auth create-key --name "laptop"','<%= config.bin %> auth create-key --name "ci token" --no-save'];static flags={name:l.string({char:"n",description:"Name for this key",required:!0}),save:l.boolean({char:"s",description:"Save key to ~/.config/rulemetric/env for hooks/proxy",default:!0,allowNo:!0})};async run(){let{flags:i}=await this.parse(g),e=await r("/api/auth/api-keys",{name:i.name});this.log(""),this.log("API key created successfully:"),this.log(""),this.log(` Name: ${e.name}`),this.log(` Key: ${e.key}`),this.log(` Prefix: ${e.keyPrefix}`),this.log(""),this.warn("Save this key now \u2014 it will not be shown again."),i.save&&(o(e.key,process.env.RULEMETRIC_API_URL),this.log(""),this.log(`Key saved to ${c.join(s(),"env")} (RULEMETRIC_API_KEY)`),this.log("Hooks and proxy will use this key automatically."))}};export{t as default};
1
+ import{a as n}from"../../chunk-WUCACPGC.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-WL5ZWQAS.js";import"../../chunk-KEVDLLHT.js";import"../../chunk-DX6IPDED.js";import"../../chunk-3AV3GTMP.js";import{f as r}from"../../chunk-GIXHG5FK.js";import"../../chunk-X6CF5KTW.js";import"../../chunk-XQYAVSUQ.js";import{i as o,l as s}from"../../chunk-PZNWH4VQ.js";import{a}from"../../chunk-ZLLER3HP.js";import*as c from"node:path";import{Flags as l}from"@oclif/core";var t=class g extends n{static{a(this,"AuthCreateKey")}static description="Create a long-lived API key for CLI and proxy authentication";static examples=['<%= config.bin %> auth create-key --name "laptop"','<%= config.bin %> auth create-key --name "ci token" --no-save'];static flags={name:l.string({char:"n",description:"Name for this key",required:!0}),save:l.boolean({char:"s",description:"Save key to ~/.config/rulemetric/env for hooks/proxy",default:!0,allowNo:!0})};async run(){let{flags:i}=await this.parse(g),e=await r("/api/auth/api-keys",{name:i.name});this.log(""),this.log("API key created successfully:"),this.log(""),this.log(` Name: ${e.name}`),this.log(` Key: ${e.key}`),this.log(` Prefix: ${e.keyPrefix}`),this.log(""),this.warn("Save this key now \u2014 it will not be shown again."),i.save&&(o(e.key,process.env.RULEMETRIC_API_URL),this.log(""),this.log(`Key saved to ${c.join(s(),"env")} (RULEMETRIC_API_KEY)`),this.log("Hooks and proxy will use this key automatically."))}};export{t as default};
@@ -1,4 +1,4 @@
1
- import{a as f}from"../../chunk-RG3R4EAB.js";import{a as w}from"../../chunk-MU7KKU3O.js";import"../../chunk-IZTIYR5Q.js";import{c}from"../../chunk-FKTT7A4H.js";import"../../chunk-VIFOLTZT.js";import{b as n}from"../../chunk-4FJYVYCU.js";import"../../chunk-3AV3GTMP.js";import{b as r,d as a}from"../../chunk-76UKAFNM.js";import"../../chunk-42A4PUW7.js";import"../../chunk-XQYAVSUQ.js";import{b as m,d,h as u,i as g}from"../../chunk-PZNWH4VQ.js";import{a as l}from"../../chunk-ZLLER3HP.js";import{Flags as p}from"@oclif/core";var h=class y extends w{static{l(this,"AuthLogin")}static description="Log in to RuleMetric";static examples=["<%= config.bin %> auth login","<%= config.bin %> auth login -e user@example.com"];static flags={email:p.string({char:"e",description:"Email address"}),password:p.string({char:"p",description:"Password (for non-interactive use)"}),"api-key":p.string({description:"Authenticate with an API key from https://rulemetric.com/connect (required for Google/GitHub sign-ins, which have no password)",exclusive:["password"]})};async run(){let{flags:s}=await this.parse(y);if(s["api-key"]){await this.loginWithApiKey(s["api-key"]);return}let e=s.email,t=s.password;if(!e||!t){process.stdin.isTTY||this.error("Missing credentials in a non-interactive shell. Pass --email/-e and --password/-p, or set RULEMETRIC_API_KEY (create a key at https://rulemetric.com/connect).");let{input:o,password:k}=await import("@inquirer/prompts");this.log("Signed up with Google or GitHub? You have no password \u2014 press Ctrl-C and run:"),this.log(" rulemetric auth login --api-key <key> (create one at https://rulemetric.com/connect)"),this.log(""),e||(e=await o({message:"Email:"})),t||(t=await k({message:"Password:"}))}let i;try{i=await a("/auth/login",{method:"POST",body:{email:e,password:t},timeoutMs:2e4})}catch(o){throw o instanceof r&&o.statusCode===401&&this.error(`Invalid email or password.
1
+ import{a as f}from"../../chunk-QPVUGTDP.js";import{a as w}from"../../chunk-WUCACPGC.js";import"../../chunk-IZTIYR5Q.js";import{c}from"../../chunk-WL5ZWQAS.js";import"../../chunk-KEVDLLHT.js";import{b as n}from"../../chunk-DX6IPDED.js";import"../../chunk-3AV3GTMP.js";import{b as r,d as a}from"../../chunk-GIXHG5FK.js";import"../../chunk-X6CF5KTW.js";import"../../chunk-XQYAVSUQ.js";import{b as m,d,h as u,i as g}from"../../chunk-PZNWH4VQ.js";import{a as l}from"../../chunk-ZLLER3HP.js";import{Flags as p}from"@oclif/core";var h=class y extends w{static{l(this,"AuthLogin")}static description="Log in to RuleMetric";static examples=["<%= config.bin %> auth login","<%= config.bin %> auth login -e user@example.com"];static flags={email:p.string({char:"e",description:"Email address"}),password:p.string({char:"p",description:"Password (for non-interactive use)"}),"api-key":p.string({description:"Authenticate with an API key from https://rulemetric.com/connect (required for Google/GitHub sign-ins, which have no password)",exclusive:["password"]})};async run(){let{flags:s}=await this.parse(y);if(s["api-key"]){await this.loginWithApiKey(s["api-key"]);return}let e=s.email,t=s.password;if(!e||!t){process.stdin.isTTY||this.error("Missing credentials in a non-interactive shell. Pass --email/-e and --password/-p, or set RULEMETRIC_API_KEY (create a key at https://rulemetric.com/connect).");let{input:o,password:k}=await import("@inquirer/prompts");this.log("Signed up with Google or GitHub? You have no password \u2014 press Ctrl-C and run:"),this.log(" rulemetric auth login --api-key <key> (create one at https://rulemetric.com/connect)"),this.log(""),e||(e=await o({message:"Email:"})),t||(t=await k({message:"Password:"}))}let i;try{i=await a("/auth/login",{method:"POST",body:{email:e,password:t},timeoutMs:2e4})}catch(o){throw o instanceof r&&o.statusCode===401&&this.error(`Invalid email or password.
2
2
 
3
3
  If you signed up with Google or GitHub, you have no password \u2014 that is why this cannot work. Create an API key at https://rulemetric.com/connect, then run:
4
4
  rulemetric auth login --api-key <key>`),o}let v=i.expiresAt??new Date(Date.now()+3600*1e3).toISOString();d({accessToken:i.accessToken,refreshToken:i.refreshToken,expiresAt:v,email:i.email}),u(i.accessToken,process.env.RULEMETRIC_API_URL),await n(),await f(this.log.bind(this),this.warn.bind(this),this.config.version),c("auth_login",{},this.config.version),this.log(`Logged in as ${i.email}`)}async loginWithApiKey(s){let e=s.trim();e||this.error("Empty --api-key. Create one at https://rulemetric.com/connect"),process.env.RULEMETRIC_API_KEY=e;try{await a("/api/setup/status",{timeoutMs:2e4})}catch(t){throw delete process.env.RULEMETRIC_API_KEY,t instanceof r&&(t.statusCode===401||t.statusCode===403)&&this.error("That API key was rejected. Check you copied it whole (it is shown only once at creation) or mint a new one at https://rulemetric.com/connect"),t}g(e,process.env.RULEMETRIC_API_URL),m(),await n(),c("auth_login",{method:"api_key"},this.config.version),this.log(`Authenticated with API key ${e.slice(0,11)}...`),this.log("Verify any time with: rulemetric auth status")}};export{h as default};
@@ -1 +1 @@
1
- import{a as s}from"../../chunk-MU7KKU3O.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-FKTT7A4H.js";import"../../chunk-VIFOLTZT.js";import"../../chunk-4FJYVYCU.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-76UKAFNM.js";import"../../chunk-42A4PUW7.js";import"../../chunk-XQYAVSUQ.js";import{f as i,j as r}from"../../chunk-PZNWH4VQ.js";import{a as o}from"../../chunk-ZLLER3HP.js";var e=class t extends s{static{o(this,"AuthLogout")}static description="Log out of RuleMetric";static examples=["<%= config.bin %> auth logout"];async run(){await this.parse(t),i(),r(),this.log("Logged out successfully.")}};export{e as default};
1
+ import{a as s}from"../../chunk-WUCACPGC.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-WL5ZWQAS.js";import"../../chunk-KEVDLLHT.js";import"../../chunk-DX6IPDED.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-GIXHG5FK.js";import"../../chunk-X6CF5KTW.js";import"../../chunk-XQYAVSUQ.js";import{f as i,j as r}from"../../chunk-PZNWH4VQ.js";import{a as o}from"../../chunk-ZLLER3HP.js";var e=class t extends s{static{o(this,"AuthLogout")}static description="Log out of RuleMetric";static examples=["<%= config.bin %> auth logout"];async run(){await this.parse(t),i(),r(),this.log("Logged out successfully.")}};export{e as default};
@@ -1,4 +1,4 @@
1
- import{a as k}from"../../chunk-MU7KKU3O.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-FKTT7A4H.js";import"../../chunk-VIFOLTZT.js";import"../../chunk-4FJYVYCU.js";import"../../chunk-3AV3GTMP.js";import{e as n,i as c}from"../../chunk-76UKAFNM.js";import"../../chunk-42A4PUW7.js";import"../../chunk-XQYAVSUQ.js";import"../../chunk-PZNWH4VQ.js";import{a as s}from"../../chunk-ZLLER3HP.js";import{Args as y}from"@oclif/core";var a=class m extends k{static{s(this,"AuthRevokeKey")}static description="Revoke an API key (run with no argument to list active keys)";static examples=["<%= config.bin %> auth revoke-key","<%= config.bin %> auth revoke-key rm_abc12345",'<%= config.bin %> auth revoke-key "my-laptop (auto)"'];static args={id:y.string({description:"API key ID, prefix (rm_xxxxxxxx), or name"})};async run(){let{args:o}=await this.parse(m),r=(await n("/api/auth/api-keys")).filter(e=>!e.revokedAt);if(!o.id){if(r.length===0){this.log("No active API keys.");return}this.log(`Active API keys \u2014 pass an id, prefix, or name to revoke one:
1
+ import{a as k}from"../../chunk-WUCACPGC.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-WL5ZWQAS.js";import"../../chunk-KEVDLLHT.js";import"../../chunk-DX6IPDED.js";import"../../chunk-3AV3GTMP.js";import{e as n,i as c}from"../../chunk-GIXHG5FK.js";import"../../chunk-X6CF5KTW.js";import"../../chunk-XQYAVSUQ.js";import"../../chunk-PZNWH4VQ.js";import{a as s}from"../../chunk-ZLLER3HP.js";import{Args as y}from"@oclif/core";var a=class m extends k{static{s(this,"AuthRevokeKey")}static description="Revoke an API key (run with no argument to list active keys)";static examples=["<%= config.bin %> auth revoke-key","<%= config.bin %> auth revoke-key rm_abc12345",'<%= config.bin %> auth revoke-key "my-laptop (auto)"'];static args={id:y.string({description:"API key ID, prefix (rm_xxxxxxxx), or name"})};async run(){let{args:o}=await this.parse(m),r=(await n("/api/auth/api-keys")).filter(e=>!e.revokedAt);if(!o.id){if(r.length===0){this.log("No active API keys.");return}this.log(`Active API keys \u2014 pass an id, prefix, or name to revoke one:
2
2
  `);for(let e of r)this.log(` ${e.id} ${e.keyPrefix}... ${e.name}`);return}let i=o.id,t=r.filter(e=>e.id===i||e.name===i||i.startsWith("rm_")&&i.startsWith(e.keyPrefix));t.length===0&&this.error(`No active API key matches "${i}". Run \`rulemetric auth revoke-key\` with no argument to list keys.`),t.length>1&&this.error(`"${i}" matches ${t.length} keys \u2014 use the exact key ID:
3
3
  `+t.map(e=>` ${e.id} ${e.keyPrefix}... ${e.name}`).join(`
4
4
  `)),await c(`/api/auth/api-keys/${t[0].id}`),this.log(`API key ${t[0].keyPrefix}... ("${t[0].name}") revoked.`)}};export{a as default};
@@ -1 +1 @@
1
- import{a as g}from"../../chunk-RG3R4EAB.js";import{a as h}from"../../chunk-MU7KKU3O.js";import"../../chunk-IZTIYR5Q.js";import{c as d}from"../../chunk-FKTT7A4H.js";import"../../chunk-VIFOLTZT.js";import{b as l}from"../../chunk-4FJYVYCU.js";import"../../chunk-3AV3GTMP.js";import{b as m,d as p}from"../../chunk-76UKAFNM.js";import"../../chunk-42A4PUW7.js";import"../../chunk-XQYAVSUQ.js";import{d as n,h as c}from"../../chunk-PZNWH4VQ.js";import{a as o}from"../../chunk-ZLLER3HP.js";import{Flags as u}from"@oclif/core";var t=class f extends h{static{o(this,"AuthSignup")}static description="Create a RuleMetric account from the CLI";static examples=["<%= config.bin %> auth signup","<%= config.bin %> auth signup -e user@example.com"];static flags={email:u.string({char:"e",description:"Email address"}),password:u.string({char:"p",description:"Password (min 8 chars; for non-interactive use)"})};async run(){let{flags:a}=await this.parse(f),i=a.email,r=a.password;if(!i||!r){process.stdin.isTTY||this.error("Missing credentials in a non-interactive shell. Pass --email/-e and --password/-p.");let{input:s,password:v}=await import("@inquirer/prompts");i||(i=await s({message:"Email:"})),r||(r=await v({message:"Password (min 8 chars):"}))}let e;try{e=await p("/auth/signup",{method:"POST",body:{email:i,password:r},timeoutMs:2e4})}catch(s){throw s instanceof m&&s.statusCode===409&&this.error(`An account with ${i} already exists. Run: rulemetric auth login -e ${i}`),s}if(e.confirmationRequired||!e.accessToken||!e.refreshToken){this.log(`Account created for ${e.email}.`),this.log("Check your email and click the confirmation link, then run:"),this.log(` rulemetric auth login -e ${e.email}`);return}let w=e.expiresAt??new Date(Date.now()+3600*1e3).toISOString();n({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:w,email:e.email}),c(e.accessToken,process.env.RULEMETRIC_API_URL),await l(),await g(this.log.bind(this),this.warn.bind(this),this.config.version),d("auth_signup",{},this.config.version),this.log(`Signed up and logged in as ${e.email}`)}};export{t as default};
1
+ import{a as g}from"../../chunk-QPVUGTDP.js";import{a as h}from"../../chunk-WUCACPGC.js";import"../../chunk-IZTIYR5Q.js";import{c as d}from"../../chunk-WL5ZWQAS.js";import"../../chunk-KEVDLLHT.js";import{b as l}from"../../chunk-DX6IPDED.js";import"../../chunk-3AV3GTMP.js";import{b as m,d as p}from"../../chunk-GIXHG5FK.js";import"../../chunk-X6CF5KTW.js";import"../../chunk-XQYAVSUQ.js";import{d as n,h as c}from"../../chunk-PZNWH4VQ.js";import{a as o}from"../../chunk-ZLLER3HP.js";import{Flags as u}from"@oclif/core";var t=class f extends h{static{o(this,"AuthSignup")}static description="Create a RuleMetric account from the CLI";static examples=["<%= config.bin %> auth signup","<%= config.bin %> auth signup -e user@example.com"];static flags={email:u.string({char:"e",description:"Email address"}),password:u.string({char:"p",description:"Password (min 8 chars; for non-interactive use)"})};async run(){let{flags:a}=await this.parse(f),i=a.email,r=a.password;if(!i||!r){process.stdin.isTTY||this.error("Missing credentials in a non-interactive shell. Pass --email/-e and --password/-p.");let{input:s,password:v}=await import("@inquirer/prompts");i||(i=await s({message:"Email:"})),r||(r=await v({message:"Password (min 8 chars):"}))}let e;try{e=await p("/auth/signup",{method:"POST",body:{email:i,password:r},timeoutMs:2e4})}catch(s){throw s instanceof m&&s.statusCode===409&&this.error(`An account with ${i} already exists. Run: rulemetric auth login -e ${i}`),s}if(e.confirmationRequired||!e.accessToken||!e.refreshToken){this.log(`Account created for ${e.email}.`),this.log("Check your email and click the confirmation link, then run:"),this.log(` rulemetric auth login -e ${e.email}`);return}let w=e.expiresAt??new Date(Date.now()+3600*1e3).toISOString();n({accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:w,email:e.email}),c(e.accessToken,process.env.RULEMETRIC_API_URL),await l(),await g(this.log.bind(this),this.warn.bind(this),this.config.version),d("auth_signup",{},this.config.version),this.log(`Signed up and logged in as ${e.email}`)}};export{t as default};
@@ -1 +1 @@
1
- import{a as c}from"../../chunk-W2MV25SB.js";import{a as g}from"../../chunk-MU7KKU3O.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-FKTT7A4H.js";import"../../chunk-VIFOLTZT.js";import"../../chunk-4FJYVYCU.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-76UKAFNM.js";import"../../chunk-42A4PUW7.js";import"../../chunk-XQYAVSUQ.js";import{a,e as l,l as t}from"../../chunk-PZNWH4VQ.js";import{a as r}from"../../chunk-ZLLER3HP.js";import*as u from"node:path";var o=class h extends g{static{r(this,"AuthStatus")}static description="Show current authentication status";static examples=["<%= config.bin %> auth status"];async run(){await this.parse(h);let e=l(),i=process.env.RULEMETRIC_API_KEY,s=a().apiKey;if(i||s){let m=i||s,p=i?"RULEMETRIC_API_KEY env var":u.join(t(),"env");this.log(`Authenticated via API key ${m.slice(0,11)}... (${p})`),e&&this.log(`Logged in as: ${e.email}`),this.log(`Config: ${t()}`);return}if(!e){this.log("Not logged in. Run `rulemetric auth login` to authenticate.");return}let n=new Date(e.expiresAt).getTime();if(Number.isNaN(n)||Date.now()>=n){this.log("Session expired. Run `rulemetric auth login` to re-authenticate.");return}this.log(`Logged in as: ${e.email}`),this.log(`Session expires: ${c(e.expiresAt)}`),this.log(`Config: ${t()}`)}};export{o as default};
1
+ import{a as c}from"../../chunk-W2MV25SB.js";import{a as g}from"../../chunk-WUCACPGC.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-WL5ZWQAS.js";import"../../chunk-KEVDLLHT.js";import"../../chunk-DX6IPDED.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-GIXHG5FK.js";import"../../chunk-X6CF5KTW.js";import"../../chunk-XQYAVSUQ.js";import{a,e as l,l as t}from"../../chunk-PZNWH4VQ.js";import{a as r}from"../../chunk-ZLLER3HP.js";import*as u from"node:path";var o=class h extends g{static{r(this,"AuthStatus")}static description="Show current authentication status";static examples=["<%= config.bin %> auth status"];async run(){await this.parse(h);let e=l(),i=process.env.RULEMETRIC_API_KEY,s=a().apiKey;if(i||s){let m=i||s,p=i?"RULEMETRIC_API_KEY env var":u.join(t(),"env");this.log(`Authenticated via API key ${m.slice(0,11)}... (${p})`),e&&this.log(`Logged in as: ${e.email}`),this.log(`Config: ${t()}`);return}if(!e){this.log("Not logged in. Run `rulemetric auth login` to authenticate.");return}let n=new Date(e.expiresAt).getTime();if(Number.isNaN(n)||Date.now()>=n){this.log("Session expired. Run `rulemetric auth login` to re-authenticate.");return}this.log(`Logged in as: ${e.email}`),this.log(`Session expires: ${c(e.expiresAt)}`),this.log(`Config: ${t()}`)}};export{o as default};
@@ -1,2 +1,2 @@
1
- import{a as f,b as k,c as S,d as x,e as R,f as n,g as y}from"../../chunk-VALRPZXH.js";import{b as C,c as w,g as v,h as b}from"../../chunk-QI3FJKGK.js";import{a as u}from"../../chunk-MU7KKU3O.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-FKTT7A4H.js";import"../../chunk-VIFOLTZT.js";import"../../chunk-4FJYVYCU.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-76UKAFNM.js";import"../../chunk-42A4PUW7.js";import"../../chunk-XQYAVSUQ.js";import{l as m}from"../../chunk-PZNWH4VQ.js";import{a as h}from"../../chunk-ZLLER3HP.js";import{existsSync as O}from"node:fs";import{Flags as c}from"@oclif/core";var g=class E extends u{static{h(this,"CaptureScope")}static description="Show or set which projects RuleMetric captures \u2014 the Codex sweep and hook-driven sessions each have their own scope";static examples=["<%= config.bin %> <%= command.id %>","<%= config.bin %> <%= command.id %> --add ~/work/client-a --add ~/work/client-b","<%= config.bin %> <%= command.id %> --tool hooks --add ~/work/client-a","<%= config.bin %> <%= command.id %> --tool hooks --off","<%= config.bin %> <%= command.id %> --remove ~/work/client-a","<%= config.bin %> <%= command.id %> --off","<%= config.bin %> <%= command.id %> --all"];static flags={tool:c.string({description:'Which capture path to edit: "codex" (the worker transcript sweep, the default) or "hooks" (Claude Code / Cursor / Copilot / Antigravity hook sessions).',options:["codex","hooks"],default:"codex"}),add:c.string({description:"Capture sessions under this path (repeatable). Implies an allowlist.",multiple:!0}),remove:c.string({description:"Stop capturing under this path (repeatable).",multiple:!0}),off:c.boolean({description:"Turn this capture path off entirely.",exclusive:["all"]}),all:c.boolean({description:"Capture every project (the default).",exclusive:["off"]}),clear:c.boolean({description:"Remove this scope, restoring the default."})};async run(){let{flags:o}=await this.parse(E),s=m(),d=f(s);if(!((o.add?.length??0)>0||(o.remove?.length??0)>0||o.off||o.all||o.clear)){await this.show(s,d);return}for(let t of[...o.add??[],...o.remove??[]])R(t)||this.error(`Not an absolute path: ${t}
1
+ import{a as f,b as k,c as S,d as x,e as R,f as n,g as y}from"../../chunk-VALRPZXH.js";import{b as C,c as w,g as v,h as b}from"../../chunk-QI3FJKGK.js";import{a as u}from"../../chunk-WUCACPGC.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-WL5ZWQAS.js";import"../../chunk-KEVDLLHT.js";import"../../chunk-DX6IPDED.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-GIXHG5FK.js";import"../../chunk-X6CF5KTW.js";import"../../chunk-XQYAVSUQ.js";import{l as m}from"../../chunk-PZNWH4VQ.js";import{a as h}from"../../chunk-ZLLER3HP.js";import{existsSync as O}from"node:fs";import{Flags as c}from"@oclif/core";var g=class E extends u{static{h(this,"CaptureScope")}static description="Show or set which projects RuleMetric captures \u2014 the Codex sweep and hook-driven sessions each have their own scope";static examples=["<%= config.bin %> <%= command.id %>","<%= config.bin %> <%= command.id %> --add ~/work/client-a --add ~/work/client-b","<%= config.bin %> <%= command.id %> --tool hooks --add ~/work/client-a","<%= config.bin %> <%= command.id %> --tool hooks --off","<%= config.bin %> <%= command.id %> --remove ~/work/client-a","<%= config.bin %> <%= command.id %> --off","<%= config.bin %> <%= command.id %> --all"];static flags={tool:c.string({description:'Which capture path to edit: "codex" (the worker transcript sweep, the default) or "hooks" (Claude Code / Cursor / Copilot / Antigravity hook sessions).',options:["codex","hooks"],default:"codex"}),add:c.string({description:"Capture sessions under this path (repeatable). Implies an allowlist.",multiple:!0}),remove:c.string({description:"Stop capturing under this path (repeatable).",multiple:!0}),off:c.boolean({description:"Turn this capture path off entirely.",exclusive:["all"]}),all:c.boolean({description:"Capture every project (the default).",exclusive:["off"]}),clear:c.boolean({description:"Remove this scope, restoring the default."})};async run(){let{flags:o}=await this.parse(E),s=m(),d=f(s);if(!((o.add?.length??0)>0||(o.remove?.length??0)>0||o.off||o.all||o.clear)){await this.show(s,d);return}for(let t of[...o.add??[],...o.remove??[]])R(t)||this.error(`Not an absolute path: ${t}
2
2
  Use an absolute path or ~/\u2026 \u2014 relative paths cannot be matched against a session's cwd.`);for(let t of o.add??[]){let a=x(t);O(a)||this.warn(`${a} does not exist yet \u2014 added anyway, but nothing will match until it does.`)}let e;try{e=k(s)}catch(t){o.clear||this.error(t instanceof Error?t.message:String(t));let a=y(s);this.warn(`${f(s)} was not valid JSON \u2014 saved it to ${a} and starting fresh.`),e={}}let i=o.tool??"codex",r=void 0,l=!1;if(o.clear&&({config:e}=n(e,{op:"clear"},r,i)),o.off&&({config:e}=n(e,{op:"mode",mode:"off"},r,i)),o.all&&({config:e}=n(e,{op:"mode",mode:"all"},r,i)),o.remove?.length){let t=n(e,{op:"remove",roots:o.remove},r,i);e=t.config,l=t.emptiedToOff}o.add?.length&&({config:e}=n(e,{op:"add",roots:o.add},r,i)),S(s,e),l&&(this.log(`Removed the last root \u2014 ${i==="hooks"?"hook":"Codex"} capture is now OFF rather than silently capturing everything.`),this.log("Use --all to go back to capturing every project.")),await this.show(s,d),this.log(""),this.log(i==="hooks"?"Takes effect on the next hook fire. No restart needed.":"Takes effect on the next sweep (within ~30s). No restart needed.")}async show(o,s){let d=await C({configDir:o}),p=await w({configDir:o}),e=h((i,r,l,t)=>{if(this.log(`${i}: ${l}`),r.roots.length)for(let a of r.roots)this.log(` \u2022 ${a}`);r.error&&(this.log(" This scope is FAILING CLOSED \u2014 nothing is being captured on this path."),this.log(` Fix the file, or run \`rulemetric capture scope ${i==="Hook capture"?"--tool hooks ":""}--clear\` to start over.`)),r.source==="env"&&this.log(` Set by environment variable, which outranks the config file (${t}).`)},"print");e("Codex capture",d,v(d),"RULEMETRIC_CODEX_CAPTURE / RULEMETRIC_CODEX_ROOTS"),e("Hook capture",p,b(p),"RULEMETRIC_HOOKS_CAPTURE / RULEMETRIC_HOOKS_ROOTS"),this.log(`Config: ${s}`)}};export{g as default};