@rulemetric/cli 0.12.4 → 0.12.6

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 (210) hide show
  1. package/dist/base-command.js +1 -1
  2. package/dist/{chunk-LVAROIKP.js → chunk-22ZDUL6H.js} +1 -1
  3. package/dist/{chunk-FNMJ6E6F.js → chunk-2KJAM2NG.js} +1 -1
  4. package/dist/chunk-2TJ7Q2OU.js +1 -0
  5. package/dist/{chunk-3JSYVZOB.js → chunk-3DZD322E.js} +1 -1
  6. package/dist/{chunk-KHCMVYTH.js → chunk-5N5S3NKS.js} +1 -1
  7. package/dist/{chunk-2MZFB46B.js → chunk-5OX6YKTR.js} +1 -1
  8. package/dist/{chunk-K6T4ODPZ.js → chunk-5PM4E27L.js} +1 -1
  9. package/dist/{chunk-VC3DJPUB.js → chunk-A2LHEUNW.js} +1 -1
  10. package/dist/{chunk-7BLO7ECB.js → chunk-AGK5AUWT.js} +1 -1
  11. package/dist/{chunk-YRTG6SX6.js → chunk-AKXGUQ5B.js} +1 -1
  12. package/dist/{chunk-J35L3LR3.js → chunk-ARC4Q3GL.js} +1 -1
  13. package/dist/{chunk-XZY2W3D3.js → chunk-BTQQPQRG.js} +1 -1
  14. package/dist/{chunk-5BTNALJL.js → chunk-C6GLNE6X.js} +1 -1
  15. package/dist/{chunk-D4UDSY7Y.js → chunk-CPDMJGTC.js} +1 -1
  16. package/dist/{chunk-QLG6OCYF.js → chunk-CZTTW3MZ.js} +1 -1
  17. package/dist/{chunk-SZUH54L4.js → chunk-DCH3QWB7.js} +1 -1
  18. package/dist/{chunk-65TQMBNF.js → chunk-DSJNZWCZ.js} +1 -1
  19. package/dist/{chunk-ZQJWKIJS.js → chunk-E4RGYYBC.js} +1 -1
  20. package/dist/{chunk-VTUTSUFW.js → chunk-EZHL527S.js} +1 -1
  21. package/dist/{chunk-MOY7XDR6.js → chunk-FE2UWAIP.js} +1 -1
  22. package/dist/{chunk-TZUTX4PG.js → chunk-FUYR7CFD.js} +1 -1
  23. package/dist/{chunk-LW3UE2FY.js → chunk-G3HODHFN.js} +1 -1
  24. package/dist/{chunk-VIFE47RC.js → chunk-GHWBW2IW.js} +1 -1
  25. package/dist/{chunk-OEZNBFJ2.js → chunk-GOA5Q6TY.js} +1 -1
  26. package/dist/{chunk-RK2LZIBA.js → chunk-GRPUY2EZ.js} +1 -1
  27. package/dist/{chunk-E7N5R3HV.js → chunk-HQCPGDQE.js} +1 -1
  28. package/dist/{chunk-5C3DRKW3.js → chunk-INSKP5ED.js} +1 -1
  29. package/dist/{chunk-UQSUSB6G.js → chunk-MILLBGCB.js} +1 -1
  30. package/dist/{chunk-FIPW2SGV.js → chunk-MJ5H7RDK.js} +1 -1
  31. package/dist/{chunk-2IEYDOFE.js → chunk-NKJTNGXR.js} +1 -1
  32. package/dist/{chunk-EHNPJJIH.js → chunk-NVABG3AO.js} +1 -1
  33. package/dist/{chunk-LDQ6FLET.js → chunk-O65AQZYB.js} +1 -1
  34. package/dist/chunk-ONRQDI3N.js +1 -0
  35. package/dist/{chunk-6PUH7HEL.js → chunk-OOFGV7EX.js} +1 -1
  36. package/dist/chunk-OZQNSELV.js +31 -0
  37. package/dist/{chunk-OCHAV6YZ.js → chunk-PVPYLKB3.js} +1 -1
  38. package/dist/{chunk-SD626JBZ.js → chunk-PWTTCSQA.js} +1 -1
  39. package/dist/{chunk-PQMWZHEY.js → chunk-RLEMDKQ4.js} +1 -1
  40. package/dist/{chunk-4XLMX642.js → chunk-S2SKT5PV.js} +1 -1
  41. package/dist/chunk-SIGZEQ3K.js +1 -0
  42. package/dist/{chunk-XUGWUFIQ.js → chunk-TBU5SWA4.js} +1 -1
  43. package/dist/chunk-TYFEWLYZ.js +2 -0
  44. package/dist/{chunk-CRPOQMQ2.js → chunk-UA5GEVGW.js} +1 -1
  45. package/dist/{chunk-2AVGUZ2P.js → chunk-UGACB66X.js} +1 -1
  46. package/dist/{chunk-LZJXW3B6.js → chunk-UKOI2Q4J.js} +1 -1
  47. package/dist/{chunk-PMW35N32.js → chunk-UTAETY5Z.js} +1 -1
  48. package/dist/chunk-UUFCTEBT.js +1 -0
  49. package/dist/chunk-UXB6DRR7.js +3 -0
  50. package/dist/chunk-VS5ROGDP.js +1 -0
  51. package/dist/{chunk-WRQEHXSN.js → chunk-VYZKKSX4.js} +1 -1
  52. package/dist/{chunk-T67L2YTW.js → chunk-W23MESHM.js} +1 -1
  53. package/dist/{chunk-LYP3LNFL.js → chunk-W67DO5PT.js} +1 -1
  54. package/dist/{chunk-TJYXSMQV.js → chunk-WCIX5KWG.js} +1 -1
  55. package/dist/{chunk-OOGTQOL3.js → chunk-WMIUFMDI.js} +5 -5
  56. package/dist/{chunk-Y6TAPCA5.js → chunk-WO6MS654.js} +1 -1
  57. package/dist/{chunk-SVON2JIS.js → chunk-WTMJSL7R.js} +1 -1
  58. package/dist/{chunk-YTPQ7VBO.js → chunk-YSLKV4XC.js} +1 -1
  59. package/dist/{chunk-NMWP3JLW.js → chunk-Z4YVOVMM.js} +1 -1
  60. package/dist/commands/antigravity/backfill.js +1 -1
  61. package/dist/commands/auth/create-key.js +1 -1
  62. package/dist/commands/auth/login.js +1 -1
  63. package/dist/commands/auth/logout.js +1 -1
  64. package/dist/commands/auth/revoke-key.js +1 -1
  65. package/dist/commands/auth/signup.js +1 -1
  66. package/dist/commands/auth/status.js +1 -1
  67. package/dist/commands/capture/scope.js +1 -1
  68. package/dist/commands/catalog/index.js +1 -1
  69. package/dist/commands/catalog/recommend.js +1 -1
  70. package/dist/commands/crons/list.js +1 -1
  71. package/dist/commands/crons/run.js +1 -1
  72. package/dist/commands/dashboard.js +1 -1
  73. package/dist/commands/diagnostics.js +1 -1
  74. package/dist/commands/eval-targets/create.js +1 -1
  75. package/dist/commands/eval-targets/list.js +1 -1
  76. package/dist/commands/evals/agent.js +1 -1
  77. package/dist/commands/evals/auto-run.js +1 -1
  78. package/dist/commands/evals/benchmark.js +1 -1
  79. package/dist/commands/evals/compare.js +1 -1
  80. package/dist/commands/evals/create.js +1 -1
  81. package/dist/commands/evals/optimize-description.js +1 -1
  82. package/dist/commands/evals/optimize.js +1 -1
  83. package/dist/commands/evals/refine-cases.js +1 -1
  84. package/dist/commands/evals/run.js +1 -1
  85. package/dist/commands/evals/validate-judge.js +1 -1
  86. package/dist/commands/experiments/list.js +1 -1
  87. package/dist/commands/gateway/ensure.js +1 -1
  88. package/dist/commands/hooks/install.js +1 -1
  89. package/dist/commands/hooks/run.js +1 -1
  90. package/dist/commands/hooks/uninstall.js +1 -1
  91. package/dist/commands/instructions/create.js +1 -1
  92. package/dist/commands/instructions/dedupe.js +1 -1
  93. package/dist/commands/instructions/delete.js +1 -1
  94. package/dist/commands/instructions/fork.js +1 -1
  95. package/dist/commands/instructions/get.js +1 -1
  96. package/dist/commands/instructions/list.js +1 -1
  97. package/dist/commands/instructions/promote.js +1 -1
  98. package/dist/commands/instructions/pull.js +1 -1
  99. package/dist/commands/instructions/restore.js +1 -1
  100. package/dist/commands/instructions/retract.js +1 -1
  101. package/dist/commands/instructions/upstream.js +1 -1
  102. package/dist/commands/instructions/versions.js +1 -1
  103. package/dist/commands/launcher.js +1 -1
  104. package/dist/commands/local/down.js +1 -1
  105. package/dist/commands/local/up.js +1 -1
  106. package/dist/commands/org/current.js +1 -1
  107. package/dist/commands/org/list.js +1 -1
  108. package/dist/commands/org/switch.js +1 -1
  109. package/dist/commands/packs/add-instruction.js +1 -1
  110. package/dist/commands/packs/apply.js +1 -1
  111. package/dist/commands/packs/create.js +1 -1
  112. package/dist/commands/packs/fork.js +1 -1
  113. package/dist/commands/packs/get.js +1 -1
  114. package/dist/commands/packs/list.js +1 -1
  115. package/dist/commands/packs/remove-instruction.js +1 -1
  116. package/dist/commands/proxy/env.js +1 -1
  117. package/dist/commands/proxy/logs.js +1 -1
  118. package/dist/commands/proxy/restart.js +1 -1
  119. package/dist/commands/proxy/setup.js +1 -1
  120. package/dist/commands/proxy/start.js +1 -1
  121. package/dist/commands/proxy/status.js +1 -1
  122. package/dist/commands/proxy/stop.js +1 -1
  123. package/dist/commands/research/backfill.js +1 -1
  124. package/dist/commands/research/tail-transcript.js +1 -1
  125. package/dist/commands/service/install.js +1 -1
  126. package/dist/commands/service/status.js +1 -1
  127. package/dist/commands/service/uninstall.js +1 -1
  128. package/dist/commands/sessions/analyze.js +1 -1
  129. package/dist/commands/sessions/delete.js +1 -1
  130. package/dist/commands/sessions/end.js +1 -1
  131. package/dist/commands/sessions/import.js +1 -1
  132. package/dist/commands/sessions/list.js +1 -1
  133. package/dist/commands/sessions/start.js +1 -1
  134. package/dist/commands/setup.js +1 -1
  135. package/dist/commands/skills/export-approved.js +1 -1
  136. package/dist/commands/skills/install.js +1 -1
  137. package/dist/commands/skills/list.js +1 -1
  138. package/dist/commands/skills/publish.js +1 -1
  139. package/dist/commands/skills/search.js +1 -1
  140. package/dist/commands/skills/update.js +1 -1
  141. package/dist/commands/suggestions/accept.js +1 -1
  142. package/dist/commands/suggestions/auto.js +1 -1
  143. package/dist/commands/suggestions/dismiss.js +1 -1
  144. package/dist/commands/suggestions/list.js +1 -1
  145. package/dist/commands/suggestions/refresh.js +1 -1
  146. package/dist/commands/suggestions/undo.js +1 -1
  147. package/dist/dashboard/Dashboard.js +1 -1
  148. package/dist/dashboard/data.js +1 -1
  149. package/dist/dashboard/launcher/LauncherOverlay.js +1 -1
  150. package/dist/dashboard/launcher/api.js +1 -1
  151. package/dist/dashboard/launcher/useLaunchJobs.js +1 -1
  152. package/dist/lib/active-org-refresh.js +1 -1
  153. package/dist/lib/agent-loop.js +1 -1
  154. package/dist/lib/antigravity-capture-status.js +1 -0
  155. package/dist/lib/antigravity-transcript.js +1 -1
  156. package/dist/lib/api-client.js +1 -1
  157. package/dist/lib/attribution-recovery.js +1 -1
  158. package/dist/lib/claude-hook-timeouts.js +1 -0
  159. package/dist/lib/editor-proxy-pins.js +1 -1
  160. package/dist/lib/ensure-api-key.js +1 -1
  161. package/dist/lib/ensure-fresh-token.js +1 -1
  162. package/dist/lib/eval-benchmark.js +1 -1
  163. package/dist/lib/eval-candidate-run.js +1 -1
  164. package/dist/lib/eval-conversation-handler.js +1 -1
  165. package/dist/lib/eval-resume.js +1 -1
  166. package/dist/lib/eval-run-batch.js +1 -1
  167. package/dist/lib/evolution-enrolment.js +1 -1
  168. package/dist/lib/hooks-config.js +1 -1
  169. package/dist/lib/insights/generation/installed-asks.js +1 -1
  170. package/dist/lib/insights/nomination/nominate.js +1 -1
  171. package/dist/lib/instructions/acceptance/accept-events.js +1 -1
  172. package/dist/lib/instructions/acceptance/accept-hook.js +1 -1
  173. package/dist/lib/instructions/acceptance/hook-install.js +1 -1
  174. package/dist/lib/instructions/acceptance/reverse-applications.js +1 -1
  175. package/dist/lib/instructions/acceptance/suggestion-accept.js +1 -1
  176. package/dist/lib/jobs/handlers/cron-auto-accept-suggestions.js +1 -1
  177. package/dist/lib/jobs/handlers/cron-eval-autorun.js +1 -1
  178. package/dist/lib/jobs/handlers/cron-instruction-evolution.js +1 -1
  179. package/dist/lib/jobs/handlers/cron-instruction-training.js +1 -1
  180. package/dist/lib/jobs/handlers/cron-reconcile-attribution.js +1 -1
  181. package/dist/lib/jobs/handlers/cron-refine-cases.js +1 -1
  182. package/dist/lib/jobs/handlers/cron-refresh-pricing.js +1 -1
  183. package/dist/lib/jobs/handlers/cron-retire-unused-skills.js +1 -1
  184. package/dist/lib/jobs/handlers/cron-suggest-instructions.js +1 -1
  185. package/dist/lib/jobs/handlers/distill-memories.js +1 -1
  186. package/dist/lib/jobs/handlers/process-changelog.js +1 -1
  187. package/dist/lib/jobs/handlers/process-conversation.js +1 -1
  188. package/dist/lib/jobs/handlers/process-eval.js +1 -1
  189. package/dist/lib/jobs/handlers/process-insights.js +1 -1
  190. package/dist/lib/jobs/handlers/process-judge-review.js +1 -1
  191. package/dist/lib/jobs/handlers/process-launch.js +1 -1
  192. package/dist/lib/jobs/handlers/process-memory-ab.js +1 -1
  193. package/dist/lib/jobs/handlers/process-run-cleanup.js +1 -1
  194. package/dist/lib/jobs/handlers/process-session-goal.js +1 -1
  195. package/dist/lib/judge-review-runner.js +1 -1
  196. package/dist/lib/mac-sleep-log.js +1 -0
  197. package/dist/lib/machine-pause-detector.js +1 -0
  198. package/dist/lib/manual-tasks.js +1 -1
  199. package/dist/lib/refine-cases.js +1 -1
  200. package/dist/lib/research-client.js +1 -1
  201. package/dist/lib/retraction.js +1 -1
  202. package/dist/lib/setup-steps.js +1 -1
  203. package/dist/lib/telemetry.js +1 -1
  204. package/dist/lib/terminal-target-heartbeat.js +1 -1
  205. package/oclif.manifest.json +1 -1
  206. package/package.json +6 -6
  207. package/dist/chunk-2K3RUBKC.js +0 -3
  208. package/dist/chunk-3QXRLIGC.js +0 -31
  209. package/dist/chunk-D55QB3QI.js +0 -1
  210. package/dist/chunk-QUOH6GWM.js +0 -1
@@ -0,0 +1,31 @@
1
+ import{f as x}from"./chunk-HFGO5762.js";import{a as b}from"./chunk-VS5ROGDP.js";import{a as r}from"./chunk-ZLLER3HP.js";import{execSync as h}from"node:child_process";import{existsSync as c,mkdirSync as y,readFileSync as p,writeFileSync as a,unlinkSync as v,copyFileSync as N}from"node:fs";import{homedir as f}from"node:os";import{join as i,dirname as U}from"node:path";function Z(e,t=f()){let o=["claude_code"];return c(i(t,".codex"))&&o.push("codex"),c(i(e,".cursor"))&&o.push("cursor"),c(i(e,".github"))&&o.push("copilot_agent"),c(i(t,".gemini"))&&o.push("antigravity"),o}r(Z,"detectInstalledTools");function L(e){let t=e?`PATH="${e}:$PATH" `:"",o=r(n=>({command:`${t}rulemetric hooks run ${n}`}),"cmd");return{version:1,hooks:{sessionStart:[o("session-start")],beforeSubmitPrompt:[o("user-prompt")],afterFileEdit:[o("post-tool-use")],beforeShellExecution:[o("post-tool-use")],afterShellExecution:[o("post-tool-use")],beforeMCPExecution:[o("post-tool-use")],afterMCPExecution:[o("post-tool-use")],afterAgentResponse:[o("assistant-response")],stop:[o("post-tool-use")],sessionEnd:[o("session-end")]}}}r(L,"generateCursorHooksConfig");function B(e){let t=e?`PATH="${e}:$PATH" `:"",o=r(n=>({type:"command",bash:`${t}rulemetric hooks run ${n}`}),"cmd");return{version:1,hooks:{sessionStart:[o("session-start")],userPromptSubmitted:[o("user-prompt")],postToolUse:[o("post-tool-use")],sessionEnd:[o("session-end")]}}}r(B,"generateCopilotHooksConfig");function J(e){let t=e?`PATH="${e}:$PATH" `:"",o=r(n=>({type:"command",command:`${t}rulemetric hooks run ${n}`,timeout:b[n]}),"mk");return{SessionStart:[{hooks:[o("session-start")]}],UserPromptSubmit:[{hooks:[o("user-prompt")]}],PostToolUse:[{matcher:".*",hooks:[o("post-tool-use")]}],SessionEnd:[{hooks:[o("session-end")]}]}}r(J,"generateClaudeCodeHooksConfig");function D(e){if(!c(e))return{settings:{},recoveredBackup:null};let t=p(e,"utf-8");try{return{settings:JSON.parse(t),recoveredBackup:null}}catch{let o=`${e}.corrupt.bak`;return a(o,t),{settings:{},recoveredBackup:o}}}r(D,"readClaudeSettings");function C(e,t){y(U(e),{recursive:!0});let o=null;return c(e)&&(o=`${e}.bak`,N(e,o)),a(e,JSON.stringify(t,null,2)+`
2
+ `),{backupPath:o}}r(C,"writeClaudeSettingsWithBackup");function k(e){if(!c(e))return{};let t=p(e,"utf-8");try{return JSON.parse(t)}catch{try{a(`${e}.corrupt.bak`,t)}catch{}return null}}r(k,"readMergeableJson");function tt(e,t){let o=J(t),n=e.hooks??{};for(let[s,u]of Object.entries(o)){let l=n[s]??[];l.some(m=>m?.hooks?.some(d=>typeof d?.command=="string"&&d.command.includes("rulemetric")))||(n[s]=[...l,...u])}e.hooks=n}r(tt,"mergeClaudeCodeHooks");function et(e){if(!e.hooks||typeof e.hooks!="object")return!1;let t=e.hooks;return Object.values(t).some(o=>Array.isArray(o)&&o.some(n=>n?.hooks?.some(s=>typeof s?.command=="string"&&s.command.includes("rulemetric"))))}r(et,"hasRulemetricClaudeHooks");function X(e){if(!e.hooks||typeof e.hooks!="object")return!1;let t=e.hooks,o=0;for(let n of Object.keys(t)){let s=t[n];if(!Array.isArray(s))continue;let u=s.filter(l=>{let g=l?.hooks?.some(m=>typeof m?.command=="string"&&m.command.includes("rulemetric"));return g&&(o+=1),!g});u.length===0?delete t[n]:t[n]=u}return Object.keys(t).length===0&&delete e.hooks,o>0}r(X,"removeClaudeCodeHooks");var M="localhost,127.0.0.1,*.supabase.co,*.supabase.in";function ot(e,t){return i(e,t?"settings.json":"settings.local.json")}r(ot,"claudeSettingsInstallPath");function F(e,t){let o=e.env;if(!o||typeof o!="object")return!1;let n=!1,s=o.HTTPS_PROXY;(s===`http://localhost:${t}`||s===`http://127.0.0.1:${t}`)&&(delete o.HTTPS_PROXY,n=!0),o.NO_PROXY===M&&(delete o.NO_PROXY,n=!0);let u=o.NODE_EXTRA_CA_CERTS;return typeof u=="string"&&u.includes(".mitmproxy")&&u.endsWith("mitmproxy-ca-cert.pem")&&(delete o.NODE_EXTRA_CA_CERTS,n=!0),n&&Object.keys(o).length===0&&delete e.env,n}r(F,"removeRulemetricProxyEnv");function R(e,t){let o=X(e),n=F(e,t),s=x(e);return{removedHooks:o,removedProxyEnv:n,removedStatusline:s,removed:o||n||s}}r(R,"removeRulemetricMachineState");function nt(e,t){let o={migrated:!1,backupPath:null,removedHooks:!1,removedProxyEnv:!1,removedStatusline:!1,removed:!1};if(!c(e))return o;let n;try{n=JSON.parse(p(e,"utf-8"))}catch{return o}let s=R(n,t);if(!s.removed)return o;let{backupPath:u}=C(e,n);return{...s,migrated:!0,backupPath:u}}r(nt,"migrateSharedClaudeSettings");function rt(e,t){let o=[];for(let n of["settings.json","settings.local.json"]){let s=i(e,n);if(!c(s))continue;let{settings:u,recoveredBackup:l}=D(s),g=R(u,t);g.removed&&C(s,u),o.push({...g,configPath:s,fileName:n,recoveredBackup:l,changed:g.removed})}return o}r(rt,"cleanClaudeSettingsFiles");function A(e,t){if(!c(e))return null;let o=i(e,"hooks.json"),n=L(t),s=k(o);if(s===null)return null;let u=s,l={...u.hooks??{}},g=r(d=>typeof d=="object"&&d!==null&&"command"in d&&typeof d.command=="string"&&d.command.includes("rulemetric"),"isRulemetricHook");for(let[d,j]of Object.entries(n.hooks)){let _=(l[d]??[]).filter($=>!g($));l[d]=[..._,...j]}let m={version:u.version??n.version,hooks:l};return a(o,JSON.stringify(m,null,2)+`
3
+ `),o}r(A,"writeCursorHooksToDir");function st(e,t){return A(i(e,".cursor"),t)}r(st,"writeCursorHooks");function it(e,t=f()){let o=i(t,".cursor");return c(o)?A(o,e):null}r(it,"writeCursorUserHooks");function ut(e,t){let o=i(e,".github");if(!c(o))return null;let n=i(o,"hooks");y(n,{recursive:!0});let s=i(n,"rulemetric.json"),u=B(t);return a(s,JSON.stringify(u,null,2)+`
4
+ `),s}r(ut,"writeCopilotHooks");function H(e){if(!c(e))return!1;let t;try{t=JSON.parse(p(e,"utf-8"))}catch{return!1}if(!t.hooks)return!1;let o=!1;for(let[n,s]of Object.entries(t.hooks)){let u=s.filter(l=>{if(typeof l!="object"||l===null||!("command"in l))return!0;let g=l.command;return typeof g=="string"&&g.includes("rulemetric")?(o=!0,!1):!0});u.length===0?delete t.hooks[n]:t.hooks[n]=u}return o&&a(e,JSON.stringify(t,null,2)+`
5
+ `),o}r(H,"removeCursorHooksFromFile");function ct(e){return H(i(e,".cursor","hooks.json"))}r(ct,"removeCursorHooks");function lt(){return H(i(f(),".cursor","hooks.json"))}r(lt,"removeCursorUserHooks");function at(e,t,o){let n=i(e,".cursor");if(!c(n))return!1;let s=i(n,"settings.json"),u=k(s);return u===null?!1:(u["http.proxy"]=`http://localhost:${t}`,u["http.proxyStrictSSL"]=c(o),a(s,JSON.stringify(u,null,2)+`
6
+ `),!0)}r(at,"writeCursorProxyConfig");function gt(e,t,o){let n=i(e,".vscode");if(!c(n))return!1;let s=i(n,"settings.json"),u=k(s);if(u===null)return!1;u["http.proxy"]=`http://localhost:${t}`,u["http.proxyStrictSSL"]=c(o);let l=u["github.copilot.advanced"]??{};return l["debug.overrideProxyUrl"]=`http://localhost:${t}`,u["github.copilot.advanced"]=l,a(s,JSON.stringify(u,null,2)+`
7
+ `),!0}r(gt,"writeVSCodeProxyConfig");function ft(e){let t=i(e,".vscode","settings.json");if(!c(t))return!1;let o;try{o=JSON.parse(p(t,"utf-8"))}catch{return!1}let n=!1;o["http.proxy"]&&(delete o["http.proxy"],delete o["http.proxyStrictSSL"],n=!0);let s=o["github.copilot.advanced"];return s?.["debug.overrideProxyUrl"]&&(delete s["debug.overrideProxyUrl"],Object.keys(s).length===0&&delete o["github.copilot.advanced"],n=!0),n&&a(t,JSON.stringify(o,null,2)+`
8
+ `),n}r(ft,"removeVSCodeProxyConfig");function dt(e){let t=i(e,".github","hooks","rulemetric.json");return c(t)?(v(t),!0):!1}r(dt,"removeCopilotHooks");var P="com.rulemetric.env";function O(){return i(f(),"Library","LaunchAgents",`${P}.plist`)}r(O,"getLaunchAgentPath");function pt(e,t){if(process.platform!=="darwin")return!1;let o=`http://localhost:${e}`;try{h(`launchctl setenv HTTPS_PROXY ${o}`,{stdio:"pipe"}),c(t)&&h(`launchctl setenv NODE_EXTRA_CA_CERTS ${t}`,{stdio:"pipe"})}catch{return!1}let n=O(),s=i(f(),"Library","LaunchAgents");y(s,{recursive:!0});let u=c(t)?`launchctl setenv NODE_EXTRA_CA_CERTS ${t};`:"",l=`if nc -z -w 1 127.0.0.1 ${e} 2>/dev/null; then launchctl setenv HTTPS_PROXY ${o};${u} else launchctl unsetenv HTTPS_PROXY; launchctl unsetenv NODE_EXTRA_CA_CERTS; fi`,g=`<?xml version="1.0" encoding="UTF-8"?>
9
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
10
+ "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
11
+ <plist version="1.0">
12
+ <dict>
13
+ <key>Label</key>
14
+ <string>${P}</string>
15
+ <key>ProgramArguments</key>
16
+ <array>
17
+ <string>/bin/sh</string>
18
+ <string>-c</string>
19
+ <string>${l}</string>
20
+ </array>
21
+ <key>RunAtLoad</key>
22
+ <true/>
23
+ </dict>
24
+ </plist>
25
+ `;return a(n,g),!0}r(pt,"installMacOSProxyEnv");function mt(){if(process.platform!=="darwin")return!1;let e=!1;try{h("launchctl unsetenv HTTPS_PROXY",{stdio:"pipe"}),h("launchctl unsetenv NODE_EXTRA_CA_CERTS",{stdio:"pipe"})}catch{}let t=O();return c(t)&&(v(t),e=!0),e}r(mt,"uninstallMacOSProxyEnv");function T(){return process.platform==="darwin"?i(f(),"Library","Application Support","Code","User","settings.json"):process.platform==="win32"?i(process.env.APPDATA??"","Code","User","settings.json"):i(f(),".config","Code","User","settings.json")}r(T,"getVSCodeUserSettingsPath");function kt(e){let t=T();if(!c(i(t,"..")))return!1;let o=k(t);return o===null||o["http.proxy"]&&!o["http.proxy"].includes("localhost")?!1:(o["http.proxy"]=`http://localhost:${e}`,o["http.proxyStrictSSL"]=!1,a(t,JSON.stringify(o,null,2)+`
26
+ `),!0)}r(kt,"writeVSCodeUserProxyConfig");function ht(){let e=T();if(!c(e))return!1;let t;try{t=JSON.parse(p(e,"utf-8"))}catch{return!1}return t["http.proxy"]?.includes("localhost")?(delete t["http.proxy"],delete t["http.proxyStrictSSL"],a(e,JSON.stringify(t,null,2)+`
27
+ `),!0):!1}r(ht,"removeVSCodeUserProxyConfig");function E(){return process.platform==="darwin"?i(f(),"Library","Application Support","Cursor","User","settings.json"):process.platform==="win32"?i(process.env.APPDATA??"","Cursor","User","settings.json"):i(f(),".config","Cursor","User","settings.json")}r(E,"getCursorUserSettingsPath");function yt(e){let t=E();if(!c(i(t,"..")))return!1;let o=k(t);return o===null||o["http.proxy"]&&!o["http.proxy"].includes("localhost")?!1:(o["http.proxy"]=`http://localhost:${e}`,o["http.proxyStrictSSL"]=!1,a(t,JSON.stringify(o,null,2)+`
28
+ `),!0)}r(yt,"writeCursorUserProxyConfig");function St(){let e=E();if(!c(e))return!1;let t;try{t=JSON.parse(p(e,"utf-8"))}catch{return!1}return t["http.proxy"]?.includes("localhost")?(delete t["http.proxy"],delete t["http.proxyStrictSSL"],a(e,JSON.stringify(t,null,2)+`
29
+ `),!0):!1}r(St,"removeCursorUserProxyConfig");function Y(){let e=process.execPath,t=process.argv[1];return t&&t.endsWith("run.js")?`${e} ${t}`:"rulemetric"}r(Y,"getRulemetricCommand");function I(){let e=Y(),t=r(o=>({type:"command",command:`RULEMETRIC_HOOK_TOOL=antigravity ${e} hooks run ${o}`,timeout:30}),"mk");return{rulemetric:{enabled:!0,SessionStart:[{hooks:[t("session-start")]}],PostToolUse:[{matcher:".*",hooks:[t("post-tool-use")]}],SessionEnd:[{hooks:[t("session-end")]}]}}}r(I,"generateAntigravityHooksConfig");function w(e){let t=i(e,"hooks.json"),o=k(t);if(o===null)return null;let n=I(),s={...o,rulemetric:n.rulemetric};return y(e,{recursive:!0}),a(t,JSON.stringify(s,null,2)+`
30
+ `),t}r(w,"writeAntigravityHooksToDir");function vt(e){return w(i(e,".agents"))}r(vt,"writeAntigravityHooks");function xt(e=f()){let t=i(e,".gemini");return c(t)?w(i(t,"config")):null}r(xt,"writeAntigravityUserHooks");function S(e){if(!c(e))return!1;let t;try{t=JSON.parse(p(e,"utf-8"))}catch{return!1}if(!("rulemetric"in t))return!1;if(delete t.rulemetric,Object.keys(t).length===0)try{v(e)}catch{}else a(e,JSON.stringify(t,null,2)+`
31
+ `);return!0}r(S,"removeAntigravityHooksFromFile");function bt(e){return S(i(e,".agents","hooks.json"))}r(bt,"removeAntigravityHooks");function Ct(){let e=S(i(f(),".gemini","config","hooks.json")),t=S(i(f(),".gemini","hooks.json"));return e||t}r(Ct,"removeAntigravityUserHooks");export{Z as a,L as b,B as c,J as d,D as e,C as f,tt as g,et as h,X as i,M as j,ot as k,F as l,R as m,nt as n,rt as o,st as p,it as q,ut as r,ct as s,lt as t,at as u,gt as v,ft as w,dt as x,pt as y,mt as z,T as A,kt as B,ht as C,E as D,yt as E,St as F,I as G,vt as H,xt as I,bt as J,Ct as K};
@@ -1 +1 @@
1
- import{a as I}from"./chunk-LVAROIKP.js";import{b as A,c as l,d as b}from"./chunk-D4UDSY7Y.js";import{f as k}from"./chunk-2AVGUZ2P.js";import{n as f,o as g,p as u,v,w as $,x as y}from"./chunk-OOGTQOL3.js";import{a as c}from"./chunk-ZLLER3HP.js";import{randomUUID as P}from"node:crypto";async function H(s){let{applyMode:e="human",...r}=s;await k("/api/recommendation-applications",{...r,harness:"claude_code",applyMode:e,status:"applied",applyBatchId:P(),applySeq:0})}c(H,"recordApplication");async function M(s,e){let r=c(t=>({action:"manual-required",instructionId:e.id,name:e.name,fileModified:!1,messages:t}),"refuse");if(s.actor!=="human")return r([`Not installed: ${e.name} is a hook, and a hook is a command this machine runs unattended.`,"Installing one is always a human decision \u2014 the same refusal the API makes server-side.",` Review it: rulemetric suggestions accept ${s.suggestionId}`]);let n=y(e);if(!n.spec)return r([`Not installed: ${e.name} does not contain an installable hook spec.`,...n.problems.map(t=>` ${t.field}: ${t.message}`)]);if(n.problems.length>0)return r([`Not installed: ${e.name}'s hook spec is not fit to act on.`,...n.problems.map(t=>` ${t.field}: ${t.message}`)]);let w=u(e.frontmatter),i=v(n.spec,w??void 0),p=f(i);if(p.length>0)return r([`Not installed: ${e.name}'s artifact spec is not fit to act on.`,...p.map(t=>` ${t.field}: ${t.message}`)]);let o=b(s.dir,i.requires);if(o.missing.length>0)return r([`Not installed: ${e.name} needs ${o.missing.join(", ")}, which is not present here.`,"It is left unapplied rather than installed and broken \u2014 a hook whose command is missing still runs, and fails, on every matching event.","Accept it again once the dependency exists."]);let a=A({dir:s.dir,instructionId:e.id,spec:n.spec});if(a.status==="refused")return r([`Not installed: ${e.name}.`,` ${a.reason}`]);let m=g(i,a.inverse);if(m.length>0)return l({dir:s.dir,inverse:a.inverse}),r([`Not installed: ${e.name} was written and then rolled back \u2014 the actuator could not produce a valid inverse.`,...m.map(t=>` ${t.field}: ${t.message}`)]);try{await H({instructionId:e.id,projectPath:s.projectPath,targetPath:a.target,beforeHash:a.beforeHash,appliedHash:a.inverse.hashAtWrite,boundaryClass:i.boundaryClass,targets:i.targets,inverse:a.inverse,requires:i.requires,provides:i.provides})}catch(t){let h=l({dir:s.dir,inverse:a.inverse});return r([`Not installed: ${e.name} \u2014 the effect could not be recorded, so it was undone.`,` ${t instanceof Error?t.message:String(t)}`,h.removed?" The hook was removed; your settings are as they were.":` WARNING: the rollback did not complete (${h.reason??"unknown reason"}). Check ${a.target} for the entry tagged with ${e.id}.`])}await I(s.suggestionId,s.projectPath,e.id,s.actor);let d=a.status==="installed"?[`Accepted: installed a ${n.spec.event} hook into ${a.target}.`]:[`Already present: this hook is already installed in ${a.target}.`];for(let t of $(n.spec))d.push(` ${t}`);return o.unverifiable.length>0&&d.push(` unchecked: ${o.unverifiable.join(", ")} \u2014 this command cannot verify that namespace.`),d.push(`Undo with: rulemetric suggestions undo ${e.id}`),{action:a.status==="installed"?"added":"already-present",instructionId:e.id,name:e.name,fileModified:a.status==="installed",messages:d}}c(M,"acceptHook");export{H as a,M as b};
1
+ import{a as I}from"./chunk-22ZDUL6H.js";import{b as A,c as l,d as b}from"./chunk-CPDMJGTC.js";import{f as k}from"./chunk-UGACB66X.js";import{n as f,o as g,p as u,v,w as $,x as y}from"./chunk-WMIUFMDI.js";import{a as c}from"./chunk-ZLLER3HP.js";import{randomUUID as P}from"node:crypto";async function H(s){let{applyMode:e="human",...r}=s;await k("/api/recommendation-applications",{...r,harness:"claude_code",applyMode:e,status:"applied",applyBatchId:P(),applySeq:0})}c(H,"recordApplication");async function M(s,e){let r=c(t=>({action:"manual-required",instructionId:e.id,name:e.name,fileModified:!1,messages:t}),"refuse");if(s.actor!=="human")return r([`Not installed: ${e.name} is a hook, and a hook is a command this machine runs unattended.`,"Installing one is always a human decision \u2014 the same refusal the API makes server-side.",` Review it: rulemetric suggestions accept ${s.suggestionId}`]);let n=y(e);if(!n.spec)return r([`Not installed: ${e.name} does not contain an installable hook spec.`,...n.problems.map(t=>` ${t.field}: ${t.message}`)]);if(n.problems.length>0)return r([`Not installed: ${e.name}'s hook spec is not fit to act on.`,...n.problems.map(t=>` ${t.field}: ${t.message}`)]);let w=u(e.frontmatter),i=v(n.spec,w??void 0),p=f(i);if(p.length>0)return r([`Not installed: ${e.name}'s artifact spec is not fit to act on.`,...p.map(t=>` ${t.field}: ${t.message}`)]);let o=b(s.dir,i.requires);if(o.missing.length>0)return r([`Not installed: ${e.name} needs ${o.missing.join(", ")}, which is not present here.`,"It is left unapplied rather than installed and broken \u2014 a hook whose command is missing still runs, and fails, on every matching event.","Accept it again once the dependency exists."]);let a=A({dir:s.dir,instructionId:e.id,spec:n.spec});if(a.status==="refused")return r([`Not installed: ${e.name}.`,` ${a.reason}`]);let m=g(i,a.inverse);if(m.length>0)return l({dir:s.dir,inverse:a.inverse}),r([`Not installed: ${e.name} was written and then rolled back \u2014 the actuator could not produce a valid inverse.`,...m.map(t=>` ${t.field}: ${t.message}`)]);try{await H({instructionId:e.id,projectPath:s.projectPath,targetPath:a.target,beforeHash:a.beforeHash,appliedHash:a.inverse.hashAtWrite,boundaryClass:i.boundaryClass,targets:i.targets,inverse:a.inverse,requires:i.requires,provides:i.provides})}catch(t){let h=l({dir:s.dir,inverse:a.inverse});return r([`Not installed: ${e.name} \u2014 the effect could not be recorded, so it was undone.`,` ${t instanceof Error?t.message:String(t)}`,h.removed?" The hook was removed; your settings are as they were.":` WARNING: the rollback did not complete (${h.reason??"unknown reason"}). Check ${a.target} for the entry tagged with ${e.id}.`])}await I(s.suggestionId,s.projectPath,e.id,s.actor);let d=a.status==="installed"?[`Accepted: installed a ${n.spec.event} hook into ${a.target}.`]:[`Already present: this hook is already installed in ${a.target}.`];for(let t of $(n.spec))d.push(` ${t}`);return o.unverifiable.length>0&&d.push(` unchecked: ${o.unverifiable.join(", ")} \u2014 this command cannot verify that namespace.`),d.push(`Undo with: rulemetric suggestions undo ${e.id}`),{action:a.status==="installed"?"added":"already-present",instructionId:e.id,name:e.name,fileModified:a.status==="installed",messages:d}}c(M,"acceptHook");export{H as a,M as b};
@@ -1 +1 @@
1
- import{a as E}from"./chunk-SVON2JIS.js";import{b as R,c as x}from"./chunk-KGURGIZ2.js";import{f as F}from"./chunk-2AVGUZ2P.js";import{a as s}from"./chunk-ZLLER3HP.js";var A="with_candidate",$="with_prior_version";function k(n){let t=n.filter(e=>e.configuration===A),r=[];for(let e of t){let u=n.find(o=>o.configuration===$&&o.evalId===e.evalId&&o.runNumber===e.runNumber);if(!u)continue;let l=h(e),f=h(u);l==null||f==null||r.push({withScore:l,withoutScore:f})}return r}s(k,"pairCandidateRuns");function h(n){return n.status!=="completed"?null:n.grading?.summary?.pass_rate??null}s(h,"evidenceOf");function P(n){let t=[],r=0;for(let e of n){if(e.status==="failed"){t.push(e.failure??{kind:"unknown",class:"infrastructure"});continue}h(e)==null&&(r+=1)}return{infrastructureFailed:t.length,ungradeable:r,summary:R(t)}}s(P,"accountForFailures");function Q(n){let{pairs:t,minPairs:r,accounting:e}=n;return t>=r?{kind:"proceed"}:e.infrastructureFailed<=0?{kind:"proceed"}:{kind:"infrastructure-incomplete",reason:`${t}/${r} pair(s) \u2014 ${e.infrastructureFailed} run(s) never executed (${e.summary.describe()}). Retry when the environment recovers; this is not a statement about the target.`}}s(Q,"attributeShortfall");function w(n,t,r,e){let u=[];for(let l of n)u.push({eval_:l,configuration:A,targetContent:t,runNumber:e}),u.push({eval_:l,configuration:$,targetContent:r,runNumber:e});return u}s(w,"buildCandidateQueue");async function N(n){let{cases:t,candidateContent:r,priorVersionContent:e,concurrency:u,runNumber:l,opts:f,onLog:o=s(()=>{},"onLog")}=n,p=w(t,r,e,l),i=[],b=Math.max(1,u),g=null;for(let a=0;a<p.length;a+=b){let d=p.slice(a,a+b);i.push(...await Promise.all(d.map(c=>E(c,f,o))));let y=i.find(c=>c.failure&&x(c.failure.kind));if(y?.failure){g=y.failure.kind;let c=p.length-i.length;o(` \u26D4 aborting batch \u2014 ${g}: the account is out of quota. Skipped ${c} remaining run(s) that would certainly have failed.`);break}}for(let a of i)try{await F("/api/eval-runs",a)}catch(d){o(` \u26A0 failed to post a run result: ${d instanceof Error?d.message:String(d)}`)}let C=k(i),m=P(i),v=t.length-C.length;if(v>0){let a=m.infrastructureFailed?` \u2014 ${m.infrastructureFailed} run(s) never executed (${m.summary.describe()})`:"";o(` \u26A0 ${v}/${t.length} case(s) produced no usable pair (failed or ungradeable arm)${a}`)}return{completed:i.filter(a=>a.status==="completed").length,failed:i.filter(a=>a.status==="failed").length,results:i,pairs:C,accounting:m,abortedForQuota:g}}s(N,"runCandidateBatchAndPost");export{A as a,$ as b,k as c,P as d,Q as e,w as f,N as g};
1
+ import{a as E}from"./chunk-WTMJSL7R.js";import{b as R,c as x}from"./chunk-KGURGIZ2.js";import{f as F}from"./chunk-UGACB66X.js";import{a as s}from"./chunk-ZLLER3HP.js";var A="with_candidate",$="with_prior_version";function k(n){let t=n.filter(e=>e.configuration===A),r=[];for(let e of t){let u=n.find(o=>o.configuration===$&&o.evalId===e.evalId&&o.runNumber===e.runNumber);if(!u)continue;let l=h(e),f=h(u);l==null||f==null||r.push({withScore:l,withoutScore:f})}return r}s(k,"pairCandidateRuns");function h(n){return n.status!=="completed"?null:n.grading?.summary?.pass_rate??null}s(h,"evidenceOf");function P(n){let t=[],r=0;for(let e of n){if(e.status==="failed"){t.push(e.failure??{kind:"unknown",class:"infrastructure"});continue}h(e)==null&&(r+=1)}return{infrastructureFailed:t.length,ungradeable:r,summary:R(t)}}s(P,"accountForFailures");function Q(n){let{pairs:t,minPairs:r,accounting:e}=n;return t>=r?{kind:"proceed"}:e.infrastructureFailed<=0?{kind:"proceed"}:{kind:"infrastructure-incomplete",reason:`${t}/${r} pair(s) \u2014 ${e.infrastructureFailed} run(s) never executed (${e.summary.describe()}). Retry when the environment recovers; this is not a statement about the target.`}}s(Q,"attributeShortfall");function w(n,t,r,e){let u=[];for(let l of n)u.push({eval_:l,configuration:A,targetContent:t,runNumber:e}),u.push({eval_:l,configuration:$,targetContent:r,runNumber:e});return u}s(w,"buildCandidateQueue");async function N(n){let{cases:t,candidateContent:r,priorVersionContent:e,concurrency:u,runNumber:l,opts:f,onLog:o=s(()=>{},"onLog")}=n,p=w(t,r,e,l),i=[],b=Math.max(1,u),g=null;for(let a=0;a<p.length;a+=b){let d=p.slice(a,a+b);i.push(...await Promise.all(d.map(c=>E(c,f,o))));let y=i.find(c=>c.failure&&x(c.failure.kind));if(y?.failure){g=y.failure.kind;let c=p.length-i.length;o(` \u26D4 aborting batch \u2014 ${g}: the account is out of quota. Skipped ${c} remaining run(s) that would certainly have failed.`);break}}for(let a of i)try{await F("/api/eval-runs",a)}catch(d){o(` \u26A0 failed to post a run result: ${d instanceof Error?d.message:String(d)}`)}let C=k(i),m=P(i),v=t.length-C.length;if(v>0){let a=m.infrastructureFailed?` \u2014 ${m.infrastructureFailed} run(s) never executed (${m.summary.describe()})`:"";o(` \u26A0 ${v}/${t.length} case(s) produced no usable pair (failed or ungradeable arm)${a}`)}return{completed:i.filter(a=>a.status==="completed").length,failed:i.filter(a=>a.status==="failed").length,results:i,pairs:C,accounting:m,abortedForQuota:g}}s(N,"runCandidateBatchAndPost");export{A as a,$ as b,k as c,P as d,Q as e,w as f,N as g};
@@ -1,4 +1,4 @@
1
- import{a as R,b as T}from"./chunk-OCHAV6YZ.js";import{a as p,b as y}from"./chunk-LVAROIKP.js";import{a as $,b as w,e as U}from"./chunk-LJRE3LZ2.js";import{g as j,i as D,j as x}from"./chunk-UPFH72PF.js";import{e as I,f as P,i as C}from"./chunk-2AVGUZ2P.js";import{B as S,C as b,o as k,z as A}from"./chunk-OOGTQOL3.js";import{a as u}from"./chunk-ZLLER3HP.js";import*as l from"node:fs";import*as m from"node:path";var O=new Set(["mcp","subagent","feature"]);function L(e,t,i){let a=m.join(e,"CLAUDE.md"),s=$(t),o=w(t),r=l.existsSync(a)?l.readFileSync(a,"utf8"):"";if(r.includes(s))return!1;let d=`${r.length>0&&!r.endsWith(`
1
+ import{a as R,b as T}from"./chunk-PVPYLKB3.js";import{a as p,b as y}from"./chunk-22ZDUL6H.js";import{a as $,b as w,e as U}from"./chunk-LJRE3LZ2.js";import{g as j,i as D,j as x}from"./chunk-UPFH72PF.js";import{e as I,f as P,i as C}from"./chunk-UGACB66X.js";import{B as S,C as b,o as k,z as A}from"./chunk-WMIUFMDI.js";import{a as u}from"./chunk-ZLLER3HP.js";import*as l from"node:fs";import*as m from"node:path";var O=new Set(["mcp","subagent","feature"]);function L(e,t,i){let a=m.join(e,"CLAUDE.md"),s=$(t),o=w(t),r=l.existsSync(a)?l.readFileSync(a,"utf8"):"";if(r.includes(s))return!1;let d=`${r.length>0&&!r.endsWith(`
2
2
  `)?`
3
3
 
4
4
  `:r.length>0?`
@@ -1 +1 @@
1
- import{a as v}from"./chunk-RBSEE2Z6.js";import{a as R}from"./chunk-M7QSC64D.js";import{b}from"./chunk-SVON2JIS.js";import{e as u}from"./chunk-2AVGUZ2P.js";import{a as d}from"./chunk-ZLLER3HP.js";var k=6e5;async function T(a,w){let i=d(e=>w?.logger?.info?.(e)??console.log(e),"log"),{evalTargetId:n}=a,l=await u(`/api/eval-targets/${n}/judge-calibration`),o=v({powered:l.powerCheck.powered,mde:l.powerCheck.mde??Number.POSITIVE_INFINITY},l.caseDiscrimination??{total:0,discriminating:0,nonDiscriminating:0,unpaired:0},{runsCompleted:0,maxRuns:a.maxRuns??24,batchesRun:0,maxBatches:1});if(o.action==="stop")return i(`[cron_eval_autorun] ${n}: ${o.reason}`),{skipped:o.code,reason:o.reason};let r=await u(`/api/eval-targets/${n}`),c=R(r);if(c)return i(`[cron_eval_autorun] ${n}: ${c.reason}`),c;let p=(await u(`/api/eval-targets/${n}/evals`)).filter(e=>!e.retiredAt);if(p.length===0)return{skipped:"no-live-cases"};let{completed:g,failed:f,results:$}=await b({cases:p,targetContent:r.content,concurrency:2,runNumber:1,opts:{targetId:n,targetVersion:r.version??1,iteration:1,timeout:a.timeout??k,model:a.model,graderModel:a.graderModel,skipGrading:!1,targetType:r.type,targetName:r.name},onLog:i}),m={};for(let e of $){if(e.status!=="failed")continue;let t=e.failure?.kind??"unknown";m[t]=(m[t]??0)+1}let s=Object.entries(m).sort(([,e],[,t])=>t-e).map(([e,t])=>`${e}x${t}`).join(", ");return i(`[cron_eval_autorun] ${r.name}: ${g} completed, ${f} failed`+(s===""?"":` (${s})`)),{ranRuns:g,failedRuns:f,...s===""?{}:{failures:s},reason:o.reason}}d(T,"cronEvalAutorun");export{T as a};
1
+ import{a as v}from"./chunk-RBSEE2Z6.js";import{a as R}from"./chunk-M7QSC64D.js";import{b}from"./chunk-WTMJSL7R.js";import{e as u}from"./chunk-UGACB66X.js";import{a as d}from"./chunk-ZLLER3HP.js";var k=6e5;async function T(a,w){let i=d(e=>w?.logger?.info?.(e)??console.log(e),"log"),{evalTargetId:n}=a,l=await u(`/api/eval-targets/${n}/judge-calibration`),o=v({powered:l.powerCheck.powered,mde:l.powerCheck.mde??Number.POSITIVE_INFINITY},l.caseDiscrimination??{total:0,discriminating:0,nonDiscriminating:0,unpaired:0},{runsCompleted:0,maxRuns:a.maxRuns??24,batchesRun:0,maxBatches:1});if(o.action==="stop")return i(`[cron_eval_autorun] ${n}: ${o.reason}`),{skipped:o.code,reason:o.reason};let r=await u(`/api/eval-targets/${n}`),c=R(r);if(c)return i(`[cron_eval_autorun] ${n}: ${c.reason}`),c;let p=(await u(`/api/eval-targets/${n}/evals`)).filter(e=>!e.retiredAt);if(p.length===0)return{skipped:"no-live-cases"};let{completed:g,failed:f,results:$}=await b({cases:p,targetContent:r.content,concurrency:2,runNumber:1,opts:{targetId:n,targetVersion:r.version??1,iteration:1,timeout:a.timeout??k,model:a.model,graderModel:a.graderModel,skipGrading:!1,targetType:r.type,targetName:r.name},onLog:i}),m={};for(let e of $){if(e.status!=="failed")continue;let t=e.failure?.kind??"unknown";m[t]=(m[t]??0)+1}let s=Object.entries(m).sort(([,e],[,t])=>t-e).map(([e,t])=>`${e}x${t}`).join(", ");return i(`[cron_eval_autorun] ${r.name}: ${g} completed, ${f} failed`+(s===""?"":` (${s})`)),{ranRuns:g,failedRuns:f,...s===""?{}:{failures:s},reason:o.reason}}d(T,"cronEvalAutorun");export{T as a};
@@ -0,0 +1 @@
1
+ import{a as i}from"./chunk-ZLLER3HP.js";import{existsSync as c,readdirSync as u,statSync as a}from"node:fs";import{homedir as p}from"node:os";import{join as l}from"node:path";var d=i(r=>/^\/(Users|home)\/[^/]+\/?$/.test(r),"isHomeDir"),m=i(r=>/^\/(private\/)?(tmp|var\/folders)/.test(r),"isThrowaway");function y(r,t){return{exists:i(e=>c(e),"exists"),listDirs:i(e=>{try{return u(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>n.name)}catch{return[]}},"listDirs"),readTranscriptCwd:t,gitAnchors:r,stat:i(e=>{try{let n=a(e);return{mtimeMs:n.mtimeMs,size:n.size}}catch{return null}},"stat"),home:p()}}i(y,"defaultRecoveryEnv");function f(r,t){let e=l(t.home,".claude","projects");if(!t.exists(e))return null;for(let n of t.listDirs(e)){let o=l(e,n,`${r}.jsonl`);if(t.exists(o))return o}return null}i(f,"findClaudeCodeTranscript");function g(r,t){let e=f(r,t);return e?t.readTranscriptCwd(e):null}i(g,"findClaudeCodeCwd");var h=20*1024*1024;function b(r){if(r.tool!=="claude_code")return{reimport:!1,reason:"not-claude-code"};if(!r.transcript)return{reimport:!1,reason:"no-transcript"};if(r.transcript.size>h)return{reimport:!1,reason:"transcript-too-large"};if(r.pathWasJunk)return{reimport:!0,reason:"junk-path"};if(!r.endedAt)return{reimport:!0,reason:"never-closed"};let t=Date.parse(r.endedAt);return Number.isFinite(t)&&r.transcript.mtimeMs>t+300*1e3?{reimport:!0,reason:"transcript-outgrew-row"}:{reimport:!1,reason:"row-current"}}i(b,"shouldReimportTranscript");function A(r,t){let e=i(s=>s&&!d(s)&&!m(s)?s:null,"usable"),n=e(r.projectPath);if(!n&&r.tool==="claude_code"&&r.externalSessionId&&(n=e(g(r.externalSessionId,t))),!n||!t.exists(n))return null;let o=t.gitAnchors(n);return!o||!o.gitRemote&&!o.gitRootCommit?null:{projectPath:n,...o}}i(A,"recoverAnchors");export{d as a,y as b,f as c,g as d,h as e,b as f,A as g};
@@ -1 +1 @@
1
- import{a as i}from"./chunk-VC3DJPUB.js";import{a as f}from"./chunk-ZLLER3HP.js";import{useEffect as J,useState as u,useCallback as m,useRef as s}from"react";var y=5e3;function T(a=20){let[d,b]=u([]),[g,l]=u(null),[h,p]=u(!0),r=s(!1),e=s(null),c=s(0),t=m(async()=>{let o=++c.current;try{let n=await i({limit:a});if(r.current||o!==c.current)return;b(n),l(null)}catch(n){if(r.current||o!==c.current)return;l(n instanceof Error?n.message:String(n))}finally{if(r.current||o!==c.current)return;p(!1),e.current=setTimeout(()=>{t()},y)}},[a]),L=m(()=>{e.current&&clearTimeout(e.current),t()},[t]);return J(()=>(r.current=!1,t(),()=>{r.current=!0,e.current&&clearTimeout(e.current)}),[t]),{jobs:d,error:g,loading:h,refetch:L}}f(T,"useLaunchJobs");export{T as a};
1
+ import{a as i}from"./chunk-A2LHEUNW.js";import{a as f}from"./chunk-ZLLER3HP.js";import{useEffect as J,useState as u,useCallback as m,useRef as s}from"react";var y=5e3;function T(a=20){let[d,b]=u([]),[g,l]=u(null),[h,p]=u(!0),r=s(!1),e=s(null),c=s(0),t=m(async()=>{let o=++c.current;try{let n=await i({limit:a});if(r.current||o!==c.current)return;b(n),l(null)}catch(n){if(r.current||o!==c.current)return;l(n instanceof Error?n.message:String(n))}finally{if(r.current||o!==c.current)return;p(!1),e.current=setTimeout(()=>{t()},y)}},[a]),L=m(()=>{e.current&&clearTimeout(e.current),t()},[t]);return J(()=>(r.current=!1,t(),()=>{r.current=!0,e.current&&clearTimeout(e.current)}),[t]),{jobs:d,error:g,loading:h,refetch:L}}f(T,"useLaunchJobs");export{T as a};
@@ -0,0 +1,2 @@
1
+ import{a as u}from"./chunk-ZLLER3HP.js";import{execFile as S}from"node:child_process";var k=/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} [+-]\d{4})\s+(Sleep|Wake|DarkWake)[ ]{2,}\s*(.*)$/,m=/(\d+)\s+secs\s*$/;function f(e){let s=[];for(let r of e.split(`
2
+ `)){let t=k.exec(r.trimEnd());if(!t)continue;let[,o,l,a]=t,i=new Date(o.replace(" ","T").replace(/ ([+-]\d{2})(\d{2})$/,"$1:$2"));if(Number.isNaN(i.getTime()))continue;let c=l==="Sleep"?"sleep":l==="DarkWake"?"darkwake":"wake",p=m.exec(a),n=a.replace(m,"").replace(/\s+/g," ").trim(),d={kind:c,at:i,reason:n};p&&(d.seconds=Number(p[1])),s.push(d)}return s}u(f,"parsePmsetLog");function g(e,s,r=24){let t=s.getTime()-r*36e5,o=e.filter(n=>n.at.getTime()>=t),l=0,a=0,i=0,c=0,p=0;for(let n of o)n.kind==="sleep"?(l++,n.seconds!=null&&(p+=n.seconds,n.seconds>c&&(c=n.seconds))):n.kind==="darkwake"?a++:i++;return{windowHours:r,sleeps:l,darkWakes:a,fullWakes:i,longestSleepSec:c,totalSleepSec:p,recent:o.slice(-6)}}u(g,"summarizeSleep");function E(e=new Date,s=24,r=process.platform){return r!=="darwin"?Promise.resolve(null):new Promise(t=>{S("pmset",["-g","log"],{timeout:8e3,maxBuffer:64*1024*1024,encoding:"utf8"},(o,l)=>{if(o||!l)return t(null);try{t(g(f(l),e,s))}catch{t(null)}})})}u(E,"readMacSleepLog");function $(e){if(e.sleeps===0&&e.darkWakes===0)return`no sleep in the last ${e.windowHours}h`;let s=Math.round(e.longestSleepSec/60),r=Math.round(e.totalSleepSec/60),t=[`${e.sleeps} sleep${e.sleeps===1?"":"s"} in the last ${e.windowHours}h`];return e.totalSleepSec>0&&t.push(`${r}m asleep total, longest ${s}m`),e.darkWakes>0&&t.push(`${e.darkWakes} dark wake${e.darkWakes===1?"":"s"} (seconds-long maintenance wakes)`),t.join(", ")}u($,"formatSleepSummary");export{f as a,g as b,E as c,$ as d};
@@ -1,4 +1,4 @@
1
- import{d as b,f as y}from"./chunk-QBNLZJIR.js";import{e as M,f as w}from"./chunk-2AVGUZ2P.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{d as b,f as y}from"./chunk-QBNLZJIR.js";import{e as M,f as w}from"./chunk-UGACB66X.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{l as E}from"./chunk-OOGTQOL3.js";import{a as p,e as w}from"./chunk-PZNWH4VQ.js";import{a as o}from"./chunk-ZLLER3HP.js";import{fileURLToPath as v}from"node:url";import{existsSync as A,readFileSync as b}from"node:fs";import{dirname as L,join as x}from"node:path";function C(){let t=L(v(import.meta.url));for(let e=0;e<8;e++){let s=x(t,"package.json");if(A(s))try{let i=JSON.parse(b(s,"utf8"));if(i.name==="@rulemetric/cli"&&i.version)return i.version}catch{}let n=L(t);if(n===t)break;t=n}return"0.0.0"}o(C,"readCliVersion");var O=C(),I="https://rulemetric.com",l=class extends Error{constructor(s,n){super(n);this.statusCode=s;this.name="ApiError"}static{o(this,"ApiError")}};function S(){let t=p(),e=process.env.RULEMETRIC_API_URL??t.apiUrl;if(!e){if(process.env.RULEMETRIC_STRICT_LOCAL==="1"||t.strictLocal==="1")throw new Error("RULEMETRIC_STRICT_LOCAL is set but no RULEMETRIC_API_URL is configured \u2014 refusing the cloud default. Set RULEMETRIC_API_URL in the environment or ~/.config/rulemetric/env.");e=I}let s=new URL(e);if(s.protocol==="http:"&&s.hostname!=="localhost"&&s.hostname!=="127.0.0.1")throw new Error(`API URL must use HTTPS for non-localhost hosts: ${e}`);return e}o(S,"getBaseUrl");async function a(t,e={}){let n=`${S()}${t}`,i={"Content-Type":"application/json","User-Agent":`rulemetric-cli/${O}`,...e.headers},m=p(),d=process.env.RULEMETRIC_API_KEY||m.apiKey||w()?.accessToken||m.accessToken;d&&(i.Authorization=`Bearer ${d}`);let h=new URL(n),f=h.hostname==="localhost"||h.hostname==="127.0.0.1",P=process.env.HTTPS_PROXY,R=process.env.HTTP_PROXY;f&&(delete process.env.HTTPS_PROXY,delete process.env.HTTP_PROXY);let u=e.timeoutMs?new AbortController:void 0,g=!1,y=u?setTimeout(()=>{g=!0,u.abort()},e.timeoutMs):void 0,r;try{r=await fetch(n,{method:e.method??"GET",headers:i,body:e.body?JSON.stringify(e.body):void 0,signal:u?.signal})}catch(T){if(g){let U=new URL(n).host,_=Math.round(e.timeoutMs/1e3);throw new l(408,`Request to ${U} timed out after ${_}s. This is usually transient or a local proxy/gateway issue \u2014 retry, and if it persists check HTTPS_PROXY / the RuleMetric gateway (:8787).`)}throw T}finally{y&&clearTimeout(y),f&&(P!==void 0&&(process.env.HTTPS_PROXY=P),R!==void 0&&(process.env.HTTP_PROXY=R))}let c;if(r.headers.get("content-type")?.includes("application/json")?c=await r.json():c=await r.text(),!r.ok){let{message:T}=E(r.status,c);throw new l(r.status,T)}return c}o(a,"api");var j=o(t=>a(t),"apiGet"),F=o((t,e)=>a(t,{method:"POST",body:e}),"apiPost"),B=o((t,e)=>a(t,{method:"PUT",body:e}),"apiPut"),D=o((t,e)=>a(t,{method:"PATCH",body:e}),"apiPatch"),G=o(t=>a(t,{method:"DELETE"}),"apiDelete");export{I as a,l as b,S as c,a as d,j as e,F as f,B as g,D as h,G as i};
1
+ import{l as E}from"./chunk-WMIUFMDI.js";import{a as p,e as w}from"./chunk-PZNWH4VQ.js";import{a as o}from"./chunk-ZLLER3HP.js";import{fileURLToPath as v}from"node:url";import{existsSync as A,readFileSync as b}from"node:fs";import{dirname as L,join as x}from"node:path";function C(){let t=L(v(import.meta.url));for(let e=0;e<8;e++){let s=x(t,"package.json");if(A(s))try{let i=JSON.parse(b(s,"utf8"));if(i.name==="@rulemetric/cli"&&i.version)return i.version}catch{}let n=L(t);if(n===t)break;t=n}return"0.0.0"}o(C,"readCliVersion");var O=C(),I="https://rulemetric.com",l=class extends Error{constructor(s,n){super(n);this.statusCode=s;this.name="ApiError"}static{o(this,"ApiError")}};function S(){let t=p(),e=process.env.RULEMETRIC_API_URL??t.apiUrl;if(!e){if(process.env.RULEMETRIC_STRICT_LOCAL==="1"||t.strictLocal==="1")throw new Error("RULEMETRIC_STRICT_LOCAL is set but no RULEMETRIC_API_URL is configured \u2014 refusing the cloud default. Set RULEMETRIC_API_URL in the environment or ~/.config/rulemetric/env.");e=I}let s=new URL(e);if(s.protocol==="http:"&&s.hostname!=="localhost"&&s.hostname!=="127.0.0.1")throw new Error(`API URL must use HTTPS for non-localhost hosts: ${e}`);return e}o(S,"getBaseUrl");async function a(t,e={}){let n=`${S()}${t}`,i={"Content-Type":"application/json","User-Agent":`rulemetric-cli/${O}`,...e.headers},m=p(),d=process.env.RULEMETRIC_API_KEY||m.apiKey||w()?.accessToken||m.accessToken;d&&(i.Authorization=`Bearer ${d}`);let h=new URL(n),f=h.hostname==="localhost"||h.hostname==="127.0.0.1",P=process.env.HTTPS_PROXY,R=process.env.HTTP_PROXY;f&&(delete process.env.HTTPS_PROXY,delete process.env.HTTP_PROXY);let u=e.timeoutMs?new AbortController:void 0,g=!1,y=u?setTimeout(()=>{g=!0,u.abort()},e.timeoutMs):void 0,r;try{r=await fetch(n,{method:e.method??"GET",headers:i,body:e.body?JSON.stringify(e.body):void 0,signal:u?.signal})}catch(T){if(g){let U=new URL(n).host,_=Math.round(e.timeoutMs/1e3);throw new l(408,`Request to ${U} timed out after ${_}s. This is usually transient or a local proxy/gateway issue \u2014 retry, and if it persists check HTTPS_PROXY / the RuleMetric gateway (:8787).`)}throw T}finally{y&&clearTimeout(y),f&&(P!==void 0&&(process.env.HTTPS_PROXY=P),R!==void 0&&(process.env.HTTP_PROXY=R))}let c;if(r.headers.get("content-type")?.includes("application/json")?c=await r.json():c=await r.text(),!r.ok){let{message:T}=E(r.status,c);throw new l(r.status,T)}return c}o(a,"api");var j=o(t=>a(t),"apiGet"),F=o((t,e)=>a(t,{method:"POST",body:e}),"apiPost"),B=o((t,e)=>a(t,{method:"PUT",body:e}),"apiPut"),D=o((t,e)=>a(t,{method:"PATCH",body:e}),"apiPatch"),G=o(t=>a(t,{method:"DELETE"}),"apiDelete");export{I as a,l as b,S as c,a as d,j as e,F as f,B as g,D as h,G as i};
@@ -1 +1 @@
1
- import{b as m}from"./chunk-KHCMVYTH.js";import{a as g}from"./chunk-ZLLER3HP.js";var p=5;function b(t){let r=g((e,f)=>({retire:[],survivingCases:0,replacementsRequired:!1,refused:e,summary:f}),"none");if(!t||t.cases.length===0&&t.unpairedCases.length===0)return r("no-discrimination-data","No case-discrimination data yet \u2014 the target needs runs in BOTH cohorts before any case can be judged dead.");let c=[...t.cases.filter(e=>!e.discriminating).map(e=>({evalId:e.evalId,name:e.name,feedback:{name:e.name,withPassRate:e.withPassRate,withoutPassRate:e.withoutPassRate,reason:e.note}})),...t.unpairedCases.map(e=>({evalId:e.evalId,name:e.name,feedback:{name:e.name,withPassRate:e.withPassRate??0,withoutPassRate:e.withoutPassRate,reason:"runs in only one cohort (no with-vs-without comparison possible)"}}))];if(c.length===0)return r("all-discriminating","Every case discriminates \u2014 nothing to retire.");let s=new Map(t.cases.map(e=>[e.evalId,e.separation])),o=[...c].sort((e,f)=>(s.get(e.evalId)??-1)-(s.get(f.evalId)??-1)).slice(0,p),u=c.length-o.length,d=t.total+t.unpaired,l=d-o.length,i=l<m,n=`${o.length} of ${d} live case(s) carry no treatment signal`+(u>0?` (${u} more over the ${p}-per-run cap)`:"")+(i?`; retiring them leaves ${l}, below the ${m}-case evolution floor, so replacements must be generated first`:"");return{retire:o,survivingCases:l,replacementsRequired:i,refused:null,summary:n}}g(b,"planCaseRefinement");async function v(t,r){let h=r.log??(()=>{}),c=g((n,e)=>({retired:0,generated:0,skipped:n,summary:e,retiredNames:[],generatedNames:[]}),"empty");if(t.refused)return c(t.refused,t.summary);let s=await r.generate(t.retire.map(n=>n.feedback)),a=[];for(let n of s??[]){let e=await r.createCase(n);a.push(e.name),h(` + ${e.name} (${e.id})`)}let o=t.survivingCases+t.retire.length+a.length,u=Math.max(0,o-m),d=t.retire.slice(0,Math.min(t.retire.length,u)),l=t.retire.length-d.length;if(d.length===0)return{retired:0,generated:a.length,skipped:s===null?"no-llm-backend":"no-replacements-generated",summary:`${t.summary}. `+(s===null?"No local LLM backend available, so nothing was retired":`The generator produced ${a.length} usable replacement(s), not enough to retire anything`)+` \u2014 dropping below the ${m}-case floor would silently disenrol the target from the nightly loop.`,retiredNames:[],generatedNames:a};let i=[];for(let n of d)await r.retireCase(n.evalId,n.feedback.reason),i.push(n.name),h(` retired ${n.name}`);return{retired:i.length,generated:a.length,skipped:null,summary:`Retired ${i.length} non-discriminating case(s), added ${a.length} replacement(s)`+(l>0?`; held ${l} back to stay at the ${m}-case floor (they remain condemned and will be retired once replacements exist)`:"")+". The replacements have no runs yet \u2014 the next autorun batch builds their depth.",retiredNames:i,generatedNames:a}}g(v,"executeCaseRefinement");export{p as a,b,v as c};
1
+ import{b as m}from"./chunk-5N5S3NKS.js";import{a as g}from"./chunk-ZLLER3HP.js";var p=5;function b(t){let r=g((e,f)=>({retire:[],survivingCases:0,replacementsRequired:!1,refused:e,summary:f}),"none");if(!t||t.cases.length===0&&t.unpairedCases.length===0)return r("no-discrimination-data","No case-discrimination data yet \u2014 the target needs runs in BOTH cohorts before any case can be judged dead.");let c=[...t.cases.filter(e=>!e.discriminating).map(e=>({evalId:e.evalId,name:e.name,feedback:{name:e.name,withPassRate:e.withPassRate,withoutPassRate:e.withoutPassRate,reason:e.note}})),...t.unpairedCases.map(e=>({evalId:e.evalId,name:e.name,feedback:{name:e.name,withPassRate:e.withPassRate??0,withoutPassRate:e.withoutPassRate,reason:"runs in only one cohort (no with-vs-without comparison possible)"}}))];if(c.length===0)return r("all-discriminating","Every case discriminates \u2014 nothing to retire.");let s=new Map(t.cases.map(e=>[e.evalId,e.separation])),o=[...c].sort((e,f)=>(s.get(e.evalId)??-1)-(s.get(f.evalId)??-1)).slice(0,p),u=c.length-o.length,d=t.total+t.unpaired,l=d-o.length,i=l<m,n=`${o.length} of ${d} live case(s) carry no treatment signal`+(u>0?` (${u} more over the ${p}-per-run cap)`:"")+(i?`; retiring them leaves ${l}, below the ${m}-case evolution floor, so replacements must be generated first`:"");return{retire:o,survivingCases:l,replacementsRequired:i,refused:null,summary:n}}g(b,"planCaseRefinement");async function v(t,r){let h=r.log??(()=>{}),c=g((n,e)=>({retired:0,generated:0,skipped:n,summary:e,retiredNames:[],generatedNames:[]}),"empty");if(t.refused)return c(t.refused,t.summary);let s=await r.generate(t.retire.map(n=>n.feedback)),a=[];for(let n of s??[]){let e=await r.createCase(n);a.push(e.name),h(` + ${e.name} (${e.id})`)}let o=t.survivingCases+t.retire.length+a.length,u=Math.max(0,o-m),d=t.retire.slice(0,Math.min(t.retire.length,u)),l=t.retire.length-d.length;if(d.length===0)return{retired:0,generated:a.length,skipped:s===null?"no-llm-backend":"no-replacements-generated",summary:`${t.summary}. `+(s===null?"No local LLM backend available, so nothing was retired":`The generator produced ${a.length} usable replacement(s), not enough to retire anything`)+` \u2014 dropping below the ${m}-case floor would silently disenrol the target from the nightly loop.`,retiredNames:[],generatedNames:a};let i=[];for(let n of d)await r.retireCase(n.evalId,n.feedback.reason),i.push(n.name),h(` retired ${n.name}`);return{retired:i.length,generated:a.length,skipped:null,summary:`Retired ${i.length} non-discriminating case(s), added ${a.length} replacement(s)`+(l>0?`; held ${l} back to stay at the ${m}-case floor (they remain condemned and will be retired once replacements exist)`:"")+". The replacements have no runs yet \u2014 the next autorun batch builds their depth.",retiredNames:i,generatedNames:a}}g(v,"executeCaseRefinement");export{p as a,b,v as c};
@@ -1 +1 @@
1
- import{c as d,d as t}from"./chunk-UQSUSB6G.js";import{a as r}from"./chunk-ZLLER3HP.js";async function g(o,i){let{evalTargetId:s}=o;try{let e=await t({targetId:s,engineFlag:"auto",skipReviewed:!0,log:r(a=>i.logger.info(`[judge-review] ${a}`),"log"),warn:r(a=>i.logger.warn(`[judge-review] ${a}`),"warn")});return{evalTargetId:s,reviewerModel:e.reviewerModel,comparedPairs:e.report.pairs,disagreements:e.report.disagreements.length,persisted:e.persisted,alreadyReviewed:e.alreadyReviewed,deferredPartialRuns:e.deferredPartialRuns}}catch(e){if(e instanceof d)return i.logger.info(`[judge-review] skipped (${e.reason}): ${e.message}`),{evalTargetId:s,skipped:e.reason};throw e}}r(g,"processJudgeReview");export{g as a};
1
+ import{c as d,d as t}from"./chunk-MILLBGCB.js";import{a as r}from"./chunk-ZLLER3HP.js";async function g(o,i){let{evalTargetId:s}=o;try{let e=await t({targetId:s,engineFlag:"auto",skipReviewed:!0,log:r(a=>i.logger.info(`[judge-review] ${a}`),"log"),warn:r(a=>i.logger.warn(`[judge-review] ${a}`),"warn")});return{evalTargetId:s,reviewerModel:e.reviewerModel,comparedPairs:e.report.pairs,disagreements:e.report.disagreements.length,persisted:e.persisted,alreadyReviewed:e.alreadyReviewed,deferredPartialRuns:e.deferredPartialRuns}}catch(e){if(e instanceof d)return i.logger.info(`[judge-review] skipped (${e.reason}): ${e.message}`),{evalTargetId:s,skipped:e.reason};throw e}}r(g,"processJudgeReview");export{g as a};
@@ -0,0 +1 @@
1
+ import{a as l}from"./chunk-ZLLER3HP.js";var k=5e3;function v(){let e=process.cpuUsage();return{wallMs:Date.now(),monoMs:Number(process.hrtime.bigint()/1000000n),cpuMs:(e.user+e.system)/1e3}}l(v,"takeClockSample");function P(e,n,u,o=5e3){let r=n.wallMs-e.wallMs,s=n.monoMs-e.monoMs,i=Math.max(0,n.cpuMs-e.cpuMs);if(r<u+o)return null;let a={detectedAt:new Date(n.wallMs).toISOString(),lastSeenAt:new Date(e.wallMs).toISOString(),wallGapMs:r,monoGapMs:s,cpuMs:i,expectedMs:u};return r-s>o?{kind:"suspend",evidence:"clock",...a}:{kind:i>r*.25?"stall":"suspend",evidence:"cpu",...a}}l(P,"classifyGap");var b=15e3,f=50;function w(e={}){let n=e.intervalMs??b,u=e.sample??v,o=e.setIntervalFn??setInterval,r=e.clearIntervalFn??clearInterval,s=u(),i=new Date(s.wallMs).toISOString(),a=[],p=0,d=0,m=0,M=o(l(()=>{let t=u(),c=P(s,t,n);if(s=t,!!c){c.kind==="suspend"?p++:d++,m+=c.wallGapMs-c.expectedMs,a.push(c),a.length>f&&a.shift();try{e.onPause?.(c)}catch{}}},"tick"),n);M.unref?.();let S=l(()=>r(M),"stop");return e.signal?.addEventListener("abort",S,{once:!0}),{summary:l(()=>{let t=a[a.length-1];return{suspends:p,stalls:d,pausedMs:m,lastPause:t?{kind:t.kind,evidence:t.evidence,detectedAt:t.detectedAt,lastSeenAt:t.lastSeenAt,wallGapMs:t.wallGapMs}:null,since:i}},"summary"),pausesSince:l(t=>a.filter(c=>new Date(c.detectedAt).getTime()>=t),"pausesSince"),stop:S}}l(w,"startPauseDetector");function A(e){if(e.length===0)return"";let n=e.reduce((s,i)=>s+i.wallGapMs,0),u=new Set(e.map(s=>s.kind==="suspend"?"machine suspended":"event loop stalled")),o=Math.round(n/6e4),r=o>=1?`${o}m`:`${Math.round(n/1e3)}s`;return`${[...u].join(" + ")} for ${r} during this job (${e.length} pause${e.length===1?"":"s"}, last resumed ${e[e.length-1].detectedAt})`}l(A,"describePauses");export{k as a,v as b,P as c,w as d,A as e};
@@ -0,0 +1,3 @@
1
+ import{a as R,b as S,c as v,f as $,g as A}from"./chunk-SIGZEQ3K.js";import{e as y,f}from"./chunk-UGACB66X.js";import{a as p}from"./chunk-ZLLER3HP.js";import{execFileSync as w}from"node:child_process";import{openSync as x,readSync as P,closeSync as C,readFileSync as j}from"node:fs";function E(c){let t;try{t=x(c,"r");let o=Buffer.alloc(64*1024),s=P(t,o,0,o.length,0),i=o.subarray(0,s).toString("utf-8");for(let r of i.split(`
2
+ `))if(r.startsWith("{"))try{let a=JSON.parse(r).cwd;if(typeof a=="string"&&a.startsWith("/"))return a}catch{}return null}catch{return null}finally{t!==void 0&&C(t)}}p(E,"readTranscriptCwd");function I(c){let t=p(r=>{try{return w("git",["-C",c,...r],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()||null}catch{return null}},"git");if(!t(["rev-parse","--show-toplevel"]))return null;let s=t(["rev-parse","--git-dir"]),i=t(["rev-parse","--git-common-dir"]);return{gitRemote:t(["remote","get-url","origin"]),gitRootCommit:t(["rev-list","--max-parents=0","HEAD"])?.split(`
3
+ `).pop()?.trim()??null,gitBranch:t(["branch","--show-current"]),isWorktree:!!s&&!!i&&s!==i}}p(I,"gitAnchors");async function H(c,t,o=S(I,E)){let s=Math.min(c.limit??200,1e3),i=await y(`/api/sessions/unattributed?limit=${s}`),r=i.sessions??[],a=i.total??r.length;if(r.length===0)return t.logger.info("no unattributed sessions"),{scanned:0,repaired:0,reimported:0,unrepairable:0,remaining:0};let d=0,g=0,l=0;for(let e of r){if(!e.externalSessionId){l++;continue}let n=A(e,o);if(!n){l++;continue}try{await f("/api/sessions",{tool:e.tool,externalSessionId:e.externalSessionId,projectPath:n.projectPath,...n.gitBranch?{gitBranch:n.gitBranch}:{},metadata:{...n.gitRemote?{gitRemote:n.gitRemote}:{},...n.gitRootCommit?{gitRootCommit:n.gitRootCommit}:{},isWorktree:n.isWorktree,reconciledAttribution:!0}}),d++}catch(u){l++,t.logger.info(`reconcile failed for ${e.externalSessionId}: ${u.message}`);continue}let m=e.tool==="claude_code"?v(e.externalSessionId,o):null,b=$({tool:e.tool,pathWasJunk:!!e.projectPath&&R(e.projectPath),endedAt:e.endedAt??null,transcript:m?o.stat(m):null});if(b.reimport&&m)try{let u=j(m,"utf-8");await f(`/api/sessions/${e.id}/reimport`,{content:u,tool:"claude_code"}),g++}catch(u){t.logger.info(`reimport failed for ${e.externalSessionId} (${b.reason}): ${u.message}`)}}let h=a-d;return t.logger.info(`reconciled attribution: scanned=${r.length} repaired=${d} reimported=${g} unrepairable=${l} remaining=${h} (of ${a} total)`),{scanned:r.length,repaired:d,reimported:g,unrepairable:l,remaining:h}}p(H,"cronReconcileAttribution");export{H as a};
@@ -0,0 +1 @@
1
+ var s={"session-start":30,"user-prompt":15,"post-tool-use":15,"session-end":60};export{s as a};
@@ -1 +1 @@
1
- import{c as l}from"./chunk-2AVGUZ2P.js";import{c as a,l as u}from"./chunk-PZNWH4VQ.js";import{a as o}from"./chunk-ZLLER3HP.js";var c=120*1e3,t=null;async function k(){if(process.env.RULEMETRIC_API_KEY)return!0;let e=a(u());if(!e.isRefreshable(c))return!0;let r=e.loadToken();return r?.refreshToken?t||(t=f(e,r).finally(()=>{t=null}),t):!0}o(k,"ensureFreshToken");async function f(e,r){let s;try{s=await fetch(`${l()}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:r.refreshToken})})}catch{return!0}if(s.status===401)return e.clearToken(),!1;if(!s.ok)return!0;let n=await s.json().catch(()=>null);if(!n?.accessToken||!n.refreshToken)return!0;let i={accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:n.expiresAt??r.expiresAt,email:n.email??r.email};return e.saveToken(i),e.saveEnvFile(i.accessToken),!0}o(f,"doRefresh");export{k as a};
1
+ import{c as l}from"./chunk-UGACB66X.js";import{c as a,l as u}from"./chunk-PZNWH4VQ.js";import{a as o}from"./chunk-ZLLER3HP.js";var c=120*1e3,t=null;async function k(){if(process.env.RULEMETRIC_API_KEY)return!0;let e=a(u());if(!e.isRefreshable(c))return!0;let r=e.loadToken();return r?.refreshToken?t||(t=f(e,r).finally(()=>{t=null}),t):!0}o(k,"ensureFreshToken");async function f(e,r){let s;try{s=await fetch(`${l()}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:r.refreshToken})})}catch{return!0}if(s.status===401)return e.clearToken(),!1;if(!s.ok)return!0;let n=await s.json().catch(()=>null);if(!n?.accessToken||!n.refreshToken)return!0;let i={accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:n.expiresAt??r.expiresAt,email:n.email??r.email};return e.saveToken(i),e.saveEnvFile(i.accessToken),!0}o(f,"doRefresh");export{k as a};
@@ -1 +1 @@
1
- import{c}from"./chunk-SD626JBZ.js";import{e as p,g as u}from"./chunk-2AVGUZ2P.js";import{a as o}from"./chunk-ZLLER3HP.js";var l="openCandidate";function g(n,i){let t=(n??{})[l];if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;return typeof e.content!="string"||!e.content||typeof e.hash!="string"||!e.hash||typeof e.priorHash!="string"||e.priorHash!==i?null:{content:e.content,hash:e.hash,priorHash:e.priorHash,plannedPairs:typeof e.plannedPairs=="number"?e.plannedPairs:0,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:""}}o(g,"resolveOpenCandidate");function m(n){let{plannedPairs:i,carriedPairs:t,liveCases:e}=n;if(e<=0)return 0;let a=i-t;return a<=0?0:Math.ceil(a/e)}o(m,"owedPasses");var d=100;async function b(n){let{evalTargetId:i,candidateContentHash:t}=n,e=[];for(let a=0;;a+=d){let r=await p(`/api/eval-targets/${i}/runs?candidateContentHash=${encodeURIComponent(t)}&limit=${d}&offset=${a}`);if(!Array.isArray(r)||r.length===0||(e.push(...r),r.length<d))break}return c(e)}o(b,"fetchCarriedPairs");async function P(n){let{evalTargetId:i,meta:t,blob:e,log:a,tag:r}=n;try{let s={...t};e?s[l]=e:delete s[l],await u(`/api/eval-targets/${i}`,{metadata:s}),a(e?`${r}: banked candidate ${e.hash.slice(0,8)} \u2014 the next run resumes instead of restarting`:`${r}: cleared the banked candidate (this cycle reached a decision)`)}catch(s){a(`${r}: could not update the candidate bank (${s instanceof Error?s.message:String(s)})`)}}o(P,"bankOpenCandidate");function C(n){return{content:n.content,hash:n.hash,priorHash:n.priorHash,plannedPairs:n.plannedPairs,updatedAt:n.now.toISOString()}}o(C,"buildOpenCandidate");export{l as a,g as b,m as c,b as d,P as e,C as f};
1
+ import{c}from"./chunk-PWTTCSQA.js";import{e as p,g as u}from"./chunk-UGACB66X.js";import{a as o}from"./chunk-ZLLER3HP.js";var l="openCandidate";function g(n,i){let t=(n??{})[l];if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;return typeof e.content!="string"||!e.content||typeof e.hash!="string"||!e.hash||typeof e.priorHash!="string"||e.priorHash!==i?null:{content:e.content,hash:e.hash,priorHash:e.priorHash,plannedPairs:typeof e.plannedPairs=="number"?e.plannedPairs:0,updatedAt:typeof e.updatedAt=="string"?e.updatedAt:""}}o(g,"resolveOpenCandidate");function m(n){let{plannedPairs:i,carriedPairs:t,liveCases:e}=n;if(e<=0)return 0;let a=i-t;return a<=0?0:Math.ceil(a/e)}o(m,"owedPasses");var d=100;async function b(n){let{evalTargetId:i,candidateContentHash:t}=n,e=[];for(let a=0;;a+=d){let r=await p(`/api/eval-targets/${i}/runs?candidateContentHash=${encodeURIComponent(t)}&limit=${d}&offset=${a}`);if(!Array.isArray(r)||r.length===0||(e.push(...r),r.length<d))break}return c(e)}o(b,"fetchCarriedPairs");async function P(n){let{evalTargetId:i,meta:t,blob:e,log:a,tag:r}=n;try{let s={...t};e?s[l]=e:delete s[l],await u(`/api/eval-targets/${i}`,{metadata:s}),a(e?`${r}: banked candidate ${e.hash.slice(0,8)} \u2014 the next run resumes instead of restarting`:`${r}: cleared the banked candidate (this cycle reached a decision)`)}catch(s){a(`${r}: could not update the candidate bank (${s instanceof Error?s.message:String(s)})`)}}o(P,"bankOpenCandidate");function C(n){return{content:n.content,hash:n.hash,priorHash:n.priorHash,plannedPairs:n.plannedPairs,updatedAt:n.now.toISOString()}}o(C,"buildOpenCandidate");export{l as a,g as b,m as c,b as d,P as e,C as f};
@@ -1 +1 @@
1
- import{a as T}from"./chunk-5RBLIVBF.js";import{a as S}from"./chunk-XFAFMYIP.js";import{b as A}from"./chunk-KJRMGTAO.js";import{e as x}from"./chunk-GN3ZHQ46.js";import{a as C}from"./chunk-BJSVATVJ.js";import{d as M}from"./chunk-TZA4HAVF.js";import{e as k,f as E,h as p}from"./chunk-2AVGUZ2P.js";import{a as w}from"./chunk-ZLLER3HP.js";async function W(v,f){let{mirrorId:i,evalTargetId:g,config:o}=v,a=w(e=>f.logger.info(e),"log"),s=await k(`/api/eval-targets/${g}`),$=await k(`/api/eval-targets/${g}/evals`);if($.length===0&&o.generateIfEmpty){a("No eval cases on target \u2014 generating from content via local LLM...");let e=await A({content:s.content,name:s.name});if(e===null)throw new Error("Case generation requires an LLM backend (claude CLI on PATH or ANTHROPIC_API_KEY) \u2014 none available on this worker.");let n=[];for(let t of e)n.push(await E(`/api/eval-targets/${g}/evals`,t));$=n,a(`Generated ${n.length} eval case(s)`)}if($.length===0)throw new T("No evals defined for target");let G=o.runsPerEval??1,R=o.timeout??12e4,j=o.iteration??1,y=new Set;if(f.job.attempts>1)for(let n=0;;n+=100){let t=await k(`/api/eval-targets/${g}/runs?jobId=${i}&limit=100&offset=${n}`);for(let r of t)y.add(`${r.evalId}|${r.configuration}|${r.runNumber}|${r.iteration}`);if(t.length<100)break}let _=[{name:"with_target",content:s.content}];o.skipBaseline||_.push({name:"without_target"});let d=[];for(let e of $)for(let n of _)for(let t=1;t<=G;t++)y.has(`${e.id}|${n.name}|${t}|${j}`)||d.push({eval_:e,configuration:n.name,targetContent:n.content,runNumber:t});y.size>0&&a(`Resuming attempt ${f.job.attempts}: ${y.size} run(s) already persisted, ${d.length} remaining`);let l=d.length,u=0,m=Math.min(o.parallel??1,4);await p(`/api/eval-jobs/${i}/progress`,{status:"running",progress:{total:l,completed:0,current:null,message:`Starting ${l} eval runs (concurrency: ${m})...`}});let b=[];async function I(e){let n=`${e.configuration} \xB7 ${e.eval_.name} \xB7 run#${e.runNumber}`;a(`[${u+1}/${l}] ${n}`);let t=x({targetType:s.type,targetContent:e.targetContent,targetName:s.name});t.leakedFiles.length&&a(`\u26A0 CONTAMINATED ${n}: ${t.leakedFiles.join(", ")} survived the strip`);try{let r=await M({prompt:e.eval_.prompt,targetContent:t.systemPrompt,workDir:t.workDir,timeout:R,model:o.model}),c={};return!o.skipGrading&&e.eval_.expectations.length>0&&!r.error&&(c=await C({prompt:e.eval_.prompt,output:r.output,expectations:e.eval_.expectations,model:o.graderModel??o.model,timeout:R})),{jobId:i,evalId:e.eval_.id,evalTargetId:s.id,evalTargetVersion:s.version,configuration:e.configuration,runNumber:e.runNumber,iteration:j,status:r.error?"failed":"completed",outputs:{...r.error?{error:r.error}:{transcript:r.output,...r.model?{model:r.model}:{}},methodology:t.methodology,delivery:t.delivery,isolated:t.isWorktree,...t.leakedFiles.length?{leakedFiles:t.leakedFiles}:{}},timing:{duration_ms:r.durationMs,total_tokens:r.totalTokens},grading:c,worktree:t.isWorktree?!0:void 0}}finally{t.cleanup()}}if(w(I,"processItem"),m<=1)for(let e of d){let n=`${e.configuration} \xB7 ${e.eval_.name} \xB7 run#${e.runNumber}`;await p(`/api/eval-jobs/${i}/progress`,{status:"running",progress:{total:l,completed:u,current:n,message:`Executing ${n}...`}});let t=await I(e);await E("/api/eval-runs",t),b.push(t),u++,await p(`/api/eval-jobs/${i}/progress`,{status:"running",progress:{total:l,completed:u,current:n,message:`Completed ${n}`}})}else{a(`Running ${l} evals with concurrency=${m} (worktree isolation)`);for(let e=0;e<d.length;e+=m){let n=d.slice(e,e+m),t=`batch ${Math.floor(e/m)+1}/${Math.ceil(d.length/m)}`;await p(`/api/eval-jobs/${i}/progress`,{status:"running",progress:{total:l,completed:u,current:t,message:`Executing ${t} (${n.length} parallel)...`}});let r=await Promise.all(n.map(I));for(let c of r)await E("/api/eval-runs",c),b.push(c),u++;await p(`/api/eval-jobs/${i}/progress`,{status:"running",progress:{total:l,completed:u,current:t,message:`Completed ${t}`}})}}let P=J(b),h;if(!o.skipGrading&&b.some(e=>e.grading&&Object.keys(e.grading).length>0))try{a(`Running meta-judge for job ${i}...`);let e=$.map(n=>{let r=b.filter(c=>c.evalId===n.id&&c.configuration==="with_target")[0];return{evalName:n.name,prompt:n.prompt,expectations:n.expectations,grading:r?.grading?r.grading:null,output:r?.outputs?.transcript?.slice(0,500)}});h=await S({targetName:s.name,evalResults:e,model:o.graderModel??o.model,timeout:6e4}),a(`Meta-judge: quality=${h.quality_score}/5, issues=${h.issues.length}`)}catch(e){a(`Meta-judge failed (non-fatal): ${e instanceof Error?e.message:String(e)}`)}let N=h?{...P,meta_judgement:h}:P;return a(`Job ${i} completed: ${u}/${l} runs`),await p(`/api/eval-jobs/${i}/state`,{result:N}).catch(e=>{a(`result persist failed: ${e instanceof Error?e.message:String(e)}`)}),N}w(W,"processEval");function J(v){let f=v.filter(a=>a.status==="completed"),i=v.filter(a=>a.status==="failed"),g=f.filter(a=>{let s=a.grading;return s&&Object.keys(s).length>0}),o=g.length>0?g.reduce((a,s)=>a+(s.grading?.summary?.pass_rate??0),0)/g.length:null;return{total:v.length,completed:f.length,failed:i.length,avgPassRate:o}}w(J,"buildSummary");export{W as a};
1
+ import{a as T}from"./chunk-5RBLIVBF.js";import{a as S}from"./chunk-XFAFMYIP.js";import{b as A}from"./chunk-KJRMGTAO.js";import{e as x}from"./chunk-GN3ZHQ46.js";import{a as C}from"./chunk-BJSVATVJ.js";import{d as M}from"./chunk-TZA4HAVF.js";import{e as k,f as E,h as p}from"./chunk-UGACB66X.js";import{a as w}from"./chunk-ZLLER3HP.js";async function W(v,f){let{mirrorId:i,evalTargetId:g,config:o}=v,a=w(e=>f.logger.info(e),"log"),s=await k(`/api/eval-targets/${g}`),$=await k(`/api/eval-targets/${g}/evals`);if($.length===0&&o.generateIfEmpty){a("No eval cases on target \u2014 generating from content via local LLM...");let e=await A({content:s.content,name:s.name});if(e===null)throw new Error("Case generation requires an LLM backend (claude CLI on PATH or ANTHROPIC_API_KEY) \u2014 none available on this worker.");let n=[];for(let t of e)n.push(await E(`/api/eval-targets/${g}/evals`,t));$=n,a(`Generated ${n.length} eval case(s)`)}if($.length===0)throw new T("No evals defined for target");let G=o.runsPerEval??1,R=o.timeout??12e4,j=o.iteration??1,y=new Set;if(f.job.attempts>1)for(let n=0;;n+=100){let t=await k(`/api/eval-targets/${g}/runs?jobId=${i}&limit=100&offset=${n}`);for(let r of t)y.add(`${r.evalId}|${r.configuration}|${r.runNumber}|${r.iteration}`);if(t.length<100)break}let _=[{name:"with_target",content:s.content}];o.skipBaseline||_.push({name:"without_target"});let d=[];for(let e of $)for(let n of _)for(let t=1;t<=G;t++)y.has(`${e.id}|${n.name}|${t}|${j}`)||d.push({eval_:e,configuration:n.name,targetContent:n.content,runNumber:t});y.size>0&&a(`Resuming attempt ${f.job.attempts}: ${y.size} run(s) already persisted, ${d.length} remaining`);let l=d.length,u=0,m=Math.min(o.parallel??1,4);await p(`/api/eval-jobs/${i}/progress`,{status:"running",progress:{total:l,completed:0,current:null,message:`Starting ${l} eval runs (concurrency: ${m})...`}});let b=[];async function I(e){let n=`${e.configuration} \xB7 ${e.eval_.name} \xB7 run#${e.runNumber}`;a(`[${u+1}/${l}] ${n}`);let t=x({targetType:s.type,targetContent:e.targetContent,targetName:s.name});t.leakedFiles.length&&a(`\u26A0 CONTAMINATED ${n}: ${t.leakedFiles.join(", ")} survived the strip`);try{let r=await M({prompt:e.eval_.prompt,targetContent:t.systemPrompt,workDir:t.workDir,timeout:R,model:o.model}),c={};return!o.skipGrading&&e.eval_.expectations.length>0&&!r.error&&(c=await C({prompt:e.eval_.prompt,output:r.output,expectations:e.eval_.expectations,model:o.graderModel??o.model,timeout:R})),{jobId:i,evalId:e.eval_.id,evalTargetId:s.id,evalTargetVersion:s.version,configuration:e.configuration,runNumber:e.runNumber,iteration:j,status:r.error?"failed":"completed",outputs:{...r.error?{error:r.error}:{transcript:r.output,...r.model?{model:r.model}:{}},methodology:t.methodology,delivery:t.delivery,isolated:t.isWorktree,...t.leakedFiles.length?{leakedFiles:t.leakedFiles}:{}},timing:{duration_ms:r.durationMs,total_tokens:r.totalTokens},grading:c,worktree:t.isWorktree?!0:void 0}}finally{t.cleanup()}}if(w(I,"processItem"),m<=1)for(let e of d){let n=`${e.configuration} \xB7 ${e.eval_.name} \xB7 run#${e.runNumber}`;await p(`/api/eval-jobs/${i}/progress`,{status:"running",progress:{total:l,completed:u,current:n,message:`Executing ${n}...`}});let t=await I(e);await E("/api/eval-runs",t),b.push(t),u++,await p(`/api/eval-jobs/${i}/progress`,{status:"running",progress:{total:l,completed:u,current:n,message:`Completed ${n}`}})}else{a(`Running ${l} evals with concurrency=${m} (worktree isolation)`);for(let e=0;e<d.length;e+=m){let n=d.slice(e,e+m),t=`batch ${Math.floor(e/m)+1}/${Math.ceil(d.length/m)}`;await p(`/api/eval-jobs/${i}/progress`,{status:"running",progress:{total:l,completed:u,current:t,message:`Executing ${t} (${n.length} parallel)...`}});let r=await Promise.all(n.map(I));for(let c of r)await E("/api/eval-runs",c),b.push(c),u++;await p(`/api/eval-jobs/${i}/progress`,{status:"running",progress:{total:l,completed:u,current:t,message:`Completed ${t}`}})}}let P=J(b),h;if(!o.skipGrading&&b.some(e=>e.grading&&Object.keys(e.grading).length>0))try{a(`Running meta-judge for job ${i}...`);let e=$.map(n=>{let r=b.filter(c=>c.evalId===n.id&&c.configuration==="with_target")[0];return{evalName:n.name,prompt:n.prompt,expectations:n.expectations,grading:r?.grading?r.grading:null,output:r?.outputs?.transcript?.slice(0,500)}});h=await S({targetName:s.name,evalResults:e,model:o.graderModel??o.model,timeout:6e4}),a(`Meta-judge: quality=${h.quality_score}/5, issues=${h.issues.length}`)}catch(e){a(`Meta-judge failed (non-fatal): ${e instanceof Error?e.message:String(e)}`)}let N=h?{...P,meta_judgement:h}:P;return a(`Job ${i} completed: ${u}/${l} runs`),await p(`/api/eval-jobs/${i}/state`,{result:N}).catch(e=>{a(`result persist failed: ${e instanceof Error?e.message:String(e)}`)}),N}w(W,"processEval");function J(v){let f=v.filter(a=>a.status==="completed"),i=v.filter(a=>a.status==="failed"),g=f.filter(a=>{let s=a.grading;return s&&Object.keys(s).length>0}),o=g.length>0?g.reduce((a,s)=>a+(s.grading?.summary?.pass_rate??0),0)/g.length:null;return{total:v.length,completed:f.length,failed:i.length,avgPassRate:o}}w(J,"buildSummary");export{W as a};
@@ -1,4 +1,4 @@
1
- import{a as g,c as w}from"./chunk-UPFH72PF.js";import{g as p,h as m,i as k,j as h,k as y}from"./chunk-OOGTQOL3.js";import{a as s}from"./chunk-ZLLER3HP.js";import{existsSync as u,readFileSync as f,writeFileSync as v,copyFileSync as R,rmSync as P,statSync as x,readdirSync as $,mkdirSync as j}from"node:fs";import{join as i,dirname as L}from"node:path";import{homedir as c}from"node:os";var I=["/plugins/cache/","/plugins/marketplaces/","/node_modules/","/.git/"];function _(e){return I.some(t=>e.includes(t))}s(_,"isUnownedPath");function K(e,t){let n=i(c(),".config","rulemetric","retraction-backups",t),r=e.replace(/^\/+/,"").replace(/\//g,"__");return i(n,r)}s(K,"backupPathFor");function b(e){return e.split(`
1
+ import{a as g,c as w}from"./chunk-UPFH72PF.js";import{g as p,h as m,i as k,j as h,k as y}from"./chunk-WMIUFMDI.js";import{a as s}from"./chunk-ZLLER3HP.js";import{existsSync as u,readFileSync as f,writeFileSync as v,copyFileSync as R,rmSync as P,statSync as x,readdirSync as $,mkdirSync as j}from"node:fs";import{join as i,dirname as L}from"node:path";import{homedir as c}from"node:os";var I=["/plugins/cache/","/plugins/marketplaces/","/node_modules/","/.git/"];function _(e){return I.some(t=>e.includes(t))}s(_,"isUnownedPath");function K(e,t){let n=i(c(),".config","rulemetric","retraction-backups",t),r=e.replace(/^\/+/,"").replace(/\//g,"__");return i(n,r)}s(K,"backupPathFor");function b(e){return e.split(`
2
2
  `).slice(0,40).map(t=>`- ${t}`).join(`
3
3
  `)}s(b,"shortDiff");function d(e,t,n){return{kind:e,path:t,ok:!1,refusal:n,preview:"",warnings:[]}}s(d,"refuse");function B(e){let[t,...n]=e.split("::"),r=n.join("::");if(!r)return null;switch(t){case"claude_md":return{kind:"claude_md_section",target:r};case"memory":return{kind:"memory_section",target:r};case"skill":return{kind:"skill_file",target:r};default:return null}}s(B,"pathFromContextIdentity");function D(e,t){let n=e.replace(/^skills--/,""),r=w(e);return[...(r===n?[n]:[r,n]).flatMap(a=>[i(t,...g.split("/"),a,"SKILL.md"),i(t,".claude","skills",a,"SKILL.md"),i(t,".claude","skills",`${a}.md`),i(c(),...g.split("/"),a,"SKILL.md"),i(c(),".claude","skills",a,"SKILL.md"),i(c(),".claude","skills",`${a}.md`)]),...F(n)]}s(D,"candidateSkillPaths");function F(e){let t=i(c(),".claude","plugins","marketplaces");if(!u(t))return[];let n=[];try{for(let r of $(t))n.push(i(t,r,"skills",e,"SKILL.md"),i(t,r,"plugins",e,"SKILL.md"),i(t,r,"skills",`${e}.md`))}catch{}return n}s(F,"pluginSkillPaths");function H(e){switch(e.kind){case"claude_md_section":case"memory_section":case"claude_md_block":return C(e);case"skill_file":return E(e);case"settings_hook":case"mcp_server":return N(e)}}s(H,"planRetraction");function C(e){let t=e.target;if(!u(t))return d(e.kind,t,`File does not exist: ${t}`);if(_(t))return d(e.kind,t,`Refusing to edit a path this tool does not own: ${t}`);let n=f(t,"utf-8"),r=e.body?m(n,e.body):p(n,e.heading??"");if(!r.removed){let l={"not-found":"The content is not present in this file (already removed, or edited since).",ambiguous:"The content appears more than once \u2014 refusing to guess which copy the verdict was about.","would-empty-file":"Removing it would empty the file. Delete the file by hand if that is really the intent."}[r.reason??"not-found"];return d(e.kind,t,l)}let o=[];return S(t,e.cwd)||o.push("This file is not tracked by git in this repo \u2014 the timestamped backup is your only undo."),{kind:e.kind,path:t,ok:!0,preview:b(r.removedText??""),nextContent:r.content,warnings:o}}s(C,"planFileEdit");function E(e){let t=e.target.startsWith("/")?[e.target]:D(e.target,e.cwd),n=t.find(l=>u(l));if(!n)return d("skill_file",t[0]??e.target,`No local skill file found for "${e.target}". Searched:
4
4
  ${t.join(`
@@ -1,5 +1,5 @@
1
1
  import{a as i}from"./chunk-ZLLER3HP.js";function X(e){return(e.trim().split(`
2
- `)[0]?.replace(/^#+\s*/,"").trim()||"Suggested instruction").slice(0,120)}i(X,"recommendationTitle");function J(e){if(!e||typeof e!="object")return e;let t=e;if(Array.isArray(t.recommendation_candidates))return e;let n=t.suggestions;if(!n||typeof n!="object")return e;let o=n.claude_md_additions;return Array.isArray(o)&&(t.recommendation_candidates=o.flatMap(r=>{if(!r||typeof r!="object")return[];let s=r;if(typeof s.addition!="string"||s.addition.trim()==="")return[];let a=s.addition.trim();return[{title:X(a),artifact:"instruction",canonicalBody:a,rationale:typeof s.why=="string"?s.why:"",evidence:[],outcomeMetric:"session_outcome",renderings:[{harness:"claude_code",target:"CLAUDE.md",body:a},{harness:"codex",target:"AGENTS.md",body:a}]}]})),e}i(J,"normalizeRecommendationCandidates");var Z=new Set(["instruction"]);function Q(e){if(!e||typeof e!="object")return e;let t=e,n=t.recommendation_candidates;if(!Array.isArray(n)||n.length===0)return e;let o=n.filter(s=>!!s&&typeof s=="object"&&typeof s.canonicalBody=="string"&&s.canonicalBody.trim().length>0);for(let s of o){if(Array.isArray(s.renderings)&&s.renderings.length>0)continue;let a=s.canonicalBody.trim(),c=Z.has(String(s.artifact));s.renderings=c?[{harness:"claude_code",target:"CLAUDE.md",body:a},{harness:"codex",target:"AGENTS.md",body:a}]:[{harness:"claude_code",target:"manual",body:a},{harness:"codex",target:"manual",body:a}]}let r=t.suggestions&&typeof t.suggestions=="object"?t.suggestions:{};return(!Array.isArray(r.claude_md_additions)||r.claude_md_additions.length===0)&&(r.claude_md_additions=o.filter(s=>s.artifact==="instruction").map(s=>({addition:s.canonicalBody.trim(),why:typeof s.rationale=="string"?s.rationale:"",prompt_scaffold:"Add to CLAUDE.md (and AGENTS.md for Codex)."}))),(!Array.isArray(r.features_to_try)||r.features_to_try.length===0)&&(r.features_to_try=o.filter(s=>s.artifact!=="instruction").map(s=>({feature:typeof s.title=="string"?s.title:"Proposed change",one_liner:typeof s.rationale=="string"?s.rationale:"",why_for_you:typeof s.outcomeMetric=="string"?`Aimed at ${s.outcomeMetric}.`:"",example_code:s.canonicalBody.trim()}))),Array.isArray(r.usage_patterns)||(r.usage_patterns=[]),t.suggestions=r,e}i(Q,"deriveLegacyPresentation");function ee(e){if(!e||typeof e!="object")return e;let t=e,n=t.project_areas;if(n!==void 0&&!Array.isArray(n)){let o=n&&typeof n=="object"?n.areas:void 0;t.project_areas=Array.isArray(o)?o:void 0}return te(e),J(e),e}i(ee,"normalizeRecommendations");function te(e){if(!e||typeof e!="object")return;let t=e;if(Array.isArray(t.recommendation_candidates)&&t.recommendation_candidates.length>0)return;let n=t.suggestions;if(!n||typeof n!="object")return;let o=n.recommendation_candidates;!Array.isArray(o)||o.length===0||(t.recommendation_candidates=o)}i(te,"liftNestedCandidates");import{z as p}from"zod";var I=["org","team","project","personal"],R=p.object({name:p.string().min(1),description:p.string().min(1),type:p.literal("instruction").default("instruction"),scope:p.enum(I),version:p.string().min(1),tags:p.array(p.string()).optional(),compatibility:p.array(p.string()).optional(),slots:p.record(p.string(),p.string()).optional(),metadata:p.record(p.string(),p.unknown()).optional()});import{z as d}from"zod";var N=d.object({name:d.string().min(1),description:d.string().min(1),type:d.literal("prompt"),version:d.string().min(1),tags:d.array(d.string()).optional(),variables:d.array(d.string()).optional(),metadata:d.record(d.string(),d.unknown()).optional()});function v(e,t){let n=t.map(o=>`- ID: ${o.id}
2
+ `)[0]?.replace(/^#+\s*/,"").trim()||"Suggested instruction").slice(0,120)}i(X,"recommendationTitle");function J(e){if(!e||typeof e!="object")return e;let t=e;if(Array.isArray(t.recommendation_candidates))return e;let n=t.suggestions;if(!n||typeof n!="object")return e;let o=n.claude_md_additions;return Array.isArray(o)&&(t.recommendation_candidates=o.flatMap(r=>{if(!r||typeof r!="object")return[];let s=r;if(typeof s.addition!="string"||s.addition.trim()==="")return[];let a=s.addition.trim();return[{title:X(a),artifact:"instruction",canonicalBody:a,rationale:typeof s.why=="string"?s.why:"",evidence:[],outcomeMetric:"session_outcome",renderings:[{harness:"claude_code",target:"CLAUDE.md",body:a},{harness:"codex",target:"AGENTS.md",body:a}]}]})),e}i(J,"normalizeRecommendationCandidates");var Z=new Set(["instruction"]);function Q(e){if(!e||typeof e!="object")return e;let t=e,n=t.recommendation_candidates;if(!Array.isArray(n)||n.length===0)return e;let o=n.filter(s=>!!s&&typeof s=="object"&&typeof s.canonicalBody=="string"&&s.canonicalBody.trim().length>0);for(let s of o){if(Array.isArray(s.renderings)&&s.renderings.length>0)continue;let a=s.canonicalBody.trim(),c=Z.has(String(s.artifact));s.renderings=c?[{harness:"claude_code",target:"CLAUDE.md",body:a},{harness:"codex",target:"AGENTS.md",body:a}]:[{harness:"claude_code",target:"manual",body:a},{harness:"codex",target:"manual",body:a}]}let r=t.suggestions&&typeof t.suggestions=="object"?t.suggestions:{};return(!Array.isArray(r.claude_md_additions)||r.claude_md_additions.length===0)&&(r.claude_md_additions=o.filter(s=>s.artifact==="instruction").map(s=>({addition:s.canonicalBody.trim(),why:typeof s.rationale=="string"?s.rationale:"",prompt_scaffold:"Add to CLAUDE.md (and AGENTS.md for Codex)."}))),(!Array.isArray(r.features_to_try)||r.features_to_try.length===0)&&(r.features_to_try=o.filter(s=>s.artifact!=="instruction").map(s=>({feature:typeof s.title=="string"?s.title:"Proposed change",one_liner:typeof s.rationale=="string"?s.rationale:"",why_for_you:typeof s.outcomeMetric=="string"?`Aimed at ${s.outcomeMetric}.`:"",example_code:s.canonicalBody.trim()}))),Array.isArray(r.usage_patterns)||(r.usage_patterns=[]),t.suggestions=r,e}i(Q,"deriveLegacyPresentation");function ee(e){if(!e||typeof e!="object")return e;let t=e,n=t.project_areas;if(n!==void 0&&!Array.isArray(n)){let o=n&&typeof n=="object"?n.areas:void 0;t.project_areas=Array.isArray(o)?o:void 0}return te(e),J(e),e}i(ee,"normalizeRecommendations");function te(e){if(!e||typeof e!="object")return;let t=e;if(Array.isArray(t.recommendation_candidates)&&t.recommendation_candidates.length>0)return;let n=t.suggestions;if(!n||typeof n!="object")return;let o=n.recommendation_candidates;!Array.isArray(o)||o.length===0||(t.recommendation_candidates=o)}i(te,"liftNestedCandidates");import{z as p}from"zod";var L=["org","team","project","personal"],R=p.object({name:p.string().min(1),description:p.string().min(1),type:p.literal("instruction").default("instruction"),scope:p.enum(L),version:p.string().min(1),tags:p.array(p.string()).optional(),compatibility:p.array(p.string()).optional(),slots:p.record(p.string(),p.string()).optional(),metadata:p.record(p.string(),p.unknown()).optional()});import{z as d}from"zod";var N=d.object({name:d.string().min(1),description:d.string().min(1),type:d.literal("prompt"),version:d.string().min(1),tags:d.array(d.string()).optional(),variables:d.array(d.string()).optional(),metadata:d.record(d.string(),d.unknown()).optional()});function v(e,t){let n=t.map(o=>`- ID: ${o.id}
3
3
  Name: ${o.name}
4
4
  Description: ${o.description}
5
5
  Tags: ${o.tags.join(", ")}
@@ -32,7 +32,7 @@ Return your response as JSON in this exact format:
32
32
  ]
33
33
  }
34
34
 
35
- Only include instructions with a relevance score >= 0.5. Order by score descending. Return valid JSON only, no markdown fences.`}i(v,"buildRecommendationPrompt");var P=32e3,ne={name:"x".repeat(64),description:"x".repeat(256),languages:["TypeScript","Python","Go"],topics:["x".repeat(32)],dependencies:["x".repeat(32)]};function D(e,t={}){if(e.length===0)return[];let n=t.charBudget??P,o=v(ne,[]).length,r=[],s=[],a=0;for(let c of e){let l=oe(c);s.length>0&&o+a+l>n&&(r.push(s),s=[],a=0),s.push(c),a+=l}return s.length>0&&r.push(s),r}i(D,"batchCandidatesForPrompt");function oe(e){return`- ID: ${e.id}
35
+ Only include instructions with a relevance score >= ${.5}. Order by score descending. Return valid JSON only, no markdown fences.`}i(v,"buildRecommendationPrompt");var P=32e3,ne={name:"x".repeat(64),description:"x".repeat(256),languages:["TypeScript","Python","Go"],topics:["x".repeat(32)],dependencies:["x".repeat(32)]};function D(e,t={}){if(e.length===0)return[];let n=t.charBudget??P,o=v(ne,[]).length,r=[],s=[],a=0;for(let c of e){let l=oe(c);s.length>0&&o+a+l>n&&(r.push(s),s=[],a=0),s.push(c),a+=l}return s.length>0&&r.push(s),r}i(D,"batchCandidatesForPrompt");function oe(e){return`- ID: ${e.id}
36
36
  Name: ${e.name}
37
37
  Description: ${e.description}
38
38
  Tags: ${e.tags.join(", ")}
@@ -43,6 +43,6 @@ Only include instructions with a relevance score >= 0.5. Order by score descendi
43
43
 
44
44
  `),removed:!0,removedText:l}}i(ue,"removeMarkdownSection");function me(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(me,"removeExactBlock");var M=["HTTPS_PROXY","HTTP_PROXY","NODE_EXTRA_CA_CERTS"];function pe(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(pe,"removeHookByCommand");function de(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(de,"removeMcpServer");function E(e){if(!e||typeof e!="object")return[];let t=e.env;return t?M.filter(n=>n in t):[]}i(E,"protectedEnvKeysPresent");function fe(e,t){let n=E(e),o=new Set(E(t));return n.filter(r=>!o.has(r))}i(fe,"lostProtectedEnvKeys");function he(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(he,"parseApiError");var b=["inside","outside"];function y(e){return e.trim().toLowerCase()}i(y,"normalizeDependencyKey");function ge(e){let t=[];if(b.includes(e.boundaryClass)||t.push({field:"boundaryClass",message:`must be one of ${b.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(ge,"validateArtifactSpec");function ye(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(ye,"validateArtifactInverse");var U="artifact";function A(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}i(A,"stringArray");function xe(e){if(!e||typeof e!="object")return null;let t=e[U];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(xe,"parseArtifactSpec");var ve=["applied","measuring","improved","inconclusive","harmful","rollback_ready"];function H(e){return e.appliedAt?e.appliedAt instanceof Date?e.appliedAt.getTime():new Date(e.appliedAt).getTime():0}i(H,"appliedAtMs");function Se(e){return[...e].sort((t,n)=>{let o=H(n)-H(t);return o!==0?o:(n.applySeq??0)-(t.applySeq??0)})}i(Se,"orderForReversal");var z=["SessionStart","SessionEnd","UserPromptSubmit","PreToolUse","PostToolUse","PreCompact","Notification","Stop","SubagentStop"],T=".claude/settings.local.json";function F(e){return`# rm-artifact:${e}`}i(F,"hookTag");function _e(e,t){return`${e.trim()} ${F(t)}`}i(_e,"taggedHookCommand");var Ee=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)||Ee.has(t)?null:y(`cmd:${t}`)}i(k,"inferredCommandRequirement");function Ae(e,t){let n=new Set((t?.requires??[]).map(y).filter(Boolean)),o=k(e.command);return o&&n.add(o),{boundaryClass:"outside",targets:[T],requires:[...n],provides:(t?.provides??[]).map(y).filter(Boolean)}}i(Ae,"hookArtifactSpec");function x(e){let t=[];z.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 be(e){let t=[`runs on: ${e.event}${e.matcher?` (tools matching ${e.matcher})`:""}`,`spawns: ${e.command.trim()}`,`writes: ${T} (one entry, tagged with this artifact's id)`],n=k(e.command);return n&&t.push(`needs: ${n} on PATH`),t}i(be,"describeHookCapability");var Y="hook";function h(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}i(h,"asRecord");function K(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(K,"readBareSpec");function B(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(B,"readSettingsFragment");function Te(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(Te,"fencedBlocks");function ke(e){let t=h(h(e.frontmatter)?.artifact),n=t?h(t[Y]):null;if(n){let o=K(n);if(o)return{spec:o,problems:x(o),source:"envelope"};let r=B(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 Te(e.content??"")){let r;try{r=JSON.parse(o)}catch{continue}let s=h(r);if(!s)continue;let a=K(s);if(a)return{spec:a,problems:x(a),source:"content-fragment"};let c=B(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(ke,"parseHookSpec");var Ce=/[\p{L}\p{N}]+/gu;function C(e){let t=new Set;for(let n of e.toLowerCase().matchAll(Ce)){let o=` ${n[0]} `;for(let r=0;r+3<=o.length;r+=1)t.add(o.slice(r,r+3))}return t}i(C,"trigrams");function g(e,t){let n=C(e),o=C(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 L=.3,we=15;function w(e){let n=e.replace(/<!--[\s\S]*?-->/g," ").replace(/```[\s\S]*?```/g," "),o=[];for(let r of n.split(`
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>=we&&o.push(l)}}return o}i(w,"splitDirectives");function W(e,t,n=L){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(W,"assessRedundancy");function Le(e,t=L){let n=[];for(let o=0;o<e.length;o+=1){let r=W(e[o].content,e.slice(0,o),t);r.matches.length>0&&n.push({instruction:e[o],verdict:r})}return n}i(Le,"findInternalRedundancy");var G=.5,Oe=/-(?=[0-9a-f]{6}$)[0-9a-f]*[0-9][0-9a-f]*$/;function O(e){return e.trim().toLowerCase().replace(/^skills--/,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").replace(Oe,"").replace(/-+$/,"")}i(O,"skillNameStem");function Ie(e,t,n=G){let o=O(e.name);for(let s of t)if(o.length>0&&O(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(Ie,"assessSkillDuplication");var Re=new Set(["sh","bash","zsh","fish"]),Ne=new Set(["mjs","cjs","js","ts","py","rb","pl"]),Pe=/(?:^|[\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+)*$/,De=/(?:\.\/)?(?:[\w.@-]+\/)+[\w.@-]+\.\w+/g;function je(e){return e.replace(/```[\w-]*\n?/g," ").replace(/`/g," ")}i(je,"stripCodeMarkers");function $e(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($e,"normalise");function q(e){let t=je(e),n=new Set,o=[];for(let r of t.matchAll(De)){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=$e(s);if(!l)continue;let u=l.slice(l.lastIndexOf(".")+1).toLowerCase();(Re.has(u)||Ne.has(u)&&(s.startsWith("./")||Pe.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(q,"extractCommandReferences");function Me(e,t){return q(e).filter(n=>!t(n.path))}i(Me,"findUnresolvableReferences");import Nt from"gray-matter";import{z as V}from"zod";var $t=V.object({type:V.enum(["instruction","prompt"])});export{Q as a,ee as b,v as c,D as d,ce as e,le as f,ue as g,me as h,pe as i,de as j,fe as k,he as l,y as m,ge as n,ye as o,xe as p,ve as q,Se as r,T as s,F as t,_e as u,Ae as v,be as w,ke as x,w as y,W as z,Le as A,Ie as B,Me as C};
46
+ `);return r.trim().length===0?{content:e,removed:!1,removedText:null,reason:"would-empty-file"}:{content:r,removed:!0,removedText:n}}i(me,"removeExactBlock");var M=["HTTPS_PROXY","HTTP_PROXY","NODE_EXTRA_CA_CERTS"];function pe(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(pe,"removeHookByCommand");function de(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(de,"removeMcpServer");function E(e){if(!e||typeof e!="object")return[];let t=e.env;return t?M.filter(n=>n in t):[]}i(E,"protectedEnvKeysPresent");function fe(e,t){let n=E(e),o=new Set(E(t));return n.filter(r=>!o.has(r))}i(fe,"lostProtectedEnvKeys");function he(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(he,"parseApiError");var T=["inside","outside"];function y(e){return e.trim().toLowerCase()}i(y,"normalizeDependencyKey");function ge(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(ge,"validateArtifactSpec");function ye(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(ye,"validateArtifactInverse");var U="artifact";function A(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}i(A,"stringArray");function xe(e){if(!e||typeof e!="object")return null;let t=e[U];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(xe,"parseArtifactSpec");var ve=["applied","measuring","improved","inconclusive","harmful","rollback_ready"];function H(e){return e.appliedAt?e.appliedAt instanceof Date?e.appliedAt.getTime():new Date(e.appliedAt).getTime():0}i(H,"appliedAtMs");function Se(e){return[...e].sort((t,n)=>{let o=H(n)-H(t);return o!==0?o:(n.applySeq??0)-(t.applySeq??0)})}i(Se,"orderForReversal");var z=["SessionStart","SessionEnd","UserPromptSubmit","PreToolUse","PostToolUse","PreCompact","Notification","Stop","SubagentStop"],b=".claude/settings.local.json";function F(e){return`# rm-artifact:${e}`}i(F,"hookTag");function _e(e,t){return`${e.trim()} ${F(t)}`}i(_e,"taggedHookCommand");var Ee=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)||Ee.has(t)?null:y(`cmd:${t}`)}i(k,"inferredCommandRequirement");function Ae(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(Ae,"hookArtifactSpec");function x(e){let t=[];z.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 Te(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(Te,"describeHookCapability");var Y="hook";function h(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}i(h,"asRecord");function K(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(K,"readBareSpec");function B(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(B,"readSettingsFragment");function be(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(be,"fencedBlocks");function ke(e){let t=h(h(e.frontmatter)?.artifact),n=t?h(t[Y]):null;if(n){let o=K(n);if(o)return{spec:o,problems:x(o),source:"envelope"};let r=B(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 be(e.content??"")){let r;try{r=JSON.parse(o)}catch{continue}let s=h(r);if(!s)continue;let a=K(s);if(a)return{spec:a,problems:x(a),source:"content-fragment"};let c=B(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(ke,"parseHookSpec");var Ce=/[\p{L}\p{N}]+/gu;function C(e){let t=new Set;for(let n of e.toLowerCase().matchAll(Ce)){let o=` ${n[0]} `;for(let r=0;r+3<=o.length;r+=1)t.add(o.slice(r,r+3))}return t}i(C,"trigrams");function g(e,t){let n=C(e),o=C(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 w=.3,Oe=15;function O(e){let n=e.replace(/<!--[\s\S]*?-->/g," ").replace(/```[\s\S]*?```/g," "),o=[];for(let r of n.split(`
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>=Oe&&o.push(l)}}return o}i(O,"splitDirectives");function W(e,t,n=w){let o=O(e);if(o.length===0)return{redundant:!1,coverage:0,matches:[],novel:[]};let r=t.flatMap(c=>O(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(W,"assessRedundancy");function we(e,t=w){let n=[];for(let o=0;o<e.length;o+=1){let r=W(e[o].content,e.slice(0,o),t);r.matches.length>0&&n.push({instruction:e[o],verdict:r})}return n}i(we,"findInternalRedundancy");var G=.5,Ie=/-(?=[0-9a-f]{6}$)[0-9a-f]*[0-9][0-9a-f]*$/;function I(e){return e.trim().toLowerCase().replace(/^skills--/,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").replace(Ie,"").replace(/-+$/,"")}i(I,"skillNameStem");function Le(e,t,n=G){let o=I(e.name);for(let s of t)if(o.length>0&&I(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(Le,"assessSkillDuplication");var Re=new Set(["sh","bash","zsh","fish"]),Ne=new Set(["mjs","cjs","js","ts","py","rb","pl"]),Pe=/(?:^|[\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+)*$/,De=/(?:\.\/)?(?:[\w.@-]+\/)+[\w.@-]+\.\w+/g;function je(e){return e.replace(/```[\w-]*\n?/g," ").replace(/`/g," ")}i(je,"stripCodeMarkers");function $e(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($e,"normalise");function q(e){let t=je(e),n=new Set,o=[];for(let r of t.matchAll(De)){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=$e(s);if(!l)continue;let u=l.slice(l.lastIndexOf(".")+1).toLowerCase();(Re.has(u)||Ne.has(u)&&(s.startsWith("./")||Pe.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(q,"extractCommandReferences");function Me(e,t){return q(e).filter(n=>!t(n.path))}i(Me,"findUnresolvableReferences");import Nt from"gray-matter";import{z as V}from"zod";var $t=V.object({type:V.enum(["instruction","prompt"])});export{Q as a,ee as b,v as c,D as d,ce as e,le as f,ue as g,me as h,pe as i,de as j,fe as k,he as l,y as m,ge as n,ye as o,xe as p,ve as q,Se as r,b as s,F as t,_e as u,Ae as v,Te as w,ke as x,O as y,W as z,we as A,Le as B,Me as C};
@@ -1,4 +1,4 @@
1
- import{a as I}from"./chunk-5RBLIVBF.js";import{a as j,d as O}from"./chunk-3UKZJAFS.js";import{c as U}from"./chunk-MOY7XDR6.js";import{a as T,b as P,c as H,d as A}from"./chunk-SJKS3PYX.js";import{a as W}from"./chunk-E7N5R3HV.js";import{c as x,d as L,f as S}from"./chunk-QBNLZJIR.js";import{e as _,f as J,h as d}from"./chunk-2AVGUZ2P.js";import{a as z,b as F}from"./chunk-OOGTQOL3.js";import{a as f}from"./chunk-ZLLER3HP.js";var B=f((l,{limit:a,sort:n,eventTypes:s})=>_(`/api/sessions/${l}/events?limit=${a}&sort=${n}&eventType=${encodeURIComponent(s.join(","))}&hasContent=true`),"fetchTranscriptTurns");async function is(l,a){let{mirrorId:n,projectPath:s,projectId:r,config:g}=l,t=f(e=>a.logger.info(e),"log");if(g?.sessionId)return Y({mirrorId:n,sessionId:g.sessionId},t);t(`Processing insights job ${n}...`),await d(`/api/insights-jobs/${n}/progress`,{status:"running",progress:{step:"reading_data"}});try{let{repaired:e}=await J("/api/sessions/repair-analyzed-at",{});e>0&&t(` Repaired analyzed_at on ${e} orphan session(s).`)}catch(e){t(` Warning: analyzed_at repair failed: ${e instanceof Error?e.message:String(e)}`)}let p=20,w=200,v=15*6e4,D=3,C=Date.now()+v;if(L()!=="none"){let e=0,o=0;try{for(;e<w&&Date.now()<C;){let c=await _(`/api/sessions?needsFacets=true&graderVersion=${2}&limit=${p}&offset=${o}`);if(c.length===0)break;t(` Generating facets for ${c.length} un-analyzed sessions (drained ${e} so far)...`);for(let $=0;$<c.length&&!(e>=w||Date.now()>=C);$+=D){let R=c.slice($,$+D);await Promise.all(R.map(async m=>{if(!(e>=w||Date.now()>=C))try{let u=await O(q=>B(m.id,q));if(u.turnCount<2){e++,o++;return}let k=await S(A,u.text,4096);k&&typeof k.outcome=="string"?(await d(`/api/sessions/${m.id}/enrich`,{analysis:{source:"generated_facets",...k,graderVersion:2},...m.eventCount!=null?{analyzedEventCount:m.eventCount}:{},analyzedTurnCount:u.turnCount}),t(` Generated facets for session ${m.id} (${m.tool}, ${u.turnCount} turns)`)):o++,e++}catch(u){t(` Failed to generate facets for session ${m.id}: ${u instanceof Error?u.message:String(u)}`),e++,o++}}))}if(c.length<p)break}}catch(c){t(` Warning: facet generation failed after ${e} sessions: ${c instanceof Error?c.message:String(c)}`)}if(e>0){let c=Date.now()>=C?`time budget (${Math.round(v/6e4)}m)`:e>=w?`hard cap (${w})`:"queue empty";t(` Facet drain stopped on ${c} after ${e} session(s); the rest resume next run.`)}}let b=await K(s,r);if(!b)throw new I("No session data found \u2014 ensure sessions are captured and enriched.");t(` Found ${b.stats.sessions} sessions, generating recommendations...`);let E=await Z(s,t);E&&t(` Generator memory: ${E.split(`
1
+ import{a as I}from"./chunk-5RBLIVBF.js";import{a as W}from"./chunk-HQCPGDQE.js";import{a as j,d as O}from"./chunk-3UKZJAFS.js";import{c as U}from"./chunk-FE2UWAIP.js";import{a as T,b as P,c as H,d as A}from"./chunk-SJKS3PYX.js";import{c as x,d as L,f as S}from"./chunk-QBNLZJIR.js";import{e as _,f as J,h as d}from"./chunk-UGACB66X.js";import{a as z,b as F}from"./chunk-WMIUFMDI.js";import{a as f}from"./chunk-ZLLER3HP.js";var B=f((l,{limit:a,sort:n,eventTypes:s})=>_(`/api/sessions/${l}/events?limit=${a}&sort=${n}&eventType=${encodeURIComponent(s.join(","))}&hasContent=true`),"fetchTranscriptTurns");async function is(l,a){let{mirrorId:n,projectPath:s,projectId:r,config:g}=l,t=f(e=>a.logger.info(e),"log");if(g?.sessionId)return Y({mirrorId:n,sessionId:g.sessionId},t);t(`Processing insights job ${n}...`),await d(`/api/insights-jobs/${n}/progress`,{status:"running",progress:{step:"reading_data"}});try{let{repaired:e}=await J("/api/sessions/repair-analyzed-at",{});e>0&&t(` Repaired analyzed_at on ${e} orphan session(s).`)}catch(e){t(` Warning: analyzed_at repair failed: ${e instanceof Error?e.message:String(e)}`)}let p=20,w=200,v=15*6e4,D=3,C=Date.now()+v;if(L()!=="none"){let e=0,o=0;try{for(;e<w&&Date.now()<C;){let c=await _(`/api/sessions?needsFacets=true&graderVersion=${2}&limit=${p}&offset=${o}`);if(c.length===0)break;t(` Generating facets for ${c.length} un-analyzed sessions (drained ${e} so far)...`);for(let $=0;$<c.length&&!(e>=w||Date.now()>=C);$+=D){let R=c.slice($,$+D);await Promise.all(R.map(async m=>{if(!(e>=w||Date.now()>=C))try{let u=await O(q=>B(m.id,q));if(u.turnCount<2){e++,o++;return}let k=await S(A,u.text,4096);k&&typeof k.outcome=="string"?(await d(`/api/sessions/${m.id}/enrich`,{analysis:{source:"generated_facets",...k,graderVersion:2},...m.eventCount!=null?{analyzedEventCount:m.eventCount}:{},analyzedTurnCount:u.turnCount}),t(` Generated facets for session ${m.id} (${m.tool}, ${u.turnCount} turns)`)):o++,e++}catch(u){t(` Failed to generate facets for session ${m.id}: ${u instanceof Error?u.message:String(u)}`),e++,o++}}))}if(c.length<p)break}}catch(c){t(` Warning: facet generation failed after ${e} sessions: ${c instanceof Error?c.message:String(c)}`)}if(e>0){let c=Date.now()>=C?`time budget (${Math.round(v/6e4)}m)`:e>=w?`hard cap (${w})`:"queue empty";t(` Facet drain stopped on ${c} after ${e} session(s); the rest resume next run.`)}}let b=await K(s,r);if(!b)throw new I("No session data found \u2014 ensure sessions are captured and enriched.");t(` Found ${b.stats.sessions} sessions, generating recommendations...`);let E=await Z(s,t);E&&t(` Generator memory: ${E.split(`
2
2
  `).length} lines of prior-advice context`);let i={},y=[],h=P.length+1;for(let e=0;e<P.length;e++){let o=P[e];t(` [${e+1}/${h}] Generating ${o.name}...`);try{await d(`/api/insights-jobs/${n}/progress`,{status:"running",progress:{step:o.name,current:e+1,total:h,partial:{...i}}})}catch(u){t(` Warning: progress update failed for ${o.name}: ${u instanceof Error?u.message:String(u)}`)}t(` Running LLM prompt for ${o.name}...`);let c=o.usesGeneratorMemory&&E?`${b.summary}
3
3
  ${E}`:b.summary,$=Date.now(),R=await S(o.prompt,c,o.maxTokens,{timeoutMs:o.timeoutMs}),m=Date.now()-$;R?(i[o.name]=R,t(` Got result for ${o.name} (${Math.round(m/1e3)}s)`)):(y.push(o.name),t(` No result for ${o.name} after ${Math.round(m/1e3)}s (budget ${Math.round((o.timeoutMs??12e4)/1e3)}s) \u2014 section DROPPED`))}t(` [${h}/${h}] Generating at_a_glance...`),await d(`/api/insights-jobs/${n}/progress`,{status:"running",progress:{step:"at_a_glance",current:h,total:h,partial:{...i}}});let V=[b.summary,i.what_works?`
4
4
  ## What Works
@@ -1 +1 @@
1
- import{e as k}from"./chunk-GN3ZHQ46.js";import{a as f}from"./chunk-KGURGIZ2.js";import{a as $}from"./chunk-BJSVATVJ.js";import{d as v}from"./chunk-TZA4HAVF.js";import{f as p}from"./chunk-2AVGUZ2P.js";import{a as c}from"./chunk-ZLLER3HP.js";async function x(m,t,s=()=>{}){let{eval_:r,configuration:i,targetContent:g,runNumber:o}=m;s(`[${i}] ${r.name} run#${o} \u2014 executing...`);let a=k({targetType:t.targetType,targetContent:g,targetName:t.targetName}),d={methodology:a.methodology,delivery:a.delivery,isolated:a.isWorktree,...t.candidateContentHash?{candidateContentHash:t.candidateContentHash}:{},...a.leakedFiles.length?{leakedFiles:a.leakedFiles}:{}};a.isWorktree||s(`[${i}] ${r.name} run#${o} \u2014 \u26A0 no git worktree; running without repo context`),a.leakedFiles.length&&s(`[${i}] ${r.name} run#${o} \u2014 \u26A0 CONTAMINATED: ${a.leakedFiles.join(", ")} survived the strip`);try{let n=await v({prompt:r.prompt,targetContent:a.systemPrompt,workDir:a.workDir,timeout:t.timeout,model:t.model});if(n.error){let e=f(n.error);return s(`[${i}] ${r.name} run#${o} \u2014 FAILED (${e.kind}): ${n.error}`),{evalId:r.id,evalTargetId:t.targetId,evalTargetVersion:t.targetVersion,configuration:i,runNumber:o,iteration:t.iteration,status:"failed",outputs:{error:n.error,failureKind:e.kind,failureClass:e.class,...d},timing:{duration_ms:n.durationMs,total_tokens:n.totalTokens},grading:{},failure:e}}s(`[${i}] ${r.name} run#${o} \u2014 completed in ${(n.durationMs/1e3).toFixed(1)}s`);let u={};if(!t.skipGrading&&r.expectations.length>0){s(`[${i}] ${r.name} run#${o} \u2014 grading...`);let e=await $({prompt:r.prompt,output:n.output,expectations:r.expectations,model:t.graderModel??t.model,timeout:t.timeout});u=e,s(`[${i}] ${r.name} run#${o} \u2014 grading done: pass_rate=${e.summary.pass_rate==null?"n/a (all assertions errored)":`${(e.summary.pass_rate*100).toFixed(0)}%`}`)}return{evalId:r.id,evalTargetId:t.targetId,evalTargetVersion:t.targetVersion,configuration:i,runNumber:o,iteration:t.iteration,status:"completed",outputs:{transcript:n.output,...d},timing:{duration_ms:n.durationMs,total_tokens:n.totalTokens,total_duration_seconds:n.durationMs/1e3},grading:u}}finally{a.cleanup()}}c(x,"executeAndGradeCase");async function R(m){let{cases:t,targetContent:s,concurrency:r,runNumber:i,opts:g,skipBaseline:o,onLog:a=c(()=>{},"onLog")}=m,d=o?["with_target"]:["with_target","without_target"],n=[];for(let e of t)for(let l of d)n.push({eval_:e,configuration:l,targetContent:l==="with_target"?s:void 0,runNumber:i});let u=[];for(let e=0;e<n.length;e+=Math.max(1,r)){let l=n.slice(e,e+Math.max(1,r)),h=await Promise.all(l.map(b=>x(b,g,a)));u.push(...h)}for(let e of u)try{await p("/api/eval-runs",e)}catch(l){a(` \u26A0 failed to post a run result: ${l instanceof Error?l.message:String(l)}`)}try{await p(`/api/eval-targets/${g.targetId}/label-state`,{})}catch(e){a(` \u26A0 label-state notification skipped: ${e instanceof Error?e.message:String(e)}`)}return{completed:u.filter(e=>e.status==="completed").length,failed:u.filter(e=>e.status==="failed").length,results:u}}c(R,"runBatchAndPost");export{x as a,R as b};
1
+ import{e as k}from"./chunk-GN3ZHQ46.js";import{a as f}from"./chunk-KGURGIZ2.js";import{a as $}from"./chunk-BJSVATVJ.js";import{d as v}from"./chunk-TZA4HAVF.js";import{f as p}from"./chunk-UGACB66X.js";import{a as c}from"./chunk-ZLLER3HP.js";async function x(m,t,s=()=>{}){let{eval_:r,configuration:i,targetContent:g,runNumber:o}=m;s(`[${i}] ${r.name} run#${o} \u2014 executing...`);let a=k({targetType:t.targetType,targetContent:g,targetName:t.targetName}),d={methodology:a.methodology,delivery:a.delivery,isolated:a.isWorktree,...t.candidateContentHash?{candidateContentHash:t.candidateContentHash}:{},...a.leakedFiles.length?{leakedFiles:a.leakedFiles}:{}};a.isWorktree||s(`[${i}] ${r.name} run#${o} \u2014 \u26A0 no git worktree; running without repo context`),a.leakedFiles.length&&s(`[${i}] ${r.name} run#${o} \u2014 \u26A0 CONTAMINATED: ${a.leakedFiles.join(", ")} survived the strip`);try{let n=await v({prompt:r.prompt,targetContent:a.systemPrompt,workDir:a.workDir,timeout:t.timeout,model:t.model});if(n.error){let e=f(n.error);return s(`[${i}] ${r.name} run#${o} \u2014 FAILED (${e.kind}): ${n.error}`),{evalId:r.id,evalTargetId:t.targetId,evalTargetVersion:t.targetVersion,configuration:i,runNumber:o,iteration:t.iteration,status:"failed",outputs:{error:n.error,failureKind:e.kind,failureClass:e.class,...d},timing:{duration_ms:n.durationMs,total_tokens:n.totalTokens},grading:{},failure:e}}s(`[${i}] ${r.name} run#${o} \u2014 completed in ${(n.durationMs/1e3).toFixed(1)}s`);let u={};if(!t.skipGrading&&r.expectations.length>0){s(`[${i}] ${r.name} run#${o} \u2014 grading...`);let e=await $({prompt:r.prompt,output:n.output,expectations:r.expectations,model:t.graderModel??t.model,timeout:t.timeout});u=e,s(`[${i}] ${r.name} run#${o} \u2014 grading done: pass_rate=${e.summary.pass_rate==null?"n/a (all assertions errored)":`${(e.summary.pass_rate*100).toFixed(0)}%`}`)}return{evalId:r.id,evalTargetId:t.targetId,evalTargetVersion:t.targetVersion,configuration:i,runNumber:o,iteration:t.iteration,status:"completed",outputs:{transcript:n.output,...d},timing:{duration_ms:n.durationMs,total_tokens:n.totalTokens,total_duration_seconds:n.durationMs/1e3},grading:u}}finally{a.cleanup()}}c(x,"executeAndGradeCase");async function R(m){let{cases:t,targetContent:s,concurrency:r,runNumber:i,opts:g,skipBaseline:o,onLog:a=c(()=>{},"onLog")}=m,d=o?["with_target"]:["with_target","without_target"],n=[];for(let e of t)for(let l of d)n.push({eval_:e,configuration:l,targetContent:l==="with_target"?s:void 0,runNumber:i});let u=[];for(let e=0;e<n.length;e+=Math.max(1,r)){let l=n.slice(e,e+Math.max(1,r)),h=await Promise.all(l.map(b=>x(b,g,a)));u.push(...h)}for(let e of u)try{await p("/api/eval-runs",e)}catch(l){a(` \u26A0 failed to post a run result: ${l instanceof Error?l.message:String(l)}`)}try{await p(`/api/eval-targets/${g.targetId}/label-state`,{})}catch(e){a(` \u26A0 label-state notification skipped: ${e instanceof Error?e.message:String(e)}`)}return{completed:u.filter(e=>e.status==="completed").length,failed:u.filter(e=>e.status==="failed").length,results:u}}c(R,"runBatchAndPost");export{x as a,R as b};
@@ -1 +1 @@
1
- import{a as s,b as n,c as a,d as g}from"./chunk-3AV3GTMP.js";import{e as o}from"./chunk-2AVGUZ2P.js";import{a as e}from"./chunk-ZLLER3HP.js";var i=!1;async function c(){if(process.env.RULEMETRIC_ORG_ID)return;let r=s();if(!(r&&!g(r)))try{let t=await o("/api/profile");if(!t.activeOrgId){a();return}if(r&&t.activeOrgId===r.orgId){n({orgId:r.orgId,orgSlug:r.orgSlug,syncedAt:Date.now()});return}let d=(await o("/api/orgs")).find(l=>l.id===t.activeOrgId);n({orgId:t.activeOrgId,orgSlug:d?.slug,syncedAt:Date.now()})}catch{}}e(c,"syncActiveOrgFromServer");async function p(){i||(i=!0,await c())}e(p,"maybeRefreshActiveOrg");async function v(){i=!0,await c()}e(v,"bootstrapActiveOrg");function O(){i=!1}e(O,"_resetRefreshAttempt");export{p as a,v as b,O as c};
1
+ import{a as s,b as n,c as a,d as g}from"./chunk-3AV3GTMP.js";import{e as o}from"./chunk-UGACB66X.js";import{a as e}from"./chunk-ZLLER3HP.js";var i=!1;async function c(){if(process.env.RULEMETRIC_ORG_ID)return;let r=s();if(!(r&&!g(r)))try{let t=await o("/api/profile");if(!t.activeOrgId){a();return}if(r&&t.activeOrgId===r.orgId){n({orgId:r.orgId,orgSlug:r.orgSlug,syncedAt:Date.now()});return}let d=(await o("/api/orgs")).find(l=>l.id===t.activeOrgId);n({orgId:t.activeOrgId,orgSlug:d?.slug,syncedAt:Date.now()})}catch{}}e(c,"syncActiveOrgFromServer");async function p(){i||(i=!0,await c())}e(p,"maybeRefreshActiveOrg");async function v(){i=!0,await c()}e(v,"bootstrapActiveOrg");function O(){i=!1}e(O,"_resetRefreshAttempt");export{p as a,v as b,O as c};
@@ -1 +1 @@
1
- import{c as X}from"./chunk-HOQPVOMF.js";import{b as D}from"./chunk-GIRPEMTW.js";import{a as x}from"./chunk-MODXEGCU.js";import{d as J,f as B}from"./chunk-QBNLZJIR.js";import{e as w,f as R}from"./chunk-2AVGUZ2P.js";import{c as H,d as U}from"./chunk-OOGTQOL3.js";import{a as u}from"./chunk-ZLLER3HP.js";import{readFileSync as q,realpathSync as V}from"node:fs";import y from"node:path";import A from"node:os";function Q(s){let n=y.resolve(s);if(n===y.resolve(A.homedir()))return!1;let a=y.parse(n).root;if(n===a)return!1;try{let o=V(A.tmpdir());if(V(n)===o)return!1}catch{}return!0}u(Q,"isScorableProjectPath");var Z=5,ee=Number(process.env.RULEMETRIC_MAX_SUGGESTION_PROJECTS??10),te=48,ne=.5,O=400,oe=3,re=.6,se=1;function ae(s){let n=s.bloated??[],a=new Set([...s.harmful.map(o=>o.id),...s.candidates.map(o=>o.id)]);return n.filter(o=>!a.has(o.id)).slice(0,se).map(o=>({instructionId:o.id,estimatedTokens:o.estimatedTokens,topProjectId:o.topProjectId??null,score:.55,reason:`Costs ~${o.estimatedTokens} tokens every session and measures neutral across ${o.exposures} exposed session(s) \u2014 enough data to detect an effect, and none found. Consider shortening "${o.name}" rather than removing it.`+(o.containsSafetyLanguage?" CAUTION: it contains guardrail language (destructive-command or credential rules) \u2014 preserve those lines when shortening.":"")}))}u(ae,"buildTrimProposals");async function ie(s,n,a){let o=[],i=0;for(let d of s)try{await a("/api/instruction-experiments",{instructionId:d.instructionId,projectPath:n,source:"groom"}),i++}catch(g){let m=g instanceof Error?g.message:String(g);o.push({...d,reason:`${d.reason} (not measurable by withholding: ${m})`})}return{nominated:i,unmeasurable:o}}u(ie,"nominateRemovals");function ce(s){let n=[];for(let o of s.harmful){let i=o.verdict.delta;n.push({instructionId:o.id,score:Math.min(.95,.75+Math.abs(i)),topProjectId:o.topProjectId??null,reason:`Measured harmful: sessions using "${o.name}" scored ${(i*100).toFixed(1)}pp worse across ${o.exposures} exposed session(s). Observational \u2014 review before archiving.`})}let a=new Set(s.harmful.map(o=>o.id));for(let o of s.candidates)a.has(o.id)||n.push({instructionId:o.id,score:re,topProjectId:o.topProjectId??null,reason:`Unused: "${o.name}" is ${o.reason} (${o.totalExposures} lifetime exposure(s)) but still costs context budget every session.`});return n.slice(0,oe)}u(ce,"buildRemovalProposals");function le(){let s=y.join(A.homedir(),".config","rulemetric","skills-registry.json");try{let n=q(s,"utf-8"),a=JSON.parse(n),o=new Date(a.generatedAt).getTime();return Number.isNaN(o)?"unknown":Date.now()-o>te*60*60*1e3?"stale":"fresh"}catch{return"unknown"}}u(le,"observeSkillsRegistry");var Re=u(async(s,n)=>{let a=J(),o=a!=="none";o?n.logger.info(`Scoring backend: ${a}`):n.logger.warn("No LLM backend available (claude CLI missing and ANTHROPIC_API_KEY unset); skipping relevance scoring. Removal/trim proposals still run \u2014 they need no LLM.");let i;try{i=(await w("/api/sessions/project-paths?limit="+ee)).projectPaths}catch(e){n.logger.warn(`Failed to fetch project paths: ${e instanceof Error?e.message:String(e)}`);return}if(i.length===0){n.logger.info("No recent project paths; nothing to score");return}let d=new Map;try{let e=await w("/api/projects?limit=200");for(let t of e.projects??[])t.primaryCheckoutPath&&d.set(x(t.primaryCheckoutPath),t.id)}catch(e){n.logger.warn(`Failed to fetch projects for id resolution: ${e instanceof Error?e.message:String(e)}`)}let g=new Map;try{let e=await w(`/api/catalog?limit=200&proposable=1&contentPreview=${O}`);for(let t of e)g.set(t.id,{id:t.id,name:t.name,description:t.description??"",tags:t.tags??[],contentPreview:(t.contentPreview??"").slice(0,O)})}catch(e){n.logger.warn(`Failed to fetch catalog: ${e instanceof Error?e.message:String(e)}`)}try{let e=await w("/api/instructions?limit=100");for(let t of e.instructions??[])g.has(t.id)||g.set(t.id,{id:t.id,name:t.name,description:t.description??"",tags:t.tags??[],contentPreview:(t.content??"").slice(0,O)})}catch(e){n.logger.warn(`Failed to fetch personal instructions: ${e instanceof Error?e.message:String(e)}`)}let m=[],p=[];try{let e=await w("/api/insights/groom-candidates");if(!e.captureHealthy)n.logger.info(`Grooming paused: ${e.reason??"capture unhealthy"}`);else{m=ce(e),p=ae(e);let t=e.safetyGuarded+e.harmfulSafetyGuarded;n.logger.info(`Removal proposals: ${m.length} (${e.harmful.length} measured-harmful, ${e.candidates.length} never-used, ${t} withheld by the safety allowlist); trim proposals: ${p.length} (${(e.bloated??[]).length} measured-neutral and expensive, ${e.trimSafetyFlagged??0} flagged as containing guardrail language)`)}}catch(e){n.logger.warn(`Failed to fetch groom candidates: ${e instanceof Error?e.message:String(e)}`)}let b=[...g.values()];if(b.length===0&&m.length===0&&p.length===0){n.logger.info("No candidate instructions and nothing to retire; nothing to score");return}n.logger.info(`Scoring ${b.length} candidates across ${i.length} project(s)`);let M=0,l=null,I=new Set;for(let e of i)try{let t=x(e);if(!Q(t)){n.logger.info(`Skipping ${t}: not a project directory (home/root)`);continue}let f=D(t),k=o&&f.length>0;f.length===0&&n.logger.info(`${t}: insufficient language signals; removal/trim only`);let v=X(t),z={name:y.basename(t),description:v.description,languages:f,topics:v.topics,dependencies:v.dependencies},E=k?U(b):[];k&&n.logger.info(`Scoring ${b.length} candidates for ${t} in ${E.length} batch(es)`);let C=[],$=0;for(let r of E)try{let c=await B(H(z,r),"",4096);if(!c){$++;continue}let T=c.recommendations??[];for(let P of T)typeof P.instructionId=="string"&&typeof P.score=="number"&&typeof P.reason=="string"&&C.push({instructionId:P.instructionId,score:P.score,reason:P.reason})}catch(c){$++,n.logger.warn(`Batch failed for ${t}: ${c instanceof Error?c.message:String(c)}`)}$>0&&n.logger.warn(`${$}/${E.length} batch(es) failed for ${t} (backend ${a}); suggestions are partial`),k&&C.length===0&&n.logger.warn(`No usable LLM output for ${t} (backend ${a})`);let K=C.filter(r=>r.score>=ne).sort((r,c)=>c.score-r.score).slice(0,Z),_=d.get(t),W=l===null||l===t;l===null&&(l=t);let N=u(r=>r.topProjectId?r.topProjectId===_:W,"placeHere"),F=m.filter(N),{nominated:L,unmeasurable:G}=await ie(F,t,R);L>0&&n.logger.info(`${t}: ${L} removal candidate(s) nominated for randomised withholding instead of the feed`);let h=[...K.map(r=>({instructionId:r.instructionId,score:r.score,reason:r.reason,kind:"add"})),...G.map(({topProjectId:r,...c})=>({...c,kind:"remove"})),...p.filter(N).map(({estimatedTokens:r,topProjectId:c,...T})=>({...T,kind:"trim"}))];if(h.length===0){n.logger.info(`Nothing to suggest for ${t}`);continue}await R("/api/instruction-suggestions/batch-upsert",{projectPath:t,..._?{projectId:_}:{},suggestions:h}),n.logger.info(`${t}: ${h.filter(r=>r.kind==="add").length} add + ${h.filter(r=>r.kind==="remove").length} remove + ${h.filter(r=>r.kind==="trim").length} trim`);for(let r of h)r.kind!=="add"&&I.add(r.instructionId);let Y=new Set(G.map(r=>r.instructionId));for(let r of F)Y.has(r.instructionId)||I.add(r.instructionId);M++}catch(t){n.logger.warn(`Failed to score ${e}: ${t instanceof Error?t.message:String(t)}`)}let j=[...m.filter(e=>!I.has(e.instructionId)),...p.filter(e=>!I.has(e.instructionId)).map(({estimatedTokens:e,...t})=>t)];if(j.length>0&&l)try{let e=new Set(p.map(t=>t.instructionId));await R("/api/instruction-suggestions/batch-upsert",{projectPath:l,...d.get(l)?{projectId:d.get(l)}:{},suggestions:j.map(({topProjectId:t,...f})=>({...f,kind:e.has(f.instructionId)?"trim":"remove"}))}),n.logger.info(`Orphan sweep: ${j.length} proposal(s) whose project was not scored this run placed on ${l}`)}catch(e){n.logger.warn(`Orphan sweep failed: ${e instanceof Error?e.message:String(e)}`)}let S=le();if(S==="unknown")n.logger.warn("Skills registry unreadable or has no usable generatedAt; leaving suggestion staleness unchanged");else try{await R("/api/instruction-suggestions/mark-stale",{stale:S==="stale"}),S==="stale"?n.logger.warn("Skills registry is stale (>48h); marked catalog-skill suggestions stale"):n.logger.info("Skills registry is fresh; cleared staleness on catalog-skill suggestions")}catch{}n.logger.info(`Done: scored ${M}/${i.length} projects`)},"cronSuggestInstructions");export{Q as a,ae as b,ie as c,ce as d,Re as e};
1
+ import{c as X}from"./chunk-HOQPVOMF.js";import{b as D}from"./chunk-GIRPEMTW.js";import{a as x}from"./chunk-MODXEGCU.js";import{d as J,f as B}from"./chunk-QBNLZJIR.js";import{e as w,f as R}from"./chunk-UGACB66X.js";import{c as H,d as U}from"./chunk-WMIUFMDI.js";import{a as u}from"./chunk-ZLLER3HP.js";import{readFileSync as q,realpathSync as V}from"node:fs";import y from"node:path";import A from"node:os";function Q(s){let n=y.resolve(s);if(n===y.resolve(A.homedir()))return!1;let a=y.parse(n).root;if(n===a)return!1;try{let o=V(A.tmpdir());if(V(n)===o)return!1}catch{}return!0}u(Q,"isScorableProjectPath");var Z=5,ee=Number(process.env.RULEMETRIC_MAX_SUGGESTION_PROJECTS??10),te=48,ne=.5,O=400,oe=3,re=.6,se=1;function ae(s){let n=s.bloated??[],a=new Set([...s.harmful.map(o=>o.id),...s.candidates.map(o=>o.id)]);return n.filter(o=>!a.has(o.id)).slice(0,se).map(o=>({instructionId:o.id,estimatedTokens:o.estimatedTokens,topProjectId:o.topProjectId??null,score:.55,reason:`Costs ~${o.estimatedTokens} tokens every session and measures neutral across ${o.exposures} exposed session(s) \u2014 enough data to detect an effect, and none found. Consider shortening "${o.name}" rather than removing it.`+(o.containsSafetyLanguage?" CAUTION: it contains guardrail language (destructive-command or credential rules) \u2014 preserve those lines when shortening.":"")}))}u(ae,"buildTrimProposals");async function ie(s,n,a){let o=[],i=0;for(let d of s)try{await a("/api/instruction-experiments",{instructionId:d.instructionId,projectPath:n,source:"groom"}),i++}catch(g){let m=g instanceof Error?g.message:String(g);o.push({...d,reason:`${d.reason} (not measurable by withholding: ${m})`})}return{nominated:i,unmeasurable:o}}u(ie,"nominateRemovals");function ce(s){let n=[];for(let o of s.harmful){let i=o.verdict.delta;n.push({instructionId:o.id,score:Math.min(.95,.75+Math.abs(i)),topProjectId:o.topProjectId??null,reason:`Measured harmful: sessions using "${o.name}" scored ${(i*100).toFixed(1)}pp worse across ${o.exposures} exposed session(s). Observational \u2014 review before archiving.`})}let a=new Set(s.harmful.map(o=>o.id));for(let o of s.candidates)a.has(o.id)||n.push({instructionId:o.id,score:re,topProjectId:o.topProjectId??null,reason:`Unused: "${o.name}" is ${o.reason} (${o.totalExposures} lifetime exposure(s)) but still costs context budget every session.`});return n.slice(0,oe)}u(ce,"buildRemovalProposals");function le(){let s=y.join(A.homedir(),".config","rulemetric","skills-registry.json");try{let n=q(s,"utf-8"),a=JSON.parse(n),o=new Date(a.generatedAt).getTime();return Number.isNaN(o)?"unknown":Date.now()-o>te*60*60*1e3?"stale":"fresh"}catch{return"unknown"}}u(le,"observeSkillsRegistry");var Re=u(async(s,n)=>{let a=J(),o=a!=="none";o?n.logger.info(`Scoring backend: ${a}`):n.logger.warn("No LLM backend available (claude CLI missing and ANTHROPIC_API_KEY unset); skipping relevance scoring. Removal/trim proposals still run \u2014 they need no LLM.");let i;try{i=(await w("/api/sessions/project-paths?limit="+ee)).projectPaths}catch(e){n.logger.warn(`Failed to fetch project paths: ${e instanceof Error?e.message:String(e)}`);return}if(i.length===0){n.logger.info("No recent project paths; nothing to score");return}let d=new Map;try{let e=await w("/api/projects?limit=200");for(let t of e.projects??[])t.primaryCheckoutPath&&d.set(x(t.primaryCheckoutPath),t.id)}catch(e){n.logger.warn(`Failed to fetch projects for id resolution: ${e instanceof Error?e.message:String(e)}`)}let g=new Map;try{let e=await w(`/api/catalog?limit=200&proposable=1&contentPreview=${O}`);for(let t of e)g.set(t.id,{id:t.id,name:t.name,description:t.description??"",tags:t.tags??[],contentPreview:(t.contentPreview??"").slice(0,O)})}catch(e){n.logger.warn(`Failed to fetch catalog: ${e instanceof Error?e.message:String(e)}`)}try{let e=await w("/api/instructions?limit=100");for(let t of e.instructions??[])g.has(t.id)||g.set(t.id,{id:t.id,name:t.name,description:t.description??"",tags:t.tags??[],contentPreview:(t.content??"").slice(0,O)})}catch(e){n.logger.warn(`Failed to fetch personal instructions: ${e instanceof Error?e.message:String(e)}`)}let m=[],p=[];try{let e=await w("/api/insights/groom-candidates");if(!e.captureHealthy)n.logger.info(`Grooming paused: ${e.reason??"capture unhealthy"}`);else{m=ce(e),p=ae(e);let t=e.safetyGuarded+e.harmfulSafetyGuarded;n.logger.info(`Removal proposals: ${m.length} (${e.harmful.length} measured-harmful, ${e.candidates.length} never-used, ${t} withheld by the safety allowlist); trim proposals: ${p.length} (${(e.bloated??[]).length} measured-neutral and expensive, ${e.trimSafetyFlagged??0} flagged as containing guardrail language)`)}}catch(e){n.logger.warn(`Failed to fetch groom candidates: ${e instanceof Error?e.message:String(e)}`)}let b=[...g.values()];if(b.length===0&&m.length===0&&p.length===0){n.logger.info("No candidate instructions and nothing to retire; nothing to score");return}n.logger.info(`Scoring ${b.length} candidates across ${i.length} project(s)`);let M=0,l=null,I=new Set;for(let e of i)try{let t=x(e);if(!Q(t)){n.logger.info(`Skipping ${t}: not a project directory (home/root)`);continue}let f=D(t),k=o&&f.length>0;f.length===0&&n.logger.info(`${t}: insufficient language signals; removal/trim only`);let v=X(t),z={name:y.basename(t),description:v.description,languages:f,topics:v.topics,dependencies:v.dependencies},E=k?U(b):[];k&&n.logger.info(`Scoring ${b.length} candidates for ${t} in ${E.length} batch(es)`);let C=[],$=0;for(let r of E)try{let c=await B(H(z,r),"",4096);if(!c){$++;continue}let T=c.recommendations??[];for(let P of T)typeof P.instructionId=="string"&&typeof P.score=="number"&&typeof P.reason=="string"&&C.push({instructionId:P.instructionId,score:P.score,reason:P.reason})}catch(c){$++,n.logger.warn(`Batch failed for ${t}: ${c instanceof Error?c.message:String(c)}`)}$>0&&n.logger.warn(`${$}/${E.length} batch(es) failed for ${t} (backend ${a}); suggestions are partial`),k&&C.length===0&&n.logger.warn(`No usable LLM output for ${t} (backend ${a})`);let K=C.filter(r=>r.score>=ne).sort((r,c)=>c.score-r.score).slice(0,Z),_=d.get(t),W=l===null||l===t;l===null&&(l=t);let N=u(r=>r.topProjectId?r.topProjectId===_:W,"placeHere"),F=m.filter(N),{nominated:L,unmeasurable:G}=await ie(F,t,R);L>0&&n.logger.info(`${t}: ${L} removal candidate(s) nominated for randomised withholding instead of the feed`);let h=[...K.map(r=>({instructionId:r.instructionId,score:r.score,reason:r.reason,kind:"add"})),...G.map(({topProjectId:r,...c})=>({...c,kind:"remove"})),...p.filter(N).map(({estimatedTokens:r,topProjectId:c,...T})=>({...T,kind:"trim"}))];if(h.length===0){n.logger.info(`Nothing to suggest for ${t}`);continue}await R("/api/instruction-suggestions/batch-upsert",{projectPath:t,..._?{projectId:_}:{},suggestions:h}),n.logger.info(`${t}: ${h.filter(r=>r.kind==="add").length} add + ${h.filter(r=>r.kind==="remove").length} remove + ${h.filter(r=>r.kind==="trim").length} trim`);for(let r of h)r.kind!=="add"&&I.add(r.instructionId);let Y=new Set(G.map(r=>r.instructionId));for(let r of F)Y.has(r.instructionId)||I.add(r.instructionId);M++}catch(t){n.logger.warn(`Failed to score ${e}: ${t instanceof Error?t.message:String(t)}`)}let j=[...m.filter(e=>!I.has(e.instructionId)),...p.filter(e=>!I.has(e.instructionId)).map(({estimatedTokens:e,...t})=>t)];if(j.length>0&&l)try{let e=new Set(p.map(t=>t.instructionId));await R("/api/instruction-suggestions/batch-upsert",{projectPath:l,...d.get(l)?{projectId:d.get(l)}:{},suggestions:j.map(({topProjectId:t,...f})=>({...f,kind:e.has(f.instructionId)?"trim":"remove"}))}),n.logger.info(`Orphan sweep: ${j.length} proposal(s) whose project was not scored this run placed on ${l}`)}catch(e){n.logger.warn(`Orphan sweep failed: ${e instanceof Error?e.message:String(e)}`)}let S=le();if(S==="unknown")n.logger.warn("Skills registry unreadable or has no usable generatedAt; leaving suggestion staleness unchanged");else try{await R("/api/instruction-suggestions/mark-stale",{stale:S==="stale"}),S==="stale"?n.logger.warn("Skills registry is stale (>48h); marked catalog-skill suggestions stale"):n.logger.info("Skills registry is fresh; cleared staleness on catalog-skill suggestions")}catch{}n.logger.info(`Done: scored ${M}/${i.length} projects`)},"cronSuggestInstructions");export{Q as a,ae as b,ie as c,ce as d,Re as e};
@@ -1,2 +1,2 @@
1
- import{a as v,b as u,e as y,g as d}from"../../chunk-VTUTSUFW.js";import{a as h}from"../../chunk-65TQMBNF.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-6PUH7HEL.js";import"../../chunk-WRQEHXSN.js";import"../../chunk-YTPQ7VBO.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-2AVGUZ2P.js";import"../../chunk-OOGTQOL3.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-EZHL527S.js";import{a as h}from"../../chunk-DSJNZWCZ.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-OOFGV7EX.js";import"../../chunk-VYZKKSX4.js";import"../../chunk-YSLKV4XC.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-UGACB66X.js";import"../../chunk-WMIUFMDI.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-65TQMBNF.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-6PUH7HEL.js";import"../../chunk-WRQEHXSN.js";import"../../chunk-YTPQ7VBO.js";import"../../chunk-3AV3GTMP.js";import{f as r}from"../../chunk-2AVGUZ2P.js";import"../../chunk-OOGTQOL3.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-DSJNZWCZ.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-OOFGV7EX.js";import"../../chunk-VYZKKSX4.js";import"../../chunk-YSLKV4XC.js";import"../../chunk-3AV3GTMP.js";import{f as r}from"../../chunk-UGACB66X.js";import"../../chunk-WMIUFMDI.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-LW3UE2FY.js";import{a as w}from"../../chunk-65TQMBNF.js";import"../../chunk-IZTIYR5Q.js";import{c}from"../../chunk-6PUH7HEL.js";import"../../chunk-WRQEHXSN.js";import{b as n}from"../../chunk-YTPQ7VBO.js";import"../../chunk-3AV3GTMP.js";import{b as r,d as a}from"../../chunk-2AVGUZ2P.js";import"../../chunk-OOGTQOL3.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-G3HODHFN.js";import{a as w}from"../../chunk-DSJNZWCZ.js";import"../../chunk-IZTIYR5Q.js";import{c}from"../../chunk-OOFGV7EX.js";import"../../chunk-VYZKKSX4.js";import{b as n}from"../../chunk-YSLKV4XC.js";import"../../chunk-3AV3GTMP.js";import{b as r,d as a}from"../../chunk-UGACB66X.js";import"../../chunk-WMIUFMDI.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-65TQMBNF.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-6PUH7HEL.js";import"../../chunk-WRQEHXSN.js";import"../../chunk-YTPQ7VBO.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-2AVGUZ2P.js";import"../../chunk-OOGTQOL3.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-DSJNZWCZ.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-OOFGV7EX.js";import"../../chunk-VYZKKSX4.js";import"../../chunk-YSLKV4XC.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-UGACB66X.js";import"../../chunk-WMIUFMDI.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};