@rulemetric/cli 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (328) hide show
  1. package/dist/base-command.js +1 -1
  2. package/dist/{chunk-UE76F2NQ.js → chunk-2WQUOC6S.js} +20 -20
  3. package/dist/{chunk-DUBBL57L.js → chunk-5XEGRU2R.js} +1 -1
  4. package/dist/chunk-74QIUVWY.js +1 -0
  5. package/dist/chunk-7ML2UCI7.js +1 -0
  6. package/dist/chunk-AHLVY52I.js +1 -0
  7. package/dist/{chunk-O2HCD6XL.js → chunk-AT2MMCOJ.js} +1 -1
  8. package/dist/{chunk-GJBS6QYC.js → chunk-AXJAGWZB.js} +1 -1
  9. package/dist/{chunk-UYPBIXF2.js → chunk-BVOXWAJO.js} +1 -1
  10. package/dist/chunk-CT7FWSIU.js +3 -0
  11. package/dist/{chunk-KV5A77XW.js → chunk-DDYGA2DS.js} +1 -1
  12. package/dist/{chunk-5XK6LB2T.js → chunk-E5YE25QG.js} +1 -1
  13. package/dist/chunk-E7GQJML3.js +1 -0
  14. package/dist/{chunk-RK663O4M.js → chunk-E7RH43OS.js} +6 -6
  15. package/dist/{chunk-2EX27VJ3.js → chunk-ET7753IY.js} +1 -1
  16. package/dist/{chunk-25Q3Y7TC.js → chunk-EWGE7YTQ.js} +1 -1
  17. package/dist/{chunk-WOJ733IB.js → chunk-EXVXKJ7Y.js} +1 -1
  18. package/dist/chunk-FCTFHY3X.js +13 -0
  19. package/dist/{chunk-RJX75Y7J.js → chunk-FJX7WDPG.js} +1 -1
  20. package/dist/{chunk-3UPHCQWI.js → chunk-FK55FXKQ.js} +1 -1
  21. package/dist/chunk-GH4EZK2O.js +1 -0
  22. package/dist/chunk-GN46S7T4.js +9 -0
  23. package/dist/{chunk-BG55WDDX.js → chunk-GQGGFHX7.js} +1 -1
  24. package/dist/chunk-GYNZ3OZF.js +1 -0
  25. package/dist/{chunk-WJZY5Y22.js → chunk-H4LUPIHJ.js} +1 -1
  26. package/dist/{chunk-25RDT32M.js → chunk-HAYO6JYI.js} +1 -1
  27. package/dist/{chunk-YI2OWO6R.js → chunk-HFSISGCJ.js} +1 -1
  28. package/dist/chunk-HRJDKAJ4.js +1 -0
  29. package/dist/chunk-IC6VZHE6.js +1 -0
  30. package/dist/chunk-INAZLRY5.js +1 -0
  31. package/dist/{chunk-VXUKXGRX.js → chunk-IOX4VJPR.js} +2 -2
  32. package/dist/chunk-J4W6GNCF.js +2 -0
  33. package/dist/{chunk-VH2EAP4J.js → chunk-J7UZXRTH.js} +1 -1
  34. package/dist/{chunk-6GAIYJ6K.js → chunk-JKWB6UXA.js} +1 -1
  35. package/dist/{chunk-JWFRI32Y.js → chunk-JLBQKV4V.js} +1 -1
  36. package/dist/{chunk-VIQ25ORK.js → chunk-JRAXWASH.js} +1 -1
  37. package/dist/{chunk-PVGUDJD7.js → chunk-JRWQJZYQ.js} +1 -1
  38. package/dist/{chunk-6ZPSVZNH.js → chunk-LDUJWJ6A.js} +1 -1
  39. package/dist/chunk-LMCICVE7.js +12 -0
  40. package/dist/chunk-MHVHGKDK.js +3 -0
  41. package/dist/chunk-MMM4B3KH.js +1 -0
  42. package/dist/{chunk-CYYDQFRY.js → chunk-MX34N7Y5.js} +1 -1
  43. package/dist/{chunk-7AWFSFR7.js → chunk-N26UEHI3.js} +1 -1
  44. package/dist/{chunk-ZGW3N3A6.js → chunk-N4RJ6CN7.js} +1 -1
  45. package/dist/{chunk-J6QMBMC2.js → chunk-N7SZWKCU.js} +1 -1
  46. package/dist/{chunk-QFKUSNUB.js → chunk-NRYVMGJN.js} +1 -1
  47. package/dist/{chunk-4COLIGD7.js → chunk-NSPDDSRR.js} +1 -1
  48. package/dist/{chunk-GBWQENAH.js → chunk-O62OLKQL.js} +1 -1
  49. package/dist/{chunk-WY3VVX3R.js → chunk-OLJF4K7L.js} +1 -1
  50. package/dist/{chunk-6W2GSV4O.js → chunk-OMRH4JXS.js} +1 -1
  51. package/dist/{chunk-WH3IPXXQ.js → chunk-OO2ZRKZY.js} +5 -5
  52. package/dist/chunk-OUK2AWEI.js +1 -0
  53. package/dist/chunk-OYAOLJUH.js +1 -0
  54. package/dist/chunk-PPAHIVG5.js +1 -0
  55. package/dist/{chunk-3MDEGOUG.js → chunk-PPIZMPNI.js} +1 -1
  56. package/dist/chunk-PUX6P5KC.js +2 -0
  57. package/dist/chunk-QI3FJKGK.js +1 -0
  58. package/dist/chunk-RRM4HQG4.js +1 -0
  59. package/dist/{chunk-QTCWOIT4.js → chunk-S5CQSP35.js} +1 -1
  60. package/dist/chunk-S5U76YUI.js +1 -0
  61. package/dist/chunk-SE3UKA3M.js +25 -0
  62. package/dist/{chunk-BZS5QRWB.js → chunk-SG4UDDHB.js} +1 -1
  63. package/dist/chunk-SPJ73X7A.js +4 -0
  64. package/dist/chunk-SV73ASP2.js +1 -0
  65. package/dist/chunk-SWSOEYC7.js +1 -0
  66. package/dist/{chunk-I3M5VBLT.js → chunk-TTSDPDRH.js} +1 -1
  67. package/dist/chunk-TWPG3TEQ.js +48 -0
  68. package/dist/{chunk-WQX4RRBQ.js → chunk-U7BPWFOP.js} +1 -1
  69. package/dist/{chunk-NBEZ5FAU.js → chunk-UFQ43KXE.js} +1 -1
  70. package/dist/chunk-UJ7EPLKC.js +1 -0
  71. package/dist/{chunk-V2USQH27.js → chunk-UQDOOQCM.js} +1 -1
  72. package/dist/{chunk-M2VVRQKA.js → chunk-V4PUYPTU.js} +1 -1
  73. package/dist/{chunk-SHYP27B7.js → chunk-VALRPZXH.js} +1 -1
  74. package/dist/{chunk-LTQ5BJYL.js → chunk-VLWNSTYW.js} +1 -1
  75. package/dist/chunk-WSWZPNLG.js +1 -0
  76. package/dist/{chunk-MNQPCNGQ.js → chunk-XAOLOR4Q.js} +1 -1
  77. package/dist/{chunk-6QLZT7EP.js → chunk-XAXEZI6Z.js} +1 -1
  78. package/dist/{chunk-Y7QIOPN5.js → chunk-XFLKW6SJ.js} +1 -1
  79. package/dist/chunk-YNLHJHUP.js +1 -0
  80. package/dist/{chunk-U7TBEC3I.js → chunk-YP2CBUXH.js} +1 -1
  81. package/dist/{chunk-P2WSDHIA.js → chunk-YUIRDBQQ.js} +1 -1
  82. package/dist/{chunk-4N43IBXH.js → chunk-ZA6NXNPR.js} +1 -1
  83. package/dist/{chunk-APDRR6FS.js → chunk-ZZHIBOMT.js} +1 -1
  84. package/dist/commands/antigravity/backfill.js +1 -1
  85. package/dist/commands/auth/create-key.js +1 -1
  86. package/dist/commands/auth/login.js +1 -1
  87. package/dist/commands/auth/logout.js +1 -1
  88. package/dist/commands/auth/revoke-key.js +1 -1
  89. package/dist/commands/auth/signup.js +1 -1
  90. package/dist/commands/auth/status.js +1 -1
  91. package/dist/commands/capture/scope.js +1 -1
  92. package/dist/commands/catalog/index.js +1 -1
  93. package/dist/commands/catalog/recommend.js +1 -1
  94. package/dist/commands/crons/list.js +1 -1
  95. package/dist/commands/crons/run.js +2 -2
  96. package/dist/commands/dashboard.js +1 -1
  97. package/dist/commands/diagnostics.js +1 -1
  98. package/dist/commands/eval-targets/create.js +1 -1
  99. package/dist/commands/eval-targets/list.js +1 -1
  100. package/dist/commands/evals/agent.js +3 -3
  101. package/dist/commands/evals/auto-run.js +1 -1
  102. package/dist/commands/evals/benchmark.js +1 -1
  103. package/dist/commands/evals/compare.js +1 -1
  104. package/dist/commands/evals/create.js +1 -1
  105. package/dist/commands/evals/optimize-description.js +1 -1
  106. package/dist/commands/evals/optimize.js +1 -1
  107. package/dist/commands/evals/refine-cases.js +1 -1
  108. package/dist/commands/evals/run.js +1 -1
  109. package/dist/commands/evals/validate-judge.js +1 -1
  110. package/dist/commands/experiments/list.js +1 -1
  111. package/dist/commands/gateway/ensure.js +1 -1
  112. package/dist/commands/hooks/emit-instructions.js +1 -1
  113. package/dist/commands/hooks/install.js +1 -1
  114. package/dist/commands/hooks/run.js +1 -1
  115. package/dist/commands/hooks/uninstall.js +1 -1
  116. package/dist/commands/instructions/create.js +1 -1
  117. package/dist/commands/instructions/dedupe.js +1 -1
  118. package/dist/commands/instructions/delete.js +1 -1
  119. package/dist/commands/instructions/fork.js +1 -1
  120. package/dist/commands/instructions/get.js +1 -1
  121. package/dist/commands/instructions/list.js +1 -1
  122. package/dist/commands/instructions/promote.js +1 -1
  123. package/dist/commands/instructions/pull.js +1 -1
  124. package/dist/commands/instructions/restore.js +1 -1
  125. package/dist/commands/instructions/retract.js +1 -1
  126. package/dist/commands/instructions/upstream.js +1 -1
  127. package/dist/commands/instructions/versions.js +1 -1
  128. package/dist/commands/launcher.js +1 -1
  129. package/dist/commands/local/down.js +1 -1
  130. package/dist/commands/local/up.js +1 -1
  131. package/dist/commands/org/current.js +1 -1
  132. package/dist/commands/org/list.js +1 -1
  133. package/dist/commands/org/switch.js +1 -1
  134. package/dist/commands/packs/add-instruction.js +1 -1
  135. package/dist/commands/packs/apply.js +1 -1
  136. package/dist/commands/packs/create.js +1 -1
  137. package/dist/commands/packs/fork.js +1 -1
  138. package/dist/commands/packs/get.js +1 -1
  139. package/dist/commands/packs/list.js +1 -1
  140. package/dist/commands/packs/remove-instruction.js +1 -1
  141. package/dist/commands/proxy/env.js +1 -1
  142. package/dist/commands/proxy/logs.js +1 -1
  143. package/dist/commands/proxy/restart.js +1 -1
  144. package/dist/commands/proxy/setup.js +1 -1
  145. package/dist/commands/proxy/start.js +1 -1
  146. package/dist/commands/proxy/status.js +1 -1
  147. package/dist/commands/proxy/stop.js +1 -1
  148. package/dist/commands/research/backfill.js +1 -1
  149. package/dist/commands/research/tail-transcript.js +1 -1
  150. package/dist/commands/service/install.js +18 -18
  151. package/dist/commands/service/status.js +1 -1
  152. package/dist/commands/service/uninstall.js +1 -1
  153. package/dist/commands/sessions/analyze.js +1 -1
  154. package/dist/commands/sessions/delete.js +1 -1
  155. package/dist/commands/sessions/end.js +1 -1
  156. package/dist/commands/sessions/import.js +1 -1
  157. package/dist/commands/sessions/list.js +1 -1
  158. package/dist/commands/sessions/start.js +1 -1
  159. package/dist/commands/setup.js +1 -1
  160. package/dist/commands/skills/export-approved.js +1 -1
  161. package/dist/commands/skills/install.js +1 -1
  162. package/dist/commands/skills/list.js +1 -1
  163. package/dist/commands/skills/publish.js +1 -1
  164. package/dist/commands/skills/search.js +1 -1
  165. package/dist/commands/skills/update.js +1 -1
  166. package/dist/commands/suggestions/accept.js +1 -1
  167. package/dist/commands/suggestions/auto.js +1 -1
  168. package/dist/commands/suggestions/dismiss.js +1 -1
  169. package/dist/commands/suggestions/list.js +1 -1
  170. package/dist/commands/suggestions/refresh.js +1 -1
  171. package/dist/commands/suggestions/undo.js +1 -1
  172. package/dist/dashboard/Dashboard.js +1 -1
  173. package/dist/dashboard/data.js +1 -1
  174. package/dist/dashboard/launcher/LauncherOverlay.js +1 -1
  175. package/dist/dashboard/launcher/api.js +1 -1
  176. package/dist/dashboard/launcher/useLaunchJobs.js +1 -1
  177. package/dist/dist-NHS7HY5Q.js +1 -0
  178. package/dist/harbor/cost_delta.py +377 -0
  179. package/dist/harbor/mcp_container_shell.py +156 -0
  180. package/dist/harbor/provenance.py +361 -0
  181. package/dist/harbor/rm-batch-task/environment/Dockerfile +6 -0
  182. package/dist/harbor/rm-batch-task/environment/items.jsonl +60 -0
  183. package/dist/harbor/rm-batch-task/inject.md +8 -0
  184. package/dist/harbor/rm-batch-task/instruction.md +8 -0
  185. package/dist/harbor/rm-batch-task/solution/solve.sh +68 -0
  186. package/dist/harbor/rm-batch-task/task.toml +30 -0
  187. package/dist/harbor/rm-batch-task/tests/test.sh +23 -0
  188. package/dist/harbor/rm-batch-task/tests/test_outputs.py +32 -0
  189. package/dist/harbor/rm-locality-task/environment/Dockerfile +8 -0
  190. package/dist/harbor/rm-locality-task/environment/workspace/deploy/prod/ingest.yaml +3 -0
  191. package/dist/harbor/rm-locality-task/environment/workspace/deploy/staging/ingest.yaml +3 -0
  192. package/dist/harbor/rm-locality-task/environment/workspace/docs/architecture/ingest.md +6 -0
  193. package/dist/harbor/rm-locality-task/environment/workspace/legacy/ingest_v1/config.yaml +2 -0
  194. package/dist/harbor/rm-locality-task/environment/workspace/packages/shared/defaults.py +4 -0
  195. package/dist/harbor/rm-locality-task/environment/workspace/services/ingest/config/limits.defaults.yaml +4 -0
  196. package/dist/harbor/rm-locality-task/environment/workspace/services/ingest/config/limits.yaml +3 -0
  197. package/dist/harbor/rm-locality-task/environment/workspace/services/ingest/loader.py +15 -0
  198. package/dist/harbor/rm-locality-task/environment/workspace/tests/fixtures/ingest_config.yaml +3 -0
  199. package/dist/harbor/rm-locality-task/inject.md +12 -0
  200. package/dist/harbor/rm-locality-task/instruction.md +4 -0
  201. package/dist/harbor/rm-locality-task/solution/solve.sh +14 -0
  202. package/dist/harbor/rm-locality-task/task.toml +30 -0
  203. package/dist/harbor/rm-locality-task/tests/test.sh +23 -0
  204. package/dist/harbor/rm-locality-task/tests/test_outputs.py +19 -0
  205. package/dist/harbor/rm-migrations-task/environment/Dockerfile +7 -0
  206. package/dist/harbor/rm-migrations-task/environment/applied.txt +2 -0
  207. package/dist/harbor/rm-migrations-task/environment/migrations/00001_init.sql +1 -0
  208. package/dist/harbor/rm-migrations-task/environment/migrations/00002_add_email.sql +1 -0
  209. package/dist/harbor/rm-migrations-task/inject.md +7 -0
  210. package/dist/harbor/rm-migrations-task/instruction.md +8 -0
  211. package/dist/harbor/rm-migrations-task/solution/solve.sh +8 -0
  212. package/dist/harbor/rm-migrations-task/task.toml +30 -0
  213. package/dist/harbor/rm-migrations-task/tests/test.sh +23 -0
  214. package/dist/harbor/rm-migrations-task/tests/test_outputs.py +36 -0
  215. package/dist/harbor/rm-pagination-task/environment/Dockerfile +6 -0
  216. package/dist/harbor/rm-pagination-task/environment/store.py +29 -0
  217. package/dist/harbor/rm-pagination-task/inject.md +8 -0
  218. package/dist/harbor/rm-pagination-task/instruction.md +5 -0
  219. package/dist/harbor/rm-pagination-task/solution/solve.sh +7 -0
  220. package/dist/harbor/rm-pagination-task/task.toml +30 -0
  221. package/dist/harbor/rm-pagination-task/tests/test.sh +23 -0
  222. package/dist/harbor/rm-pagination-task/tests/test_outputs.py +14 -0
  223. package/dist/harbor/rm_host_claude.py +264 -0
  224. package/dist/harbor/rm_host_codex.py +208 -0
  225. package/dist/harbor/run.sh +268 -0
  226. package/dist/harbor/summarize.py +248 -0
  227. package/dist/lib/active-org-refresh.js +1 -1
  228. package/dist/lib/agent-loop.js +1 -1
  229. package/dist/lib/antigravity-transcript.js +1 -1
  230. package/dist/lib/api-client.js +1 -1
  231. package/dist/lib/capture-scope-config.js +1 -1
  232. package/dist/lib/codex-capture-scope.js +1 -1
  233. package/dist/lib/codex-exec.js +1 -1
  234. package/dist/lib/ensure-api-key.js +1 -1
  235. package/dist/lib/ensure-fresh-token.js +1 -1
  236. package/dist/lib/eval-accumulation.js +1 -0
  237. package/dist/lib/eval-analyzer.js +1 -1
  238. package/dist/lib/eval-benchmark.js +1 -1
  239. package/dist/lib/eval-candidate-run.js +1 -1
  240. package/dist/lib/eval-case-generator.js +1 -1
  241. package/dist/lib/eval-conversation-handler.js +1 -1
  242. package/dist/lib/eval-executor.js +1 -1
  243. package/dist/lib/eval-grader.js +1 -1
  244. package/dist/lib/eval-meta-judge.js +1 -1
  245. package/dist/lib/eval-resume.js +1 -1
  246. package/dist/lib/eval-run-batch.js +1 -1
  247. package/dist/lib/eval-trigger-tester.js +1 -1
  248. package/dist/lib/evolution-enrolment.js +1 -1
  249. package/dist/lib/harbor-readiness.js +1 -1
  250. package/dist/lib/hooks-capture-gate.js +1 -1
  251. package/dist/lib/insights/generation/installed-asks.js +1 -1
  252. package/dist/lib/insights/nomination/nominate.js +1 -1
  253. package/dist/lib/instruction-proposer.js +1 -1
  254. package/dist/lib/instruction-snapshot.js +1 -1
  255. package/dist/lib/instructions/acceptance/accept-events.js +1 -1
  256. package/dist/lib/instructions/acceptance/accept-hook.js +1 -1
  257. package/dist/lib/instructions/acceptance/agent-instruction-files.js +1 -1
  258. package/dist/lib/instructions/acceptance/hook-install.js +1 -1
  259. package/dist/lib/instructions/acceptance/reverse-applications.js +1 -1
  260. package/dist/lib/instructions/acceptance/suggestion-accept.js +1 -1
  261. package/dist/lib/jobs/handlers/cron-auto-accept-suggestions.js +1 -1
  262. package/dist/lib/jobs/handlers/cron-eval-autorun.js +1 -1
  263. package/dist/lib/jobs/handlers/cron-instruction-evolution.js +1 -1
  264. package/dist/lib/jobs/handlers/cron-instruction-training.js +1 -1
  265. package/dist/lib/jobs/handlers/cron-reconcile-attribution.js +1 -1
  266. package/dist/lib/jobs/handlers/cron-refine-cases.js +1 -1
  267. package/dist/lib/jobs/handlers/cron-refresh-pricing.js +1 -1
  268. package/dist/lib/jobs/handlers/cron-retire-unused-skills.js +1 -1
  269. package/dist/lib/jobs/handlers/cron-suggest-instructions.js +1 -1
  270. package/dist/lib/jobs/handlers/distill-memories.js +1 -1
  271. package/dist/lib/jobs/handlers/harbor-ab-verdict.js +1 -1
  272. package/dist/lib/jobs/handlers/harbor-ab.js +1 -1
  273. package/dist/lib/jobs/handlers/process-changelog.js +1 -1
  274. package/dist/lib/jobs/handlers/process-conversation.js +1 -1
  275. package/dist/lib/jobs/handlers/process-eval.js +1 -1
  276. package/dist/lib/jobs/handlers/process-insights.js +1 -1
  277. package/dist/lib/jobs/handlers/process-judge-review.js +1 -1
  278. package/dist/lib/jobs/handlers/process-launch.js +1 -1
  279. package/dist/lib/jobs/handlers/process-memory-ab.js +1 -1
  280. package/dist/lib/jobs/handlers/process-run-cleanup.js +1 -1
  281. package/dist/lib/jobs/handlers/process-session-goal.js +1 -1
  282. package/dist/lib/jobs/shed-retry.js +1 -1
  283. package/dist/lib/judge-review-runner.js +1 -1
  284. package/dist/lib/llm-client.js +1 -1
  285. package/dist/lib/llm-reply-parsers.js +1 -0
  286. package/dist/lib/manual-tasks.js +1 -1
  287. package/dist/lib/measurement-llm.js +1 -0
  288. package/dist/lib/pi-exec.js +1 -0
  289. package/dist/lib/projects/workspace/eval-workspace.js +1 -1
  290. package/dist/lib/projects/workspace/worktree.js +1 -1
  291. package/dist/lib/refine-cases.js +1 -1
  292. package/dist/lib/research-client.js +1 -1
  293. package/dist/lib/retraction.js +1 -1
  294. package/dist/lib/service-environment.js +1 -0
  295. package/dist/lib/setup-steps.js +1 -1
  296. package/dist/lib/telemetry.js +1 -1
  297. package/dist/lib/terminal-target-heartbeat.js +1 -1
  298. package/dist/lib/tool-cli-map.js +1 -0
  299. package/dist/lib/transcript-instruction-linking.js +1 -1
  300. package/dist/lib/transcript-sync.js +1 -1
  301. package/dist/lib/work-report.js +1 -1
  302. package/oclif.manifest.json +7 -1
  303. package/package.json +5 -4
  304. package/dist/chunk-4FSQSETR.js +0 -12
  305. package/dist/chunk-6WQG6C7F.js +0 -1
  306. package/dist/chunk-C42NTI2V.js +0 -3
  307. package/dist/chunk-F6DAHCJC.js +0 -20
  308. package/dist/chunk-GN3ZHQ46.js +0 -1
  309. package/dist/chunk-H3BCWSYO.js +0 -1
  310. package/dist/chunk-HLNHBZLI.js +0 -1
  311. package/dist/chunk-HLQZR4XJ.js +0 -13
  312. package/dist/chunk-J5HW45PZ.js +0 -48
  313. package/dist/chunk-JNFB22FD.js +0 -1
  314. package/dist/chunk-KCOJLTVX.js +0 -1
  315. package/dist/chunk-MLV2RHRE.js +0 -1
  316. package/dist/chunk-N7GK33PU.js +0 -1
  317. package/dist/chunk-NRYLYMDM.js +0 -1
  318. package/dist/chunk-OZNKMJ5B.js +0 -1
  319. package/dist/chunk-PPXOC7IV.js +0 -1
  320. package/dist/chunk-QXPYGN7I.js +0 -1
  321. package/dist/chunk-R4QIPG4V.js +0 -2
  322. package/dist/chunk-RGUCR7T6.js +0 -1
  323. package/dist/chunk-RO3ZZVCG.js +0 -1
  324. package/dist/chunk-SN3CHV66.js +0 -1
  325. package/dist/chunk-U3XKXJ3A.js +0 -5
  326. package/dist/chunk-UM4CBCXI.js +0 -1
  327. package/dist/chunk-WHQ4BDSM.js +0 -4
  328. package/dist/dist-45KJH5M7.js +0 -1
@@ -0,0 +1 @@
1
+ import{b as S,c as B,f as s,g as I,i as w}from"./chunk-NRYVMGJN.js";import{c as ne}from"./chunk-ZA6NXNPR.js";import{b as re}from"./chunk-IEQDLURA.js";import{d as te,e as oe,f as se}from"./chunk-KINIFUZQ.js";import{a as $}from"./chunk-FCTFHY3X.js";import{a as q}from"./chunk-JRAXWASH.js";import{b as J}from"./chunk-LDUJWJ6A.js";import{a as K}from"./chunk-WSWZPNLG.js";import{a as Y}from"./chunk-OLJF4K7L.js";import{a as O}from"./chunk-ZYGBABMZ.js";import{a as U}from"./chunk-YP2CBUXH.js";import{a as ee}from"./chunk-U7BPWFOP.js";import{e as P}from"./chunk-XFLKW6SJ.js";import{b as G}from"./chunk-5XEGRU2R.js";import{c as N}from"./chunk-SPJ73X7A.js";import{a as F}from"./chunk-PPIZMPNI.js";import{a as W}from"./chunk-IC6VZHE6.js";import{b as V}from"./chunk-5RBLIVBF.js";import{a as z}from"./chunk-EXVXKJ7Y.js";import{a as X}from"./chunk-INAZLRY5.js";import{a as Z}from"./chunk-OMRH4JXS.js";import{a as x}from"./chunk-JLBQKV4V.js";import{a as j}from"./chunk-EWGE7YTQ.js";import{a as Q}from"./chunk-XAOLOR4Q.js";import{a as D}from"./chunk-PZS55PW2.js";import{b as C}from"./chunk-YNLHJHUP.js";import{k as L}from"./chunk-S5U76YUI.js";import{d as R}from"./chunk-SBGXIPRN.js";import{b as M,e as T,f as y}from"./chunk-ZZHIBOMT.js";import{a as i}from"./chunk-ZLLER3HP.js";var H=null,h=null,ce={process_eval:W,process_insights:$,process_launch:J,process_send_message:O,process_conversation:F,process_session_goal:U,distill_memories:G,memory_ab:K,process_run_cleanup:Y,cron_refine_cases:j,cron_retire_unused_skills:ee,cron_reconcile_attribution:x,cron_suggest_instructions:P,cron_refresh_skills:D,cron_refresh_pricing:Q,cron_eval_autorun:X,cron_auto_accept_suggestions:z,cron_instruction_training:Z,cron_instruction_evolution:L,process_judge_review:q,harbor_ab:N},ae=Object.keys(ce),me=new Set([]);function pe(e=process.env){return e.DATABASE_URL?ae:ae.filter(t=>!me.has(t))}i(pe,"availableCapabilities");var ge=3e4,_e=3e4,fe=3e4,ie=500,le=1e4,ve=`thin-agent-${process.pid}`,A=null;function ke(e,t,r,p){let d;try{let l=R();d={claude:l.claudeBin!=null,codex:l.codexBin!=null,codexModel:l.codexConfiguredModel}}catch{}let m;try{m=C()}catch{}let g=i(l=>y("/api/workers/heartbeat",{workerType:"cli-worker",clientName:ve,clientVersion:p,workerVersion:"0.1.0",currentJobId:null,inFlightCount:0,lastError:null,status:l,metadata:{capabilities:e,mode:"thin-agent",measurementProtocol:1,llmEngines:d,harborReady:m,machine:H?.summary()}}).then(c=>{let u=c?.advisory;u&&u.message!==A?(A=u.message,s(r,{event:"worker_advisory",code:u.code,message:u.message})):u||(A=null)}).catch(c=>{s(r,{event:"presence_heartbeat_error",error:c instanceof Error?c.message:String(c)})}),"send");g("alive");let f=setInterval(()=>g("alive"),fe),a=null,n=i(()=>a||(clearInterval(f),a=Promise.race([g("shutting_down"),new Promise(l=>setTimeout(l,2e3).unref())]),a),"sayGoodbye");return t.addEventListener("abort",()=>{n()},{once:!0}),{shutdown:n}}i(ke,"startPresenceHeartbeat");async function be(e,t,r=R()){let p=[...r.claudeBin?["claude"]:[],...r.codexBin?["codex"]:[]],d=`capabilities=${encodeURIComponent(e.join(","))}&waitMs=${t}&measurementProtocol=1&measurementEngines=${encodeURIComponent(p.join(","))}`,m=await T(`/api/work/next?${d}`);return m==null||typeof m=="string"?null:m}i(be,"pollForWork");function we(e,t){return{logger:{info:i(r=>t(r),"info"),warn:i(r=>t(r),"warn"),error:i(r=>t(r),"error")},job:{attempts:e}}}i(we,"makeHelpers");async function he(e,t,r,p){let d=ce[e.kind],m=Date.now();if(s(r,{event:"claim",jobId:e.id,kind:e.kind,attempts:e.attempts}),!d){let n=`unknown kind: ${e.kind}`;s(r,{event:"fail",jobId:e.id,kind:e.kind,terminal:!0,error:n}),await y(`/api/work/${e.id}/fail`,{leaseToken:e.leaseToken,error:n,terminal:!0}).catch(()=>{});return}let g=i(()=>{s(r,{event:"heartbeat",jobId:e.id}),w(`/api/work/${e.id}/heartbeat`,{leaseToken:e.leaseToken},{budgetMs:Math.min(B,Math.max(0,t-1e3)),signal:p,log:r,event:"heartbeat",jobId:e.id}).then(n=>{n.ok||s(r,{event:"heartbeat_error",jobId:e.id,attempts:n.attempts,error:n.error instanceof Error?n.error.message:String(n.error)})})},"beat"),f=setInterval(g,t);h={jobId:e.id,beat:g};let a;try{let n=we(e.attempts,r);a={kind:"complete",result:await d(e.payload,n)??{}}}catch(n){let l=H?.pausesSince(m)??[],c=se(l),u=n instanceof Error?n.message:String(n),v=V(n),o=!v&&oe(l);a={kind:"fail",message:c?`${c}; ${u}`:u,pausedDuringJob:!!c,terminal:v,hostSuspended:o}}try{if(a.kind==="complete"){s(r,{event:"complete",jobId:e.id,kind:e.kind,durationMs:Date.now()-m});let n=await w(`/api/work/${e.id}/complete`,{leaseToken:e.leaseToken,result:a.result},{budgetMs:S,signal:p,log:r,event:"complete_post",jobId:e.id});n.ok||s(r,{event:"complete_post_error",jobId:e.id,kind:e.kind,attempts:n.attempts,error:n.error instanceof Error?n.error.message:String(n.error)})}else{s(r,{event:"fail",jobId:e.id,kind:e.kind,durationMs:Date.now()-m,terminal:a.terminal,error:a.message,...a.pausedDuringJob?{pausedDuringJob:!0}:{},...a.hostSuspended?{hostSuspended:!0}:{}});let n=await w(`/api/work/${e.id}/fail`,{leaseToken:e.leaseToken,error:a.message,terminal:a.terminal,hostSuspended:a.hostSuspended},{budgetMs:S,signal:p,log:r,event:"fail_post",jobId:e.id});n.ok||s(r,{event:"fail_post_error",jobId:e.id,attempts:n.attempts,error:n.error instanceof Error?n.error.message:String(n.error)})}}finally{clearInterval(f),h=null}}i(he,"runOne");var de=new Set(["process_eval","process_conversation","process_insights","process_session_goal","distill_memories","memory_ab","cron_suggest_instructions","cron_eval_autorun","cron_instruction_evolution","process_judge_review","harbor_ab"]);async function Ze(e){let t=e.log??(()=>{}),r=e.pollWaitMs??ge,p=e.heartbeatIntervalMs??_e,d=e.capabilities??pe();s(t,{event:"agent_start",capabilities:d,pollWaitMs:r,heartbeatIntervalMs:p});try{let o=re();o.removed.length>0&&s(t,{event:"eval_worktrees_swept",removed:o.removed.length})}catch(o){s(t,{event:"eval_worktree_sweep_failed",error:o instanceof Error?o.message:String(o)})}H=te({signal:e.signal,onPause:i(o=>{s(t,{event:"machine_pause",...o,jobId:h?.jobId??null}),h?.beat()},"onPause")});let m=ke(d,e.signal,t,e.version);ne({signal:e.signal,log:t}).catch(o=>{s(t,{event:"tt_heartbeat_fatal",error:o instanceof Error?o.message:String(o)})});let g=5*6e4,f=0,a=i(()=>{if(!e.readInstalledVersion||!e.version)return!1;let o=Date.now();if(o-f<g)return!1;f=o;let b=e.readInstalledVersion();return!!(b&&b!==e.version)},"versionDrifted"),n=new AbortController,l=n.signal;e.signal.aborted?n.abort():e.signal.addEventListener("abort",()=>n.abort(),{once:!0});let c=i(async(o,b)=>{let _=ie;for(;!l.aborted;){if(a()){s(t,{event:"agent_version_drift",bootVersion:e.version,installedVersion:e.readInstalledVersion?.()??null}),n.abort(),e.onVersionDrift?.();break}let E=null;try{E=await be([...b],r)}catch(k){let ue=k instanceof M?k.statusCode:void 0;if(s(t,{event:"poll_error",lane:o,status:ue,error:k instanceof Error?k.message:String(k)}),!await I(_,l))break;_=Math.min(_*2,le);continue}if(!E){if(s(t,{event:"poll_204",lane:o}),!await I(_,l))break;_=Math.min(_*2,le);continue}_=ie,await he(E,p,t,l)}},"runLane"),u=d.filter(o=>de.has(o)),v=d.filter(o=>!de.has(o));u.length>0&&v.length>0?(s(t,{event:"agent_lanes",heavy:u.length,fast:v.length}),await Promise.all([c("heavy",u),c("fast",v)])):await c("single",d),await m.shutdown(),s(t,{event:"agent_stop"})}i(Ze,"runAgentLoop");export{ce as a,ae as b,pe as c,be as d,Ze as e};
@@ -0,0 +1 @@
1
+ import{a as o}from"./chunk-ZLLER3HP.js";var e={claude_code:{bin:"claude",args:["-p","--output-format","json"]},cursor:{bin:"cursor",args:["--pipe"]},codex:{bin:"codex",args:["exec","--sandbox","read-only","--skip-git-repo-check","--ephemeral","--color","never","-"]},opencode:{bin:"opencode",args:["--pipe"]},pi:{bin:"pi",args:["--print","--no-prompt-templates","--no-session","--no-tools","--mode","json"],delivery:"argv-file"},copilot:{bin:"copilot",args:["--output-format","json","--no-color","--log-level","none","--no-custom-instructions"]},vscode_copilot:{bin:"copilot",args:["--output-format","json","--no-color","--log-level","none","--no-custom-instructions"]},copilot_agent:{bin:"copilot",args:["--output-format","json","--no-color","--log-level","none","--no-custom-instructions"]},rulemetric_mcp:{bin:"claude",args:["-p","--output-format","json"]}};function t(n){return e[n]??e.claude_code}o(t,"getToolCli");export{e as a,t as b};
@@ -1 +1 @@
1
- import{a as i}from"./chunk-PVGUDJD7.js";import{h as s}from"./chunk-APDRR6FS.js";import{a as n}from"./chunk-ZLLER3HP.js";async function l(a,c){let{mirrorId:g,evalTargetId:p,config:r}=a,e=n(o=>c.logger.info(o),"log");await i(r,p,e);let t={type:"conversation",conversationId:r.conversationId};return await s(`/api/eval-jobs/${g}/state`,{result:t}).catch(o=>{e(`result persist failed: ${o instanceof Error?o.message:String(o)}`)}),t}n(l,"processConversation");export{l as a};
1
+ import{a as i}from"./chunk-JRWQJZYQ.js";import{h as s}from"./chunk-ZZHIBOMT.js";import{a as n}from"./chunk-ZLLER3HP.js";async function l(a,c){let{mirrorId:g,evalTargetId:p,config:r}=a,e=n(o=>c.logger.info(o),"log");await i(r,p,e);let t={type:"conversation",conversationId:r.conversationId};return await s(`/api/eval-jobs/${g}/state`,{result:t}).catch(o=>{e(`result persist failed: ${o instanceof Error?o.message:String(o)}`)}),t}n(l,"processConversation");export{l as a};
@@ -0,0 +1,2 @@
1
+ import{a as w}from"./chunk-6XTLP2G7.js";import{a as l}from"./chunk-ZLLER3HP.js";import{spawn as y}from"node:child_process";function b(o){let i=["--print","--mode","json","--no-session","--no-tools","--no-extensions","--no-skills","--no-prompt-templates"];return o.systemPrompt&&i.push("--system-prompt",o.systemPrompt),o.model&&i.push("--model",o.model),i.push(o.prompt),i}l(b,"buildPiArgs");var v=l((o,i)=>`pi:${o}/${i}`,"piModelId");function c(o){return typeof o=="number"&&Number.isFinite(o)?o:0}l(c,"finiteNumber");function T(o){let i=null;for(let r of o.split(`
2
+ `)){if(!r.trim())continue;let s;try{s=JSON.parse(r)}catch{continue}let p=s;p.type==="agent_end"&&Array.isArray(p.messages)&&(i=p.messages)}if(!i)return{ok:!1,reason:"pi exited without an agent_end event in its JSON stream"};let m=i.filter(r=>r.role==="assistant"),e=m[m.length-1];if(!e)return{ok:!1,reason:"pi agent_end carried no assistant message"};if(e.stopReason==="error"||e.stopReason==="aborted")return{ok:!1,reason:`pi provider error: ${String(e.errorMessage??e.stopReason).slice(0,500)}`};let g=(Array.isArray(e.content)?e.content:[]).map(r=>{if(!r||typeof r!="object")return"";let s=r;return s.type==="text"&&typeof s.text=="string"?s.text:""}).join("");if(!g.trim())return{ok:!1,reason:`pi assistant message held no text (stopReason ${String(e.stopReason)})`};let k=typeof e.provider=="string"?e.provider:void 0,f=typeof e.model=="string"?e.model:void 0,u=e.usage&&typeof e.usage=="object"?e.usage:null,d,a;if(u){let r=c(u.input),s=c(u.output),p=c(u.cacheRead),t=c(u.cacheWrite),n=c(u.totalTokens);(r||s||p||t||n)&&(d={inputTokens:r,outputTokens:s,cacheReadTokens:p,cacheWriteTokens:t,totalTokens:n||r+s+p+t});let P=u.cost;if(P&&typeof P=="object"){let x=P.total;typeof x=="number"&&Number.isFinite(x)&&(a=x)}}return{ok:!0,output:g,provider:k,model:f,usage:d,costUsd:a}}l(T,"parsePiAgentEnd");async function E(o){let{timeout:i=12e4,workDir:m=process.cwd()}=o,e=w("pi");if(!e)return{output:"",exitCode:null,durationMs:0,error:"Pi CLI not found on PATH, well-known install dirs, or the node bin dir \u2014 is it installed?"};let g=Date.now();return new Promise(k=>{let f={...process.env};delete f.HTTPS_PROXY;let u=y(e,b(o),{cwd:m,env:f,stdio:["ignore","pipe","pipe"]}),d="",a="",r=!1,s=l(t=>{r||(r=!0,k({...t,durationMs:Date.now()-g}))},"finish");u.stdout.on("data",t=>{d+=t.toString(),d.length>1024*1024&&(d=d.slice(-1024*1024))}),u.stderr.on("data",t=>{a+=t.toString(),a.length>64*1024&&(a=a.slice(-64*1024))});let p=setTimeout(()=>{u.kill("SIGTERM"),s({output:"",exitCode:null,error:`pi timed out after ${i}ms`})},i);u.on("error",t=>{clearTimeout(p),s({output:"",exitCode:null,error:`failed to spawn pi: ${t.message}`})}),u.on("close",t=>{clearTimeout(p);let n=T(d);if(!n.ok){s({output:"",exitCode:t,error:`${n.reason}${a.trim()?`: ${a.trim().slice(-500)}`:""}`});return}if(t!==0){s({output:n.output,exitCode:t,usage:n.usage,costUsd:n.costUsd,error:`pi failed (exit ${t}): ${a.trim().slice(-500)||"no stderr"}`});return}s({output:n.output,exitCode:t,provider:n.provider,model:n.provider&&n.model?v(n.provider,n.model):n.model,usage:n.usage,costUsd:n.costUsd})})})}l(E,"executePiEval");export{b as a,v as b,T as c,E as d};
@@ -0,0 +1 @@
1
+ import{a as t}from"./chunk-ZLLER3HP.js";import{readFile as b,stat as w}from"node:fs/promises";import{homedir as F}from"node:os";import{isAbsolute as y,join as f,resolve as E,sep as v}from"node:path";var p="capture.json",C={codex:{section:"codex",label:"Codex capture",envFlag:"RULEMETRIC_CODEX_CAPTURE",envRoots:"RULEMETRIC_CODEX_ROOTS"},pi:{section:"pi",label:"Pi capture",envFlag:"RULEMETRIC_PI_CAPTURE",envRoots:"RULEMETRIC_PI_ROOTS"},hooks:{section:"hooks",label:"Hook capture",envFlag:"RULEMETRIC_HOOKS_CAPTURE",envRoots:"RULEMETRIC_HOOKS_ROOTS"}};function T(e,r){return e==="~"?r:e.startsWith("~/")?f(r,e.slice(2)):e}t(T,"expandTilde");function R(e,r){return e.map(o=>typeof o=="string"?o.trim():"").filter(Boolean).map(o=>T(o,r)).filter(o=>y(o)).map(o=>E(o))}t(R,"normaliseRoots");function P(e){return{mode:"off",roots:[],source:"config",error:e}}t(P,"failClosed");async function g(e,r){let o=r.env??process.env,n=r.home??F(),i=o[e.envFlag]?.trim().toLowerCase();if(i==="off"||i==="none"||i==="0")return{mode:"off",roots:[],source:"env"};if(i==="all"||i==="1")return{mode:"all",roots:[],source:"env"};let c=o[e.envRoots]?.trim();if(c){let h=R(c.split(","),n);return h.length>0?{mode:"allowlist",roots:h,source:"env"}:{mode:"off",roots:[],source:"env",error:`${e.envRoots} had no absolute paths`}}let s=f(r.configDir,p),l;try{l=await b(s,"utf8")}catch{return{mode:"all",roots:[],source:"default"}}let u;try{u=JSON.parse(l)}catch{return P(`${p} is present but is not valid JSON \u2014 ${e.label} is OFF until it parses.`)}let a=u?.[e.section];if(!a||typeof a!="object")return{mode:"all",roots:[],source:"default"};let d=typeof a.mode=="string"?a.mode.trim().toLowerCase():void 0;if(d==="off")return{mode:"off",roots:[],source:"config"};if(d==="all")return{mode:"all",roots:[],source:"config"};let m=Array.isArray(a.roots)?a.roots:[];if(d===void 0&&m.length===0)return{mode:"all",roots:[],source:"default"};let x=R(m,n);return x.length===0?P(`${p} selects an allowlist but lists no roots (absolute paths required) \u2014 ${e.label} is OFF.`):{mode:"allowlist",roots:x,source:"config"}}t(g,"loadSectionScope");async function _(e){return g(C.codex,e)}t(_,"loadCodexCaptureScope");async function M(e){return g(C.hooks,e)}t(M,"loadHooksCaptureScope");async function k(e){return g(C.pi,e)}t(k,"loadPiCaptureScope");function N(e,r){if(e.mode==="off")return!1;if(e.mode==="all")return!0;if(!r)return!1;let o=E(r);return e.roots.some(n=>o===n||o.startsWith(n.endsWith(v)?n:n+v))}t(N,"isPathInScope");function S(e,r){if(e.error)return`OFF \u2014 ${e.error}`;switch(e.mode){case"off":return`off (${e.source}) \u2014 ${r}`;case"allowlist":return`scoped to ${e.roots.length} path${e.roots.length===1?"":"s"} (${e.source})`;default:return"all projects (unscoped)"}}t(S,"describeCaptureScope");function U(e){return S(e,"no Codex transcripts are swept")}t(U,"describeCodexCaptureScope");function D(e){return S(e,"no hook-captured sessions are uploaded")}t(D,"describeHooksCaptureScope");function L(e){return S(e,"no Pi transcripts are swept")}t(L,"describePiCaptureScope");function O(e,r){let o=null,n=null;return async()=>{let i=f(e.configDir,p),c;try{let u=await w(i);c=`${u.mtimeMs}:${u.size}`}catch{c="absent"}if(o&&n===c)return o;let s=await r(e),l=o===null||o.mode!==s.mode||o.error!==s.error||o.roots.join("\0")!==s.roots.join("\0");return o=s,n=c,l&&e.onChange?.(s),s}}t(O,"createScopeWatcher");function A(e){return O(e,_)}t(A,"createCodexScopeWatcher");function J(e){return O(e,k)}t(J,"createPiScopeWatcher");export{p as a,_ as b,M as c,k as d,N as e,S as f,U as g,D as h,L as i,A as j,J as k};
@@ -0,0 +1 @@
1
+ import{d as E}from"./chunk-OUK2AWEI.js";import{b as F,c as x}from"./chunk-KGURGIZ2.js";import{f as R}from"./chunk-ZZHIBOMT.js";import{a}from"./chunk-ZLLER3HP.js";var _="with_candidate",w="with_prior_version";function S(e){return JSON.stringify([e.outputs.engine??null,e.outputs.model??null,e.outputs.methodology??null,e.outputs.deliveryRegime??null,e.grading.judge_engine??null,e.grading.judge_model??null])}a(S,"observedExecutionKey");function I(e){let r=e.filter(n=>n.status==="completed"),i=new Set(r.map(n=>JSON.stringify([n.outputs.engine??null,n.outputs.model??null,n.outputs.methodology??null,n.outputs.deliveryRegime??null]))),t=new Set(r.filter(n=>n.grading.judge_model!=null).map(n=>JSON.stringify([n.grading.judge_engine??"claude",n.grading.judge_model])));return i.size===1&&t.size<=1?JSON.stringify([[...i][0],[...t][0]??null]):null}a(I,"measurementBatchKey");function A(e){let r=e.filter(t=>t.configuration===_),i=[];for(let t of r){let n=e.find(s=>s.configuration===w&&s.evalId===t.evalId&&s.runNumber===t.runNumber);if(!n||S(n)!==S(t))continue;let l=h(t),m=h(n);l==null||m==null||i.push({withScore:l,withoutScore:m})}return i}a(A,"pairCandidateRuns");function h(e){return e.status!=="completed"?null:e.grading?.summary?.pass_rate??null}a(h,"evidenceOf");function $(e){let r=[],i=0;for(let t of e){if(t.status==="failed"){r.push(t.failure??{kind:"unknown",class:"infrastructure"});continue}h(t)==null&&(i+=1)}return{infrastructureFailed:r.length,ungradeable:i,summary:F(r)}}a($,"accountForFailures");function Q(e){let{pairs:r,minPairs:i,accounting:t}=e;return r>=i?{kind:"proceed"}:t.infrastructureFailed<=0?{kind:"proceed"}:{kind:"infrastructure-incomplete",reason:`${r}/${i} pair(s) \u2014 ${t.infrastructureFailed} run(s) never executed (${t.summary.describe()}). Retry when the environment recovers; this is not a statement about the target.`}}a(Q,"attributeShortfall");function k(e,r,i,t){let n=[];for(let l of e)n.push({eval_:l,configuration:_,targetContent:r,runNumber:t}),n.push({eval_:l,configuration:w,targetContent:i,runNumber:t});return n}a(k,"buildCandidateQueue");async function j(e){let{cases:r,candidateContent:i,priorVersionContent:t,concurrency:n,runNumber:l,opts:m,onLog:s=a(()=>{},"onLog")}=e,g=k(r,i,t,l),o=[],y=Math.max(1,n),p=null;for(let u=0;u<g.length;u+=y){let d=g.slice(u,u+y);o.push(...await Promise.all(d.map(c=>E(c,m,s))));let C=o.find(c=>c.failure&&x(c.failure.kind));if(C?.failure){p=C.failure.kind;let c=g.length-o.length;s(` \u26D4 aborting batch \u2014 ${p}: the account is out of quota. Skipped ${c} remaining run(s) that would certainly have failed.`);break}}for(let u of o)try{await R("/api/eval-runs",u)}catch(d){s(` \u26A0 failed to post a run result: ${d instanceof Error?d.message:String(d)}`)}let b=A(o),f=$(o),v=r.length-b.length;if(v>0){let u=f.infrastructureFailed?` \u2014 ${f.infrastructureFailed} run(s) never executed (${f.summary.describe()})`:"";s(` \u26A0 ${v}/${r.length} case(s) produced no usable pair (failed or ungradeable arm)${u}`)}return{completed:o.filter(u=>u.status==="completed").length,failed:o.filter(u=>u.status==="failed").length,results:o,pairs:b,accounting:f,abortedForQuota:p}}a(j,"runCandidateBatchAndPost");export{_ as a,w as b,S as c,I as d,A as e,$ as f,Q as g,k as h,j as i};
@@ -1,4 +1,4 @@
1
- import{b as E,d as R}from"./chunk-APDRR6FS.js";import{a as o}from"./chunk-ZLLER3HP.js";import{createHash as C}from"node:crypto";import{existsSync as A,mkdirSync as I,readFileSync as p,renameSync as L,rmdirSync as M,writeFileSync as m}from"node:fs";import{homedir as U,tmpdir as x}from"node:os";import{join as c}from"node:path";var $=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function v(t){return $.test(t)?t:`antigravity-${C("sha256").update(t).digest("hex").slice(0,16)}`}o(v,"hookSessionKey");var _=100,F=new Set(["RUN_COMMAND","VIEW_FILE","LIST_DIRECTORY","CODE_ACTION","GREP_SEARCH","SEARCH_WEB"]),H=new Set(["CONVERSATION_HISTORY","KNOWLEDGE_ARTIFACTS","CHECKPOINT"]);function T(){return process.env.RULEMETRIC_CONFIG_DIR??c(U(),".config","rulemetric")}o(T,"configDir");function O(){return c(T(),"antigravity-state")}o(O,"stateDir");function P(t){return c(O(),`${t}.json`)}o(P,"stateFile");function k(){let t=c(T(),"env");if(A(t))try{let n=p(t,"utf-8");for(let r of n.split(/\r?\n/)){let e=r.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);if(!e)continue;let i=e[1];if(process.env[i]!==void 0)continue;let s=e[2];(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),process.env[i]=s}}catch{}}o(k,"loadEnvFile");function b(t){try{let n=p(P(t),"utf-8"),r=JSON.parse(n);if(r&&typeof r=="object"&&"lastStepIdx"in r){let e=r.lastStepIdx;if(typeof e=="number"&&Number.isFinite(e))return{lastStepIdx:e}}}catch{}return null}o(b,"loadState");function g(t,n){I(O(),{recursive:!0});let r=P(t),e=`${r}.tmp`;m(e,JSON.stringify(n),{mode:384});try{L(e,r)}catch{m(r,JSON.stringify(n),{mode:384})}}o(g,"saveState");function N(t){let n=process.env.TMPDIR??x(),r=c(n,"rulemetric"),e=c(r,v(t));try{return p(e,"utf-8").trim()||null}catch{return null}}o(N,"resolveRwSessionId");function W(t){let n=process.env.TMPDIR??x(),r=c(n,"rulemetric"),e=v(t),i=c(r,`${e}.seq`),s=c(r,`${e}.seqlock`),l=Date.now()+5e3;for(;Date.now()<l;)try{I(s);break}catch{}let a=1;try{a=parseInt(p(i,"utf-8").trim(),10)+1,(!Number.isFinite(a)||a<1)&&(a=1)}catch{a=1}try{m(i,String(a))}catch{}try{M(s)}catch{}return a}o(W,"nextSequence");function Y(t,n){let r;try{r=p(t,"utf-8")}catch{return[]}let e=[];for(let i of r.split(/\r?\n/))if(i.trim())try{let s=JSON.parse(i);typeof s.step_index=="number"&&s.step_index>n&&e.push(s)}catch{}return e.sort((i,s)=>i.step_index-s.step_index),e}o(Y,"readNewRecords");function G(t){let n;try{n=p(t,"utf-8")}catch{return-1}let r=-1;for(let e of n.split(/\r?\n/))if(e.trim())try{let i=JSON.parse(e);typeof i.step_index=="number"&&i.step_index>r&&(r=i.step_index)}catch{}return r}o(G,"findMaxStepIndex");function J(t){let n=t.match(/<USER_REQUEST>\s*([\s\S]*?)\s*<\/USER_REQUEST>/);return n?n[1].trim():t.trim()}o(J,"extractUserPrompt");function j(t,n){let r=t.created_at??new Date().toISOString(),e={antigravityStepIndex:t.step_index,antigravitySource:t.source,antigravityType:t.type};if(H.has(t.type)||F.has(t.type))return null;if(t.source==="USER_EXPLICIT"&&t.type==="USER_INPUT")return{sequence:n,eventType:"user_message",content:J(t.content??""),timestamp:r,metadata:e};if(t.source==="MODEL"&&t.type==="PLANNER_RESPONSE"){let i=[];return t.thinking&&t.thinking.trim()&&i.push(`[thinking]
1
+ import{b as E,d as R}from"./chunk-ZZHIBOMT.js";import{a as o}from"./chunk-ZLLER3HP.js";import{createHash as C}from"node:crypto";import{existsSync as A,mkdirSync as I,readFileSync as p,renameSync as L,rmdirSync as M,writeFileSync as m}from"node:fs";import{homedir as U,tmpdir as x}from"node:os";import{join as c}from"node:path";var $=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function v(t){return $.test(t)?t:`antigravity-${C("sha256").update(t).digest("hex").slice(0,16)}`}o(v,"hookSessionKey");var _=100,F=new Set(["RUN_COMMAND","VIEW_FILE","LIST_DIRECTORY","CODE_ACTION","GREP_SEARCH","SEARCH_WEB"]),H=new Set(["CONVERSATION_HISTORY","KNOWLEDGE_ARTIFACTS","CHECKPOINT"]);function T(){return process.env.RULEMETRIC_CONFIG_DIR??c(U(),".config","rulemetric")}o(T,"configDir");function O(){return c(T(),"antigravity-state")}o(O,"stateDir");function P(t){return c(O(),`${t}.json`)}o(P,"stateFile");function k(){let t=c(T(),"env");if(A(t))try{let n=p(t,"utf-8");for(let r of n.split(/\r?\n/)){let e=r.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);if(!e)continue;let i=e[1];if(process.env[i]!==void 0)continue;let s=e[2];(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1)),process.env[i]=s}}catch{}}o(k,"loadEnvFile");function b(t){try{let n=p(P(t),"utf-8"),r=JSON.parse(n);if(r&&typeof r=="object"&&"lastStepIdx"in r){let e=r.lastStepIdx;if(typeof e=="number"&&Number.isFinite(e))return{lastStepIdx:e}}}catch{}return null}o(b,"loadState");function g(t,n){I(O(),{recursive:!0});let r=P(t),e=`${r}.tmp`;m(e,JSON.stringify(n),{mode:384});try{L(e,r)}catch{m(r,JSON.stringify(n),{mode:384})}}o(g,"saveState");function N(t){let n=process.env.TMPDIR??x(),r=c(n,"rulemetric"),e=c(r,v(t));try{return p(e,"utf-8").trim()||null}catch{return null}}o(N,"resolveRwSessionId");function W(t){let n=process.env.TMPDIR??x(),r=c(n,"rulemetric"),e=v(t),i=c(r,`${e}.seq`),s=c(r,`${e}.seqlock`),l=Date.now()+5e3;for(;Date.now()<l;)try{I(s);break}catch{}let a=1;try{a=parseInt(p(i,"utf-8").trim(),10)+1,(!Number.isFinite(a)||a<1)&&(a=1)}catch{a=1}try{m(i,String(a))}catch{}try{M(s)}catch{}return a}o(W,"nextSequence");function Y(t,n){let r;try{r=p(t,"utf-8")}catch{return[]}let e=[];for(let i of r.split(/\r?\n/))if(i.trim())try{let s=JSON.parse(i);typeof s.step_index=="number"&&s.step_index>n&&e.push(s)}catch{}return e.sort((i,s)=>i.step_index-s.step_index),e}o(Y,"readNewRecords");function G(t){let n;try{n=p(t,"utf-8")}catch{return-1}let r=-1;for(let e of n.split(/\r?\n/))if(e.trim())try{let i=JSON.parse(e);typeof i.step_index=="number"&&i.step_index>r&&(r=i.step_index)}catch{}return r}o(G,"findMaxStepIndex");function J(t){let n=t.match(/<USER_REQUEST>\s*([\s\S]*?)\s*<\/USER_REQUEST>/);return n?n[1].trim():t.trim()}o(J,"extractUserPrompt");function j(t,n){let r=t.created_at??new Date().toISOString(),e={antigravityStepIndex:t.step_index,antigravitySource:t.source,antigravityType:t.type};if(H.has(t.type)||F.has(t.type))return null;if(t.source==="USER_EXPLICIT"&&t.type==="USER_INPUT")return{sequence:n,eventType:"user_message",content:J(t.content??""),timestamp:r,metadata:e};if(t.source==="MODEL"&&t.type==="PLANNER_RESPONSE"){let i=[];return t.thinking&&t.thinking.trim()&&i.push(`[thinking]
2
2
  ${t.thinking.trim()}`),t.content&&t.content.trim()&&i.push(t.content.trim()),t.tool_calls&&t.tool_calls.length>0&&(e.antigravityToolCalls=t.tool_calls.map(s=>s.name).filter(Boolean)),{sequence:n,eventType:"assistant_response",content:i.join(`
3
3
 
4
4
  `)||null,timestamp:r,metadata:e}}return t.source==="MODEL"&&t.type==="GENERIC"?{sequence:n,eventType:"tool_result",content:t.content??null,timestamp:r,metadata:e}:t.source==="SYSTEM"&&(t.type==="SYSTEM_MESSAGE"||t.type==="ERROR_MESSAGE")?null:{sequence:n,eventType:`antigravity_${t.type.toLowerCase()}`,content:t.content??null,timestamp:r,metadata:e}}o(j,"classifyRecord");function q(t){try{let n=JSON.parse(t);return n&&typeof n=="object"?n:null}catch{return null}}o(q,"parseHookPayload");async function K(t,n,r,e,i={}){let s=i.errorSink??(u=>process.stderr.write(u)),l=0,a=0,d=0,S=0,f=e;for(let u of t){l++,i.onProgress?.({attempted:l,total:t.length,record:u});let w=W(r),y=j(u,w);if(!y)S++;else try{await R(`/api/sessions/${n}/events`,{method:"POST",body:y}),a++}catch(h){d++;let D=h instanceof E?h.statusCode:"unknown";s(`[antigravity-tailer] failed step=${u.step_index} type=${u.type} status=${D}
@@ -0,0 +1 @@
1
+ import{a as Me}from"./chunk-M7QSC64D.js";import{i as Ie}from"./chunk-VLWNSTYW.js";import{c as Ae}from"./chunk-G7V4ZZZ3.js";import{a as Re,b as xe,c as Se,d as De,e as ae,f as Oe}from"./chunk-SV73ASP2.js";import{b as pe,i as me,j as ge,k as fe,l as he,m as be,n as $e}from"./chunk-LB24UKHZ.js";import{d as ye,f as ke,g as Ce,i as Ee}from"./chunk-RRM4HQG4.js";import{a as we}from"./chunk-7ML2UCI7.js";import{a as re}from"./chunk-AHLVY52I.js";import{c as ve}from"./chunk-OUK2AWEI.js";import{b as Pe}from"./chunk-SWSOEYC7.js";import{d as ue,e as ne,f as de}from"./chunk-VBXL7XO7.js";import{e as y,f as te}from"./chunk-ZZHIBOMT.js";import{a as g}from"./chunk-ZLLER3HP.js";import{createHash as Je}from"node:crypto";import{existsSync as _e,readFileSync as Te,writeFileSync as Ge}from"node:fs";var H=g(r=>Je("sha256").update(r).digest("hex"),"sha256"),He=1.3,se=4,Xe=20;function ze(r,i){if(!r.configured||i<=0)return se;let e=Math.ceil(r.minPairs*He/i);return Math.min(Xe,Math.max(se,e))}g(ze,"passCapFor");function Be(r,i=10,e=se){if(r<=0)return{passes:0,expectedPairs:0,feasible:!1,reason:"no live cases"};let o=Math.ceil(i*He),l=Math.min(e,Math.ceil(o/r)),n=l*r;return n<i?{passes:l,expectedPairs:n,feasible:!1,reason:`${r} live case(s) x ${e} passes = ${r*e} pairs at best, below the ${i} a controlled verdict requires \u2014 add cases rather than replaying these`}:{passes:l,expectedPairs:n,feasible:!0}}g(Be,"planPasses");var Qe=60,Ve=5,Ne=g(r=>Array.isArray(r)?r.filter(i=>typeof i=="string"):[],"stringList"),J=g(r=>typeof r=="number"&&Number.isFinite(r)?r:null,"finite");function Ye(r,i,e=Ve){let o=[...r].filter(a=>a.fromContentHash===i).sort((a,c)=>Date.parse(c.createdAt)-Date.parse(a.createdAt)),l=[],n=new Set;for(let a of o){let c=a.toContentHash??a.id;if(n.has(c))continue;n.add(c);let d=a.verdict??null,k=J(d?.delta),M=J(d?.ci?.lower),x=J(d?.ci?.upper),S=J(d?.nWith),L=d?.sufficient===!0&&k!=null&&M!=null&&x!=null&&S!=null?{delta:k,ciLower:M,ciUpper:x,nPairs:S}:null;if(l.push({decision:typeof a.decision=="string"?a.decision:"unknown",applied:a.applied===!0,at:typeof a.createdAt=="string"?a.createdAt:"",rationale:typeof a.proposalRationale=="string"?a.proposalRationale:"",touched:Ne(a.touchedSections),refusals:Ne(a.refusals),measured:L}),l.length>=e)break}return l}g(Ye,"summarisePriorDecisions");function Ze(r,i){let e=i.accumulate??(r.autoEvolveAccumulate===!0||r.autoEvolveAccumulate==="true"),o=i.accumulateTargetPairs??r.autoEvolveAccumulateTarget,l=typeof o=="string"?Number.parseInt(o,10):o,n=typeof l=="number"&&Number.isInteger(l)&&l>0?l:Qe;return{enabled:e,targetPairs:n}}g(Ze,"readAccumulateConfig");function et(r){let i=r.accumulateEnabled&&r.pairCount<r.targetPairs;return{apply:r.consented&&!i,peeking:i}}g(et,"resolveApply");async function bt(r,i){let e=g(t=>i?.logger?.info?.(t)??console.log(t),"log"),{evalTargetId:o}=r,l=r.measurement?ve(r):{},n=`[cron_instruction_evolution] ${o}`,a=await y(`/api/eval-targets/${o}`),c=a.metadata??{},d=r.measurement?JSON.stringify([l.engine,l.model,l.graderEngine,l.graderModel,a.type,Pe(r.measurement.engine)]):void 0,k=null,M=!1;if(a.name.startsWith("/")&&_e(a.name))try{if(k=Te(a.name,"utf8"),k!==a.content){let t=await te(`/api/eval-targets/${o}/sync-content`,{content:k});M=t.synced,e(`${n}: target content drifted from disk by ${Math.abs(k.length-a.content.length)} chars \u2014 synced to disk truth (v${t.version}). Prior verdicts against the old text dissolve via content-hash keying.`),a={...a,content:k,version:t.version}}}catch(t){e(`${n}: disk sync failed (${t instanceof Error?t.message:String(t)}) \u2014 measuring the stored snapshot`)}let x=!1;try{x=(await y("/api/settings/evolution-account")).paused}catch(t){e(`${n}: could not read the account switch (${t instanceof Error?t.message:String(t)}) \u2014 pausing to be safe`),x=!0}if(x)return e(`${n}: PAUSED for the whole account (profiles.evolution_paused) \u2014 no model budget spent.`),{skipped:"paused-account"};if(ge(c))return e(`${n}: PAUSED (metadata.autoEvolvePaused) \u2014 no model budget spent. Opt-in is intact.`),{skipped:"paused"};let S=Me(a);if(S)return e(`${n}: ${S.reason}`),S;let L=r.apply??(c.autoEvolveApply===!0||c.autoEvolveApply==="true"),F=tt(c);if(F==null){if(L)return e(`${n}: refusing \u2014 metadata.immutableSections is unset. Set it (use [] to explicitly protect nothing) before letting the loop edit this target unattended.`),{skipped:"immutable-sections-unset"};e(`${n}: metadata.immutableSections unset \u2014 measure-only cycle proceeds with [] (nothing protected). Writing still requires setting it explicitly.`),F=[]}let w=(await y(`/api/eval-targets/${o}/evals`)).filter(t=>!t.retiredAt);if(w.length===0)return{skipped:"no-live-cases"};let j=me(c);j.note&&e(`${n}: ${j.note}`);let C=Be(w.length,j.minPairs,ze(j,w.length));if(!C.feasible)return e(`${n}: cannot reach a sufficient verdict \u2014 ${C.reason}`),{skipped:"cannot-reach-min-n",reason:C.reason};let Le=fe({liveCases:w.length,passes:C.passes});e(`${n}: budget for this run \u2014 ${$e(Le)}`);let G=await y(`/api/eval-targets/${o}/judge-calibration`);if(!G.powerCheck.adequate){let t=(G.powerCheck.reasons??[]).join("; ");return e(`${n}: not adequately powered, skipping before spending budget \u2014 ${t}`),{skipped:"not-adequate",reason:t}}let ie=de,Fe=Date.now()-ie*24*60*60*1e3,X=await y(`/api/eval-targets/${o}/promotions?limit=200`),oe=X.promotions.filter(t=>t.applied&&Date.parse(t.createdAt)>=Fe).length;if(oe>=ne)return e(`${n}: change budget looks exhausted (${oe}/${ne} applied in ${ie}d), skipping before spending budget`),{skipped:"budget-exhausted"};try{let t=await y("/api/usage/current-limits"),u=Ae({limits:t,now:new Date});if(!u.ok)return e(`${n}: deferring before spending budget \u2014 ${u.reason}`),{skipped:"quota-exhausted",reason:u.reason}}catch(t){e(`${n}: quota unknown (${t instanceof Error?t.message:String(t)}) \u2014 proceeding`)}let U=ue();if(!U.green)return e(`${n}: A/A canary is RED \u2014 halting. ${U.failures.join(" | ")}`),{skipped:"canary-red",reason:U.failures.join(" | ")};let z=a.content,D=H(z),f=Ze(c,r),v=f.enabled?re(X.promotions,D,f.targetPairs,d):null,b,q,$=[],_=0,B=pe,p=v?null:xe(c,D,d);if(p){b=p.content,q="",B=0;try{$=await De({evalTargetId:o,candidateContentHash:p.hash,executionKey:d,observedKey:p.observedKey})}catch(t){return e(`${n}: could not rebuild banked pairs (${t instanceof Error?t.message:String(t)})`),{skipped:"resume-read-failed",reason:p.hash}}e(`${n}: resuming interrupted cycle \u2014 ${$.length}/${p.plannedPairs} pair(s) rebuilt from eval_runs, no proposal call spent`)}else if(v){let t=await y(`/api/promotions/${v.promotionId}`);if(H(t.toContent)!==v.candidateContentHash)return e(`${n}: stored candidate does not match its recorded hash \u2014 refusing to continue`),{skipped:"accumulation-hash-mismatch",reason:v.promotionId};b=t.toContent,q=t.proposalRationale??"",$=v.pairs,_=v.runs,B=0,e(`${n}: continuing accumulation ${v.promotionId} \u2014 ${$.length}/${f.targetPairs} pair(s) carried from ${_} prior run(s)`)}else{let t=G.caseDiscrimination?.cases??[],u=[];if(a.name.startsWith("/")){let s=a.name.slice(0,a.name.lastIndexOf("/"));try{let m=await y(`/api/insights/evidence?projectPath=${encodeURIComponent(s)}`);m.analyzedAt&&(u=[...m.friction.map(ee=>`Real-session friction (insights, ${m.analyzedAt.slice(0,10)}): ${ee}`),...m.whatWorks.map(ee=>`Working well in real sessions \u2014 do not break: ${ee}`)],u.length>0&&e(`${n}: proposer sees ${m.friction.length} friction + ${m.whatWorks.length} what-works item(s) from insights`))}catch(m){e(`${n}: insights evidence unavailable (${m instanceof Error?m.message:String(m)}) \u2014 proposing without it`)}}let N=[];try{N=Ye(X.promotions,D)}catch(s){e(`${n}: could not summarise prior decisions (${s instanceof Error?s.message:String(s)}) \u2014 proposing without them`)}N.length>0&&e(`${n}: proposer sees ${N.length} prior decision(s) against this exact body (${N.map(s=>`${s.decision}${s.measured?"/measured":""}`).join(", ")})`);let W=await Ie({currentContent:a.content,targetType:a.type,targetName:a.name,immutableSections:F,evidence:{nonDiscriminating:t.filter(s=>!s.discriminating).map(s=>`${s.name??s.assertion??"unnamed"} \u2014 ${s.note}`),weakest:t.filter(s=>s.discriminating&&s.withPassRate<s.withoutPassRate).map(s=>({name:s.name??s.assertion??"unnamed",withPassRate:s.withPassRate,withoutPassRate:s.withoutPassRate})),priorDecisions:N,notes:u}},void 0,r.measurement?(s,m)=>we(r.measurement,s,m):void 0);if(!W.ok)return e(`${n}: no usable proposal \u2014 ${W.reason}`),{skipped:"no-proposal",reason:W.reason};b=W.proposal.candidateContent,q=W.proposal.rationale}let O=p?Se({plannedPairs:p.plannedPairs||C.expectedPairs,carriedPairs:$.length,liveCases:w.length}):C.passes;e(`${n}: measuring ${w.length} case(s) x ${O} pass(es) = up to ${w.length*O} pairs, candidate vs prior version`+(p?` (resumed; ${$.length} pair(s) already banked)`:""));let E=[],K=[],je=Date.now(),le=0,Q=0;for(let t=1;t<=O;t++){let u=await Ee({cases:w,candidateContent:b,priorVersionContent:z,concurrency:r.concurrency??2,runNumber:t,opts:{targetId:o,targetVersion:a.version??1,iteration:1,timeout:r.timeout??24e4,model:r.model,graderModel:r.graderModel,graderEngine:r.graderEngine,...l,executionKey:d,skipGrading:!1,targetType:a.type,targetName:a.name,candidateContentHash:H(b)},onLog:e});if(E.push(...u.pairs),K.push(...u.results),le+=u.completed,Q+=u.failed,e(`${n}: pass ${t}/${O} \u2014 ${u.pairs.length} pair(s), running total ${E.length}`),u.abortedForQuota){e(`${n}: stopping after pass ${t}/${O} \u2014 ${u.abortedForQuota}. Remaining passes would spend against an exhausted account.`);break}}let I=ye(K),Ue=p?.observedKey??v?.observedKey;if(r.measurement&&E.length>0&&(!I||$.length>0&&Ue!==I))return{skipped:"incomparable-execution",reason:"Actual actor/judge models or delivery changed; recorded runs are retained, but incompatible evidence cannot be pooled or promoted."};let A=[...$,...E],T=ke(K),V=E.length>0,h=he({runs:K,plannedPairs:C.expectedPairs,usablePairs:E.length,verdictPairs:V?A.length:E.length,proposalCalls:B,passes:O,liveCases:w.length,wallMs:Date.now()-je});if(e(`${n}: ${le} completed, ${Q} failed, ${E.length} usable pair(s) \u2014 spent ~${h.modelCalls} model calls (${h.proposalCalls} proposal + ${h.executorCalls} executor + >=${h.graderCalls} grader) in ${(h.wallMs/6e4).toFixed(1)} min`+(V?`; the ${h.verdictPairs} pair(s) behind this verdict resolve +/-${be(h.mde)} at 80% power`:"")),!V)return{skipped:T.infrastructureFailed?"infrastructure-failure":"no-pairs",reason:T.infrastructureFailed?`${T.infrastructureFailed} run(s) never executed (${T.summary.describe()}) \u2014 the environment failed, not the target`:`${Q} run(s) failed or were ungradeable`,cost:h};let Y=Ce({pairs:A.length,minPairs:10,accounting:T});if(Y.kind==="infrastructure-incomplete")return e(`${n}: not posting a verdict \u2014 ${Y.reason}`),await ae({evalTargetId:o,meta:c,blob:Oe({executionKey:d,...I?{observedKey:I}:{},content:b,hash:H(b),priorHash:D,plannedPairs:p?.plannedPairs||C.expectedPairs,now:new Date}),log:e,tag:n}),{skipped:"infrastructure-incomplete",reason:Y.reason,cost:h};f.enabled&&e(`${n}: accumulated ${A.length}/${f.targetPairs} pair(s) over ${_+1} run(s) on one candidate`);let ce=L,{apply:qe,peeking:Ke}=et({consented:ce,accumulateEnabled:f.enabled,pairCount:A.length,targetPairs:f.targetPairs});ce&&Ke&&e(`${n}: interim readout at ${A.length}/${f.targetPairs} pairs \u2014 recording the decision but not acting until the target is reached`);let P=await te(`/api/eval-targets/${o}/promotions`,{candidateContent:b,proposalSource:"llm",proposalRationale:q,pairs:A,canaryGreen:U.green,measuredAgainstContentHash:D,immutableSections:F,apply:qe,measurementCost:h,...f.enabled?{accumulation:{executionKey:d,...I?{observedKey:I}:{},candidateContentHash:H(b),priorContentHash:D,targetPairs:f.targetPairs,carriedPairs:$.length,runs:_+1}}:{}});e(`${n}: ${P.decision}${P.applied?" (APPLIED)":""} \u2014 ${P.rationale}`+(P.refusals.length>0?` | refusals: ${P.refusals.join("; ")}`:"")),(p||c[Re])&&await ae({evalTargetId:o,meta:c,blob:null,log:e,tag:n});let Z=!1,R;if(P.applied&&a.name.startsWith("/"))try{_e(a.name)?Te(a.name,"utf8")!==z?R="file changed since measurement started \u2014 refusing to clobber; next cycle re-syncs":(Ge(a.name,b,"utf8"),Z=!0):R="file no longer exists on disk",e(Z?`${n}: measured improvement written to ${a.name} (undo: git checkout -- ${a.name})`:`${n}: NOT written to disk \u2014 ${R}`)}catch(t){R=t instanceof Error?t.message:String(t),e(`${n}: disk write-back failed \u2014 ${R}. The eval target is updated; the file is not.`)}return{decision:P.decision,applied:P.applied,nPairs:A.length,promotionId:P.id,cost:h,diskSynced:M,...P.applied?{fileWritten:Z,...R?{fileWriteSkipped:R}:{}}:{},...f.enabled?{carriedPairs:$.length,accumulationRuns:_+1}:{}}}g(bt,"cronInstructionEvolution");function tt(r){let i=r.immutableSections;return i==null||!Array.isArray(i)?null:i.filter(e=>typeof e=="string")}g(tt,"readImmutableSections");export{He as a,se as b,Xe as c,ze as d,Be as e,Qe as f,Ve as g,Ye as h,Ze as i,et as j,bt as k,tt as l};
@@ -0,0 +1,25 @@
1
+ import{a as l,b as Mt}from"./chunk-ZLLER3HP.js";var Ve=["claude_code","cursor","vscode_copilot","copilot_agent","rulemetric_mcp","codex","pi","opencode","antigravity"],Ke=["user_message","assistant_message","assistant_response","tool_call","tool_result","thinking","error"];var qt=new Set(["","unknown","<synthetic>"]);function Jt(e){if(typeof e!="string")return null;let t=e.trim();return qt.has(t)?null:t}l(Jt,"resolveEventModel");var A=class{static{l(this,"ClaudeCodeAdapter")}tool="claude_code";parse(t){let n=t.split(`
2
+ `).filter(p=>p.trim()),o=[];for(let p of n)try{o.push(JSON.parse(p))}catch{}let s=o.filter(p=>p.type==="user"||p.type==="assistant"),r=null,i=null,c={},a=o.find(p=>p.type==="user");a&&(r=a.cwd??null,i=a.gitBranch??null,a.version&&(c.claudeCodeVersion=a.version),a.sessionId&&(c.sessionId=a.sessionId));let u=o.find(p=>p.type==="assistant");u?.message?.model&&(c.model=u.message.model);let d=[],f=0;for(let p of s){let y=p.timestamp??new Date().toISOString();if(p.type==="user"){let g=p.message?.content;if(typeof g=="string")d.push({sequence:f++,eventType:"user_message",content:g,toolName:null,toolInput:null,toolOutput:null,tokenUsage:null,timestamp:y,metadata:{}});else if(Array.isArray(g))for(let _ of g)_.type==="tool_result"&&d.push({sequence:f++,eventType:"tool_result",content:typeof _.content=="string"?_.content:JSON.stringify(_.content),toolName:null,toolInput:null,toolOutput:null,tokenUsage:null,timestamp:y,metadata:{toolUseId:_.tool_use_id}})}else if(p.type==="assistant"){let g=Array.isArray(p.message?.content)?p.message.content:[],_=p.message?.usage,x=_?{input:_.input_tokens??0,output:_.output_tokens??0,cacheRead:_.cache_read_input_tokens??0,cacheWrite:_.cache_creation_input_tokens??0}:null,v={};p.message?.model&&(v.model=p.message.model);let w=Jt(p.message?.model);p.message?.stop_reason&&(v.stopReason=p.message.stop_reason),p.requestId&&(v.requestId=p.requestId),_?.service_tier&&(v.serviceTier=_.service_tier),_?.speed&&(v.speed=_.speed),_?.cache_creation&&(v.cacheCreationDetail=_.cache_creation),_?.server_tool_use&&(v.serverToolUse=_.server_tool_use);for(let S of g)S.type==="text"?d.push({sequence:f++,eventType:"assistant_message",content:S.text??"",toolName:null,toolInput:null,toolOutput:null,tokenUsage:x,model:w,timestamp:y,metadata:v}):S.type==="thinking"?d.push({sequence:f++,eventType:"thinking",content:S.thinking??"",toolName:null,toolInput:null,toolOutput:null,tokenUsage:x,model:w,timestamp:y,metadata:v}):S.type==="tool_use"&&d.push({sequence:f++,eventType:"tool_call",content:null,toolName:S.name??"unknown",toolInput:S.input??null,toolOutput:null,tokenUsage:x,model:w,timestamp:y,metadata:{...v,toolUseId:S.id}})}}let m=d.map(p=>p.timestamp).sort(),h=new Date().toISOString();return{tool:"claude_code",projectPath:r,gitBranch:i,startedAt:m[0]??h,endedAt:m[m.length-1]??null,events:d,metadata:c}}};var N=class{static{l(this,"CursorAdapter")}tool="cursor";parse(t){let n=Mt("better-sqlite3"),o=new n(t,{readonly:!0});try{let s=o.prepare("SELECT value FROM ItemTable WHERE key = 'composer.composerData'").get();return s?this.parseComposerJson(s.value):this.emptySession()}finally{o.close()}}parseComposerJson(t){let n;try{n=JSON.parse(t)}catch{return this.emptySession()}let o=Object.values(n.allComposers??{});if(o.length===0)return this.emptySession();let s=o.sort((u,d)=>{let f=u.createdAt?new Date(u.createdAt).getTime():0;return(d.createdAt?new Date(d.createdAt).getTime():0)-f})[0],r=s.conversation??[],i=[];for(let u=0;u<r.length;u++){let d=r[u],f=d.createdAt??new Date().toISOString();i.push({sequence:u,eventType:d.type===1?"user_message":"assistant_message",content:d.text,toolName:null,toolInput:null,toolOutput:null,tokenUsage:null,timestamp:f,metadata:{}})}let c=i.map(u=>u.timestamp).sort(),a=new Date().toISOString();return{tool:"cursor",projectPath:null,gitBranch:null,startedAt:c[0]??a,endedAt:c[c.length-1]??null,events:i,metadata:{composerId:s.composerId}}}emptySession(){return{tool:"cursor",projectPath:null,gitBranch:null,startedAt:new Date().toISOString(),endedAt:null,events:[],metadata:{}}}};var P=class{static{l(this,"VSCodeCopilotAdapter")}tool="vscode_copilot";parse(t){let n;try{n=JSON.parse(t)}catch{return this.emptySession()}let o=n.requests??[],s=[],r=0;for(let a of o){let u=a.timestamp?new Date(a.timestamp).toISOString():new Date().toISOString();if(s.push({sequence:r++,eventType:"user_message",content:a.message,toolName:null,toolInput:null,toolOutput:null,tokenUsage:null,timestamp:u,metadata:{}}),a.response){let d=a.response.timestamp?new Date(a.response.timestamp).toISOString():u;s.push({sequence:r++,eventType:"assistant_message",content:a.response.message,toolName:null,toolInput:null,toolOutput:null,tokenUsage:null,timestamp:d,metadata:{}})}}let i=s.map(a=>a.timestamp).sort(),c=new Date().toISOString();return{tool:"vscode_copilot",projectPath:null,gitBranch:null,startedAt:i[0]??c,endedAt:i[i.length-1]??null,events:s,metadata:{...n.requesterUsername&&{username:n.requesterUsername},...n.customTitle&&{title:n.customTitle}}}}emptySession(){return{tool:"vscode_copilot",projectPath:null,gitBranch:null,startedAt:new Date().toISOString(),endedAt:null,events:[],metadata:{}}}};var b=class{static{l(this,"CopilotAgentAdapter")}tool="copilot_agent";parse(t){let n;try{n=JSON.parse(t)}catch{return this.emptySession()}let o=n.requests??[],s=[],r=0;for(let a of o){let u=a.timestamp?new Date(a.timestamp).toISOString():new Date().toISOString();if(s.push({sequence:r++,eventType:"user_message",content:a.message,toolName:null,toolInput:null,toolOutput:null,tokenUsage:null,timestamp:u,metadata:{}}),a.toolCalls)for(let d of a.toolCalls){let f=d.timestamp?new Date(d.timestamp).toISOString():u;s.push({sequence:r++,eventType:"tool_call",content:null,toolName:d.name??"unknown",toolInput:d.input??null,toolOutput:d.output??null,tokenUsage:null,timestamp:f,metadata:{}})}if(a.response){let d=a.response.timestamp?new Date(a.response.timestamp).toISOString():u;s.push({sequence:r++,eventType:"assistant_message",content:a.response.message,toolName:null,toolInput:null,toolOutput:null,tokenUsage:null,timestamp:d,metadata:{}})}}let i=s.map(a=>a.timestamp).sort(),c=new Date().toISOString();return{tool:"copilot_agent",projectPath:null,gitBranch:null,startedAt:i[0]??c,endedAt:i[i.length-1]??null,events:s,metadata:{...n.requesterUsername&&{username:n.requesterUsername},...n.customTitle&&{title:n.customTitle},...n.agentMode!=null&&{agentMode:n.agentMode}}}}emptySession(){return{tool:"copilot_agent",projectPath:null,gitBranch:null,startedAt:new Date().toISOString(),endedAt:null,events:[],metadata:{}}}};var D=class{static{l(this,"RuleMetricMcpAdapter")}tool="rulemetric_mcp";parse(t){let n;try{n=JSON.parse(t)}catch{return this.emptySession()}let s=(n.events??[]).map((i,c)=>({sequence:i.sequence??c,eventType:this.normalizeEventType(i.eventType),content:i.content??null,toolName:i.toolName??null,toolInput:i.toolInput??null,toolOutput:i.toolOutput??null,tokenUsage:i.tokenUsage??null,timestamp:i.timestamp??new Date().toISOString(),metadata:i.metadata??{}})),r=new Date().toISOString();return{tool:"rulemetric_mcp",projectPath:n.projectPath??null,gitBranch:n.gitBranch??null,startedAt:n.startedAt??s[0]?.timestamp??r,endedAt:n.endedAt??s[s.length-1]?.timestamp??null,events:s,metadata:n.metadata??{}}}normalizeEventType(t){return t&&["user_message","assistant_message","tool_call","tool_result","thinking","error"].includes(t)?t:"assistant_message"}emptySession(){return{tool:"rulemetric_mcp",projectPath:null,gitBranch:null,startedAt:new Date().toISOString(),endedAt:null,events:[],metadata:{}}}};function Bt(e){try{return JSON.parse(e)}catch{return e}}l(Bt,"safeJsonParse");function Q(e,t){return Array.isArray(e)?e.filter(n=>n.type&&t.includes(n.type)).map(n=>n.text??"").filter(Boolean).join(`
3
+
4
+ `):""}l(Q,"textFromBlocks");function Gt(e){if(!e)return null;let t=e.cached_input_tokens??0,n=Math.max(0,(e.input_tokens??0)-t),o=(e.output_tokens??0)+(e.reasoning_output_tokens??0);return n===0&&o===0&&t===0?null:{input:n,output:o,cacheRead:t,cacheWrite:0}}l(Gt,"tokenUsageFromCodex");function Lt(e){if(!e)return new Date().toISOString();let t=new Date(e);return Number.isFinite(t.getTime())?t.toISOString():new Date().toISOString()}l(Lt,"normalizeTimestamp");function tt(){return{sequence:0,model:null,prevCumulativeTotal:0,callNames:{}}}l(tt,"freshCodexState");var C=class{static{l(this,"CodexAdapter")}tool="codex";parse(t){let n=tt(),{events:o,projectPath:s,gitBranch:r,metadata:i}=this.parseLines(t,n),c=o.map(u=>u.timestamp).sort(),a=new Date().toISOString();return{tool:"codex",projectPath:s,gitBranch:r,startedAt:c[0]??a,endedAt:c[c.length-1]??null,events:o,metadata:i}}parseAppend(t,n){let o={...n,callNames:{...n.callNames}},{events:s}=this.parseLines(t,o);return{events:s,state:o}}parseLines(t,n){let o=t.split(`
5
+ `).filter(d=>d.trim()),s=[],r={},i=n.callNames,c=null,a=null,u=null;for(let d of o){let f;try{f=JSON.parse(d)}catch{continue}let m=f.payload;if(!m)continue;let h=Lt(f.timestamp);if(f.type==="session_meta"){u=m.session_id??m.id??u,c=m.cwd??c,m.git_branch&&(a=m.git_branch),m.model&&(n.model=m.model),r.sessionId=u,r.codexSessionId=u,r.originator=m.originator,r.source=m.source,r.modelProvider=m.model_provider,r.codexCliVersion=m.cli_version;continue}if(f.type==="turn_context"){c=m.cwd??c,m.model&&(n.model=m.model,r.model=m.model);continue}if(f.type==="response_item"&&m.type==="message"){if(m.role==="user"){let p=Q(m.content,["input_text"]);if(!p)continue;s.push({sequence:n.sequence++,eventType:"user_message",content:p,toolName:null,toolInput:null,toolOutput:null,tokenUsage:null,timestamp:h,metadata:{}})}else if(m.role==="assistant"){let p=Q(m.content,["output_text"]);if(!p)continue;s.push({sequence:n.sequence++,eventType:"assistant_message",content:p,toolName:null,toolInput:null,toolOutput:null,tokenUsage:null,model:n.model,timestamp:h,metadata:n.model?{model:n.model}:{}})}continue}if(f.type==="response_item"&&m.type==="function_call"){let p=m.name??"unknown";m.call_id&&(i[m.call_id]=p);let y=typeof m.arguments=="string"?Bt(m.arguments):{};s.push({sequence:n.sequence++,eventType:"tool_call",content:null,toolName:p,toolInput:y&&typeof y=="object"&&!Array.isArray(y)?y:{arguments:y},toolOutput:null,tokenUsage:null,model:n.model,timestamp:h,metadata:{callId:m.call_id}});continue}if(f.type==="response_item"&&m.type==="function_call_output"){let p=m.call_id?i[m.call_id]??null:null;s.push({sequence:n.sequence++,eventType:"tool_result",content:m.output??null,toolName:p,toolInput:null,toolOutput:m.output==null?null:{output:m.output},tokenUsage:null,model:n.model,timestamp:h,metadata:{callId:m.call_id}});continue}if(f.type==="event_msg"&&m.type==="token_count"){let p=m.info,y=p?.total_token_usage?.total_tokens??0;if(y>0&&y===n.prevCumulativeTotal)continue;y>0&&(n.prevCumulativeTotal=y);let g=Gt(p?.last_token_usage??p?.total_token_usage);if(!g)continue;let _=p?.model??p?.model_name??n.model;s.push({sequence:n.sequence++,eventType:"assistant_response",content:null,toolName:null,toolInput:null,toolOutput:null,tokenUsage:g,model:_??null,timestamp:h,metadata:{codexEventType:"token_count",..._?{model:_}:{},reasoningOutputTokens:p?.last_token_usage?.reasoning_output_tokens??0,usage:{input_tokens:g.input,output_tokens:g.output,cache_read_input_tokens:g.cacheRead??0,cache_creation_input_tokens:g.cacheWrite??0}}})}}return{events:s,projectPath:c,gitBranch:a,sessionId:u,metadata:r}}};function et(e,t){let n=e??(typeof t=="number"?new Date(t).toISOString():""),o=new Date(n);return Number.isFinite(o.getTime())?o.toISOString():new Date().toISOString()}l(et,"timestamp");function ot(e){return Array.isArray(e.content)?e.content:[]}l(ot,"blocks");function nt(e){return typeof e.content=="string"?e.content:ot(e).filter(t=>t.type==="text").map(t=>t.text??"").filter(Boolean).join(`
6
+
7
+ `)}l(nt,"messageText");function Ft(e){if(!e)return null;let t={input:Math.max(0,e.input??0),output:Math.max(0,e.output??0),cacheRead:Math.max(0,e.cacheRead??0),cacheWrite:Math.max(0,e.cacheWrite??0)};return Object.values(t).some(n=>n>0)?t:null}l(Ft,"usageOf");var j=class{static{l(this,"PiAdapter")}tool="pi";parse(t){let n=[],o={},s=null,r=null,i=null,c=null,a=l(f=>{n.push({sequence:n.length,...f})},"push");for(let f of t.split(`
8
+ `)){if(!f.trim())continue;let m;try{m=JSON.parse(f)}catch{continue}if(m.type==="session"){r||(r=et(m.timestamp)),s=m.cwd??s,o.sessionId=m.id,o.piSessionId=m.id,o.sessionVersion=m.version;continue}if(m.type==="model_change"){i=m.provider??i,c=m.modelId??c,i&&(o.provider=i),c&&(o.model=c);continue}if(m.type!=="message"||!m.message)continue;let h=m.message,p=et(m.timestamp,h.timestamp);if(i=h.provider??i,c=h.model??c,i&&(o.provider=i),c&&(o.model=c),h.role==="user"){let g=nt(h);if(!g)continue;a({eventType:"user_message",content:g,toolName:null,toolInput:null,toolOutput:null,tokenUsage:null,timestamp:p,metadata:{}});continue}if(h.role==="toolResult"){let g=nt(h);a({eventType:"tool_result",content:g||null,toolName:h.toolName??null,toolInput:null,toolOutput:{content:g,details:h.details??null,isError:h.isError??!1},tokenUsage:null,model:c,timestamp:p,metadata:{toolCallId:h.toolCallId,isError:h.isError??!1}});continue}if(h.role!=="assistant")continue;if(h.stopReason==="error"||h.stopReason==="aborted"){a({eventType:"error",content:h.errorMessage??`Pi stopped with ${h.stopReason}`,toolName:null,toolInput:null,toolOutput:null,tokenUsage:null,model:c,timestamp:p,metadata:{provider:i,stopReason:h.stopReason}});continue}for(let g of ot(h))g.type==="thinking"&&g.thinking?a({eventType:"thinking",content:g.thinking,toolName:null,toolInput:null,toolOutput:null,tokenUsage:null,model:c,timestamp:p,metadata:{provider:i}}):g.type==="text"&&g.text?a({eventType:"assistant_message",content:g.text,toolName:null,toolInput:null,toolOutput:null,tokenUsage:null,model:c,timestamp:p,metadata:{provider:i}}):g.type==="toolCall"&&g.name&&a({eventType:"tool_call",content:null,toolName:g.name,toolInput:g.arguments??{},toolOutput:null,tokenUsage:null,model:c,timestamp:p,metadata:{provider:i,toolCallId:g.id}});let y=Ft(h.usage);y&&a({eventType:"assistant_response",content:null,toolName:null,toolInput:null,toolOutput:null,tokenUsage:y,model:c,timestamp:p,metadata:{piEventType:"assistant_usage",provider:i,responseId:h.responseId,stopReason:h.stopReason,costUsd:h.usage?.cost?.total,usage:{input_tokens:y.input,output_tokens:y.output,cache_read_input_tokens:y.cacheRead??0,cache_creation_input_tokens:y.cacheWrite??0}}})}let u=n.map(f=>f.timestamp).sort(),d=new Date().toISOString();return{tool:"pi",projectPath:s,gitBranch:null,startedAt:r??u[0]??d,endedAt:u[u.length-1]??null,events:n,metadata:o}}};var Wt={claude_code:l(()=>new A,"claude_code"),cursor:l(()=>new N,"cursor"),vscode_copilot:l(()=>new P,"vscode_copilot"),copilot_agent:l(()=>new b,"copilot_agent"),rulemetric_mcp:l(()=>new D,"rulemetric_mcp"),codex:l(()=>new C,"codex"),pi:l(()=>new j,"pi")};function Ht(e){let t=Wt[e];if(!t)throw new Error(`Unknown session tool: ${e}`);return t()}l(Ht,"getAdapter");function zt(e){let t=e.trim();if(t.startsWith("{")){let n=t.split(`
9
+ `)[0],o=null;try{o=JSON.parse(n)}catch{try{o=JSON.parse(t)}catch{}}if(o){if(o.type==="user"||o.type==="assistant")return"claude_code";if(o.type==="session"&&typeof o.id=="string"&&typeof o.cwd=="string"&&typeof o.version=="number")return"pi";if(Array.isArray(o.events)&&!o.requests&&!o.allComposers)return"rulemetric_mcp";if(Array.isArray(o.requests))return o.requests.some(r=>Array.isArray(r.toolCalls))||o.agentMode?"copilot_agent":"vscode_copilot";if(o.allComposers)return"cursor"}if(!o)try{let s=t.split(`
10
+ `).filter(r=>r.trim());if(s.length>1){let r=JSON.parse(s[0]);if(r.type==="user"||r.type==="assistant")return"claude_code"}}catch{}}return null}l(zt,"detectTool");import{readdir as F,stat as W}from"fs/promises";import{basename as Vt,join as I}from"path";import{homedir as $}from"os";var Kt={"claude-opus-4-7":"Opus 4.7","claude-opus-4-6":"Opus 4.6","claude-opus-4-5":"Opus 4.5","claude-opus-4-1":"Opus 4.1","claude-opus-4":"Opus 4","claude-sonnet-4-6":"Sonnet 4.6","claude-sonnet-4-5":"Sonnet 4.5","claude-sonnet-4":"Sonnet 4","claude-3-7-sonnet":"Sonnet 3.7","claude-3-5-sonnet":"Sonnet 3.5","claude-haiku-4-5":"Haiku 4.5","claude-3-5-haiku":"Haiku 3.5"};function Xt(){return process.env.CLAUDE_CONFIG_DIR||I($(),".claude")}l(Xt,"getClaudeDir");function Yt(){return I(Xt(),"projects")}l(Yt,"getProjectsDir");function Zt(){return process.platform==="darwin"?I($(),"Library","Application Support","Claude","local-agent-mode-sessions"):process.platform==="win32"?I($(),"AppData","Roaming","Claude","local-agent-mode-sessions"):I($(),".config","Claude","local-agent-mode-sessions")}l(Zt,"getDesktopSessionsDir");async function Qt(e){let t=[];async function n(o,s){if(s>8)return;let r=await F(o).catch(()=>[]);for(let i of r){if(i==="node_modules"||i===".git")continue;let c=I(o,i);if((await W(c).catch(()=>null))?.isDirectory())if(i==="projects"){let u=await F(c).catch(()=>[]);for(let d of u){let f=I(c,d);(await W(f).catch(()=>null))?.isDirectory()&&t.push(f)}}else await n(c,s+1)}}return l(n,"walk"),await n(e,0),t}l(Qt,"findDesktopProjectDirs");var st={name:"claude",displayName:"Claude Code",modelDisplayName(e){let t=e.replace(/@.*$/,"").replace(/-\d{8}$/,"");for(let[n,o]of Object.entries(Kt))if(t.startsWith(n))return o;return t},toolDisplayName(e){return e},async discoverSessions(){let e=[],t=Yt();try{let o=await F(t);for(let s of o){let r=I(t,s);(await W(r).catch(()=>null))?.isDirectory()&&e.push({path:r,project:s,provider:"claude"})}}catch{}let n=await Qt(Zt());for(let o of n)e.push({path:o,project:Vt(o),provider:"claude"});return e},createSessionParser(){return{async*parse(){}}}};import{readdir as U,readFile as rt,stat as te}from"fs/promises";import{basename as ee,join as O}from"path";import{homedir as ne}from"os";var oe={"gpt-5.3-codex":"GPT-5.3 Codex","gpt-5.4-mini":"GPT-5.4 Mini","gpt-5.4":"GPT-5.4","gpt-5":"GPT-5","gpt-4o-mini":"GPT-4o Mini","gpt-4o":"GPT-4o"},at={exec_command:"Bash",read_file:"Read",write_file:"Edit",apply_diff:"Edit",apply_patch:"Edit",spawn_agent:"Agent",close_agent:"Agent",wait_agent:"Agent",read_dir:"Glob"};function se(){return process.env.CODEX_HOME??O(ne(),".codex")}l(se,"getCodexDir");function re(e){return e.replace(/^\//,"").replace(/\//g,"-")}l(re,"sanitizeProject");async function ae(e){try{let n=(await rt(e,"utf-8")).split(`
11
+ `)[0];return n?.trim()?JSON.parse(n):null}catch{return null}}l(ae,"readFirstLine");async function ie(e){let t=await ae(e);if(!t)return{valid:!1};let n=t.type==="session_meta"&&typeof t.payload?.originator=="string"&&t.payload.originator.toLowerCase().startsWith("codex");return{valid:n,meta:n?t:void 0}}l(ie,"isValidCodexSession");async function le(e){let t=O(e,"sessions"),n=[],o;try{o=await U(t)}catch{return n}for(let s of o){if(!/^\d{4}$/.test(s))continue;let r=O(t,s),i=await U(r).catch(()=>[]);for(let c of i){if(!/^\d{2}$/.test(c))continue;let a=O(r,c),u=await U(a).catch(()=>[]);for(let d of u){if(!/^\d{2}$/.test(d))continue;let f=O(a,d),m=await U(f).catch(()=>[]);for(let h of m){if(!h.startsWith("rollout-")||!h.endsWith(".jsonl"))continue;let p=O(f,h);if(!(await te(p).catch(()=>null))?.isFile())continue;let{valid:g,meta:_}=await ie(p);if(!g||!_)continue;let x=_.payload?.cwd??"unknown";n.push({path:p,project:re(x),provider:"codex"})}}}}return n}l(le,"discoverSessionsInDir");function ce(e,t){return e?.info?.model??e?.info?.model_name??t??"gpt-5"}l(ce,"resolveModel");function ue(e,t){return{async*parse(){let n;try{n=await rt(e.path,"utf-8")}catch{return}let o=n.split(`
12
+ `).filter(h=>h.trim()),s,r="",i=0,c=0,a=0,u=0,d=0,f=[],m="";for(let h of o){let p;try{p=JSON.parse(h)}catch{continue}if(p.type==="session_meta"){r=p.payload?.session_id??ee(e.path,".jsonl"),s=p.payload?.model;continue}if(p.type==="response_item"&&p.payload?.type==="function_call"){let y=p.payload.name??"";f.push(at[y]??y);continue}if(p.type==="response_item"&&p.payload?.type==="message"&&p.payload?.role==="user"){let y=(p.payload.content??[]).filter(g=>g.type==="input_text").map(g=>g.text??"").filter(Boolean);y.length>0&&(m=y.join(" "));continue}if(p.type==="event_msg"&&p.payload?.type==="token_count"){let y=p.payload.info;if(!y)continue;let g=y.total_token_usage?.total_tokens??0;if(g>0&&g===i)continue;i=g;let _=y.last_token_usage,x=0,v=0,w=0,S=0;if(_)x=_.input_tokens??0,v=_.cached_input_tokens??0,w=_.output_tokens??0,S=_.reasoning_output_tokens??0;else if(g>0){let T=y.total_token_usage;if(!T)continue;x=(T.input_tokens??0)-c,v=(T.cached_input_tokens??0)-a,w=(T.output_tokens??0)-u,S=(T.reasoning_output_tokens??0)-d}if(!_){let T=y.total_token_usage;T&&(c=T.input_tokens??0,a=T.cached_input_tokens??0,u=T.output_tokens??0,d=T.reasoning_output_tokens??0)}if(x+v+w+S===0)continue;let Rt=Math.max(0,x-v),Et=ce(p.payload,s),Z=p.timestamp??"",L=`codex:${e.path}:${Z}:${g}`;if(t.has(L))continue;t.add(L),yield{provider:"codex",model:Et,inputTokens:Rt,outputTokens:w,cacheCreationInputTokens:0,cacheReadInputTokens:v,cachedInputTokens:v,reasoningTokens:S,costUSD:0,tools:f,bashCommands:[],timestamp:Z,speed:"standard",deduplicationKey:L,userMessage:m,sessionId:r},f=[],m=""}}}}}l(ue,"createParser");var it={name:"codex",displayName:"Codex",modelDisplayName(e){for(let[t,n]of Object.entries(oe))if(e.startsWith(t))return n;return e},toolDisplayName(e){return at[e]??e},async discoverSessions(){return le(se())},createSessionParser(e,t){return ue(e,t)}};import{readdir as pe,readFile as lt,stat as me}from"fs/promises";import{basename as ct,dirname as de,join as H}from"path";import{homedir as fe}from"os";var he={"gpt-4.1-nano":"GPT-4.1 Nano","gpt-4.1-mini":"GPT-4.1 Mini","gpt-4.1":"GPT-4.1","gpt-4o-mini":"GPT-4o Mini","gpt-4o":"GPT-4o","gpt-5-mini":"GPT-5 Mini","gpt-5":"GPT-5","claude-sonnet-4-5":"Sonnet 4.5","claude-sonnet-4":"Sonnet 4","claude-3-7-sonnet":"Sonnet 3.7","claude-3-5-sonnet":"Sonnet 3.5","o4-mini":"o4-mini",o3:"o3"},ut={bash:"Bash",read_file:"Read",write_file:"Edit",edit_file:"Edit",create_file:"Write",delete_file:"Delete",search_files:"Grep",find_files:"Glob",list_directory:"LS",web_search:"WebSearch",fetch_webpage:"WebFetch",github_repo:"GitHub"},ge=Object.entries(he).sort((e,t)=>t[0].length-e[0].length);function ye(){return H(fe(),".copilot","session-state")}l(ye,"getCopilotSessionStateDir");function _e(e){let t=e.match(/^cwd:\s*(.+)$/m);return t?.[1]&&t[1].replace(/\s*#.*$/,"").replace(/^['"]|['"]$/g,"").trim()||null}l(_e,"parseCwd");function Se(e,t){return{async*parse(){let n;try{n=await lt(e.path,"utf-8")}catch{return}let o=ct(de(e.path)),s=n.split(`
13
+ `).filter(c=>c.trim()),r="",i="";for(let c of s){let a;try{a=JSON.parse(c)}catch{continue}if(a.type==="session.model_change"){r=a.data.newModel??r;continue}if(a.type==="user.message"){i=a.data.content??"";continue}if(a.type==="assistant.message"){let{messageId:u,outputTokens:d,toolRequests:f=[]}=a.data;if(d===0||!r)continue;let m=`copilot:${o}:${u}`;if(t.has(m))continue;t.add(m);let h=f.map(p=>p.name??"").filter(Boolean).map(p=>ut[p]??p);yield{provider:"copilot",model:r,inputTokens:0,outputTokens:d,cacheCreationInputTokens:0,cacheReadInputTokens:0,cachedInputTokens:0,reasoningTokens:0,costUSD:0,tools:h,bashCommands:[],timestamp:a.timestamp??"",speed:"standard",deduplicationKey:m,userMessage:i,sessionId:o},i=""}}}}}l(Se,"createParser");async function ve(e){let t=[],n;try{n=await pe(e)}catch{return t}for(let o of n){let s=H(e,o,"events.jsonl");if(!(await me(s).catch(()=>null))?.isFile())continue;let i=o;try{let c=await lt(H(e,o,"workspace.yaml"),"utf-8"),a=_e(c);a&&(i=ct(a))}catch{}t.push({path:s,project:i,provider:"copilot"})}return t}l(ve,"discoverSessionsInDir");var pt={name:"copilot",displayName:"GitHub Copilot",modelDisplayName(e){for(let[t,n]of ge)if(e===t||e.startsWith(t+"-"))return n;return e},toolDisplayName(e){return ut[e]??e},async discoverSessions(){return ve(ye())},createSessionParser(e,t){return Se(e,t)}};import{readdir as mt,readFile as ft,stat as dt}from"fs/promises";import{basename as ht,join as z}from"path";import{homedir as xe}from"os";var Te={"gpt-5.4":"GPT-5.4","gpt-5.4-mini":"GPT-5.4 Mini","gpt-5":"GPT-5","gpt-4o":"GPT-4o","gpt-4o-mini":"GPT-4o Mini"},gt={bash:"Bash",read:"Read",edit:"Edit",write:"Write",glob:"Glob",grep:"Grep",task:"Agent",dispatch_agent:"Agent",fetch:"WebFetch",search:"WebSearch",todo:"TodoWrite",patch:"Patch"},we=Object.entries(Te).sort((e,t)=>t[0].length-e[0].length);function Ie(){return z(xe(),".pi","agent","sessions")}l(Ie,"getPiSessionsDir");async function ke(e){try{let n=(await ft(e,"utf-8")).split(`
14
+ `)[0];return n?.trim()?JSON.parse(n):null}catch{return null}}l(ke,"readFirstEntry");function Oe(e){return e.split(/[;&|]+/).map(t=>t.trim().split(/\s+/)[0]).filter(Boolean)}l(Oe,"extractBashCommands");async function Ae(e){let t=[],n;try{n=await mt(e)}catch{return t}for(let o of n){let s=z(e,o);if(!(await dt(s).catch(()=>null))?.isDirectory())continue;let i;try{i=await mt(s)}catch{continue}for(let c of i){if(!c.endsWith(".jsonl"))continue;let a=z(s,c);if(!(await dt(a).catch(()=>null))?.isFile())continue;let d=await ke(a);if(!d||d.type!=="session")continue;let f=d.cwd??o;t.push({path:a,project:ht(f),provider:"pi"})}}return t}l(Ae,"discoverSessionsInDir");function Ne(e,t){return{async*parse(){let n;try{n=await ft(e.path,"utf-8")}catch{return}let o=n.split(`
15
+ `).filter(i=>i.trim()),s=ht(e.path,".jsonl"),r="";for(let[i,c]of o.entries()){let a;try{a=JSON.parse(c)}catch{continue}if(a.type==="session"){s=a.id??s;continue}if(a.type!=="message")continue;let u=a.message;if(!u)continue;if(u.role==="user"){let S=(u.content??[]).filter(k=>k.type==="text").map(k=>k.text??"").filter(Boolean);S.length>0&&(r=S.join(" "));continue}if(u.role!=="assistant"||!u.usage)continue;let{input:d,output:f,cacheRead:m,cacheWrite:h}=u.usage;if(d===0&&f===0)continue;let p=u.model??"gpt-5",y=u.responseId??"",g=`pi:${e.path}:${y||a.id||a.timestamp||String(i)}`;if(t.has(g))continue;t.add(g);let _=(u.content??[]).filter(S=>S.type==="toolCall"&&S.name),x=_.map(S=>gt[S.name]??S.name),v=_.filter(S=>S.name==="bash").flatMap(S=>{let k=S.arguments?.command;return typeof k=="string"?Oe(k):[]}),w=a.timestamp??"";yield{provider:"pi",model:p,inputTokens:d,outputTokens:f,cacheCreationInputTokens:h,cacheReadInputTokens:m,cachedInputTokens:m,reasoningTokens:0,costUSD:0,tools:x,bashCommands:v,timestamp:w,speed:"standard",deduplicationKey:g,userMessage:r,sessionId:s},r=""}}}}l(Ne,"createParser");var yt={name:"pi",displayName:"Pi",modelDisplayName(e){for(let[t,n]of we)if(e.startsWith(t))return n;return e},toolDisplayName(e){return gt[e]??e},async discoverSessions(){return Ae(Ie())},createSessionParser(e,t){return Ne(e,t)}};var Tt=[st,it,pt,yt],_t=null,St=!1;async function wt(){if(St)return _t;St=!0;try{let{cursor:e}=await import("./cursor-T7AMCMKS.js");return _t=e,e}catch{return null}}l(wt,"loadCursor");var vt=null,xt=!1;async function It(){if(xt)return vt;xt=!0;try{let{opencode:e}=await import("./opencode-QRJ3BH23.js");return vt=e,e}catch{return null}}l(It,"loadOpenCode");async function kt(){let[e,t]=await Promise.all([wt(),It()]),n=[...Tt];return e&&n.push(e),t&&n.push(t),n}l(kt,"getAllProviders");async function Pe(e){let t=await kt(),n=e&&e!=="all"?t.filter(s=>s.name===e):t,o=[];for(let s of n){let r=await s.discoverSessions();o.push(...r)}return o}l(Pe,"discoverAllSessions");async function be(e){return e==="cursor"?await wt()??void 0:e==="opencode"?await It()??void 0:Tt.find(t=>t.name===e)}l(be,"getProvider");import{spawn as Y}from"node:child_process";import{randomUUID as $e}from"node:crypto";import{writeFile as At}from"node:fs/promises";import{tmpdir as Nt}from"node:os";import{join as Pt}from"node:path";import{spawn as De}from"node:child_process";function V(e){return`rm-${e.trim().replace(/[^A-Za-z0-9_.-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"session"}`}l(V,"sanitizeTmuxName");function K(e){let t=e.runId?["env",`RULEMETRIC_RUN_ID=${e.runId}`,"claude"]:["claude"];return e.resumeSessionId&&t.push("--resume",e.resumeSessionId),e.model&&t.push("--model",e.model),["new-session","-d","-s",e.sessionName,"-c",e.projectPath,"--",...t]}l(K,"buildTmuxLaunchArgs");function R(e,t,n={}){return n.literal===!1?["send-keys","-t",e,t]:["send-keys","-t",e,"-l","--",t]}l(R,"buildTmuxSendKeysArgs");function Ce(e){return["has-session","-t",e]}l(Ce,"buildTmuxHasSessionArgs");function E(e){return`tmux attach -t ${e}`}l(E,"buildTmuxAttachCommand");function je(){let e=["/opt/homebrew/bin","/usr/local/bin"],t=(process.env.PATH??"").split(":").filter(Boolean),n=e.filter(o=>!t.includes(o));return n.length===0?process.env:{...process.env,PATH:[...t,...n].join(":")}}l(je,"tmuxSpawnEnv");function X(e){return new Promise(t=>{let n=De("tmux",e,{stdio:["ignore","ignore","pipe"],env:je()}),o="";n.stderr.on("data",s=>{o+=s.toString()}),n.on("close",s=>t({code:s,stderr:o})),n.on("error",s=>t({code:null,stderr:s.message}))})}l(X,"runTmux");async function Ot(){return(await X(["-V"])).code===0}l(Ot,"isTmuxAvailable");var Ue=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Re(e){if(e!==void 0){if(Ue.test(e))return e;console.warn(`[claude-code-launcher] dropping non-uuid runId (RULEMETRIC_RUN_ID not injected): ${JSON.stringify(e)}`)}}l(Re,"validateRunId");function Ee(e){return`'${e.replace(/'/g,"'\\''")}'`}l(Ee,"shellSingleQuote");var M=class{static{l(this,"ClaudeCodeLauncher")}options;tool="claude_code";constructor(t={}){this.options=t}capabilities={headless:!0,interactive:!0,remoteSpawn:!0};async launch(t){let n=$e(),o={...t,runId:Re(t.runId)};return o.mode==="headless"?this.launchHeadless(o,n):this.launchInteractive(o,n)}async launchHeadless(t,n){let o=["-p",t.prompt??"","--output-format","json"];t.systemPrompt&&o.push("--system-prompt",t.systemPrompt),t.model&&o.push("--model",t.model);let s={...process.env};return delete s.CLAUDECODE,delete s.HTTPS_PROXY,t.runId&&(s.RULEMETRIC_RUN_ID=t.runId),new Promise(r=>{let i=Y("claude",o,{cwd:t.projectPath,env:s,stdio:["ignore","pipe","pipe"]}),c="",a="";i.stdout.on("data",d=>{c+=d.toString()}),i.stderr.on("data",d=>{a+=d.toString()});let u=t.timeout?setTimeout(()=>{i.kill("SIGTERM")},t.timeout):null;i.on("close",d=>{u&&clearTimeout(u);let f=c;try{let m=JSON.parse(c);f=m.result??m.content??c}catch{}r({sessionId:n,pid:i.pid,exitCode:d,output:f,error:d!==0?a:void 0})}),i.on("error",d=>{u&&clearTimeout(u),r({sessionId:n,error:`Failed to spawn claude: ${d.message}`})})})}async launchInteractive(t,n){return await(this.options.tmuxAvailable??Ot)().catch(()=>!1)?this.launchInteractiveTmux(t,n):this.launchInteractiveTerminal(t,n,"tmux_not_found")}async launchInteractiveTmux(t,n){let o=this.options.runTmux??X,s=V(`claude-${t.resumeSessionId??n}`),r=await o(K({sessionName:s,projectPath:t.projectPath,resumeSessionId:t.resumeSessionId,model:t.model,runId:t.runId}));if(r.code!==0)return this.launchInteractiveTerminal(t,n,"tmux_launch_failed",`tmux new-session exited ${r.code}: ${r.stderr.trim()||"no stderr"}`);let i=await this.openTerminalAttach(s,n);if(t.prompt){let c=await o(R(s,t.prompt));if(c.code!==0)return{sessionId:n,liveSendAvailable:!1,fallbackReason:"tmux_launch_failed",error:`tmux send-keys exited ${c.code}: ${c.stderr.trim()||"no stderr"}`};let a=await o(R(s,"Enter",{literal:!1}));if(a.code!==0)return{sessionId:n,liveSendAvailable:!1,fallbackReason:"tmux_launch_failed",error:`tmux send Enter exited ${a.code}: ${a.stderr.trim()||"no stderr"}`}}return{sessionId:n,pid:i.pid,liveSendAvailable:!0,...i.error?{error:i.error}:{},terminalTarget:{kind:"tmux",target:s,attachCommand:E(s),live:!0}}}async openTerminalAttach(t,n){let o=Pt(Nt(),`rulemetric-attach-${n}.command`),s=`#!/bin/zsh
16
+ rm -- "$0"
17
+ ${E(t)}
18
+ `;return await At(o,s,{mode:493}),new Promise(r=>{let i=Y("open",["-a","Terminal",o],{stdio:["ignore","pipe","pipe"]}),c="";i.stderr.on("data",a=>{c+=a.toString()}),i.on("close",a=>{r(a===0?{pid:i.pid}:{pid:i.pid,error:`open attach exited ${a}: ${c.trim()||"no stderr"}`})}),i.on("error",a=>{r({error:`Failed to spawn open attach: ${a.message}`})})})}async launchInteractiveTerminal(t,n,o,s){let r=["claude"];t.resumeSessionId?r.push("--resume",t.resumeSessionId):t.prompt&&r.push("-p",JSON.stringify(t.prompt)),t.model&&r.push("--model",t.model);let i=r.join(" "),c=Pt(Nt(),`rulemetric-launch-${n}.command`),a=t.runId?`export RULEMETRIC_RUN_ID=${Ee(t.runId)}
19
+ `:"",u=`#!/bin/zsh
20
+ rm -- "$0"
21
+ cd ${JSON.stringify(t.projectPath)} || exit
22
+ `+a+`${i}
23
+ `;return await At(c,u,{mode:493}),new Promise(d=>{let f=Y("open",["-a","Terminal",c],{stdio:["ignore","pipe","pipe"]}),m="";f.stderr.on("data",h=>{m+=h.toString()}),f.on("close",h=>{if(h===0)d({sessionId:n,pid:f.pid,liveSendAvailable:!1,fallbackReason:o,...s?{error:s}:{}});else{let p=m.trim()||"no stderr";d({sessionId:n,pid:f.pid,liveSendAvailable:!1,fallbackReason:o,error:s?`${s}; open exited ${h}: ${p}`:`open exited ${h}: ${p}`})}}),f.on("error",h=>{d({sessionId:n,liveSendAvailable:!1,fallbackReason:o,error:`Failed to spawn open: ${h.message}`})})})}};import{spawn as bt}from"node:child_process";import{randomUUID as Me}from"node:crypto";var q=class{static{l(this,"CodexLauncher")}tool="codex";capabilities={headless:!0,interactive:!0,remoteSpawn:!0};async launch(t){let n=Me();return t.mode==="headless"?this.launchHeadless(t,n):this.launchInteractive(t,n)}launchHeadless(t,n){let o=["-q",t.prompt??""];return t.model&&o.push("--model",t.model),new Promise(s=>{let r=bt("codex",o,{cwd:t.projectPath,stdio:["ignore","pipe","pipe"]}),i="",c="";r.stdout.on("data",u=>{i+=u.toString()}),r.stderr.on("data",u=>{c+=u.toString()});let a=t.timeout?setTimeout(()=>{r.kill("SIGTERM")},t.timeout):null;r.on("close",u=>{a&&clearTimeout(a),s({sessionId:n,pid:r.pid,exitCode:u,output:i,error:u!==0?c:void 0})}),r.on("error",u=>{a&&clearTimeout(a),s({sessionId:n,error:`Failed to spawn codex: ${u.message}`})})})}launchInteractive(t,n){let o=["codex"];t.prompt&&o.push(JSON.stringify(t.prompt));let s=`cd ${JSON.stringify(t.projectPath)} && ${o.join(" ")}`,r=bt("osascript",["-e",`tell application "Terminal" to do script ${JSON.stringify(s)}`],{stdio:"ignore",detached:!0});return r.unref(),Promise.resolve({sessionId:n,pid:r.pid})}};import{spawn as Dt}from"node:child_process";import{randomUUID as qe}from"node:crypto";function Je(e){let t=e.mode==="headless"?["--print","--mode","json","--no-session"]:[];return e.systemPrompt&&t.push("--system-prompt",e.systemPrompt),e.model&&t.push("--model",e.model),e.prompt&&t.push(e.prompt),t}l(Je,"buildPiLaunchArgs");function Be(e){let t;for(let o of e.split(`
24
+ `))if(o.trim())try{let s=JSON.parse(o);if(s.type!=="agent_end"||!Array.isArray(s.messages))continue;t=s.messages.filter(r=>r.role==="assistant").at(-1)}catch{}if(!t)return{output:e};if(t.stopReason==="error"||t.stopReason==="aborted")return{output:"",error:`Pi provider error: ${t.errorMessage??t.stopReason}`};let n=t.content?.filter(o=>o.type==="text"&&typeof o.text=="string").map(o=>o.text).join(`
25
+ `)??"";return n?{output:n}:{output:e}}l(Be,"parsePiLaunchOutput");var J=class{static{l(this,"PiLauncher")}tool="pi";capabilities={headless:!0,interactive:!0,remoteSpawn:!0};async launch(t){let n=qe(),o=Je(t);if(t.mode==="interactive"){let s=["pi",...o].map(c=>JSON.stringify(c)).join(" "),r=`cd ${JSON.stringify(t.projectPath)} && ${s}`,i=Dt("osascript",["-e",`tell application "Terminal" to do script ${JSON.stringify(r)}`],{stdio:"ignore",detached:!0});return i.unref(),{sessionId:n,pid:i.pid}}return new Promise(s=>{let r=Dt("pi",o,{cwd:t.projectPath,stdio:["ignore","pipe","pipe"]}),i="",c="";r.stdout.on("data",u=>{i+=u.toString()}),r.stderr.on("data",u=>{c+=u.toString()});let a=t.timeout?setTimeout(()=>r.kill("SIGTERM"),t.timeout):null;r.on("close",u=>{a&&clearTimeout(a);let d=Be(i);s({sessionId:n,pid:r.pid,exitCode:u,output:d.output,error:d.error??(u!==0?c.trim()||i.trim()||`pi exited ${u}`:void 0)})}),r.on("error",u=>{a&&clearTimeout(a),s({sessionId:n,error:`Failed to spawn pi: ${u.message}`})})})}};import{spawn as Ct}from"node:child_process";import{randomUUID as Ge}from"node:crypto";var B=class{static{l(this,"AiderLauncher")}tool="aider";capabilities={headless:!0,interactive:!0,remoteSpawn:!0};async launch(t){let n=Ge();return t.mode==="headless"?this.launchHeadless(t,n):this.launchInteractive(t,n)}launchHeadless(t,n){let o=["--message",t.prompt??"","--yes"];return t.model&&o.push("--model",t.model),new Promise(s=>{let r=Ct("aider",o,{cwd:t.projectPath,stdio:["ignore","pipe","pipe"]}),i="",c="";r.stdout.on("data",u=>{i+=u.toString()}),r.stderr.on("data",u=>{c+=u.toString()});let a=t.timeout?setTimeout(()=>{r.kill("SIGTERM")},t.timeout):null;r.on("close",u=>{a&&clearTimeout(a),s({sessionId:n,pid:r.pid,exitCode:u,output:i,error:u!==0?c:void 0})}),r.on("error",u=>{a&&clearTimeout(a),s({sessionId:n,error:`Failed to spawn aider: ${u.message}`})})})}launchInteractive(t,n){let o=["aider"];t.model&&o.push("--model",t.model);let s=`cd ${JSON.stringify(t.projectPath)} && ${o.join(" ")}`,r=Ct("osascript",["-e",`tell application "Terminal" to do script ${JSON.stringify(s)}`],{stdio:"ignore",detached:!0});return r.unref(),Promise.resolve({sessionId:n,pid:r.pid})}};import{spawn as Le}from"node:child_process";import{randomUUID as Fe}from"node:crypto";var G=class{static{l(this,"GenericLauncher")}tool;constructor(t){this.tool=t}capabilities={headless:!1,interactive:!0,remoteSpawn:!1};async launch(t){let n=Fe();if(t.mode==="headless")return{sessionId:n,error:`${this.tool} does not support headless mode`};let o=`cd ${JSON.stringify(t.projectPath)} && echo "Session ${n} \u2014 tool: ${this.tool}" && exec $SHELL`,s=Le("osascript",["-e",`tell application "Terminal" to do script ${JSON.stringify(o)}`],{stdio:"ignore",detached:!0});return s.unref(),{sessionId:n,pid:s.pid}}};var jt={claude_code:l(()=>new M,"claude_code"),codex:l(()=>new q,"codex"),pi:l(()=>new J,"pi"),aider:l(()=>new B,"aider")};function We(e){let t=jt[e];return t?t():new G(e)}l(We,"getLauncher");function He(){return Object.entries(jt).map(([e,t])=>({tool:e,capabilities:t().capabilities}))}l(He,"getAvailableLaunchers");import $t from"node:path";function Ut(e){return e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^[-.]+|[-.]+$/g,"")||"worktree"}l(Ut,"sanitizeBranch");function ze(e){return $t.resolve(e.basePath??$t.join(e.repoRoot,"..",".rulemetric-worktrees",Ut(e.branch)))}l(ze,"worktreePathFor");export{Ve as a,Ke as b,A as c,N as d,P as e,b as f,D as g,tt as h,C as i,j,Ht as k,zt as l,kt as m,Pe as n,be as o,V as p,K as q,R as r,Ce as s,E as t,We as u,He as v,Ut as w,ze as x};
@@ -1,4 +1,4 @@
1
- import{a as y}from"./chunk-6XTLP2G7.js";import{a as s}from"./chunk-ZLLER3HP.js";import{spawn as v}from"node:child_process";import{mkdtempSync as O,readFileSync as D,rmSync as I}from"node:fs";import{tmpdir as M}from"node:os";import{join as E}from"node:path";var R=s(t=>`codex:${t}`,"codexModelId");function $(t,o){return["exec","--json","--sandbox","read-only","--skip-git-repo-check","--ephemeral","--model",t,"--output-last-message",o,"-"]}s($,"buildCodexArgs");function A(t){let o;for(let m of t.split(`
1
+ import{a as y}from"./chunk-6XTLP2G7.js";import{a as s}from"./chunk-ZLLER3HP.js";import{spawn as v}from"node:child_process";import{mkdtempSync as O,readFileSync as D,rmSync as I}from"node:fs";import{tmpdir as M}from"node:os";import{join as E}from"node:path";var R=s(t=>`codex:${t.replace(/^codex:/,"")}`,"codexModelId");function $(t,o){return["exec","--json","--sandbox","read-only","--skip-git-repo-check","--ephemeral","--model",t.replace(/^codex:/,""),"--output-last-message",o,"-"]}s($,"buildCodexArgs");function A(t){let o;for(let m of t.split(`
2
2
  `)){let u=m.trim();if(!u.startsWith("{"))continue;let n;try{n=JSON.parse(u)}catch{continue}if(typeof n!="object"||n===null)continue;let c=n.usage;if(typeof c!="object"||c===null)continue;let i=s(x=>{let a=c[x];return typeof a=="number"&&Number.isFinite(a)?a:0},"num"),d=i("input_tokens"),l=i("output_tokens");o={inputTokens:d,cachedInputTokens:i("cached_input_tokens"),outputTokens:l,reasoningOutputTokens:i("reasoning_output_tokens"),totalTokens:d+l}}return o}s(A,"parseCodexUsage");async function L(t){let{prompt:o,systemPrompt:m,model:u,timeout:n=12e4,workDir:c=process.cwd()}=t,i=m?`${m}
3
3
 
4
4
  ${o}`:o,d=y("codex");if(!d)return{output:"",exitCode:null,durationMs:0,error:"Codex CLI not found on PATH, well-known install dirs, or the node bin dir \u2014 is it installed?"};let l=O(E(M(),"rulemetric-codex-")),x=E(l,"last-message.txt"),a=Date.now();return new Promise(S=>{let f={...process.env};delete f.HTTPS_PROXY;let _=["/opt/homebrew/bin","/usr/local/bin"],k=(f.PATH??"").split(":").filter(Boolean),C=_.filter(e=>!k.includes(e));C.length&&(f.PATH=[...k,...C].join(":"));let r=v(d,$(u,x),{cwd:c,env:f,stdio:["pipe","pipe","pipe"]}),b="",p="",w=256*1024;r.stdout.on("data",e=>{p+=e.toString(),p.length>w&&(p=p.slice(-w))}),r.stderr.on("data",e=>{b+=e.toString()});let g=s(e=>{I(l,{recursive:!0,force:!0}),S({...e,durationMs:Date.now()-a})},"finish"),h=setTimeout(()=>{r.kill("SIGTERM"),g({output:"",exitCode:null,error:`codex exec timed out after ${n}ms`})},n);r.on("error",e=>{clearTimeout(h),g({output:"",exitCode:null,error:`failed to spawn codex: ${e.message} (is the Codex CLI installed?)`})}),r.on("close",e=>{clearTimeout(h);let T="";try{T=D(x,"utf8").trim()}catch{}let P=A(p);if(e!==0||T===""){g({output:T,exitCode:e,usage:P,error:`codex exec failed (exit ${e}): ${b.trim().slice(-500)||"no last message produced"}`});return}g({output:T,exitCode:e,model:R(u),usage:P})}),r.stdin.write(i),r.stdin.end()})}s(L,"executeCodexEval");export{R as a,$ as b,A as c,L as d};
@@ -0,0 +1,4 @@
1
+ import{d as I}from"./chunk-E7GQJML3.js";import{a as O}from"./chunk-YNLHJHUP.js";import{a as J}from"./chunk-6XTLP2G7.js";import{y as T}from"./chunk-TWPG3TEQ.js";import{a as L}from"./chunk-74QIUVWY.js";import{a as t}from"./chunk-ZLLER3HP.js";import{spawn as z}from"node:child_process";import{existsSync as V,mkdirSync as Z,readdirSync as K}from"node:fs";import{homedir as q,tmpdir as G}from"node:os";import{dirname as W,join as d,resolve as F}from"node:path";var Q=10800*1e3,X=/^rm-[a-z0-9-]+-task$/,Y=/^[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+)*$/,y=/^[A-Za-z0-9._-]+$/;function rr(r,o,n){return new Promise((l,i)=>{let a=z(r,o,{cwd:n.cwd,env:n.env,stdio:["ignore","pipe","pipe"]}),e="",g="",m="",_=setTimeout(()=>a.kill("SIGKILL"),n.timeoutMs);a.stdout.on("data",s=>{let w=s.toString("utf8");if(e+=w,!n.onLine)return;m+=w;let $=m.split(`
2
+ `);m=$.pop()??"";for(let p of $)n.onLine(p)}),a.stderr.on("data",s=>{g+=s.toString("utf8")}),a.on("error",s=>{clearTimeout(_),i(s)}),a.on("close",s=>{clearTimeout(_),m&&n.onLine&&n.onLine(m),l({status:s,stdout:e,stderr:g})})})}t(rr,"defaultRun");var nr={harnessDir:t(()=>O(),"harnessDir"),resolveBin:J,run:rr,exists:V,mkdir:t(r=>Z(r,{recursive:!0}),"mkdir"),readdir:K,jobsRoot:d(G(),"rulemetric-harbor"),now:t(()=>Date.now(),"now")};function er(r){if(r.trials&&r.trials.length>0){let o=r.trials.filter(n=>n.reward!=null);return{n:o.length,passes:o.filter(n=>n.reward>=.5).length}}return r.reward_mean==null||!r.n_trials?{n:r.n_trials??0,passes:null}:{n:r.n_trials,passes:Math.round(r.reward_mean*r.n_trials)}}t(er,"armReward");function sr(r){if(!X.test(r.task??""))throw new Error(`harbor_ab: refusing task "${r.task}" \u2014 not an rm-*-task name; a task is a directory name, never a path`);if(!Y.test(r.instructions??"")||r.instructions.split("/").includes(".."))throw new Error(`harbor_ab: refusing instructions "${r.instructions}" \u2014 must be a plain relative path under scripts/harbor`);if(!y.test(r.model??""))throw new Error(`harbor_ab: refusing model "${r.model}"`);if(!Number.isInteger(r.nTrials)||r.nTrials<1||r.nTrials>200)throw new Error(`harbor_ab: refusing nTrials=${r.nTrials} \u2014 must be an integer in 1..200`);if(r.class!=="proven"&&r.class!=="negative"&&r.class!=="unvalidated")throw new Error(`harbor_ab: unknown task class "${r.class}"`);if(r.axis!=="reward"&&r.axis!=="cost")throw new Error(`harbor_ab: unknown axis "${r.axis}"`)}t(sr,"validate");function tr(r,o){let n=new Set((process.env.PATH??"").split(":").filter(Boolean));for(let l of["harbor","docker","claude","codex","python3"]){let i=r.resolveBin(l);i&&n.add(W(i))}for(let l of[d(q(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"])n.add(l);return{...process.env,PATH:[...n].join(":"),HARBOR_JOBS_DIR:o}}t(tr,"spawnEnv");function f(r,o=20){return r.trim().split(`
3
+ `).slice(-o).join(`
4
+ `)}t(f,"tail");async function j(r,o,n,l,i,a=[]){let e=await r.run("python3",[d(o,l),...i],{cwd:o,env:n,timeoutMs:3e5});if(e.status!==0&&!a.includes(e.status))return{status:e.status,json:null,stderr:e.stderr};try{return{status:e.status,json:JSON.parse(e.stdout),stderr:e.stderr}}catch{throw new Error(`harbor_ab: ${l} printed something that is not JSON: ${f(e.stdout,5)}`)}}t(j,"readJson");async function wr(r,o,n=nr){let l=t(u=>o?.logger?.info?.(u)??console.log(u),"log"),i=r.measurement?L.parse(r.measurement):null,a=i?.engine??"claude";if(i){if(r={...r,model:i.model??T,class:a==="claude"&&i.model===T?r.class:"unvalidated"},a==="codex"&&r.axis==="cost")throw new Error("harbor_ab: dollar-cost telemetry is unavailable for Codex");if(!n.resolveBin(a))throw new Error(`harbor_ab: ${a} engine unavailable on this worker`)}sr(r);let e=n.harnessDir();if(!e)throw new Error("harbor_ab: no Harbor harness on this worker \u2014 scripts/harbor/run.sh was not found from the CLI build, the working directory, or RULEMETRIC_HARBOR_DIR. This job should not have been enqueued here: the readiness probe reports harness=false for a worker like this one.");let g=d(e,r.task),m=F(e,r.instructions);if(!n.exists(g))throw new Error(`harbor_ab: task directory not found: ${g}`);if(!n.exists(m))throw new Error(`harbor_ab: instruction file not found: ${m}`);let _=n.now(),s=d(n.jobsRoot,`${r.task}-${_}`);n.mkdir(s);let w=tr(n,s);l(`[harbor_ab] ${r.task} (${r.class}/${r.axis}, lane ${r.lane}): n=${r.nTrials}/arm on ${r.model} \u2192 ${s}`);let $=[d(e,"run.sh"),"ab",g,"--instructions",m,"--engine",a,"-m",r.model,"--n-attempts",String(r.nTrials)],p=await n.run("bash",$,{cwd:e,env:w,timeoutMs:Q,onLine:t(u=>l(`[harbor_ab] ${u}`),"onLine")});if(p.status!==0)throw new Error(`harbor_ab: ${r.task} run.sh exited ${p.status??"by signal"} after ${Math.round((n.now()-_)/1e3)}s: ${f(p.stderr)||f(p.stdout)||"(no output)"}`);let A=n.readdir(s),k=A.find(u=>/^ab-\d+-baseline$/.test(u)),E=A.find(u=>/^ab-\d+-with$/.test(u));if(!k||!E)throw new Error(`harbor_ab: run.sh exited 0 but the arm job dirs are missing under ${s} (found: ${A.join(", ")||"nothing"})`);let x=d(s,k),S=d(s,E),D=t(async u=>{let c=await j(n,e,w,"summarize.py",[u]);if(!c.json)throw new Error(`harbor_ab: summarize.py failed on ${u}: ${f(c.stderr,5)}`);return c.json},"summarize"),[N,U]=await Promise.all([D(x),D(S)]),R=await j(n,e,w,"cost_delta.py",[x,S,"--json"]);if(R.status!==0&&R.status!==3)throw new Error(`harbor_ab: cost_delta.py exited ${R.status}: ${f(R.stderr,5)}`);let b=R.json,h=await j(n,e,w,"provenance.py",["--compare",x,S,"--json"],[1]);if(h.status!==0&&h.status!==1)throw new Error(`harbor_ab: provenance.py exited ${h.status}: ${f(h.stderr,5)}`);if(!h.json)throw new Error(`harbor_ab: provenance.py printed no comparison: ${f(h.stderr,5)}`);let M=h.json,B=t((u,c)=>{let C=er(c);return{job:u,rewardMean:c.reward_mean,n:C.n,passes:C.passes,costUsd:c.cost_usd,tokens:c.tokens??null,durationMs:c.duration_ms,turns:c.turns,agentErrors:c.agent_errors}},"arm"),H=B(k,N),P=B(E,U),v=I({taskClass:r.class,axis:r.axis,baseline:{n:H.n,passes:H.passes},with:{n:P.n,passes:P.passes},cost:b,provenance:M});return l(`[harbor_ab] ${r.task}: ${v.decision} \u2014 ${v.reason}`),{task:r.task,class:r.class,axis:r.axis,lane:r.lane,model:r.model,...i?{measurement:i}:{},nTrials:r.nTrials,decision:v.decision,reason:v.reason,baseline:H,with:P,rewardDelta:v.reward.delta,rewardCi:v.reward.ci,cost:b?{decision:b.decision,deltaUsd:b.delta_usd,deltaPct:b.delta_pct,ciUsd:b.ci_usd,perSuccess:b.per_success?{decision:b.per_success.decision,deltaPct:b.per_success.delta_pct}:null,rewardRegressed:b.reward.regressed}:null,provenance:M,jobsDir:s,durationMs:n.now()-_}}t(wr,"harborAb");export{Q as a,er as b,wr as c};
@@ -0,0 +1 @@
1
+ import{d as h,e as g}from"./chunk-RRM4HQG4.js";import{e as p,g as f}from"./chunk-ZZHIBOMT.js";import{a as o}from"./chunk-ZLLER3HP.js";var u="openCandidate";function K(n,s,a){let t=(n??{})[u];if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;return e.executionKey!==a||typeof e.content!="string"||!e.content||typeof e.hash!="string"||!e.hash||typeof e.priorHash!="string"||e.priorHash!==s?null:{...a?{executionKey:a}:{},...typeof e.observedKey=="string"?{observedKey:e.observedKey}:{},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(K,"resolveOpenCandidate");function C(n){let{plannedPairs:s,carriedPairs:a,liveCases:t}=n;if(t<=0)return 0;let e=s-a;return e<=0?0:Math.ceil(e/t)}o(C,"owedPasses");var d=100;async function x(n){let{evalTargetId:s,candidateContentHash:a}=n,t=[];for(let e=0;;e+=d){let i=await p(`/api/eval-targets/${s}/runs?candidateContentHash=${encodeURIComponent(a)}&limit=${d}&offset=${e}`);if(!Array.isArray(i)||i.length===0||(t.push(...i.filter(r=>{if(r.outputs?.executionKey!==n.executionKey)return!1;if(!n.executionKey)return!0;if(!n.observedKey)return!1;let l=h([r]);if(!l)return!1;let[y,c]=JSON.parse(l),[b,m]=JSON.parse(n.observedKey);return y===b&&(c===null||c===m)})),i.length<d))break}return g(t)}o(x,"fetchCarriedPairs");async function A(n){let{evalTargetId:s,meta:a,blob:t,log:e,tag:i}=n;try{let r={...a};t?r[u]=t:delete r[u],await f(`/api/eval-targets/${s}`,{metadata:r}),e(t?`${i}: banked candidate ${t.hash.slice(0,8)} \u2014 the next run resumes instead of restarting`:`${i}: cleared the banked candidate (this cycle reached a decision)`)}catch(r){e(`${i}: could not update the candidate bank (${r instanceof Error?r.message:String(r)})`)}}o(A,"bankOpenCandidate");function O(n){return{...n.executionKey?{executionKey:n.executionKey}:{},...n.observedKey?{observedKey:n.observedKey}:{},content:n.content,hash:n.hash,priorHash:n.priorHash,plannedPairs:n.plannedPairs,updatedAt:n.now.toISOString()}}o(O,"buildOpenCandidate");export{u as a,K as b,C as c,x as d,A as e,O as f};
@@ -0,0 +1 @@
1
+ import{a as v}from"./chunk-U2NT5OSQ.js";import{a as u}from"./chunk-GYNZ3OZF.js";import{c as k,e as E}from"./chunk-UPFH72PF.js";import{a}from"./chunk-ZLLER3HP.js";import{mkdirSync as N,readdirSync as h,rmSync as I,writeFileSync as S}from"node:fs";import{join as p,relative as y,sep as _}from"node:path";var b="v2-neutral-workspace";function C(e){return e==="codex"?"v3-codex-project-neutral":b}a(C,"evalMethodology");var T=["CLAUDE.md","CLAUDE.local.md","AGENTS.md"],A=new Set(["node_modules",".git","dist","build",".next","coverage"]),W={claude:{file:u.claude_code,delivery:"claude_md"},codex:{file:u.codex,delivery:"agents_md"},pi:{file:u.codex,delivery:"agents_md"}};function x(e,s="claude"){let n=[],t=new Set(T);s==="codex"&&t.add("AGENTS.override.md");let d=a(i=>{let r;try{r=h(i,{withFileTypes:!0})}catch{return}for(let o of r){let l=p(i,o.name);if(s==="codex"&&[".codex",".agents"].includes(o.name)){n.push(y(e,l));continue}if(o.isDirectory()){if(A.has(o.name)||o.name.startsWith(".")&&o.name!==".claude")continue;d(l)}else t.has(o.name)&&n.push(y(e,l))}},"walk");return d(e),n}a(x,"findAmbientInstructionFiles");function F(e,s){let n=[];for(let t of x(e,s))try{I(p(e,t),{force:!0,recursive:!0}),n.push(t)}catch{}return n}a(F,"stripAmbientInstructions");function O(e){return/[a-z0-9]/i.test(e??"")?k(e??""):"eval-target-skill"}a(O,"skillSlug");function j(e={}){let{baseDir:s,targetType:n,targetContent:t,targetName:d,engine:i="claude"}=e,r=v(s),o=F(r.workDir,i),l="none",m,f=[];if(t)switch(n){case"prompt":m=t,l="system_prompt";break;case"skill":{if(i!=="claude")throw r.cleanup(),new Error(`createEvalWorkspace: a skill target cannot be measured on ${i} \u2014 .claude/skills is read by Claude Code only, so both arms would run without it.`);let c=O(d),g=E({dirName:c,content:t});D(r.workDir,p(".claude","skills",c,"SKILL.md"),g.text),l="skill";break}default:{let{file:c,delivery:g}=W[i];D(r.workDir,c,t),f.push(c),l=g;break}}let w=x(r.workDir,i).filter(c=>!f.includes(c));return{workDir:r.workDir,systemPrompt:m,delivery:l,methodology:C(i),isWorktree:r.isWorktree,strippedFiles:o,leakedFiles:w,cleanup:r.cleanup}}a(j,"createEvalWorkspace");function D(e,s,n){let t=p(e,s),d=t.slice(0,t.lastIndexOf(_));N(d,{recursive:!0}),S(t,n,"utf8")}a(D,"writeFileInWorkspace");export{b as a,C as b,T as c,x as d,O as e,j as f};
@@ -1,4 +1,4 @@
1
- import{e as d}from"./chunk-QWCEZEDO.js";import{a as R,g as v,h as T,j as I,m as C}from"./chunk-OZQNSELV.js";import{d as g}from"./chunk-SBGXIPRN.js";import{e as _}from"./chunk-APDRR6FS.js";import{g as m,l as k}from"./chunk-PZNWH4VQ.js";import{a as i}from"./chunk-ZLLER3HP.js";import{execSync as j}from"node:child_process";import{existsSync as p,readFileSync as y}from"node:fs";import{homedir as f}from"node:os";import{join as a}from"node:path";var P=["install","auth","hooks","worker"],O=["judge"],M=[...P,...O];function $(){return{projectPath:process.cwd(),configDir:k()}}i($,"defaultContext");var A=a(f(),".mitmproxy","mitmproxy-ca-cert.pem");function S(e){if(!e)return"";if(e.length<=8)return"*".repeat(e.length);let t=e.slice(0,4),n=e.slice(-4);return`${t}${"*".repeat(Math.max(4,e.length-8))}${n}`}i(S,"maskToken");function te(e,t){let n=e===null?[]:e.replace(/\n$/,"").split(`
1
+ import{e as d}from"./chunk-QWCEZEDO.js";import{a as R,g as v,h as T,j as I,m as C}from"./chunk-OZQNSELV.js";import{d as g}from"./chunk-SBGXIPRN.js";import{e as _}from"./chunk-ZZHIBOMT.js";import{g as m,l as k}from"./chunk-PZNWH4VQ.js";import{a as i}from"./chunk-ZLLER3HP.js";import{execSync as j}from"node:child_process";import{existsSync as p,readFileSync as y}from"node:fs";import{homedir as f}from"node:os";import{join as a}from"node:path";var P=["install","auth","hooks","worker"],O=["judge"],M=[...P,...O];function $(){return{projectPath:process.cwd(),configDir:k()}}i($,"defaultContext");var A=a(f(),".mitmproxy","mitmproxy-ca-cert.pem");function S(e){if(!e)return"";if(e.length<=8)return"*".repeat(e.length);let t=e.slice(0,4),n=e.slice(-4);return`${t}${"*".repeat(Math.max(4,e.length-8))}${n}`}i(S,"maskToken");function te(e,t){let n=e===null?[]:e.replace(/\n$/,"").split(`
2
2
  `),o=t===null?[]:t.replace(/\n$/,"").split(`
3
3
  `),s=[],u=Math.max(n.length,o.length);for(let c=0;c<u;c++){let l=n[c],r=o[c];l===r?s.push(` ${l}`):(l!==void 0&&s.push(`-${l}`),r!==void 0&&s.push(`+${r}`))}return s.join(`
4
4
  `)}i(te,"renderDiff");function x(e,t){let n=a(e,"env");if(!p(n))return null;try{let s=y(n,"utf-8").match(new RegExp(`^${t}=(.+)$`,"m"));return s?s[1]:null}catch{return null}}i(x,"readEnvValue");async function b(){if(!m())return!1;try{return(await Promise.race([_("/api/setup/status"),new Promise((t,n)=>setTimeout(()=>n(new Error("setup/status timeout")),2500))]))?.workerActive===!0}catch{return!1}}i(b,"workerActive");function E(e,t){let n=a(e,".claude",t),o={},s=null;if(p(n))try{s=y(n,"utf-8").replace(/\n$/,""),o=JSON.parse(s)}catch{o={}}return{settings:o,before:s}}i(E,"readProjectSettings");function D(e){let{settings:t,before:n}=E(e,"settings.local.json");return v(t),{before:n,after:JSON.stringify(t,null,2)}}i(D,"projectHooksSettings");function N(e){let{settings:t,before:n}=E(e,"settings.local.json"),o={...t.env??{}};return o.HTTPS_PROXY=`http://localhost:${d}`,o.NO_PROXY=I,o.NODE_EXTRA_CA_CERTS=A,{before:n,after:JSON.stringify({...t,env:o},null,2)}}i(N,"projectProxyEnvSettings");function U(e){let{settings:t,before:n}=E(e,"settings.json");if(n===null)return null;let{removed:o}=C(t,d);return o?{before:n,after:JSON.stringify(t,null,2)}:null}i(U,"projectSharedSettingsMigration");var Y=a(f(),"Library","LaunchAgents","com.rulemetric.worker.plist"),G=a(f(),".config","systemd","user","rulemetric-worker.service");function h(e){j(e,{stdio:"inherit"})}i(h,"runCommand");var L=[{id:"install",title:"Install the CLI",command:"npm install -g @rulemetric/cli",async detect(){return m()||await b()},async plan(){return{id:"install",title:"Install the CLI",command:"npm install -g @rulemetric/cli",artifacts:[{path:"npm install -g @rulemetric/cli",kind:"command",before:null,after:"rulemetric --version # verifies the binary is on PATH"}]}},async apply(){h("npm install -g @rulemetric/cli")}},{id:"auth",title:"Authenticate",command:"rulemetric auth login",async detect(){return m()},async plan(e){let t=a(e.configDir,"env"),n=null;if(p(t))try{n=X(y(t,"utf-8"))}catch{n="(unreadable)"}let o=x(e.configDir,"RULEMETRIC_ACCESS_TOKEN"),u=[`RULEMETRIC_ACCESS_TOKEN=${S(o||"<token-from-login>")}`],c=x(e.configDir,"RULEMETRIC_API_KEY");c&&u.push(`RULEMETRIC_API_KEY=${S(c)}`);let l=process.env.RULEMETRIC_API_URL;l&&u.push(`RULEMETRIC_API_URL=${l}`);let r=u.join(`
@@ -0,0 +1,48 @@
1
+ import{a as I,b as N}from"./chunk-74QIUVWY.js";import{a as i}from"./chunk-ZLLER3HP.js";function ne(e){return(e.trim().split(`
2
+ `)[0]?.replace(/^#+\s*/,"").trim()||"Suggested instruction").slice(0,120)}i(ne,"recommendationTitle");function oe(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:ne(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(oe,"normalizeRecommendationCandidates");var re=new Set(["instruction"]);function se(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=re.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(se,"deriveLegacyPresentation");function ie(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 ae(e),oe(e),e}i(ie,"normalizeRecommendations");function ae(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(ae,"liftNestedCandidates");import{z as d}from"zod";var P=["org","team","project","personal"],D=d.object({name:d.string().min(1),description:d.string().min(1),type:d.literal("instruction").default("instruction"),scope:d.enum(P),version:d.string().min(1),tags:d.array(d.string()).optional(),compatibility:d.array(d.string()).optional(),slots:d.record(d.string(),d.string()).optional(),metadata:d.record(d.string(),d.unknown()).optional()});import{z as p}from"zod";var j=p.object({name:p.string().min(1),description:p.string().min(1),type:p.literal("prompt"),version:p.string().min(1),tags:p.array(p.string()).optional(),variables:p.array(p.string()).optional(),metadata:p.record(p.string(),p.unknown()).optional()});function _(e,t){let n=t.map(o=>`- ID: ${o.id}
3
+ Name: ${o.name}
4
+ Description: ${o.description}
5
+ Tags: ${o.tags.join(", ")}
6
+ Preview: ${o.contentPreview}`).join(`
7
+
8
+ `);return`You are an expert at matching AI coding instructions to software projects.
9
+
10
+ ## Project
11
+ - Name: ${e.name}
12
+ - Description: ${e.description??"No description"}
13
+ - Languages: ${e.languages.join(", ")||"Unknown"}
14
+ - Topics: ${e.topics.join(", ")||"None"}
15
+ - Dependencies: ${e.dependencies.join(", ")||"None"}
16
+
17
+ ## Available Instructions
18
+
19
+ ${n}
20
+
21
+ ## Task
22
+
23
+ Analyze the project and recommend which instructions would be most useful. Consider:
24
+ 1. Language and framework alignment
25
+ 2. Project purpose and what standards/practices would help
26
+ 3. Security, testing, and quality needs based on the project type
27
+
28
+ Return your response as JSON in this exact format:
29
+ {
30
+ "recommendations": [
31
+ { "instructionId": "<id>", "score": <0.0-1.0>, "reason": "<one sentence explanation>" }
32
+ ]
33
+ }
34
+
35
+ Only include instructions with a relevance score >= ${.5}. Order by score descending. Return valid JSON only, no markdown fences.`}i(_,"buildRecommendationPrompt");var $=32e3,ce={name:"x".repeat(64),description:"x".repeat(256),languages:["TypeScript","Python","Go"],topics:["x".repeat(32)],dependencies:["x".repeat(32)]};function M(e,t={}){if(e.length===0)return[];let n=t.charBudget??$,o=_(ce,[]).length,r=[],s=[],a=0;for(let c of e){let l=le(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(M,"batchCandidatesForPrompt");function le(e){return`- ID: ${e.id}
36
+ Name: ${e.name}
37
+ Description: ${e.description}
38
+ Tags: ${e.tags.join(", ")}
39
+ Preview: ${e.contentPreview}`.length+2}i(le,"renderedSize");var H=["Added","Changed","Fixed","Removed","Deprecated","Security"],ue=/^##\s+\[([^\]]+)\](?:\s*[-–]\s*(\d{4}-\d{2}-\d{2}))?\s*$/,me=/^###\s+(.+?)\s*$/,de=/^[-*]\s+(.*\S)\s*$/,pe=/^ {2,}(\S.*)$/;function fe(e){let t=e.split(/\r?\n/),n=[],o=null,r=null,s=null;for(let a of t){let c=a.match(ue);if(c){o&&n.push(o);let m=c[1].trim();o={version:m,date:c[2]??null,unreleased:m.toLowerCase()==="unreleased",sections:{}},r=null,s=null;continue}if(!o)continue;let l=a.match(me);if(l){let m=l[1].trim();H.includes(m)?(r=m,o.sections[r]||(o.sections[r]=[]),s=o.sections[r]):(r=null,s=null);continue}if(!r||!s)continue;let u=a.match(de);if(u){s.push(u[1]);continue}let f=a.match(pe);if(f&&s.length>0){s[s.length-1]+=" "+f[1].trim();continue}}return o&&n.push(o),{entries:n}}i(fe,"parseChangelog");function he(e){return e.entries.filter(t=>t.unreleased?!1:Object.values(t.sections).some(n=>n&&n.length>0))}i(he,"announceableEntries");function S(e){let t=/^(#{1,6})\s+/.exec(e);return t?t[1].length:0}i(S,"headingLevel");function B(e){return e.replace(/^#{1,6}\s+/,"").replace(/[`*_~]/g,"").trim().toLowerCase()}i(B,"normaliseHeading");function ge(e,t){let n=B(t);if(n.length===0)return{content:e,removed:!1,removedText:null,reason:"not-found"};let o=e.split(`
40
+ `),r=[];for(let m=0;m<o.length;m+=1)S(o[m])>0&&B(o[m])===n&&r.push(m);if(r.length===0)return{content:e,removed:!1,removedText:null,reason:"not-found"};if(r.length>1)return{content:e,removed:!1,removedText:null,reason:"ambiguous"};let s=r[0],a=S(o[s]),c=o.length;for(let m=s+1;m<o.length;m+=1){let E=S(o[m]);if(E>0&&E<=a){c=m;break}}let l=o.slice(s,c).join(`
41
+ `),u=[...o.slice(0,s),...o.slice(c)];return u.join("").trim().length===0?{content:e,removed:!1,removedText:null,reason:"would-empty-file"}:{content:u.join(`
42
+ `).replace(/\n{3,}/g,`
43
+
44
+ `),removed:!0,removedText:l}}i(ge,"removeMarkdownSection");function ye(e,t){let n=t.trim();if(n.length===0)return{content:e,removed:!1,removedText:null,reason:"not-found"};let o=e.indexOf(n);if(o===-1)return{content:e,removed:!1,removedText:null,reason:"not-found"};if(e.indexOf(n,o+1)!==-1)return{content:e,removed:!1,removedText:null,reason:"ambiguous"};let r=(e.slice(0,o)+e.slice(o+n.length)).replace(/\n{3,}/g,`
45
+
46
+ `);return r.trim().length===0?{content:e,removed:!1,removedText:null,reason:"would-empty-file"}:{content:r,removed:!0,removedText:n}}i(ye,"removeExactBlock");var U=["HTTPS_PROXY","HTTP_PROXY","NODE_EXTRA_CA_CERTS"];function xe(e,t){if(!e||typeof e!="object")return{value:e,removed:!1,removedDescriptions:[],reason:"not-found"};let n=structuredClone(e);if(!n.hooks)return{value:n,removed:!1,removedDescriptions:[],reason:"not-found"};let o=[];for(let[r,s]of Object.entries(n.hooks)){if(!Array.isArray(s))continue;let a=s.filter(c=>{let l=(c.hooks??[]).some(u=>typeof u.command=="string"&&u.command.includes(t));return l&&o.push(`${r}: ${c.matcher??"*"} \u2192 ${(c.hooks??[]).map(u=>u.command).join(", ")}`),!l});a.length===0?delete n.hooks[r]:n.hooks[r]=a}return Object.keys(n.hooks).length===0&&delete n.hooks,{value:n,removed:o.length>0,removedDescriptions:o,...o.length===0?{reason:"not-found"}:{}}}i(xe,"removeHookByCommand");function _e(e,t){if(!e||typeof e!="object")return{value:e,removed:!1,removedDescriptions:[],reason:"not-found"};let n=structuredClone(e);return!n.mcpServers||!(t in n.mcpServers)?{value:n,removed:!1,removedDescriptions:[],reason:"not-found"}:(delete n.mcpServers[t],Object.keys(n.mcpServers).length===0&&delete n.mcpServers,{value:n,removed:!0,removedDescriptions:[`mcpServers.${t}`]})}i(_e,"removeMcpServer");function v(e){if(!e||typeof e!="object")return[];let t=e.env;return t?U.filter(n=>n in t):[]}i(v,"protectedEnvKeysPresent");function Ee(e,t){let n=v(e),o=new Set(v(t));return n.filter(r=>!o.has(r))}i(Ee,"lostProtectedEnvKeys");function Se(e,t){let n=`HTTP ${e}`;if(!t||typeof t!="object")return{message:n};let o=t,r=typeof o.error=="string"&&o.error?o.error:o.error?JSON.stringify(o.error):n,s=typeof o.code=="string"&&o.code?o.code:void 0;return s?{message:r,code:s}:{message:r}}i(Se,"parseApiError");var T=["inside","outside"];function y(e){return e.trim().toLowerCase()}i(y,"normalizeDependencyKey");function ve(e){let t=[];if(T.includes(e.boundaryClass)||t.push({field:"boundaryClass",message:`must be one of ${T.join(" | ")}`}),!Array.isArray(e.targets)||e.targets.length===0)t.push({field:"targets",message:"a proposal that cannot name the paths it writes cannot be applied"});else{for(let r of e.targets)if(typeof r!="string"||r.trim().length===0){t.push({field:"targets",message:"target paths must be non-empty"});break}let n=e.targets.filter(r=>typeof r=="string"&&(r.startsWith("/")||/^[A-Za-z]:[\\/]/.test(r)));n.length>0&&t.push({field:"targets",message:`targets must be project-relative (absolute: ${n.join(", ")})`});let o=e.targets.filter(r=>typeof r=="string"&&r.split(/[\\/]/).includes(".."));o.length>0&&t.push({field:"targets",message:`targets must not traverse outside the project (${o.join(", ")})`})}for(let n of["requires","provides"]){let o=e[n];if(!Array.isArray(o)){t.push({field:n,message:"must be an array of dependency keys"});continue}o.some(r=>typeof r!="string"||r.trim().length===0)&&t.push({field:n,message:"dependency keys must be non-empty strings"})}return t}i(ve,"validateArtifactSpec");function Ae(e,t){let n=[],o=new Set(e.targets??[]);if(t.kind==="delete-paths"){e.boundaryClass!=="inside"&&n.push({field:"inverse",message:"deleting paths is only an inverse for `inside` artifacts; an `outside` path may hold text we did not write"}),t.paths.length===0&&n.push({field:"inverse.paths",message:"nothing to delete \u2014 this is not an inverse"});let r=t.paths.filter(s=>!o.has(s));return r.length>0&&n.push({field:"inverse.paths",message:`would delete paths the spec never declared: ${r.join(", ")}`}),n}return e.boundaryClass!=="outside"&&n.push({field:"inverse",message:"a compensation is only an inverse for `outside` artifacts; an `inside` path owes an exact undo"}),(!t.backupPath||t.backupPath.trim().length===0)&&n.push({field:"inverse.backupPath",message:"an `outside` write owes a backup"}),(!t.hashAtWrite||t.hashAtWrite.trim().length===0)&&n.push({field:"inverse.hashAtWrite",message:"without the post-write hash the undo cannot tell a drifted file from an untouched one"}),o.has(t.file)||n.push({field:"inverse.file",message:`wrote ${t.file}, which the spec did not declare as a target`}),t.kind==="remove-marked-region"?(!t.startMarker||!t.endMarker)&&n.push({field:"inverse",message:"an `outside` region needs both markers, or the undo cannot tell where our text ends"}):t.command.trim().length===0&&n.push({field:"inverse.command",message:"the exact command written is the identity of the entry; without it the undo is a search"}),n}i(Ae,"validateArtifactInverse");var z="artifact";function A(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}i(A,"stringArray");function Te(e){if(!e||typeof e!="object")return null;let t=e[z];if(!t||typeof t!="object")return null;let n=t;return{boundaryClass:n.boundaryClass,targets:A(n.targets),requires:A(n.requires),provides:A(n.provides)}}i(Te,"parseArtifactSpec");var be=["applied","measuring","improved","inconclusive","harmful","rollback_ready"];function K(e){return e.appliedAt?e.appliedAt instanceof Date?e.appliedAt.getTime():new Date(e.appliedAt).getTime():0}i(K,"appliedAtMs");function ke(e){return[...e].sort((t,n)=>{let o=K(n)-K(t);return o!==0?o:(n.applySeq??0)-(t.applySeq??0)})}i(ke,"orderForReversal");var Y=["SessionStart","SessionEnd","UserPromptSubmit","PreToolUse","PostToolUse","PreCompact","Notification","Stop","SubagentStop"],b=".claude/settings.local.json";function G(e){return`# rm-artifact:${e}`}i(G,"hookTag");function Ce(e,t){return`${e.trim()} ${G(t)}`}i(Ce,"taggedHookCommand");var Oe=new Set(["if","then","else","elif","fi","for","while","until","do","done","case","esac","function","return","exit","cd","echo","test","true","false"]);function k(e){let t=e.trim().split(/\s+/)[0]??"";return!/^[a-z][a-z0-9_-]*$/.test(t)||Oe.has(t)?null:y(`cmd:${t}`)}i(k,"inferredCommandRequirement");function we(e,t){let n=new Set((t?.requires??[]).map(y).filter(Boolean)),o=k(e.command);return o&&n.add(o),{boundaryClass:"outside",targets:[b],requires:[...n],provides:(t?.provides??[]).map(y).filter(Boolean)}}i(we,"hookArtifactSpec");function x(e){let t=[];Y.includes(e.event)||t.push({field:"event",message:`unknown hook event ${JSON.stringify(e.event)} \u2014 a hook on an event that never fires is indistinguishable from one that was never installed`});let n=(e.command??"").trim();return n.length===0?t.push({field:"command",message:"a hook with no command installs nothing"}):(/[\r\n]/.test(n)&&t.push({field:"command",message:"multi-line commands are refused: the identity tag is a trailing shell comment, which would silence only the final line, and a human reviewing an install should read one line"}),n.includes("\0")&&t.push({field:"command",message:"command contains a NUL byte"}),n.includes("rulemetric")&&t.push({field:"command",message:'refused: `rulemetric hooks uninstall` deletes every hook whose command contains "rulemetric", so installing one here would make this hook collateral damage of an unrelated command'}),n.includes("rm-artifact:")&&t.push({field:"command",message:"command already carries an artifact tag \u2014 installing it would produce two identities for one entry"})),e.matcher!==void 0&&(typeof e.matcher!="string"||e.matcher.trim().length===0)&&t.push({field:"matcher",message:"matcher must be a non-empty string when present"}),t}i(x,"validateHookSpec");function Re(e){let t=[`runs on: ${e.event}${e.matcher?` (tools matching ${e.matcher})`:""}`,`spawns: ${e.command.trim()}`,`writes: ${b} (one entry, tagged with this artifact's id)`],n=k(e.command);return n&&t.push(`needs: ${n} on PATH`),t}i(Re,"describeHookCapability");var q="hook";function h(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}i(h,"asRecord");function F(e){let t=e.event,n=e.command;if(typeof t!="string"||typeof n!="string")return null;let o=typeof e.matcher=="string"?e.matcher:void 0;return{event:t,matcher:o,command:n}}i(F,"readBareSpec");function W(e){let t=h(e.hooks)??e,n=[];for(let[o,r]of Object.entries(t))if(Array.isArray(r))for(let s of r){let a=h(s);if(!a)continue;let c=typeof a.matcher=="string"&&a.matcher.length>0?a.matcher:void 0,l=Array.isArray(a.hooks)?a.hooks:[];for(let u of l){let f=h(u)?.command;typeof f=="string"&&n.push({event:o,matcher:c,command:f})}}return n.length===0?{spec:null,problems:[]}:n.length>1?{spec:null,problems:[{field:"hook",message:`proposal describes ${n.length} hook entries; one proposal installs exactly one hook, so its inverse stays exact and its review stays readable`}]}:{spec:n[0],problems:[]}}i(W,"readSettingsFragment");function Le(e){let t=[],n=/```[a-zA-Z]*\n([\s\S]*?)```/g,o;for(;(o=n.exec(e))!==null;)t.push(o[1]);return t}i(Le,"fencedBlocks");function Ie(e){let t=h(h(e.frontmatter)?.artifact),n=t?h(t[q]):null;if(n){let o=F(n);if(o)return{spec:o,problems:x(o),source:"envelope"};let r=W(n);if(r.spec)return{spec:r.spec,problems:x(r.spec),source:"envelope"};if(r.problems.length>0)return{spec:null,problems:r.problems,source:"envelope"}}for(let o of Le(e.content??"")){let r;try{r=JSON.parse(o)}catch{continue}let s=h(r);if(!s)continue;let a=F(s);if(a)return{spec:a,problems:x(a),source:"content-fragment"};let c=W(s);if(c.spec)return{spec:c.spec,problems:x(c.spec),source:"content-fragment"};if(c.problems.length>0)return{spec:null,problems:c.problems,source:"content-fragment"}}return{spec:null,problems:[{field:"hook",message:"no hook spec found \u2014 a hook proposal must carry {event, command} in its artifact envelope or a JSON settings fragment in its body"}],source:"none"}}i(Ie,"parseHookSpec");var V=25,C=N,X=[{task:"rm-batch-task",instructions:"rm-batch-task/inject.md",class:"proven",axis:"reward",measured:"2026-09-02 n=25/arm Haiku 4.5: 0/25 \u2192 25/25, delta +1.000, 95% CI [+0.734, +1.000]"},{task:"rm-locality-task",instructions:"rm-locality-task/inject.md",class:"proven",axis:"cost",measured:"2026-09-02 n=25/arm Haiku 4.5: 25/25 both arms, cost \u221225.6%/trial, 95% CI [\u22120.0171, \u22120.0107]"},{task:"rm-migrations-task",instructions:"rm-migrations-task/inject.md",class:"negative",axis:"reward",measured:"2026-08-31 Haiku 4.5: flat after two reworks \u2014 redundant with the model's priors on this shape"},{task:"rm-pagination-task",instructions:"rm-pagination-task/inject.md",class:"negative",axis:"reward",measured:"2026-09-02 n=25/arm Haiku 4.5: 25/25 baseline under --allowedTools Bash; the rule costs +8.0%/trial and buys nothing"}];function Ne(e){return X.filter(t=>t.class===e)}i(Ne,"harborTasksOfClass");function J(e,t){return t?.engine==="codex"&&e.axis==="cost"?`${e.task}: dollar-cost telemetry is unavailable for Codex; reward calibration remains supported`:null}i(J,"harborTaskSupport");function Pe(e,t,n=null){let o=n?I.parse(n):null,r=J(e,o);if(r)throw new Error(r);let s=!o||o.engine==="claude"&&o.model===C;return{task:e.task,instructions:e.instructions,class:s?e.class:"unvalidated",axis:e.axis,model:o?.model??C,...o?{measurement:o}:{},nTrials:V,lane:t}}i(Pe,"harborPayloadFor");var De=/[\p{L}\p{N}]+/gu;function O(e){let t=new Set;for(let n of e.toLowerCase().matchAll(De)){let o=` ${n[0]} `;for(let r=0;r+3<=o.length;r+=1)t.add(o.slice(r,r+3))}return t}i(O,"trigrams");function g(e,t){let n=O(e),o=O(t);if(n.size===0||o.size===0)return 0;let r=0,[s,a]=n.size<=o.size?[n,o]:[o,n];for(let l of s)a.has(l)&&(r+=1);let c=n.size+o.size-r;return c===0?0:r/c}i(g,"trigramSimilarity");var R=.3,je=15;function w(e){let n=e.replace(/<!--[\s\S]*?-->/g," ").replace(/```[\s\S]*?```/g," "),o=[];for(let r of n.split(`
47
+ `)){let s=r.trim();if(s.length===0||s.startsWith("#"))continue;let a=s.replace(/^(?:[-*+]|\d+[.)])\s+/,"").trim();if(a.length!==0)for(let c of a.split(/(?<=[.!?])\s+(?=[A-Z(`"'*])/)){let l=c.trim();l.length>=je&&o.push(l)}}return o}i(w,"splitDirectives");function Z(e,t,n=R){let o=w(e);if(o.length===0)return{redundant:!1,coverage:0,matches:[],novel:[]};let r=t.flatMap(c=>w(c.content).map(l=>({text:l,id:c.id,source:c.source}))),s=[],a=[];for(let c of o){let l=null;for(let u of r){let f=g(c,u.text);f<n||(l===null||f>l.similarity)&&(l={directive:c,matchedDirective:u.text,matchedId:u.id,matchedSource:u.source,similarity:f})}l?s.push(l):a.push(c)}return{redundant:a.length===0,coverage:s.length/o.length,matches:s,novel:a}}i(Z,"assessRedundancy");function $e(e,t=R){let n=[];for(let o=0;o<e.length;o+=1){let r=Z(e[o].content,e.slice(0,o),t);r.matches.length>0&&n.push({instruction:e[o],verdict:r})}return n}i($e,"findInternalRedundancy");var Q=.5,Me=/-(?=[0-9a-f]{6}$)[0-9a-f]*[0-9][0-9a-f]*$/;function L(e){return e.trim().toLowerCase().replace(/^skills--/,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").replace(Me,"").replace(/-+$/,"")}i(L,"skillNameStem");function He(e,t,n=Q){let o=L(e.name);for(let s of t)if(o.length>0&&L(s.name)===o)return{name:s.name,similarity:g(e.content,s.content),reason:"name-stem"};let r=null;for(let s of t){let a=g(e.content,s.content);a<n||(r===null||a>r.similarity)&&(r={name:s.name,similarity:a,reason:"body"})}return r}i(He,"assessSkillDuplication");var Be=new Set(["sh","bash","zsh","fish"]),Ue=new Set(["mjs","cjs","js","ts","py","rb","pl"]),Ke=/(?:^|[\s(`'"])(?:sudo\s+)?(?:node|npx|pnpm|npm|yarn|bun|deno|tsx|ts-node|vitest|jest|python3?|python|ruby|perl|bash|sh|zsh|exec|run|dlx)\s+(?:[-\w=@./]+\s+)*$/,ze=/(?:\.\/)?(?:[\w.@-]+\/)+[\w.@-]+\.\w+/g;function Fe(e){return e.replace(/```[\w-]*\n?/g," ").replace(/`/g," ")}i(Fe,"stripCodeMarkers");function We(e){let t=e.trim();return t=t.replace(/[.,;:)\]]+$/,""),t.startsWith("./")&&(t=t.slice(2)),t.length===0||t.startsWith("/")||t.startsWith("~")||t.startsWith("..")||/[<>{}*?]/.test(t)?null:t}i(We,"normalise");function ee(e){let t=Fe(e),n=new Set,o=[];for(let r of t.matchAll(ze)){let s=r[0],a=r.index??0,c=t.slice(Math.max(0,a-1),a);if(c.length>0&&!/[\s(['"=]/.test(c))continue;let l=We(s);if(!l)continue;let u=l.slice(l.lastIndexOf(".")+1).toLowerCase();(Be.has(u)||Ue.has(u)&&(s.startsWith("./")||Ke.test(t.slice(t.lastIndexOf(`
48
+ `,Math.max(0,a-1))+1,a))))&&(n.has(l)||(n.add(l),o.push({reference:s,path:l})))}return o}i(ee,"extractCommandReferences");function Ye(e,t){return ee(e).filter(n=>!t(n.path))}i(Ye,"findUnresolvableReferences");import Yt from"gray-matter";import{z as te}from"zod";var Xt=te.object({type:te.enum(["instruction","prompt"])});export{se as a,ie as b,_ as c,M as d,fe as e,he as f,ge as g,ye as h,xe as i,_e as j,Ee as k,Se as l,y as m,ve as n,Ae as o,Te as p,be as q,ke as r,b as s,G as t,Ce as u,we as v,Re as w,Ie as x,C as y,Ne as z,J as A,Pe as B,w as C,Z as D,$e as E,He as F,Ye as G};
@@ -1 +1 @@
1
- import{b as g}from"./chunk-3ZHVP3KE.js";import{d as k,e as h}from"./chunk-GBWQENAH.js";import{e as m,i as f}from"./chunk-APDRR6FS.js";import{a as c}from"./chunk-ZLLER3HP.js";import{existsSync as b}from"node:fs";async function w($,y){let r=c(t=>y?.logger?.info?.(t)??console.log(t),"log"),{projectPath:s}=$,n=`[cron_retire_unused_skills] ${s}`;if(!s||!b(s))return{skipped:"project-missing",reason:`${s} does not exist on this machine \u2014 refusing to delete files for a project that is not here.`};let o=await m("/api/insights/groom-candidates"),e=g({captureHealthy:o.skillCaptureHealthy===!0,captureReason:o.skillCaptureHealthy===void 0?"API did not report skill capture health (older deployment)":o.skillCaptureReason,candidates:o.unusedSkills??[]});if(e.refused)return r(`${n} ${e.refused}: ${e.summary}`),{skipped:e.refused,reason:e.summary,held:e.held.length};r(`${n} ${e.summary}`);let a=[],d=[],l=0;for(let t of e.retire){let u=k({kind:"skill_file",target:t.name,cwd:s});if(!u.ok){l+=1,r(`${n} could not plan removal of ${t.name}: ${u.refusal??"unresolved"}`);continue}let R=new Date().toISOString().replace(/[:.]/g,"-"),i=h(u,R);if(!i.applied){l+=1,r(`${n} failed to remove ${t.name}: ${i.error??"unknown error"}`);continue}a.push(t.name),i.backupPath&&d.push(i.backupPath),r(`${n} retired ${t.name} (backup: ${i.backupPath??"none"})`);try{await f(`/api/instructions/${t.instructionId}`)}catch(p){r(`${n} removed ${t.name} but could not archive its instruction row: ${p instanceof Error?p.message:String(p)}`)}}return{retired:a.length,failed:l,held:e.held.length,names:a,backups:d,reason:e.summary}}c(w,"cronRetireUnusedSkills");export{w as a};
1
+ import{b as g}from"./chunk-3ZHVP3KE.js";import{d as k,e as h}from"./chunk-O62OLKQL.js";import{e as m,i as f}from"./chunk-ZZHIBOMT.js";import{a as c}from"./chunk-ZLLER3HP.js";import{existsSync as b}from"node:fs";async function w($,y){let r=c(t=>y?.logger?.info?.(t)??console.log(t),"log"),{projectPath:s}=$,n=`[cron_retire_unused_skills] ${s}`;if(!s||!b(s))return{skipped:"project-missing",reason:`${s} does not exist on this machine \u2014 refusing to delete files for a project that is not here.`};let o=await m("/api/insights/groom-candidates"),e=g({captureHealthy:o.skillCaptureHealthy===!0,captureReason:o.skillCaptureHealthy===void 0?"API did not report skill capture health (older deployment)":o.skillCaptureReason,candidates:o.unusedSkills??[]});if(e.refused)return r(`${n} ${e.refused}: ${e.summary}`),{skipped:e.refused,reason:e.summary,held:e.held.length};r(`${n} ${e.summary}`);let a=[],d=[],l=0;for(let t of e.retire){let u=k({kind:"skill_file",target:t.name,cwd:s});if(!u.ok){l+=1,r(`${n} could not plan removal of ${t.name}: ${u.refusal??"unresolved"}`);continue}let R=new Date().toISOString().replace(/[:.]/g,"-"),i=h(u,R);if(!i.applied){l+=1,r(`${n} failed to remove ${t.name}: ${i.error??"unknown error"}`);continue}a.push(t.name),i.backupPath&&d.push(i.backupPath),r(`${n} retired ${t.name} (backup: ${i.backupPath??"none"})`);try{await f(`/api/instructions/${t.instructionId}`)}catch(p){r(`${n} removed ${t.name} but could not archive its instruction row: ${p instanceof Error?p.message:String(p)}`)}}return{retired:a.length,failed:l,held:e.held.length,names:a,backups:d,reason:e.summary}}c(w,"cronRetireUnusedSkills");export{w as a};
@@ -1,4 +1,4 @@
1
- import{f as p}from"./chunk-HLNHBZLI.js";import{a as l}from"./chunk-ZLLER3HP.js";var k=[{name:"git-commit-helper",description:"Writes conventional commit messages and PR descriptions from a diff"},{name:"sql-query-optimizer",description:"Analyzes slow SQL queries and proposes indexes and rewrites"},{name:"i18n-string-extractor",description:"Finds hardcoded UI strings and extracts them into translation files"}],T=`You are an AI coding assistant with access to a set of optional skills. When a user request matches a skill's description, you invoke that skill before answering; when no skill applies, you answer directly without one. Descriptions are your ONLY information about each skill.
1
+ import{f as p}from"./chunk-UJ7EPLKC.js";import{a as l}from"./chunk-ZLLER3HP.js";var k=[{name:"git-commit-helper",description:"Writes conventional commit messages and PR descriptions from a diff"},{name:"sql-query-optimizer",description:"Analyzes slow SQL queries and proposes indexes and rewrites"},{name:"i18n-string-extractor",description:"Finds hardcoded UI strings and extracts them into translation files"}],T=`You are an AI coding assistant with access to a set of optional skills. When a user request matches a skill's description, you invoke that skill before answering; when no skill applies, you answer directly without one. Descriptions are your ONLY information about each skill.
2
2
 
3
3
  {{CATALOG}}
4
4
 
@@ -0,0 +1 @@
1
+ import{d as _}from"./chunk-PUX6P5KC.js";import{d as D}from"./chunk-SG4UDDHB.js";import{c as P,d as w}from"./chunk-SBGXIPRN.js";import{a as l}from"./chunk-ZLLER3HP.js";import{spawn as L}from"node:child_process";var E=["claude","codex","pi"];function A(e,t=process.env){if(e){if(E.includes(e))return e;throw new Error(`Eval engine "${String(e)}" is not known (expected one of: ${E.join(", ")})`)}let o=t.RULEMETRIC_EVAL_ENGINE?.trim().toLowerCase();if(!o)return"claude";if(E.includes(o))return o;throw new Error(`RULEMETRIC_EVAL_ENGINE="${t.RULEMETRIC_EVAL_ENGINE}" is not a known engine (expected one of: ${E.join(", ")})`)}l(A,"resolveEvalEngine");function N(e,t=process.env){return e?.trim()||t.RULEMETRIC_CODEX_MODEL?.trim()||w().codexConfiguredModel||P}l(N,"resolveCodexEvalModel");function h(e){try{let t=JSON.parse(e),o=t.result??t.content??e,u=t.usage?.total_tokens??(t.usage?.input_tokens??0)+(t.usage?.output_tokens??0),r;if(t.modelUsage&&typeof t.modelUsage=="object"){let n=-1;for(let[a,d]of Object.entries(t.modelUsage)){let s=typeof d?.outputTokens=="number"?d.outputTokens:0;s>n&&(n=s,r=a)}}return{output:o,totalTokens:u,model:r}}catch{return{output:e,totalTokens:0}}}l(h,"parseClaudeJsonOutput");function S(e){let{prompt:t,targetContent:o,systemPrompt:u,model:r}=e,n=["-p",t,"--output-format","json","--settings",JSON.stringify({disableAllHooks:!0})],a=o??u;return a&&n.push("--system-prompt",a),r&&n.push("--model",r),n}l(S,"buildClaudeArgs");function U(e,t,o,u){let r=t.trim()||o.trim()||u.trim()||"(no output on stderr or stdout)";return`Exit code ${e}: ${r.slice(0,1e3)}`}l(U,"describeExitFailure");async function I(e){let{prompt:t,targetContent:o,systemPrompt:u,workDir:r,timeout:n,model:a}=e,d=o??u,s=await D({prompt:t,systemPrompt:d,model:N(a),timeout:n,workDir:r});return{output:s.output,exitCode:s.exitCode,durationMs:s.durationMs,totalTokens:s.usage?.totalTokens??0,model:s.model,engine:"codex",delivery:d?"prompt_prefix":"none",error:s.error}}l(I,"executeCodexArm");async function $(e){let t=e.targetContent??e.systemPrompt,o=await _({prompt:e.prompt,systemPrompt:t,model:e.model,timeout:e.timeout,workDir:e.workDir});return{output:o.output,exitCode:o.exitCode,durationMs:o.durationMs,totalTokens:o.usage?.totalTokens??0,model:o.model,provider:o.provider,costUsd:o.costUsd,engine:"pi",delivery:t?"system_prompt":"none",error:o.error}}l($,"executePiArm");async function H(e){let{prompt:t,targetContent:o,systemPrompt:u,workDir:r=process.cwd(),timeout:n=12e4,model:a}=e,d=A(e.engine);if(d==="codex")return I({...e,workDir:r,timeout:n});if(d==="pi")return $({...e,workDir:r,timeout:n});let s=S({prompt:t,targetContent:o,systemPrompt:u,model:a}),g=o??u?"system_prompt":"none",f=Date.now();return new Promise(v=>{let p={...process.env};delete p.CLAUDECODE,delete p.HTTPS_PROXY;let b=["/opt/homebrew/bin","/usr/local/bin"],x=(p.PATH??"").split(":").filter(Boolean),y=b.filter(i=>!x.includes(i));y.length&&(p.PATH=[...x,...y].join(":"));let m=L("claude",s,{cwd:r,env:p,stdio:["ignore","pipe","pipe"]}),c="",C="";m.stdout.on("data",i=>{c+=i.toString()}),m.stderr.on("data",i=>{C+=i.toString()});let T=setTimeout(()=>{m.kill("SIGTERM"),v({output:c,exitCode:null,durationMs:Date.now()-f,totalTokens:0,engine:"claude",delivery:g,error:`Timed out after ${n}ms`})},n);m.on("close",i=>{clearTimeout(T);let M=Date.now()-f,{output:k,totalTokens:O,model:R}=h(c);v({output:k,exitCode:i,durationMs:M,totalTokens:O,model:R,engine:"claude",delivery:g,error:i!==0?U(i,C,k,c):void 0})}),m.on("error",i=>{clearTimeout(T),v({output:"",exitCode:null,durationMs:Date.now()-f,totalTokens:0,engine:"claude",delivery:g,error:`Failed to spawn claude: ${i.message}`})})})}l(H,"executeEval");export{A as a,N as b,h as c,S as d,U as e,H as f};
@@ -1 +1 @@
1
- import{b as t,e as E}from"./chunk-H3BCWSYO.js";import{a as r}from"./chunk-ZLLER3HP.js";function s(o=10,_=t){for(let e=1;e<=o;e++)if(E(e,o,_).feasible)return e;return o}r(s,"minFeasibleLiveCases");var S=s(),A=3;export{s as a,S as b,A as c};
1
+ import{b as t,e as E}from"./chunk-S5U76YUI.js";import{a as r}from"./chunk-ZLLER3HP.js";function s(o=10,_=t){for(let e=1;e<=o;e++)if(E(e,o,_).feasible)return e;return o}r(s,"minFeasibleLiveCases");var S=s(),A=3;export{s as a,S as b,A as c};
@@ -1 +1 @@
1
- import{c as u}from"./chunk-5XK6LB2T.js";import{b as c,e as y,f as m}from"./chunk-APDRR6FS.js";import{a as n,b as t,i as s,k as p}from"./chunk-PZNWH4VQ.js";import{a}from"./chunk-ZLLER3HP.js";import{hostname as l}from"node:os";async function R(f,r,h){t();let o=process.env.RULEMETRIC_API_KEY,d=n().apiKey;if(o||d)try{await y("/api/profile");return}catch(e){if(!(e instanceof c)||e.statusCode!==401)return;if(o){r('Your exported RULEMETRIC_API_KEY was rejected (revoked?). Unset it or replace it with a fresh key (`rulemetric auth create-key --name "my-laptop"`).');return}p(),t(),r("Stored API key was rejected (revoked?) \u2014 replacing it with a fresh one.")}let i=`${l()} (auto)`;try{let e=await m("/api/auth/api-keys",{name:i});s(e.key,process.env.RULEMETRIC_API_URL),t(),f(`Created API key "${i}" for hooks + proxy auth (saved to your config).`),u("key_created",{},h)}catch(e){let k=e instanceof Error?e.message:String(e);r(`Could not auto-create an API key (${k}). Hooks/proxy will work via your session token for ABOUT AN HOUR \u2014 the token expires, and capture then stops until a key exists. Run \`rulemetric auth create-key --name "my-laptop"\` (or \`rulemetric auth login\` again) to fix this permanently.`)}}a(R,"ensureDeviceApiKey");export{R as a};
1
+ import{c as u}from"./chunk-E5YE25QG.js";import{b as c,e as y,f as m}from"./chunk-ZZHIBOMT.js";import{a as n,b as t,i as s,k as p}from"./chunk-PZNWH4VQ.js";import{a}from"./chunk-ZLLER3HP.js";import{hostname as l}from"node:os";async function R(f,r,h){t();let o=process.env.RULEMETRIC_API_KEY,d=n().apiKey;if(o||d)try{await y("/api/profile");return}catch(e){if(!(e instanceof c)||e.statusCode!==401)return;if(o){r('Your exported RULEMETRIC_API_KEY was rejected (revoked?). Unset it or replace it with a fresh key (`rulemetric auth create-key --name "my-laptop"`).');return}p(),t(),r("Stored API key was rejected (revoked?) \u2014 replacing it with a fresh one.")}let i=`${l()} (auto)`;try{let e=await m("/api/auth/api-keys",{name:i});s(e.key,process.env.RULEMETRIC_API_URL),t(),f(`Created API key "${i}" for hooks + proxy auth (saved to your config).`),u("key_created",{},h)}catch(e){let k=e instanceof Error?e.message:String(e);r(`Could not auto-create an API key (${k}). Hooks/proxy will work via your session token for ABOUT AN HOUR \u2014 the token expires, and capture then stops until a key exists. Run \`rulemetric auth create-key --name "my-laptop"\` (or \`rulemetric auth login\` again) to fix this permanently.`)}}a(R,"ensureDeviceApiKey");export{R as a};
@@ -1,2 +1,2 @@
1
- import{a as m}from"./chunk-QXPYGN7I.js";import{a as n}from"./chunk-ZLLER3HP.js";import{copyFileSync as y,mkdirSync as x,readFileSync as S,writeFileSync as w}from"node:fs";import{homedir as f}from"node:os";import{isAbsolute as h,join as l,resolve as b}from"node:path";function a(e){return l(e,m)}n(a,"captureConfigPath");function v(e){let r;try{r=S(a(e),"utf-8")}catch{return{}}try{let t=JSON.parse(r);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("not a JSON object");return t}catch(t){throw new Error(`${a(e)} is not valid JSON (${t instanceof Error?t.message:String(t)}). Fix or delete it \u2014 refusing to overwrite what you wrote.`)}}n(v,"readCaptureConfig");function F(e,r){x(e,{recursive:!0});let t=a(e);return w(t,JSON.stringify(r,null,2)+`
1
+ import{a as m}from"./chunk-QI3FJKGK.js";import{a as n}from"./chunk-ZLLER3HP.js";import{copyFileSync as y,mkdirSync as x,readFileSync as S,writeFileSync as w}from"node:fs";import{homedir as f}from"node:os";import{isAbsolute as h,join as l,resolve as b}from"node:path";function a(e){return l(e,m)}n(a,"captureConfigPath");function v(e){let r;try{r=S(a(e),"utf-8")}catch{return{}}try{let t=JSON.parse(r);if(!t||typeof t!="object"||Array.isArray(t))throw new Error("not a JSON object");return t}catch(t){throw new Error(`${a(e)} is not valid JSON (${t instanceof Error?t.message:String(t)}). Fix or delete it \u2014 refusing to overwrite what you wrote.`)}}n(v,"readCaptureConfig");function F(e,r){x(e,{recursive:!0});let t=a(e);return w(t,JSON.stringify(r,null,2)+`
2
2
  `),t}n(F,"writeCaptureConfig");function C(e,r=f()){let t=e.trim(),s=t==="~"?r:t.startsWith("~/")?l(r,t.slice(2)):t;return b(s)}n(C,"normaliseRoot");function N(e,r=f()){let t=e.trim();if(!t)return!1;let s=t==="~"?r:t.startsWith("~/")?l(r,t.slice(2)):t;return h(s)}n(N,"isUsableRoot");function j(e,r,t=f(),s="codex"){let o={...e[s]??{}},u=Array.isArray(o.roots)?o.roots.map(i=>C(String(i),t)):[],g=!1;if(r.op==="mode")o.mode=r.mode,r.mode==="all"&&delete o.roots;else if(r.op==="clear")delete o.mode,delete o.roots;else{let i=r.roots.map(c=>C(c,t)),d=r.op==="add"?[...new Set([...u,...i])]:u.filter(c=>!i.includes(c));d.length===0&&r.op==="remove"?(delete o.roots,o.mode="off",g=!0):(o.roots=d.sort(),o.mode="allowlist")}let p={...e};return Object.keys(o).length===0?delete p[s]:p[s]=o,{config:p,emptiedToOff:g}}n(j,"applyScopeEdit");function J(e){let r=a(e),t=`${r}.broken`;try{y(r,t)}catch{}return t}n(J,"backupUnparseableConfig");export{a,v as b,F as c,C as d,N as e,j as f,J as g};
@@ -1,4 +1,4 @@
1
- import{g as E}from"./chunk-U3XKXJ3A.js";import{a as r}from"./chunk-ZLLER3HP.js";var g="<<<FILE-CONTENT-BEGIN>>>",m="<<<FILE-CONTENT-END>>>",b="<RATIONALE>",R="</RATIONALE>",u="<PROPOSED_INSTRUCTION>",p="</PROPOSED_INSTRUCTION>",d=.5,f=3;function y(e){let t=e.immutableSections.length>0?e.immutableSections.map(s=>` - ${s}`).join(`
1
+ import{h as E}from"./chunk-GN46S7T4.js";import{a as r}from"./chunk-ZLLER3HP.js";var g="<<<FILE-CONTENT-BEGIN>>>",m="<<<FILE-CONTENT-END>>>",b="<RATIONALE>",R="</RATIONALE>",u="<PROPOSED_INSTRUCTION>",p="</PROPOSED_INSTRUCTION>",d=.5,f=3;function y(e){let t=e.immutableSections.length>0?e.immutableSections.map(s=>` - ${s}`).join(`
2
2
  `):" (none)",o=e.evidence.priorDecisions.length>0?["6. You have edited this file before. The attempts are listed below with"," how each was judged. Do not re-propose an edit that was MEASURED and"," rejected: it was replayed against this exact file and did not beat it,"," so measuring it again spends the same budget for the same answer. An"," attempt marked NOT MEASURED is different \u2014 the gate stopped it before"," it earned a verdict, so whether it would have helped is still unknown."]:[],n=e.currentContent.trim().length,i=` It is currently ${n} characters. Your proposal must stay between ${Math.ceil(n*d)} and ${Math.floor(n*f)} characters \u2014 outside that it is discarded unmeasured as a truncation or runaway rewrite.`;return["You are improving an AI coding assistant instruction file so that it scores","better on a fixed set of evaluation cases.","",`The file is a ${e.targetType} named "${e.targetName}".`,i,"","RULES",`0. The current file is EXACTLY the text between ${g} and`,` ${m} in the data message. Headings after the closing`," sentinel (underperforming cases, notes, prior attempts) are evidence",' ABOUT the file \u2014 they are not in the file, and "removing" one of them'," is not an edit. Do not include the sentinels in your output.","1. Return the COMPLETE new file, not a diff, not a patch, not a summary,"," and not an excerpt. Everything you omit will be DELETED from the file.","2. Preserve everything you are not deliberately changing, byte for byte.","3. Make a focused edit. You are one step in a measured loop: a small change"," that can be attributed beats a rewrite that cannot.","4. Do not edit these sections or anything nested under them \u2014 an edit that"," touches them is refused downstream and the whole proposal is wasted:",t,"5. Do not add meta-commentary about the evaluation, the loop, or this"," prompt to the file. The file is read by other agents as instructions.",...o,"","OUTPUT FORMAT \u2014 exactly this, with no text before or after:",b,"One or two sentences: what you changed and which evidence motivated it.",R,u,"The complete new file content.",p].join(`
3
3
  `)}r(y,"buildProposerSystemPrompt");var h=r(e=>`${e>=0?"+":"-"}${Math.abs(e*100).toFixed(1)}pp`,"signedPp");function O(e){let t=/^\d{4}-\d{2}-\d{2}/.exec(e.at??"")?.[0]??"undated",o;if(e.measured){let i=e.measured;o=`MEASURED against this exact file and ${e.decision==="promote"?"ACCEPTED":"REJECTED"}: ${h(i.delta)} (CI ${h(i.ciLower)} to ${h(i.ciUpper)}, ${i.nPairs} paired cases)`}else o=`NOT MEASURED \u2014 the gate refused it, so its merit is still unknown: ${e.refusals.length>0?e.refusals.join("; "):"no reason recorded"}`;let n=[`- ${t} \u2014 ${o}`];return e.decision==="promote"&&n.push(e.applied?" The file WAS rewritten by this decision.":" Dry run: the file was NOT rewritten, so this edit is still available."),e.touched.length>0&&n.push(` Sections touched: ${e.touched.join(", ")}`),e.rationale.trim()!==""&&n.push(` You said at the time: ${e.rationale.trim()}`),n.join(`
4
4
  `)}r(O,"describePriorDecision");function P(e){let t=e.evidence,o=["## CURRENT FILE CONTENT","","The file is EXACTLY the text between the two sentinel lines below \u2014","nothing before the first sentinel or after the second is part of it.","Everything after the closing sentinel is evidence ABOUT the file.","",g,e.currentContent,m,""];if(t.weakest.length>0){o.push("## CASES WHERE THIS FILE CURRENTLY UNDERPERFORMS","");for(let n of t.weakest)o.push(`- ${n.name}: passes ${(n.withPassRate*100).toFixed(0)}% with the file vs ${(n.withoutPassRate*100).toFixed(0)}% without it`);o.push("")}return t.nonDiscriminating.length>0&&o.push("## CASES THAT CARRY NO SIGNAL EITHER WAY","","These score the same with and without the file. Changing the file to chase","them is unlikely to move anything.","",...t.nonDiscriminating.map(n=>`- ${n}`),""),t.priorDecisions.length>0&&o.push("## WHAT YOU ALREADY PROPOSED FOR THIS FILE, AND HOW IT WAS JUDGED","","Newest first. Every attempt listed here was made against the file above,","byte for byte. Attempts against a different version of the file are not","shown, because a verdict earned by different text says nothing about this","one.","",...t.priorDecisions.map(O),""),t.notes.length>0&&o.push("## NOTES","",...t.notes.map(n=>`- ${n}`),""),o.join(`
@@ -0,0 +1 @@
1
+ import{a as k}from"./chunk-OO2ZRKZY.js";import{b as P}from"./chunk-VBXL7XO7.js";import{f as b}from"./chunk-UJ7EPLKC.js";import{b as g,e as f,h}from"./chunk-ZZHIBOMT.js";import{a as c}from"./chunk-ZLLER3HP.js";var v=c(u=>(u.summary.pass_rate??0)>=1?1:0,"fullPassScore");async function _(u,a={}){let y=a.executeEval??b,w=a.grade??k,T=a.getExperiment??(async r=>{try{return await f(`/api/memory-experiments/${r}`)}catch(t){if(t instanceof g&&t.statusCode===404)return null;throw t}}),M=a.getMemoryBody??(async r=>{try{return(await f(`/api/memories/${r}`)).body}catch(t){if(t instanceof g&&t.statusCode===404)return null;throw t}}),l=a.updateExperiment??(async(r,t)=>{await h(`/api/memory-experiments/${r}`,t)}),e=await T(u.experimentId);if(!e)return{skipped:"not_found"};if(e.status==="completed"||e.status==="failed")return{skipped:"already_terminal",status:e.status};let x=await M(e.memoryId);if(x==null)return await l(e.id,{status:"failed",error:"memory no longer exists"}),{skipped:"memory_gone",status:"failed"};await l(e.id,{status:"running"});let E=e.expectations??[],d=e.model??void 0,i=e.engine??"claude",s=[],m=new Set,p=0;try{for(let t=0;t<e.trials;t++){let o=await y({prompt:e.taskPrompt,targetContent:x,model:d,engine:i}),n=await y({prompt:e.taskPrompt,model:d,engine:i});if(o.error||n.error){p++;continue}if(o.engine&&o.engine!==i||n.engine&&n.engine!==i||o.model&&n.model&&o.model!==n.model){p++;continue}o.model&&m.add(o.model),n.model&&m.add(n.model);let[C,U]=await Promise.all([w({prompt:e.taskPrompt,output:o.output,expectations:E,model:d}),w({prompt:e.taskPrompt,output:n.output,expectations:E,model:d})]);s.push({withScore:v(C),withoutScore:v(U),withLatency:o.durationMs/1e3,withoutLatency:n.durationMs/1e3,withTokens:o.totalTokens,withoutTokens:n.totalTokens,...o.costUsd!==void 0?{withCostUsd:o.costUsd}:{},...n.costUsd!==void 0?{withoutCostUsd:n.costUsd}:{}})}if(s.length===0){let t=`no trials completed (${p}/${e.trials} runs errored \u2014 is the ${i} CLI available?)`;return await l(e.id,{status:"failed",error:t}),{status:"failed",requestedTrials:e.trials,completedTrials:0}}let r=P(s);return await l(e.id,{status:"completed",result:{verdict:r,pairs:s,completedTrials:s.length,engine:i,model:m.size===1?[...m][0]:d??null}}),{status:"completed",requestedTrials:e.trials,completedTrials:s.length,significant:r.significant,delta:r.delta}}catch(r){let t=r instanceof Error?r.message:String(r);return await l(e.id,{status:"failed",error:t.slice(0,500)}).catch(()=>{}),{status:"failed",requestedTrials:e.trials,completedTrials:s.length}}}c(_,"processMemoryAb");export{_ as a};
@@ -1,4 +1,4 @@
1
- import{d as b,f as y}from"./chunk-U3XKXJ3A.js";import{e as M,f as w}from"./chunk-APDRR6FS.js";import{a as u}from"./chunk-ZLLER3HP.js";var $={anthropic:["https://platform.claude.com/docs/en/about-claude/pricing.md"],openai:["https://platform.openai.com/docs/pricing"]},R=.7,v=16e3,x=["You extract LLM API pricing from a provider pricing page.","You will be given the page text in <data> tags and, in this system prompt,","a list of model ids to find. For EACH requested model id, return its","published USD price per 1,000,000 tokens.","","Rules:","- Only report a model if you can find its rate ON THE PAGE. If it is not on"," the page, set found=false and omit the numbers \u2014 never guess from memory.","- inputPerM and outputPerM are the standard (non-batch, non-priority) rates.","- cacheReadPerM: the cached/discounted-input rate if published, else omit.","- For Anthropic models ONLY, if cache-write rates are not explicitly listed,"," compute them as cacheWrite5mPerM = inputPerM * 1.25 and"," cacheWrite1hPerM = inputPerM * 2.0. For all other providers, omit them.","- confidence is 0..1: how sure you are the numbers are correct for THIS id.","- contextWindow in tokens if stated, else omit.","","Respond with ONLY a JSON object of the form:",'{"rates":[{"modelId":"...","found":true,"confidence":0.9,"inputPerM":5,"outputPerM":25,"cacheReadPerM":0.5,"contextWindow":1000000}]}'].join(`
1
+ import{e as b,g as y}from"./chunk-GN46S7T4.js";import{e as M,f as w}from"./chunk-ZZHIBOMT.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{c as g}from"./chunk-J6QMBMC2.js";import{e as h,f}from"./chunk-APDRR6FS.js";import{q as u,r as m}from"./chunk-J5HW45PZ.js";import{a as c}from"./chunk-ZLLER3HP.js";import*as i from"node:fs";import*as d from"node:path";var v=new Set(u);async function w(r){let{applications:l}=await h(`/api/recommendation-applications?instructionId=${encodeURIComponent(r.instructionId)}&projectPath=${encodeURIComponent(r.projectPath)}&limit=200`),t=l.filter(e=>v.has(e.status)&&e.inverse),s=[];for(let e of m(t.map(n=>({...n,appliedAt:n.appliedAt})))){let n=e.inverse;if(n.kind==="delete-paths"){let p=y(r.dir,n.paths);s.push({applicationId:e.id,target:e.targetPath,reversed:p.removed,drifted:!1,reason:p.reason}),(p.removed||p.alreadyGone)&&await f(`/api/recommendation-applications/${encodeURIComponent(e.id)}/transition`,{status:"reverted"});continue}if(n.kind!=="remove-hook-entry"){s.push({applicationId:e.id,target:e.targetPath,reversed:!1,drifted:!1,reason:`no reverser for inverse kind '${n.kind}' \u2014 recorded, not reversed`});continue}let o=g({dir:r.dir,inverse:n});s.push({applicationId:e.id,target:e.targetPath,reversed:o.removed,drifted:o.drifted,reason:o.reason}),(o.removed||o.code==="not-present")&&await f(`/api/recommendation-applications/${encodeURIComponent(e.id)}/transition`,{status:"reverted"})}return s}c(w,"reverseApplications");function y(r,l){let t=d.resolve(r),s=!1,e=0;for(let n of l){let o=d.resolve(t,n);if(o===t||!o.startsWith(t+d.sep))return{removed:!1,alreadyGone:!1,reason:`refused: ${n} does not resolve to a path inside the project`};if(!i.existsSync(o)&&!I(o)){e+=1;continue}try{i.rmSync(o,{recursive:!0,force:!0}),s=!0;let a=d.dirname(o);a.startsWith(t+d.sep)&&i.readdirSync(a).length===0&&i.rmdirSync(a)}catch(a){return{removed:!1,alreadyGone:!1,reason:`could not remove ${n}: ${a instanceof Error?a.message:String(a)}`}}}return!s&&e===l.length?{removed:!1,alreadyGone:!0,reason:"already removed"}:{removed:s,alreadyGone:!1}}c(y,"deletePaths");function I(r){try{return i.lstatSync(r).isSymbolicLink()}catch{return!1}}c(I,"isSymlink");function b(r){let l=r.name??r.instructionId,t=[],s=r.reversals.filter(e=>e.reversed);if(r.stripped.length>0)t.push(`Removed ${l} from ${r.stripped.join(", ")}.`);else if(s.length>0)for(let e of s)t.push(`Removed ${l} from ${e.target}.`),e.drifted&&t.push(" (that file had changed since it was installed; only the recorded entry was removed)");else{let e=r.searched.length>0?` (searched ${r.searched.join(", ")})`:"";t.push(`No rulemetric-managed block for ${r.instructionId} was found in this directory${e}.`)}for(let e of r.reversals.filter(n=>!n.reversed))t.push(`Still installed in ${e.target}: ${e.reason??"the recorded inverse did not apply"}`);return r.dismissalError?(t.push(`Could not record the dismissal: ${r.dismissalError}`),t.push(s.length>0?' What was removed above stays removed \u2014 only the "stop proposing this" record failed.':" Nothing was removed, and the dismissal was not recorded either."),t.push(" This proposal may be suggested again. Re-run this command to retry."),t):(t.push("It will not be proposed again for 30 days."),t.push("Turn auto-adoption off entirely: rulemetric suggestions auto --off"),t)}c(b,"describeUndo");export{w as a,y as b,b as c};
1
+ import{c as g}from"./chunk-N7SZWKCU.js";import{e as h,f}from"./chunk-ZZHIBOMT.js";import{q as u,r as m}from"./chunk-TWPG3TEQ.js";import{a as c}from"./chunk-ZLLER3HP.js";import*as i from"node:fs";import*as d from"node:path";var v=new Set(u);async function w(r){let{applications:l}=await h(`/api/recommendation-applications?instructionId=${encodeURIComponent(r.instructionId)}&projectPath=${encodeURIComponent(r.projectPath)}&limit=200`),t=l.filter(e=>v.has(e.status)&&e.inverse),s=[];for(let e of m(t.map(n=>({...n,appliedAt:n.appliedAt})))){let n=e.inverse;if(n.kind==="delete-paths"){let p=y(r.dir,n.paths);s.push({applicationId:e.id,target:e.targetPath,reversed:p.removed,drifted:!1,reason:p.reason}),(p.removed||p.alreadyGone)&&await f(`/api/recommendation-applications/${encodeURIComponent(e.id)}/transition`,{status:"reverted"});continue}if(n.kind!=="remove-hook-entry"){s.push({applicationId:e.id,target:e.targetPath,reversed:!1,drifted:!1,reason:`no reverser for inverse kind '${n.kind}' \u2014 recorded, not reversed`});continue}let o=g({dir:r.dir,inverse:n});s.push({applicationId:e.id,target:e.targetPath,reversed:o.removed,drifted:o.drifted,reason:o.reason}),(o.removed||o.code==="not-present")&&await f(`/api/recommendation-applications/${encodeURIComponent(e.id)}/transition`,{status:"reverted"})}return s}c(w,"reverseApplications");function y(r,l){let t=d.resolve(r),s=!1,e=0;for(let n of l){let o=d.resolve(t,n);if(o===t||!o.startsWith(t+d.sep))return{removed:!1,alreadyGone:!1,reason:`refused: ${n} does not resolve to a path inside the project`};if(!i.existsSync(o)&&!I(o)){e+=1;continue}try{i.rmSync(o,{recursive:!0,force:!0}),s=!0;let a=d.dirname(o);a.startsWith(t+d.sep)&&i.readdirSync(a).length===0&&i.rmdirSync(a)}catch(a){return{removed:!1,alreadyGone:!1,reason:`could not remove ${n}: ${a instanceof Error?a.message:String(a)}`}}}return!s&&e===l.length?{removed:!1,alreadyGone:!0,reason:"already removed"}:{removed:s,alreadyGone:!1}}c(y,"deletePaths");function I(r){try{return i.lstatSync(r).isSymbolicLink()}catch{return!1}}c(I,"isSymlink");function b(r){let l=r.name??r.instructionId,t=[],s=r.reversals.filter(e=>e.reversed);if(r.stripped.length>0)t.push(`Removed ${l} from ${r.stripped.join(", ")}.`);else if(s.length>0)for(let e of s)t.push(`Removed ${l} from ${e.target}.`),e.drifted&&t.push(" (that file had changed since it was installed; only the recorded entry was removed)");else{let e=r.searched.length>0?` (searched ${r.searched.join(", ")})`:"";t.push(`No rulemetric-managed block for ${r.instructionId} was found in this directory${e}.`)}for(let e of r.reversals.filter(n=>!n.reversed))t.push(`Still installed in ${e.target}: ${e.reason??"the recorded inverse did not apply"}`);return r.dismissalError?(t.push(`Could not record the dismissal: ${r.dismissalError}`),t.push(r.stripped.length>0||s.length>0?' What was removed above stays removed \u2014 only the "stop proposing this" record failed.':" Nothing was removed, and the dismissal was not recorded either."),t.push(" This proposal may be suggested again. Re-run this command to retry."),t):(t.push("It will not be proposed again for 30 days."),t.push("Turn auto-adoption off entirely: rulemetric suggestions auto --off"),t)}c(b,"describeUndo");export{w as a,y as b,b as c};