@rulemetric/cli 0.17.3 → 0.18.1

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 (40) hide show
  1. package/dist/chunk-A6JUIZ3H.js +1 -0
  2. package/dist/{chunk-TG4C4ENM.js → chunk-CXENLSMR.js} +1 -1
  3. package/dist/{chunk-BTKVLLV2.js → chunk-FLJTAD2R.js} +1 -1
  4. package/dist/chunk-I2FPXRA6.js +2 -0
  5. package/dist/{chunk-MGT5FZJ4.js → chunk-L5ILEWHH.js} +1 -1
  6. package/dist/{chunk-YLEXR62G.js → chunk-LSZ32DUR.js} +5 -5
  7. package/dist/{chunk-JLX2D3QL.js → chunk-NVOYP4HX.js} +1 -1
  8. package/dist/{chunk-GBSIOACS.js → chunk-O7ZQEKND.js} +19 -19
  9. package/dist/{chunk-MBP5OJKE.js → chunk-RAMQVEJB.js} +1 -1
  10. package/dist/chunk-YALBJNHO.js +1 -0
  11. package/dist/{chunk-EQ2O6DSN.js → chunk-YZQZD2E6.js} +1 -1
  12. package/dist/chunk-ZFEDOPRU.js +7 -0
  13. package/dist/commands/dashboard.js +1 -1
  14. package/dist/commands/diagnostics.js +1 -1
  15. package/dist/commands/evals/agent.js +1 -1
  16. package/dist/commands/evals/refine-cases.js +1 -1
  17. package/dist/commands/hooks/run.js +3 -3
  18. package/dist/commands/launcher.js +1 -1
  19. package/dist/commands/setup.js +1 -1
  20. package/dist/dashboard/Dashboard.js +1 -1
  21. package/dist/dashboard/data.js +1 -1
  22. package/dist/dashboard/launcher/LauncherOverlay.js +1 -1
  23. package/dist/dashboard/panels/telemetry.js +1 -0
  24. package/dist/dashboard/telemetry.js +1 -0
  25. package/dist/lib/agent-loop.js +1 -1
  26. package/dist/lib/evolution-enrolment.js +1 -1
  27. package/dist/lib/jobs/handlers/cron-instruction-evolution.js +1 -1
  28. package/dist/lib/jobs/handlers/cron-refine-cases.js +1 -1
  29. package/dist/lib/jobs/handlers/process-changelog.js +1 -1
  30. package/dist/lib/jobs/handlers/process-insights.js +1 -1
  31. package/dist/lib/manual-tasks.js +1 -1
  32. package/dist/lib/refine-cases.js +1 -1
  33. package/dist/lib/session-updates.js +1 -0
  34. package/dist/lib/setup-steps.js +1 -1
  35. package/oclif.manifest.json +228 -255
  36. package/package.json +6 -6
  37. package/dist/chunk-GBMF3TP6.js +0 -1
  38. package/dist/chunk-OWXGXKK7.js +0 -2
  39. package/dist/chunk-TBLUJ6AW.js +0 -1
  40. package/dist/dashboard/panels/instructions.js +0 -1
@@ -0,0 +1 @@
1
+ import{d as a}from"./chunk-5VWVQCNR.js";import{a as s}from"./chunk-ZLLER3HP.js";async function u(){let[e,t]=await Promise.allSettled([a("/api/setup/status",{timeoutMs:5e3}),a("/api/workers/health",{timeoutMs:5e3})]),i=s((n,r)=>({label:n,severity:"warn",message:`Status unavailable: ${r instanceof Error?r.message:String(r)}`,hints:[]}),"unavailable");return[e.status==="fulfilled"?{label:"Capture",severity:e.value.anyCapturedSession?"ok":"warn",message:e.value.anyCapturedSession?"Recorded sessions found":"No captured sessions received yet",hints:e.value.anyCapturedSession?[]:["Check capture setup with: rulemetric setup"]}:i("Capture",e.reason),t.status==="fulfilled"?{label:"Worker",severity:t.value.verdict.severity,message:t.value.verdict.headline,hints:t.value.verdict.hints}:i("Worker",t.reason)]}s(u,"loadTelemetryChecks");export{u as a};
@@ -1 +1 @@
1
- import{b as u,c as d}from"./chunk-EQ2O6DSN.js";import{b as g}from"./chunk-UQJNUESP.js";import{e as m,f as p,h as l}from"./chunk-5VWVQCNR.js";import{a as s}from"./chunk-ZLLER3HP.js";async function x(f,R){let r=s(e=>R?.logger?.info?.(e)??console.log(e),"log"),{evalTargetId:n}=f,i=`[cron_refine_cases] ${n}`,t=await m(`/api/eval-targets/${n}`);if(!(t.metadata?.autoRefineCases===!0))return r(`${i} not opted in (metadata.autoRefineCases)`),{skipped:"not-opted-in",reason:`"${t.name}" has not opted into automatic case refinement. Set metadata.autoRefineCases=true to let the loop cull cases that carry no treatment signal, or run \`rulemetric evals refine-cases ${n}\` by hand.`,targetName:t.name};let C=await m(`/api/eval-targets/${n}/judge-calibration`),a=u(C.caseDiscrimination);if(a.refused)return r(`${i} ${a.refused}: ${a.summary}`),{skipped:a.refused,reason:a.summary,targetName:t.name};r(`${i} ${a.summary}`);let o=await d(a,{generate:s(e=>g({content:t.content,name:t.name,feedback:e}),"generate"),createCase:s(e=>p(`/api/eval-targets/${n}/evals`,{name:e.name,prompt:e.prompt,expectations:e.expectations}),"createCase"),retireCase:s(async(e,y)=>{await l(`/api/eval-targets/${n}/evals/${e}`,{retire:!0,retiredReason:y})},"retireCase"),log:r});r(`${i} ${o.summary}`);let{skipped:c,...$}=o;return{...$,targetName:t.name,...c?{skipped:c,reason:o.summary}:{}}}s(x,"cronRefineCases");export{x as a};
1
+ import{b as u,c as d}from"./chunk-YZQZD2E6.js";import{b as g}from"./chunk-UQJNUESP.js";import{e as m,f as p,h as l}from"./chunk-5VWVQCNR.js";import{a as s}from"./chunk-ZLLER3HP.js";async function x(f,R){let r=s(e=>R?.logger?.info?.(e)??console.log(e),"log"),{evalTargetId:n}=f,i=`[cron_refine_cases] ${n}`,t=await m(`/api/eval-targets/${n}`);if(!(t.metadata?.autoRefineCases===!0))return r(`${i} not opted in (metadata.autoRefineCases)`),{skipped:"not-opted-in",reason:`"${t.name}" has not opted into automatic case refinement. Set metadata.autoRefineCases=true to let the loop cull cases that carry no treatment signal, or run \`rulemetric evals refine-cases ${n}\` by hand.`,targetName:t.name};let C=await m(`/api/eval-targets/${n}/judge-calibration`),a=u(C.caseDiscrimination);if(a.refused)return r(`${i} ${a.refused}: ${a.summary}`),{skipped:a.refused,reason:a.summary,targetName:t.name};r(`${i} ${a.summary}`);let o=await d(a,{generate:s(e=>g({content:t.content,name:t.name,feedback:e}),"generate"),createCase:s(e=>p(`/api/eval-targets/${n}/evals`,{name:e.name,prompt:e.prompt,expectations:e.expectations}),"createCase"),retireCase:s(async(e,y)=>{await l(`/api/eval-targets/${n}/evals/${e}`,{retire:!0,retiredReason:y})},"retireCase"),log:r});r(`${i} ${o.summary}`);let{skipped:c,...$}=o;return{...$,targetName:t.name,...c?{skipped:c,reason:o.summary}:{}}}s(x,"cronRefineCases");export{x as a};
@@ -1 +1 @@
1
- import{b as t,e as E}from"./chunk-MGT5FZJ4.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-L5ILEWHH.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};
@@ -0,0 +1,2 @@
1
+ import{c as C,o as E}from"./chunk-RQBN7WNS.js";import{a as h}from"./chunk-5VWVQCNR.js";import{a as l}from"./chunk-ZLLER3HP.js";import*as p from"node:fs";import*as u from"node:path";import*as m from"node:os";function k(){if(process.env.RULEMETRIC_API_KEY||process.env.RULEMETRIC_ACCESS_TOKEN)return;let s=u.join(m.homedir(),".config","rulemetric","env");v(s)||v(u.join(process.cwd(),".env.local"))}l(k,"ensureEnv");function v(s){try{let t=p.readFileSync(s,"utf-8");for(let a of t.split(`
2
+ `)){let o=a.trim();if(!o||o.startsWith("#"))continue;let n=o.indexOf("=");if(n<0)continue;let e=o.slice(0,n).trim(),i=o.slice(n+1).trim();process.env[e]||(process.env[e]=i)}return!!(process.env.RULEMETRIC_API_KEY||process.env.RULEMETRIC_ACCESS_TOKEN)}catch{return!1}}l(v,"loadEnvFile");k();async function I(s){let t={totalSessions:0,totalCalls:0,totalInputTokens:0,totalOutputTokens:0,totalCacheReadTokens:0,totalCacheWriteTokens:0,totalCostUSD:0,providers:{}},a=await E(s);t.providers={};for(let r of a)t.providers[r.provider]=(t.providers[r.provider]||0)+1;let o=new C,n=a.filter(r=>r.provider==="claude");for(let r of n)try{let d=p.readdirSync(r.path).filter(f=>f.endsWith(".jsonl"));t.totalSessions+=d.length;for(let f of d){let T=p.readFileSync(u.join(r.path,f),"utf-8"),_=o.parse(T);for(let c of _.events)c.tokenUsage&&(t.totalCalls++,t.totalInputTokens+=c.tokenUsage.input,t.totalOutputTokens+=c.tokenUsage.output,t.totalCacheReadTokens+=c.tokenUsage.cacheRead??0,t.totalCacheWriteTokens+=c.tokenUsage.cacheWrite??0)}}catch{}let e=15,i=75;return t.totalCostUSD=Math.round((t.totalInputTokens/1e6*e+t.totalOutputTokens/1e6*i+t.totalCacheReadTokens/1e6*(e*.1)+t.totalCacheWriteTokens/1e6*(e*1.25))*100)/100,t}l(I,"loadLocalStats");async function U(s){let t=process.env.RULEMETRIC_API_URL??h,a=process.env.RULEMETRIC_API_KEY,o=process.env.RULEMETRIC_ACCESS_TOKEN,n=a??o;if(!n)return null;let e=new URLSearchParams;s&&e.set("projectPath",s);try{let i=await fetch(`${t}/api/insights/compute?${e}`,{headers:{Authorization:`Bearer ${n}`},signal:AbortSignal.timeout(5e3)});return i.ok?await i.json():null}catch{return null}}l(U,"loadApiInsights");export{I as a,U as b};
@@ -1 +1 @@
1
- import{a as _e}from"./chunk-M7QSC64D.js";import{i as Me}from"./chunk-DZRBB34J.js";import{a as Pe}from"./chunk-KR32Y5Q5.js";import{a as xe,b as Se,c as De,d as Ie,e as se,f as Oe}from"./chunk-RITL4NU3.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-GYKYJJNF.js";import{c as Re}from"./chunk-G7V4ZZZ3.js";import{a as re}from"./chunk-AHLVY52I.js";import{d as ke,f as Ce,g as Ee,i as Ae}from"./chunk-PPQFN62M.js";import{a as we}from"./chunk-V6L25LFD.js";import{c as ye}from"./chunk-NAS7FIGM.js";import{b as ve}from"./chunk-VZYNZS5U.js";import{d as ue,e as ne,f as de}from"./chunk-KFNFLMUR.js";import{e as y,f as te}from"./chunk-5VWVQCNR.js";import{a as g}from"./chunk-ZLLER3HP.js";import{createHash as Ge}from"node:crypto";import{existsSync as Te,readFileSync as Ne,writeFileSync as Xe}from"node:fs";var H=g(t=>Ge("sha256").update(t).digest("hex"),"sha256"),Le=1.3,ae=4,ze=20;function Be(t,o){if(!t.configured||o<=0)return ae;let e=Math.ceil(t.minPairs*Le/o);return Math.min(ze,Math.max(ae,e))}g(Be,"passCapFor");function Qe(t,o=10,e=ae){if(t<=0)return{passes:0,expectedPairs:0,feasible:!1,reason:"no live cases"};let i=Math.ceil(o*Le),l=Math.min(e,Math.ceil(i/t)),r=l*t;return r<o?{passes:l,expectedPairs:r,feasible:!1,reason:`${t} live case(s) x ${e} passes = ${t*e} pairs at best, below the ${o} a controlled verdict requires \u2014 add cases rather than replaying these`}:{passes:l,expectedPairs:r,feasible:!0}}g(Qe,"planPasses");var Ve=60,Ye=5,We=g(t=>Array.isArray(t)?t.filter(o=>typeof o=="string"):[],"stringList"),J=g(t=>typeof t=="number"&&Number.isFinite(t)?t:null,"finite");function Ze(t,o,e=Ye){let i=[...t].filter(s=>s.fromContentHash===o).sort((s,c)=>Date.parse(c.createdAt)-Date.parse(s.createdAt)),l=[],r=new Set;for(let s of i){let c=s.toContentHash??s.id;if(r.has(c))continue;r.add(c);let d=s.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 s.decision=="string"?s.decision:"unknown",applied:s.applied===!0,at:typeof s.createdAt=="string"?s.createdAt:"",rationale:typeof s.proposalRationale=="string"?s.proposalRationale:"",touched:We(s.touchedSections),refusals:We(s.refusals),measured:L}),l.length>=e)break}return l}g(Ze,"summarisePriorDecisions");function et(t,o){let e=o.accumulate??(t.autoEvolveAccumulate===!0||t.autoEvolveAccumulate==="true"),i=o.accumulateTargetPairs??t.autoEvolveAccumulateTarget,l=typeof i=="string"?Number.parseInt(i,10):i,r=typeof l=="number"&&Number.isInteger(l)&&l>0?l:Ve;return{enabled:e,targetPairs:r}}g(et,"readAccumulateConfig");function tt(t){let o=t.accumulateEnabled&&t.pairCount<t.targetPairs;return{apply:t.consented&&!o,peeking:o}}g(tt,"resolveApply");async function Pt(t,o){if(t.restoration)return Pe(t.evalTargetId,t.restoration);let e=g(n=>o?.logger?.info?.(n)??console.log(n),"log"),{evalTargetId:i}=t,l=t.measurement?ye(t):{},r=`[cron_instruction_evolution] ${i}`,s=await y(`/api/eval-targets/${i}`),c=s.metadata??{},d=t.measurement?JSON.stringify([l.engine,l.model,l.graderEngine,l.graderModel,s.type,ve(t.measurement.engine)]):void 0,k=null,M=!1;if(s.name.startsWith("/")&&Te(s.name))try{if(k=Ne(s.name,"utf8"),k!==s.content){let n=await te(`/api/eval-targets/${i}/sync-content`,{content:k});M=n.synced,e(`${r}: target content drifted from disk by ${Math.abs(k.length-s.content.length)} chars \u2014 synced to disk truth (v${n.version}). Prior verdicts against the old text dissolve via content-hash keying.`),s={...s,content:k,version:n.version}}}catch(n){e(`${r}: disk sync failed (${n instanceof Error?n.message:String(n)}) \u2014 measuring the stored snapshot`)}let x=!1;try{x=(await y("/api/settings/evolution-account")).paused}catch(n){e(`${r}: could not read the account switch (${n instanceof Error?n.message:String(n)}) \u2014 pausing to be safe`),x=!0}if(x)return e(`${r}: PAUSED for the whole account (profiles.evolution_paused) \u2014 no model budget spent.`),{skipped:"paused-account"};if(ge(c))return e(`${r}: PAUSED (metadata.autoEvolvePaused) \u2014 no model budget spent. Opt-in is intact.`),{skipped:"paused"};let S=_e(s);if(S)return e(`${r}: ${S.reason}`),S;let L=t.apply??(c.autoEvolveApply===!0||c.autoEvolveApply==="true"),F=nt(c);if(F==null){if(L)return e(`${r}: 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(`${r}: metadata.immutableSections unset \u2014 measure-only cycle proceeds with [] (nothing protected). Writing still requires setting it explicitly.`),F=[]}let v=(await y(`/api/eval-targets/${i}/evals`)).filter(n=>!n.retiredAt);if(v.length===0)return{skipped:"no-live-cases"};let j=me(c);j.note&&e(`${r}: ${j.note}`);let C=Qe(v.length,j.minPairs,Be(j,v.length));if(!C.feasible)return e(`${r}: cannot reach a sufficient verdict \u2014 ${C.reason}`),{skipped:"cannot-reach-min-n",reason:C.reason};let Fe=fe({liveCases:v.length,passes:C.passes});e(`${r}: budget for this run \u2014 ${$e(Fe)}`);let G=await y(`/api/eval-targets/${i}/judge-calibration`);if(!G.powerCheck.adequate){let n=(G.powerCheck.reasons??[]).join("; ");return e(`${r}: not adequately powered, skipping before spending budget \u2014 ${n}`),{skipped:"not-adequate",reason:n}}let oe=de,je=Date.now()-oe*24*60*60*1e3,X=await y(`/api/eval-targets/${i}/promotions?limit=200`),ie=X.promotions.filter(n=>n.applied&&Date.parse(n.createdAt)>=je).length;if(ie>=ne)return e(`${r}: change budget looks exhausted (${ie}/${ne} applied in ${oe}d), skipping before spending budget`),{skipped:"budget-exhausted"};try{let n=await y("/api/usage/current-limits"),u=Re({limits:n,now:new Date});if(!u.ok)return e(`${r}: deferring before spending budget \u2014 ${u.reason}`),{skipped:"quota-exhausted",reason:u.reason}}catch(n){e(`${r}: quota unknown (${n instanceof Error?n.message:String(n)}) \u2014 proceeding`)}let U=ue();if(!U.green)return e(`${r}: A/A canary is RED \u2014 halting. ${U.failures.join(" | ")}`),{skipped:"canary-red",reason:U.failures.join(" | ")};let z=s.content,D=H(z),f=et(c,t),w=f.enabled?re(X.promotions,D,f.targetPairs,d):null,b,q,$=[],_=0,B=pe,p=w?null:Se(c,D,d);if(p){b=p.content,q="",B=0;try{$=await Ie({evalTargetId:i,candidateContentHash:p.hash,executionKey:d,observedKey:p.observedKey})}catch(n){return e(`${r}: could not rebuild banked pairs (${n instanceof Error?n.message:String(n)})`),{skipped:"resume-read-failed",reason:p.hash}}e(`${r}: resuming interrupted cycle \u2014 ${$.length}/${p.plannedPairs} pair(s) rebuilt from eval_runs, no proposal call spent`)}else if(w){let n=await y(`/api/promotions/${w.promotionId}`);if(H(n.toContent)!==w.candidateContentHash)return e(`${r}: stored candidate does not match its recorded hash \u2014 refusing to continue`),{skipped:"accumulation-hash-mismatch",reason:w.promotionId};b=n.toContent,q=n.proposalRationale??"",$=w.pairs,_=w.runs,B=0,e(`${r}: continuing accumulation ${w.promotionId} \u2014 ${$.length}/${f.targetPairs} pair(s) carried from ${_} prior run(s)`)}else{let n=G.caseDiscrimination?.cases??[],u=[];if(s.name.startsWith("/")){let a=s.name.slice(0,s.name.lastIndexOf("/"));try{let m=await y(`/api/insights/evidence?projectPath=${encodeURIComponent(a)}`);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(`${r}: proposer sees ${m.friction.length} friction + ${m.whatWorks.length} what-works item(s) from insights`))}catch(m){e(`${r}: insights evidence unavailable (${m instanceof Error?m.message:String(m)}) \u2014 proposing without it`)}}let N=[];try{N=Ze(X.promotions,D)}catch(a){e(`${r}: could not summarise prior decisions (${a instanceof Error?a.message:String(a)}) \u2014 proposing without them`)}N.length>0&&e(`${r}: proposer sees ${N.length} prior decision(s) against this exact body (${N.map(a=>`${a.decision}${a.measured?"/measured":""}`).join(", ")})`);let W=await Me({currentContent:s.content,targetType:s.type,targetName:s.name,immutableSections:F,evidence:{nonDiscriminating:n.filter(a=>!a.discriminating).map(a=>`${a.name??a.assertion??"unnamed"} \u2014 ${a.note}`),weakest:n.filter(a=>a.discriminating&&a.withPassRate<a.withoutPassRate).map(a=>({name:a.name??a.assertion??"unnamed",withPassRate:a.withPassRate,withoutPassRate:a.withoutPassRate})),priorDecisions:N,notes:u}},void 0,t.measurement?(a,m)=>we(t.measurement,a,m):void 0);if(!W.ok)return e(`${r}: no usable proposal \u2014 ${W.reason}`),{skipped:"no-proposal",reason:W.reason};b=W.proposal.candidateContent,q=W.proposal.rationale}let I=p?De({plannedPairs:p.plannedPairs||C.expectedPairs,carriedPairs:$.length,liveCases:v.length}):C.passes;e(`${r}: measuring ${v.length} case(s) x ${I} pass(es) = up to ${v.length*I} pairs, candidate vs prior version`+(p?` (resumed; ${$.length} pair(s) already banked)`:""));let E=[],K=[],Ue=Date.now(),le=0,Q=0;for(let n=1;n<=I;n++){let u=await Ae({cases:v,candidateContent:b,priorVersionContent:z,concurrency:t.concurrency??2,runNumber:n,opts:{targetId:i,targetVersion:s.version??1,iteration:1,timeout:t.timeout??24e4,model:t.model,graderModel:t.graderModel,graderEngine:t.graderEngine,...l,executionKey:d,skipGrading:!1,targetType:s.type,targetName:s.name,candidateContentHash:H(b)},onLog:e});if(E.push(...u.pairs),K.push(...u.results),le+=u.completed,Q+=u.failed,e(`${r}: pass ${n}/${I} \u2014 ${u.pairs.length} pair(s), running total ${E.length}`),u.abortedForQuota){e(`${r}: stopping after pass ${n}/${I} \u2014 ${u.abortedForQuota}. Remaining passes would spend against an exhausted account.`);break}}let O=ke(K),qe=p?.observedKey??w?.observedKey;if(t.measurement&&E.length>0&&(!O||$.length>0&&qe!==O))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=Ce(K),V=E.length>0,h=he({runs:K,plannedPairs:C.expectedPairs,usablePairs:E.length,verdictPairs:V?A.length:E.length,proposalCalls:B,passes:I,liveCases:v.length,wallMs:Date.now()-Ue});if(e(`${r}: ${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=Ee({pairs:A.length,minPairs:10,accounting:T});if(Y.kind==="infrastructure-incomplete")return e(`${r}: not posting a verdict \u2014 ${Y.reason}`),await se({evalTargetId:i,meta:c,blob:Oe({executionKey:d,...O?{observedKey:O}:{},content:b,hash:H(b),priorHash:D,plannedPairs:p?.plannedPairs||C.expectedPairs,now:new Date}),log:e,tag:r}),{skipped:"infrastructure-incomplete",reason:Y.reason,cost:h};f.enabled&&e(`${r}: accumulated ${A.length}/${f.targetPairs} pair(s) over ${_+1} run(s) on one candidate`);let ce=L,{apply:Ke,peeking:Je}=tt({consented:ce,accumulateEnabled:f.enabled,pairCount:A.length,targetPairs:f.targetPairs});ce&&Je&&e(`${r}: 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/${i}/promotions`,{candidateContent:b,proposalSource:"llm",proposalRationale:q,pairs:A,canaryGreen:U.green,measuredAgainstContentHash:D,immutableSections:F,apply:Ke,measurementCost:h,...f.enabled?{accumulation:{executionKey:d,...O?{observedKey:O}:{},candidateContentHash:H(b),priorContentHash:D,targetPairs:f.targetPairs,carriedPairs:$.length,runs:_+1}}:{}});e(`${r}: ${P.decision}${P.applied?" (APPLIED)":""} \u2014 ${P.rationale}`+(P.refusals.length>0?` | refusals: ${P.refusals.join("; ")}`:"")),(p||c[xe])&&await se({evalTargetId:i,meta:c,blob:null,log:e,tag:r});let Z=!1,R;if(P.applied&&s.name.startsWith("/"))try{Te(s.name)?Ne(s.name,"utf8")!==z?R="file changed since measurement started \u2014 refusing to clobber; next cycle re-syncs":(Xe(s.name,b,"utf8"),Z=!0):R="file no longer exists on disk",e(Z?`${r}: measured improvement written to ${s.name} (undo: git checkout -- ${s.name})`:`${r}: NOT written to disk \u2014 ${R}`)}catch(n){R=n instanceof Error?n.message:String(n),e(`${r}: 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(Pt,"cronInstructionEvolution");function nt(t){let o=t.immutableSections;return o==null||!Array.isArray(o)?null:o.filter(e=>typeof e=="string")}g(nt,"readImmutableSections");export{Le as a,ae as b,ze as c,Be as d,Qe as e,Ve as f,Ye as g,Ze as h,et as i,tt as j,Pt as k,nt as l};
1
+ import{a as _e}from"./chunk-M7QSC64D.js";import{i as Me}from"./chunk-DZRBB34J.js";import{a as Pe}from"./chunk-KR32Y5Q5.js";import{c as Re}from"./chunk-G7V4ZZZ3.js";import{a as xe,b as Se,c as De,d as Ie,e as se,f as Oe}from"./chunk-RITL4NU3.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-GYKYJJNF.js";import{a as we}from"./chunk-V6L25LFD.js";import{a as re}from"./chunk-AHLVY52I.js";import{d as ke,f as Ce,g as Ee,i as Ae}from"./chunk-PPQFN62M.js";import{c as ye}from"./chunk-NAS7FIGM.js";import{b as ve}from"./chunk-VZYNZS5U.js";import{d as ue,e as ne,f as de}from"./chunk-KFNFLMUR.js";import{e as y,f as te}from"./chunk-5VWVQCNR.js";import{a as g}from"./chunk-ZLLER3HP.js";import{createHash as Ge}from"node:crypto";import{existsSync as Te,readFileSync as Ne,writeFileSync as Xe}from"node:fs";var H=g(t=>Ge("sha256").update(t).digest("hex"),"sha256"),Le=1.3,ae=4,ze=20;function Be(t,o){if(!t.configured||o<=0)return ae;let e=Math.ceil(t.minPairs*Le/o);return Math.min(ze,Math.max(ae,e))}g(Be,"passCapFor");function Qe(t,o=10,e=ae){if(t<=0)return{passes:0,expectedPairs:0,feasible:!1,reason:"no live cases"};let i=Math.ceil(o*Le),l=Math.min(e,Math.ceil(i/t)),r=l*t;return r<o?{passes:l,expectedPairs:r,feasible:!1,reason:`${t} live case(s) x ${e} passes = ${t*e} pairs at best, below the ${o} a controlled verdict requires \u2014 add cases rather than replaying these`}:{passes:l,expectedPairs:r,feasible:!0}}g(Qe,"planPasses");var Ve=60,Ye=5,We=g(t=>Array.isArray(t)?t.filter(o=>typeof o=="string"):[],"stringList"),J=g(t=>typeof t=="number"&&Number.isFinite(t)?t:null,"finite");function Ze(t,o,e=Ye){let i=[...t].filter(s=>s.fromContentHash===o).sort((s,c)=>Date.parse(c.createdAt)-Date.parse(s.createdAt)),l=[],r=new Set;for(let s of i){let c=s.toContentHash??s.id;if(r.has(c))continue;r.add(c);let d=s.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 s.decision=="string"?s.decision:"unknown",applied:s.applied===!0,at:typeof s.createdAt=="string"?s.createdAt:"",rationale:typeof s.proposalRationale=="string"?s.proposalRationale:"",touched:We(s.touchedSections),refusals:We(s.refusals),measured:L}),l.length>=e)break}return l}g(Ze,"summarisePriorDecisions");function et(t,o){let e=o.accumulate??(t.autoEvolveAccumulate===!0||t.autoEvolveAccumulate==="true"),i=o.accumulateTargetPairs??t.autoEvolveAccumulateTarget,l=typeof i=="string"?Number.parseInt(i,10):i,r=typeof l=="number"&&Number.isInteger(l)&&l>0?l:Ve;return{enabled:e,targetPairs:r}}g(et,"readAccumulateConfig");function tt(t){let o=t.accumulateEnabled&&t.pairCount<t.targetPairs;return{apply:t.consented&&!o,peeking:o}}g(tt,"resolveApply");async function Pt(t,o){if(t.restoration)return Pe(t.evalTargetId,t.restoration);let e=g(n=>o?.logger?.info?.(n)??console.log(n),"log"),{evalTargetId:i}=t,l=t.measurement?ye(t):{},r=`[cron_instruction_evolution] ${i}`,s=await y(`/api/eval-targets/${i}`),c=s.metadata??{},d=t.measurement?JSON.stringify([l.engine,l.model,l.graderEngine,l.graderModel,s.type,ve(t.measurement.engine)]):void 0,k=null,M=!1;if(s.name.startsWith("/")&&Te(s.name))try{if(k=Ne(s.name,"utf8"),k!==s.content){let n=await te(`/api/eval-targets/${i}/sync-content`,{content:k});M=n.synced,e(`${r}: target content drifted from disk by ${Math.abs(k.length-s.content.length)} chars \u2014 synced to disk truth (v${n.version}). Prior verdicts against the old text dissolve via content-hash keying.`),s={...s,content:k,version:n.version}}}catch(n){e(`${r}: disk sync failed (${n instanceof Error?n.message:String(n)}) \u2014 measuring the stored snapshot`)}let x=!1;try{x=(await y("/api/settings/evolution-account")).paused}catch(n){e(`${r}: could not read the account switch (${n instanceof Error?n.message:String(n)}) \u2014 pausing to be safe`),x=!0}if(x)return e(`${r}: PAUSED for the whole account (profiles.evolution_paused) \u2014 no model budget spent.`),{skipped:"paused-account"};if(ge(c))return e(`${r}: PAUSED (metadata.autoEvolvePaused) \u2014 no model budget spent. Opt-in is intact.`),{skipped:"paused"};let S=_e(s);if(S)return e(`${r}: ${S.reason}`),S;let L=t.apply??(c.autoEvolveApply===!0||c.autoEvolveApply==="true"),F=nt(c);if(F==null){if(L)return e(`${r}: 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(`${r}: metadata.immutableSections unset \u2014 measure-only cycle proceeds with [] (nothing protected). Writing still requires setting it explicitly.`),F=[]}let v=(await y(`/api/eval-targets/${i}/evals`)).filter(n=>!n.retiredAt);if(v.length===0)return{skipped:"no-live-cases"};let j=me(c);j.note&&e(`${r}: ${j.note}`);let C=Qe(v.length,j.minPairs,Be(j,v.length));if(!C.feasible)return e(`${r}: cannot reach a sufficient verdict \u2014 ${C.reason}`),{skipped:"cannot-reach-min-n",reason:C.reason};let Fe=fe({liveCases:v.length,passes:C.passes});e(`${r}: budget for this run \u2014 ${$e(Fe)}`);let G=await y(`/api/eval-targets/${i}/judge-calibration`);if(!G.powerCheck.adequate){let n=(G.powerCheck.reasons??[]).join("; ");return e(`${r}: not adequately powered, skipping before spending budget \u2014 ${n}`),{skipped:"not-adequate",reason:n}}let oe=de,je=Date.now()-oe*24*60*60*1e3,X=await y(`/api/eval-targets/${i}/promotions?limit=200`),ie=X.promotions.filter(n=>n.applied&&Date.parse(n.createdAt)>=je).length;if(ie>=ne)return e(`${r}: change budget looks exhausted (${ie}/${ne} applied in ${oe}d), skipping before spending budget`),{skipped:"budget-exhausted"};try{let n=await y("/api/usage/current-limits"),u=Re({limits:n,now:new Date});if(!u.ok)return e(`${r}: deferring before spending budget \u2014 ${u.reason}`),{skipped:"quota-exhausted",reason:u.reason}}catch(n){e(`${r}: quota unknown (${n instanceof Error?n.message:String(n)}) \u2014 proceeding`)}let U=ue();if(!U.green)return e(`${r}: A/A canary is RED \u2014 halting. ${U.failures.join(" | ")}`),{skipped:"canary-red",reason:U.failures.join(" | ")};let z=s.content,D=H(z),f=et(c,t),w=f.enabled?re(X.promotions,D,f.targetPairs,d):null,b,q,$=[],_=0,B=pe,p=w?null:Se(c,D,d);if(p){b=p.content,q="",B=0;try{$=await Ie({evalTargetId:i,candidateContentHash:p.hash,executionKey:d,observedKey:p.observedKey})}catch(n){return e(`${r}: could not rebuild banked pairs (${n instanceof Error?n.message:String(n)})`),{skipped:"resume-read-failed",reason:p.hash}}e(`${r}: resuming interrupted cycle \u2014 ${$.length}/${p.plannedPairs} pair(s) rebuilt from eval_runs, no proposal call spent`)}else if(w){let n=await y(`/api/promotions/${w.promotionId}`);if(H(n.toContent)!==w.candidateContentHash)return e(`${r}: stored candidate does not match its recorded hash \u2014 refusing to continue`),{skipped:"accumulation-hash-mismatch",reason:w.promotionId};b=n.toContent,q=n.proposalRationale??"",$=w.pairs,_=w.runs,B=0,e(`${r}: continuing accumulation ${w.promotionId} \u2014 ${$.length}/${f.targetPairs} pair(s) carried from ${_} prior run(s)`)}else{let n=G.caseDiscrimination?.cases??[],u=[];if(s.name.startsWith("/")){let a=s.name.slice(0,s.name.lastIndexOf("/"));try{let m=await y(`/api/insights/evidence?projectPath=${encodeURIComponent(a)}`);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(`${r}: proposer sees ${m.friction.length} friction + ${m.whatWorks.length} what-works item(s) from insights`))}catch(m){e(`${r}: insights evidence unavailable (${m instanceof Error?m.message:String(m)}) \u2014 proposing without it`)}}let N=[];try{N=Ze(X.promotions,D)}catch(a){e(`${r}: could not summarise prior decisions (${a instanceof Error?a.message:String(a)}) \u2014 proposing without them`)}N.length>0&&e(`${r}: proposer sees ${N.length} prior decision(s) against this exact body (${N.map(a=>`${a.decision}${a.measured?"/measured":""}`).join(", ")})`);let W=await Me({currentContent:s.content,targetType:s.type,targetName:s.name,immutableSections:F,evidence:{nonDiscriminating:n.filter(a=>!a.discriminating).map(a=>`${a.name??a.assertion??"unnamed"} \u2014 ${a.note}`),weakest:n.filter(a=>a.discriminating&&a.withPassRate<a.withoutPassRate).map(a=>({name:a.name??a.assertion??"unnamed",withPassRate:a.withPassRate,withoutPassRate:a.withoutPassRate})),priorDecisions:N,notes:u}},void 0,t.measurement?(a,m)=>we(t.measurement,a,m):void 0);if(!W.ok)return e(`${r}: no usable proposal \u2014 ${W.reason}`),{skipped:"no-proposal",reason:W.reason};b=W.proposal.candidateContent,q=W.proposal.rationale}let I=p?De({plannedPairs:p.plannedPairs||C.expectedPairs,carriedPairs:$.length,liveCases:v.length}):C.passes;e(`${r}: measuring ${v.length} case(s) x ${I} pass(es) = up to ${v.length*I} pairs, candidate vs prior version`+(p?` (resumed; ${$.length} pair(s) already banked)`:""));let E=[],K=[],Ue=Date.now(),le=0,Q=0;for(let n=1;n<=I;n++){let u=await Ae({cases:v,candidateContent:b,priorVersionContent:z,concurrency:t.concurrency??2,runNumber:n,opts:{targetId:i,targetVersion:s.version??1,iteration:1,timeout:t.timeout??24e4,model:t.model,graderModel:t.graderModel,graderEngine:t.graderEngine,...l,executionKey:d,skipGrading:!1,targetType:s.type,targetName:s.name,candidateContentHash:H(b)},onLog:e});if(E.push(...u.pairs),K.push(...u.results),le+=u.completed,Q+=u.failed,e(`${r}: pass ${n}/${I} \u2014 ${u.pairs.length} pair(s), running total ${E.length}`),u.abortedForQuota){e(`${r}: stopping after pass ${n}/${I} \u2014 ${u.abortedForQuota}. Remaining passes would spend against an exhausted account.`);break}}let O=ke(K),qe=p?.observedKey??w?.observedKey;if(t.measurement&&E.length>0&&(!O||$.length>0&&qe!==O))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=Ce(K),V=E.length>0,h=he({runs:K,plannedPairs:C.expectedPairs,usablePairs:E.length,verdictPairs:V?A.length:E.length,proposalCalls:B,passes:I,liveCases:v.length,wallMs:Date.now()-Ue});if(e(`${r}: ${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=Ee({pairs:A.length,minPairs:10,accounting:T});if(Y.kind==="infrastructure-incomplete")return e(`${r}: not posting a verdict \u2014 ${Y.reason}`),await se({evalTargetId:i,meta:c,blob:Oe({executionKey:d,...O?{observedKey:O}:{},content:b,hash:H(b),priorHash:D,plannedPairs:p?.plannedPairs||C.expectedPairs,now:new Date}),log:e,tag:r}),{skipped:"infrastructure-incomplete",reason:Y.reason,cost:h};f.enabled&&e(`${r}: accumulated ${A.length}/${f.targetPairs} pair(s) over ${_+1} run(s) on one candidate`);let ce=L,{apply:Ke,peeking:Je}=tt({consented:ce,accumulateEnabled:f.enabled,pairCount:A.length,targetPairs:f.targetPairs});ce&&Je&&e(`${r}: 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/${i}/promotions`,{candidateContent:b,proposalSource:"llm",proposalRationale:q,pairs:A,canaryGreen:U.green,measuredAgainstContentHash:D,immutableSections:F,apply:Ke,measurementCost:h,...f.enabled?{accumulation:{executionKey:d,...O?{observedKey:O}:{},candidateContentHash:H(b),priorContentHash:D,targetPairs:f.targetPairs,carriedPairs:$.length,runs:_+1}}:{}});e(`${r}: ${P.decision}${P.applied?" (APPLIED)":""} \u2014 ${P.rationale}`+(P.refusals.length>0?` | refusals: ${P.refusals.join("; ")}`:"")),(p||c[xe])&&await se({evalTargetId:i,meta:c,blob:null,log:e,tag:r});let Z=!1,R;if(P.applied&&s.name.startsWith("/"))try{Te(s.name)?Ne(s.name,"utf8")!==z?R="file changed since measurement started \u2014 refusing to clobber; next cycle re-syncs":(Xe(s.name,b,"utf8"),Z=!0):R="file no longer exists on disk",e(Z?`${r}: measured improvement written to ${s.name} (undo: git checkout -- ${s.name})`:`${r}: NOT written to disk \u2014 ${R}`)}catch(n){R=n instanceof Error?n.message:String(n),e(`${r}: 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(Pt,"cronInstructionEvolution");function nt(t){let o=t.immutableSections;return o==null||!Array.isArray(o)?null:o.filter(e=>typeof e=="string")}g(nt,"readImmutableSections");export{Le as a,ae as b,ze as c,Be as d,Qe as e,Ve as f,Ye as g,Ze as h,et as i,tt as j,Pt as k,nt as l};
@@ -1,11 +1,11 @@
1
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-GPBN4ROE.js";import{e as _}from"./chunk-5VWVQCNR.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
- `),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
- `)}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(`
5
- `);return{id:"auth",title:"Authenticate",command:"rulemetric auth login",artifacts:[{path:t,kind:"file",before:n,after:r,masked:!0},{path:a(e.configDir,"auth.json"),kind:"file",before:p(a(e.configDir,"auth.json"))?"(existing session tokens)":null,after:"{ accessToken, refreshToken, expiresAt, email } \u2014 OAuth session tokens (secret)",masked:!0}]}},async apply(){h("rulemetric auth login")}},{id:"hooks",title:"Install hooks + capture proxy",command:process.env.RULEMETRIC_SETUP_NO_PROXY==="1"||process.env.RULEMETRIC_SETUP_NO_PROXY==="true"?"rulemetric hooks install --no-proxy":"rulemetric hooks install",async detect(e){for(let t of["settings.local.json","settings.json"]){let n=a(e.projectPath,".claude",t);if(p(n))try{let o=JSON.parse(y(n,"utf-8"));if(T(o))return!0}catch{}}return!1},async plan(e){let t=a(e.projectPath,".claude","settings.local.json"),{before:n,after:o}=D(e.projectPath),s=[{path:t,kind:"file",before:n,after:o},{path:"what these hooks capture",kind:"service",before:null,after:"session-end reimports the FULL transcript to the API; post-tool-use records each tool call and snapshots the working tree to a LOCAL shadow git ref (paper-trail, never pushed); user-prompt posts prompt text. All scoped to sessions in this project."},{path:`${t} (proxy env block)`,kind:"file",...N(e.projectPath)},{path:"system keychain \u2014 mitmproxy root CA",kind:"service",before:p(A)?"(CA generated; trust state unchanged)":"(no CA yet)",after:"Installs + trusts the mitmproxy CA (requires sudo). This lets the proxy DECRYPT Claude Code HTTPS request/response bodies \u2014 the capability that powers rendered-system-prompt / instruction linking. Decline the sudo prompt and setup stays hooks-only (still fully onboarded)."},{path:"launchctl setenv HTTPS_PROXY (machine-wide, all GUI apps)",kind:"command",before:null,after:`http://localhost:${d} \u2014 routes every GUI app's HTTPS through the local gateway (only when the CA is trusted AND :${d} is live)`},{path:"VS Code + Cursor user settings (http.proxy)",kind:"file",before:null,after:`http.proxy \u2192 http://localhost:${d} (+ http.proxyStrictSSL=false)`},{path:`gateway process on :${d}`,kind:"service",before:null,after:"started (routes Claude Code \u2192 mitmproxy \u2192 Anthropic; falls back to direct if mitmproxy is down)"}],u=U(e.projectPath);u&&s.push({path:`${a(e.projectPath,".claude","settings.json")} (removes RuleMetric machine-local state left by an older install \u2014 see the local-file artifacts above for where it moves)`,kind:"file",...u});for(let c of R(e.projectPath).filter(l=>l==="cursor"||l==="copilot_agent"))s.push({path:`${e.projectPath} (${c} workspace proxy config)`,kind:"file",before:null,after:`proxy \u2192 http://localhost:${d}`});for(let[c,l,r]of[["Cursor",a(f(),".cursor"),a(f(),".cursor","hooks.json")],["Antigravity/Gemini",a(f(),".gemini"),a(f(),".gemini","config","hooks.json")]])p(l)&&s.push({path:`${r} (${c} user hooks)`,kind:"file",before:p(r)?"(existing config)":null,after:"adds RuleMetric session-capture hooks for this tool"});return{id:"hooks",title:"Install hooks + capture proxy",command:"rulemetric hooks install",artifacts:s}},async apply(){let e=process.env.RULEMETRIC_SETUP_NO_PROXY==="1"||process.env.RULEMETRIC_SETUP_NO_PROXY==="true";h(e?"rulemetric hooks install --no-proxy":"rulemetric hooks install")}},{id:"worker",title:"Run the worker",command:"rulemetric service install --worker-only",async detect(){return b()},async plan(){let e=process.platform==="darwin",t=e?Y:G,n=p(t)?`(service already installed at ${t})`:null,o=e?["Label: com.rulemetric.worker","ProgramArguments: <node> <cli>/bin/run.js evals agent","RunAtLoad: true, KeepAlive: true"].join(`
3
+ `),r=[],u=Math.max(n.length,o.length);for(let c=0;c<u;c++){let l=n[c],s=o[c];l===s?r.push(` ${l}`):(l!==void 0&&r.push(`-${l}`),s!==void 0&&r.push(`+${s}`))}return r.join(`
4
+ `)}i(te,"renderDiff");function x(e,t){let n=a(e,"env");if(!p(n))return null;try{let r=y(n,"utf-8").match(new RegExp(`^${t}=(.+)$`,"m"));return r?r[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={},r=null;if(p(n))try{r=y(n,"utf-8").replace(/\n$/,""),o=JSON.parse(r)}catch{o={}}return{settings:o,before:r}}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 s=u.join(`
5
+ `);return{id:"auth",title:"Authenticate",command:"rulemetric auth login",artifacts:[{path:t,kind:"file",before:n,after:s,masked:!0},{path:a(e.configDir,"auth.json"),kind:"file",before:p(a(e.configDir,"auth.json"))?"(existing session tokens)":null,after:"{ accessToken, refreshToken, expiresAt, email } \u2014 OAuth session tokens (secret)",masked:!0}]}},async apply(){h("rulemetric auth login")}},{id:"hooks",title:"Install hooks + capture proxy",command:process.env.RULEMETRIC_SETUP_NO_PROXY==="1"||process.env.RULEMETRIC_SETUP_NO_PROXY==="true"?"rulemetric hooks install --no-proxy":"rulemetric hooks install",async detect(e){for(let t of new Set([e.projectPath,f()]))for(let n of["settings.local.json","settings.json"]){let o=a(t,".claude",n);if(p(o))try{let r=JSON.parse(y(o,"utf-8"));if(T(r))return!0}catch{}}return!1},async plan(e){let t=a(e.projectPath,".claude","settings.local.json"),{before:n,after:o}=D(e.projectPath),r=[{path:t,kind:"file",before:n,after:o},{path:"what these hooks capture",kind:"service",before:null,after:"session-end reimports the FULL transcript to the API; post-tool-use records each tool call and snapshots the working tree to a LOCAL shadow git ref (paper-trail, never pushed); user-prompt posts prompt text. All scoped to sessions in this project."},{path:`${t} (proxy env block)`,kind:"file",...N(e.projectPath)},{path:"system keychain \u2014 mitmproxy root CA",kind:"service",before:p(A)?"(CA generated; trust state unchanged)":"(no CA yet)",after:"Installs + trusts the mitmproxy CA (requires sudo). This lets the proxy DECRYPT Claude Code HTTPS request/response bodies \u2014 the capability that powers rendered-system-prompt / instruction linking. Decline the sudo prompt and setup stays hooks-only (still fully onboarded)."},{path:"launchctl setenv HTTPS_PROXY (machine-wide, all GUI apps)",kind:"command",before:null,after:`http://localhost:${d} \u2014 routes every GUI app's HTTPS through the local gateway (only when the CA is trusted AND :${d} is live)`},{path:"VS Code + Cursor user settings (http.proxy)",kind:"file",before:null,after:`http.proxy \u2192 http://localhost:${d} (+ http.proxyStrictSSL=false)`},{path:`gateway process on :${d}`,kind:"service",before:null,after:"started (routes Claude Code \u2192 mitmproxy \u2192 Anthropic; falls back to direct if mitmproxy is down)"}],u=U(e.projectPath);u&&r.push({path:`${a(e.projectPath,".claude","settings.json")} (removes RuleMetric machine-local state left by an older install \u2014 see the local-file artifacts above for where it moves)`,kind:"file",...u});for(let c of R(e.projectPath).filter(l=>l==="cursor"||l==="copilot_agent"))r.push({path:`${e.projectPath} (${c} workspace proxy config)`,kind:"file",before:null,after:`proxy \u2192 http://localhost:${d}`});for(let[c,l,s]of[["Cursor",a(f(),".cursor"),a(f(),".cursor","hooks.json")],["Antigravity/Gemini",a(f(),".gemini"),a(f(),".gemini","config","hooks.json")]])p(l)&&r.push({path:`${s} (${c} user hooks)`,kind:"file",before:p(s)?"(existing config)":null,after:"adds RuleMetric session-capture hooks for this tool"});return{id:"hooks",title:"Install hooks + capture proxy",command:"rulemetric hooks install",artifacts:r}},async apply(){let e=process.env.RULEMETRIC_SETUP_NO_PROXY==="1"||process.env.RULEMETRIC_SETUP_NO_PROXY==="true";h(e?"rulemetric hooks install --no-proxy":"rulemetric hooks install")}},{id:"worker",title:"Run the worker",command:"rulemetric service install --worker-only",async detect(){return b()},async plan(){let e=process.platform==="darwin",t=e?Y:G,n=p(t)?`(service already installed at ${t})`:null,o=e?["Label: com.rulemetric.worker","ProgramArguments: <node> <cli>/bin/run.js evals agent","RunAtLoad: true, KeepAlive: true"].join(`
6
6
  `):["[Service]","ExecStart=<node> <cli>/bin/run.js evals agent","Restart=on-failure"].join(`
7
7
  `);return{id:"worker",title:"Run the worker",command:"rulemetric service install --worker-only",artifacts:[{path:t,kind:"service",before:n,after:o}]}},async apply(){h("rulemetric service install --worker-only")}},{id:"judge",title:"Second LLM engine for cross-vendor eval grading (optional)",command:"npm install -g @openai/codex",optional:!0,async detect(){let e=g();return e.claudeBin!=null&&e.codexBin!=null},async plan(){let e=g();return{id:"judge",title:"Second LLM engine for cross-vendor eval grading (optional)",command:"npm install -g @openai/codex",artifacts:[{path:"installed LLM engines",kind:"command",before:[`claude CLI: ${e.claudeBin??"not found"}`,`codex CLI: ${e.codexBin??"not found"}`].join(`
8
8
  `),after:["claude CLI + codex CLI both installed.","Hand labels + one judge already give calibrated verdicts; a second","engine additionally unlocks cross-vendor judge validation","(`rulemetric evals validate-judge`)."].join(`
9
9
  `)}]}},async apply(){let e=g();if(e.claudeBin!=null&&e.codexBin!=null){console.log("[OK] Both engines already installed \u2014 nothing to do.");return}let t=e.codexBin==null?"codex":"claude";console.log(`[..] Second GRADING engine not detected (missing: ${t} CLI).`),t==="codex"?(console.log(" This is about GRADING EVALS with a second vendor, not about capturing"),console.log(" your Codex sessions. Codex capture needs no setup: the worker imports"),console.log(" ~/.codex/sessions automatically. Nothing is missing for that."),console.log(" Optional install: npm install -g @openai/codex")):console.log(" Install it yourself when ready: npm install -g @anthropic-ai/claude-code"),console.log(" Then re-run: rulemetric setup judge --show")}}],H=new Map(L.map(e=>[e.id,e]));function ne(e){let t=H.get(e);if(!t)throw new Error(`Unknown setup step: ${e}`);return t}i(ne,"getStep");function oe(e){return M.includes(e)}i(oe,"isStepId");var K=new Set(["RULEMETRIC_API_URL","RULEMETRIC_USER_ID","RULEMETRIC_CLIENT_NAME","RESEND_FROM_EMAIL","SENTRY_DSN","PG_POOL_MAX","PG_IDLE_TIMEOUT","PG_STATEMENT_TIMEOUT_MS","NODE_ENV"]);function X(e){return e.replace(/\n$/,"").split(`
10
- `).map(t=>{let n=t.match(/^([A-Z0-9_]+)=(.+)$/);if(!n)return t;let[,o,s]=n;return K.has(o)?t:`${o}=${S(s)}`}).join(`
11
- `)}i(X,"maskEnvFile");async function re(e=$()){let t=[];for(let r of L){let w=await r.detect(e);t.push({id:r.id,done:w})}let n=new Set(P),o=t.find(r=>r.id==="install");o&&!o.done&&(o.done=t.some(r=>r.id!=="install"&&n.has(r.id)&&r.done));let s=new Set(P),u=t.filter(r=>s.has(r.id)),c=u.find(r=>!r.done)?.id??null,l=u.every(r=>r.done);return{steps:t,coreComplete:l,currentStepId:c}}i(re,"computeStatus");export{P as a,O as b,M as c,$ as d,S as e,te as f,L as g,ne as h,oe as i,re as j};
10
+ `).map(t=>{let n=t.match(/^([A-Z0-9_]+)=(.+)$/);if(!n)return t;let[,o,r]=n;return K.has(o)?t:`${o}=${S(r)}`}).join(`
11
+ `)}i(X,"maskEnvFile");async function re(e=$()){let t=[];for(let s of L){let w=await s.detect(e);t.push({id:s.id,done:w})}let n=new Set(P),o=t.find(s=>s.id==="install");o&&!o.done&&(o.done=t.some(s=>s.id!=="install"&&n.has(s.id)&&s.done));let r=new Set(P),u=t.filter(s=>r.has(s.id)),c=u.find(s=>!s.done)?.id??null,l=u.every(s=>s.done);return{steps:t,coreComplete:l,currentStepId:c}}i(re,"computeStatus");export{P as a,O as b,M as c,$ as d,S as e,te as f,L as g,ne as h,oe as i,re as j};
@@ -1 +1 @@
1
- import{c as te}from"./chunk-5U5SHJJA.js";import{b as oe}from"./chunk-IEQDLURA.js";import{d as ie,e as le,f as de}from"./chunk-KINIFUZQ.js";import{a as Y}from"./chunk-QRKMRG6W.js";import{a as B}from"./chunk-D7L7IMJQ.js";import{a as x}from"./chunk-MRQIYIQE.js";import{a as W}from"./chunk-PMMHMRFS.js";import{a as K}from"./chunk-IYX65N6T.js";import{a as V}from"./chunk-GHUW7P55.js";import{a as U}from"./chunk-MBP5OJKE.js";import{a as z}from"./chunk-BRYURAUN.js";import{b as F}from"./chunk-NLUHMHPM.js";import{a as Q}from"./chunk-DTTR4EUJ.js";import{a as X}from"./chunk-WLLIFRRE.js";import{a as G}from"./chunk-ZYGBABMZ.js";import{b as $}from"./chunk-5RBLIVBF.js";import{a as se}from"./chunk-NSO2EBYE.js";import{e as T}from"./chunk-2C7CFCMM.js";import{b as q}from"./chunk-WSUKOU3X.js";import{c as C}from"./chunk-A6XQSO62.js";import{a as ee}from"./chunk-IPNBW7ZW.js";import{a as j}from"./chunk-P577DWWL.js";import{a as ne}from"./chunk-7MQZPDDZ.js";import{a as L}from"./chunk-ANLPPIMS.js";import{a as re}from"./chunk-TG4C4ENM.js";import{a as Z}from"./chunk-MJLW5KN2.js";import{d as P}from"./chunk-SW24KZ5C.js";import{a as ae}from"./chunk-RWQG25JU.js";import{b as y,c as O,f as o,g as A,i as J,j as b}from"./chunk-3ZHBOILE.js";import{k as N}from"./chunk-MGT5FZJ4.js";import{d as M}from"./chunk-GPBN4ROE.js";import{b as R,e as H,f as D}from"./chunk-5VWVQCNR.js";import{a as l}from"./chunk-ZLLER3HP.js";var E=null,S=new Map,_e={process_eval:V,process_suggestion_eval:W,process_suggestion_discovery:x,process_insights:U,process_launch:F,process_send_message:G,process_conversation:K,process_session_goal:Y,distill_memories:q,memory_ab:Q,process_run_cleanup:X,cron_refine_cases:re,cron_retire_unused_skills:se,cron_reconcile_attribution:L,cron_suggest_instructions:T,cron_refresh_skills:P,cron_refresh_pricing:Z,cron_eval_autorun:j,process_suggestion_adoption:B,cron_auto_accept_suggestions:ee,cron_instruction_training:ne,cron_instruction_evolution:N,process_judge_review:z,harbor_ab:C},ce=500,ue=1e4,pe=Object.keys(_e),ve=new Set([]);function we(e=process.env){return e.DATABASE_URL?pe:pe.filter(s=>!ve.has(s))}l(we,"availableCapabilities");var he=3e4,be=3e4;async function Se(e,s,t=M(),i){let d=[...t.claudeBin?["claude"]:[],...t.codexBin?["codex"]:[],...t.piBin?["pi"]:[]],c=`capabilities=${encodeURIComponent(e.join(","))}&waitMs=${s}&measurementProtocol=1&studyProtocol=1&scopedCollector=2&memorySnapshots=1&boundedAutorun=1&measurementEngines=${encodeURIComponent(d.join(","))}`,u=await H(`/api/work/next?${c}${i?`&launchMode=${i}`:""}`);return u==null||typeof u=="string"?null:u}l(Se,"pollForWork");function Ie(e,s,t){return{logger:{info:l(i=>s(i),"info"),warn:l(i=>s(i),"warn"),error:l(i=>s(i),"error")},job:{attempts:e},leaseSignal:t}}l(Ie,"makeHelpers");async function ye(e,s,t,i){let d=_e[e.kind],c=Date.now();if(o(t,{event:"claim",jobId:e.id,kind:e.kind,attempts:e.attempts}),!d){let n=`unknown kind: ${e.kind}`;o(t,{event:"fail",jobId:e.id,kind:e.kind,terminal:!0,error:n}),await D(`/api/work/${e.id}/fail`,{leaseToken:e.leaseToken,error:n,terminal:!0}).catch(()=>{});return}let u=new AbortController,m=!1,k,g=l(()=>{m||(o(t,{event:"heartbeat",jobId:e.id}),b(`/api/work/${e.id}/heartbeat`,{leaseToken:e.leaseToken},{budgetMs:Math.min(O,Math.max(0,s-1e3)),signal:i,log:t,event:"heartbeat",jobId:e.id}).then(n=>{if(!(n.ok||m)){if(J(n.error)){m=!0,k!==void 0&&clearInterval(k),o(t,{event:"lease_lost",jobId:e.id,kind:e.kind,elapsedMs:Date.now()-c,error:n.error instanceof Error?n.error.message:String(n.error)}),u.abort(new Error(`lease lost for job ${e.id} (${e.kind}); stop work`));return}o(t,{event:"heartbeat_error",jobId:e.id,attempts:n.attempts,error:n.error instanceof Error?n.error.message:String(n.error)})}}))},"beat");k=setInterval(g,s),S.set(e.id,g);let a;try{let n=Ie(e.attempts,t,u.signal);a={kind:"complete",result:await d(e.payload,n)??{}}}catch(n){let v=E?.pausesSince(c)??[],_=de(v),w=n instanceof Error?n.message:String(n),r=$(n),p=!r&&le(v);a={kind:"fail",message:_?`${_}; ${w}`:w,pausedDuringJob:!!_,terminal:r,hostSuspended:p}}try{if(m)o(t,{event:"lease_lost_stop",jobId:e.id,kind:e.kind,durationMs:Date.now()-c,handlerOutcome:a.kind,...a.kind==="fail"?{error:a.message}:{}});else if(a.kind==="complete"){o(t,{event:"complete",jobId:e.id,kind:e.kind,durationMs:Date.now()-c});let n=await b(`/api/work/${e.id}/complete`,{leaseToken:e.leaseToken,result:a.result},{budgetMs:y,signal:i,log:t,event:"complete_post",jobId:e.id});n.ok||o(t,{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{o(t,{event:"fail",jobId:e.id,kind:e.kind,durationMs:Date.now()-c,terminal:a.terminal,error:a.message,...a.pausedDuringJob?{pausedDuringJob:!0}:{},...a.hostSuspended?{hostSuspended:!0}:{}});let n=await b(`/api/work/${e.id}/fail`,{leaseToken:e.leaseToken,error:a.message,terminal:a.terminal,hostSuspended:a.hostSuspended},{budgetMs:y,signal:i,log:t,event:"fail_post",jobId:e.id});n.ok||o(t,{event:"fail_post_error",jobId:e.id,attempts:n.attempts,error:n.error instanceof Error?n.error.message:String(n.error)})}}finally{clearInterval(k),S.delete(e.id)}}l(ye,"runOne");var me=new Set(["process_launch","process_eval","process_suggestion_eval","process_suggestion_discovery","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"]),ge=new Set(["cron_refresh_skills"]);async function tn(e){let s=e.log??(()=>{}),t=e.pollWaitMs??he,i=e.heartbeatIntervalMs??be,d=e.capabilities??we();o(s,{event:"agent_start",capabilities:d,pollWaitMs:t,heartbeatIntervalMs:i});try{let r=oe();r.removed.length>0&&o(s,{event:"eval_worktrees_swept",removed:r.removed.length})}catch(r){o(s,{event:"eval_worktree_sweep_failed",error:r instanceof Error?r.message:String(r)})}E=ie({signal:e.signal,onPause:l(r=>{o(s,{event:"machine_pause",...r,jobIds:[...S.keys()]});for(let p of S.values())p()},"onPause")});let c=ae(d,e.signal,s,e.version,()=>E);te({signal:e.signal,log:s}).catch(r=>{o(s,{event:"tt_heartbeat_fatal",error:r instanceof Error?r.message:String(r)})});let u=5*6e4,m=0,k=l(()=>{if(!e.readInstalledVersion||!e.version)return!1;let r=Date.now();if(r-m<u)return!1;m=r;let p=e.readInstalledVersion();return!!(p&&p!==e.version)},"versionDrifted"),g=new AbortController,a=g.signal;e.signal.aborted?g.abort():e.signal.addEventListener("abort",()=>g.abort(),{once:!0});let n=l(async(r,p,fe)=>{let f=ce;for(;!a.aborted;){if(k()){o(s,{event:"agent_version_drift",bootVersion:e.version,installedVersion:e.readInstalledVersion?.()??null}),g.abort(),e.onVersionDrift?.();break}let I=null;try{I=await Se([...p],t,void 0,fe)}catch(h){let ke=h instanceof R?h.statusCode:void 0;if(o(s,{event:"poll_error",lane:r,status:ke,error:h instanceof Error?h.message:String(h)}),!await A(f,a))break;f=Math.min(f*2,ue);continue}if(!I){if(o(s,{event:"poll_204",lane:r}),!await A(f,a))break;f=Math.min(f*2,ue);continue}f=ce,await ye(I,i,s,a)}},"runLane"),v=d.filter(r=>me.has(r)),_=d.filter(r=>(r==="process_launch"||!me.has(r))&&!ge.has(r)),w=d.filter(r=>ge.has(r));o(s,{event:"agent_lanes",heavy:v.length,fast:_.length,background:w.length}),await Promise.all([...v.length?[n("heavy",v,"headless")]:[],..._.length?[n("fast",_,"interactive")]:[],...w.length?[n("background",w)]:[]]),await c.shutdown(),o(s,{event:"agent_stop"})}l(tn,"runAgentLoop");export{_e as a,pe as b,we as c,Se as d,tn as e};
1
+ import{c as te}from"./chunk-5U5SHJJA.js";import{b as oe}from"./chunk-IEQDLURA.js";import{d as ie,e as le,f as de}from"./chunk-KINIFUZQ.js";import{a as G}from"./chunk-ZYGBABMZ.js";import{a as Y}from"./chunk-QRKMRG6W.js";import{a as B}from"./chunk-D7L7IMJQ.js";import{a as x}from"./chunk-MRQIYIQE.js";import{a as W}from"./chunk-PMMHMRFS.js";import{a as K}from"./chunk-IYX65N6T.js";import{a as V}from"./chunk-GHUW7P55.js";import{a as U}from"./chunk-RAMQVEJB.js";import{a as z}from"./chunk-BRYURAUN.js";import{b as F}from"./chunk-NLUHMHPM.js";import{a as Q}from"./chunk-DTTR4EUJ.js";import{a as X}from"./chunk-WLLIFRRE.js";import{b as $}from"./chunk-5RBLIVBF.js";import{d as P}from"./chunk-SW24KZ5C.js";import{a as se}from"./chunk-NSO2EBYE.js";import{e as T}from"./chunk-2C7CFCMM.js";import{b as q}from"./chunk-WSUKOU3X.js";import{c as C}from"./chunk-A6XQSO62.js";import{a as ee}from"./chunk-IPNBW7ZW.js";import{a as j}from"./chunk-P577DWWL.js";import{a as ne}from"./chunk-7MQZPDDZ.js";import{a as L}from"./chunk-ANLPPIMS.js";import{a as re}from"./chunk-CXENLSMR.js";import{a as Z}from"./chunk-MJLW5KN2.js";import{a as ae}from"./chunk-RWQG25JU.js";import{b as y,c as O,f as o,g as A,i as J,j as b}from"./chunk-3ZHBOILE.js";import{k as N}from"./chunk-L5ILEWHH.js";import{d as M}from"./chunk-GPBN4ROE.js";import{b as R,e as H,f as D}from"./chunk-5VWVQCNR.js";import{a as l}from"./chunk-ZLLER3HP.js";var E=null,S=new Map,_e={process_eval:V,process_suggestion_eval:W,process_suggestion_discovery:x,process_insights:U,process_launch:F,process_send_message:G,process_conversation:K,process_session_goal:Y,distill_memories:q,memory_ab:Q,process_run_cleanup:X,cron_refine_cases:re,cron_retire_unused_skills:se,cron_reconcile_attribution:L,cron_suggest_instructions:T,cron_refresh_skills:P,cron_refresh_pricing:Z,cron_eval_autorun:j,process_suggestion_adoption:B,cron_auto_accept_suggestions:ee,cron_instruction_training:ne,cron_instruction_evolution:N,process_judge_review:z,harbor_ab:C},ce=500,ue=1e4,pe=Object.keys(_e),ve=new Set([]);function we(e=process.env){return e.DATABASE_URL?pe:pe.filter(s=>!ve.has(s))}l(we,"availableCapabilities");var he=3e4,be=3e4;async function Se(e,s,t=M(),i){let d=[...t.claudeBin?["claude"]:[],...t.codexBin?["codex"]:[],...t.piBin?["pi"]:[]],c=`capabilities=${encodeURIComponent(e.join(","))}&waitMs=${s}&measurementProtocol=1&studyProtocol=1&scopedCollector=2&memorySnapshots=1&boundedAutorun=1&measurementEngines=${encodeURIComponent(d.join(","))}`,u=await H(`/api/work/next?${c}${i?`&launchMode=${i}`:""}`);return u==null||typeof u=="string"?null:u}l(Se,"pollForWork");function Ie(e,s,t){return{logger:{info:l(i=>s(i),"info"),warn:l(i=>s(i),"warn"),error:l(i=>s(i),"error")},job:{attempts:e},leaseSignal:t}}l(Ie,"makeHelpers");async function ye(e,s,t,i){let d=_e[e.kind],c=Date.now();if(o(t,{event:"claim",jobId:e.id,kind:e.kind,attempts:e.attempts}),!d){let n=`unknown kind: ${e.kind}`;o(t,{event:"fail",jobId:e.id,kind:e.kind,terminal:!0,error:n}),await D(`/api/work/${e.id}/fail`,{leaseToken:e.leaseToken,error:n,terminal:!0}).catch(()=>{});return}let u=new AbortController,m=!1,k,g=l(()=>{m||(o(t,{event:"heartbeat",jobId:e.id}),b(`/api/work/${e.id}/heartbeat`,{leaseToken:e.leaseToken},{budgetMs:Math.min(O,Math.max(0,s-1e3)),signal:i,log:t,event:"heartbeat",jobId:e.id}).then(n=>{if(!(n.ok||m)){if(J(n.error)){m=!0,k!==void 0&&clearInterval(k),o(t,{event:"lease_lost",jobId:e.id,kind:e.kind,elapsedMs:Date.now()-c,error:n.error instanceof Error?n.error.message:String(n.error)}),u.abort(new Error(`lease lost for job ${e.id} (${e.kind}); stop work`));return}o(t,{event:"heartbeat_error",jobId:e.id,attempts:n.attempts,error:n.error instanceof Error?n.error.message:String(n.error)})}}))},"beat");k=setInterval(g,s),S.set(e.id,g);let a;try{let n=Ie(e.attempts,t,u.signal);a={kind:"complete",result:await d(e.payload,n)??{}}}catch(n){let v=E?.pausesSince(c)??[],_=de(v),w=n instanceof Error?n.message:String(n),r=$(n),p=!r&&le(v);a={kind:"fail",message:_?`${_}; ${w}`:w,pausedDuringJob:!!_,terminal:r,hostSuspended:p}}try{if(m)o(t,{event:"lease_lost_stop",jobId:e.id,kind:e.kind,durationMs:Date.now()-c,handlerOutcome:a.kind,...a.kind==="fail"?{error:a.message}:{}});else if(a.kind==="complete"){o(t,{event:"complete",jobId:e.id,kind:e.kind,durationMs:Date.now()-c});let n=await b(`/api/work/${e.id}/complete`,{leaseToken:e.leaseToken,result:a.result},{budgetMs:y,signal:i,log:t,event:"complete_post",jobId:e.id});n.ok||o(t,{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{o(t,{event:"fail",jobId:e.id,kind:e.kind,durationMs:Date.now()-c,terminal:a.terminal,error:a.message,...a.pausedDuringJob?{pausedDuringJob:!0}:{},...a.hostSuspended?{hostSuspended:!0}:{}});let n=await b(`/api/work/${e.id}/fail`,{leaseToken:e.leaseToken,error:a.message,terminal:a.terminal,hostSuspended:a.hostSuspended},{budgetMs:y,signal:i,log:t,event:"fail_post",jobId:e.id});n.ok||o(t,{event:"fail_post_error",jobId:e.id,attempts:n.attempts,error:n.error instanceof Error?n.error.message:String(n.error)})}}finally{clearInterval(k),S.delete(e.id)}}l(ye,"runOne");var me=new Set(["process_launch","process_eval","process_suggestion_eval","process_suggestion_discovery","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"]),ge=new Set(["cron_refresh_skills"]);async function tn(e){let s=e.log??(()=>{}),t=e.pollWaitMs??he,i=e.heartbeatIntervalMs??be,d=e.capabilities??we();o(s,{event:"agent_start",capabilities:d,pollWaitMs:t,heartbeatIntervalMs:i});try{let r=oe();r.removed.length>0&&o(s,{event:"eval_worktrees_swept",removed:r.removed.length})}catch(r){o(s,{event:"eval_worktree_sweep_failed",error:r instanceof Error?r.message:String(r)})}E=ie({signal:e.signal,onPause:l(r=>{o(s,{event:"machine_pause",...r,jobIds:[...S.keys()]});for(let p of S.values())p()},"onPause")});let c=ae(d,e.signal,s,e.version,()=>E);te({signal:e.signal,log:s}).catch(r=>{o(s,{event:"tt_heartbeat_fatal",error:r instanceof Error?r.message:String(r)})});let u=5*6e4,m=0,k=l(()=>{if(!e.readInstalledVersion||!e.version)return!1;let r=Date.now();if(r-m<u)return!1;m=r;let p=e.readInstalledVersion();return!!(p&&p!==e.version)},"versionDrifted"),g=new AbortController,a=g.signal;e.signal.aborted?g.abort():e.signal.addEventListener("abort",()=>g.abort(),{once:!0});let n=l(async(r,p,fe)=>{let f=ce;for(;!a.aborted;){if(k()){o(s,{event:"agent_version_drift",bootVersion:e.version,installedVersion:e.readInstalledVersion?.()??null}),g.abort(),e.onVersionDrift?.();break}let I=null;try{I=await Se([...p],t,void 0,fe)}catch(h){let ke=h instanceof R?h.statusCode:void 0;if(o(s,{event:"poll_error",lane:r,status:ke,error:h instanceof Error?h.message:String(h)}),!await A(f,a))break;f=Math.min(f*2,ue);continue}if(!I){if(o(s,{event:"poll_204",lane:r}),!await A(f,a))break;f=Math.min(f*2,ue);continue}f=ce,await ye(I,i,s,a)}},"runLane"),v=d.filter(r=>me.has(r)),_=d.filter(r=>(r==="process_launch"||!me.has(r))&&!ge.has(r)),w=d.filter(r=>ge.has(r));o(s,{event:"agent_lanes",heavy:v.length,fast:_.length,background:w.length}),await Promise.all([...v.length?[n("heavy",v,"headless")]:[],..._.length?[n("fast",_,"interactive")]:[],...w.length?[n("background",w)]:[]]),await c.shutdown(),o(s,{event:"agent_stop"})}l(tn,"runAgentLoop");export{_e as a,pe as b,we as c,Se as d,tn as e};
@@ -1,35 +1,35 @@
1
- import{a as f,b as M}from"./chunk-BDWQ6J4V.js";import{e as _,f as S}from"./chunk-MHLHLJ5T.js";import{a as o}from"./chunk-ZLLER3HP.js";import*as m from"node:fs/promises";import*as x from"node:path";import{eq as j}from"drizzle-orm";import{randomBytes as Y}from"node:crypto";var A="#0d9488",h="#1a1a1a",$="#666666",C="#f5f5f7",N="#ffffff",D="#e5e5e9",I=["Added","Changed","Fixed","Removed","Deprecated","Security"];function U(e){let t=["January","February","March","April","May","June","July","August","September","October","November","December"],[n,r,a]=e.split("-").map(d=>parseInt(d,10));return!n||!r||!a||r<1||r>12?e:`${t[r-1]} ${a}, ${n}`}o(U,"formatIsoDate");function l(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}o(l,"escapeHtml");function z(e){let t=[];for(let n of I){let r=e[n];r&&r.length>0&&t.push({name:n,items:r})}return t}o(z,"orderedSections");function v(e){let{version:t,date:n,sections:r,unsubscribeUrl:a,productUrl:d,recipientName:u}=e,c=U(n),s=`What's new in RuleMetric \u2014 ${c}`,y=u?`Hi ${u},`:"Hi there,",i=z(r),p=new Date().getUTCFullYear(),b=i.map(({name:R,items:E})=>{let w=E.map(O=>` <li style="margin:0 0 6px 0;font-size:15px;line-height:1.5;color:${h};">${l(O)}</li>`).join(`
2
- `);return` <h3 style="margin:24px 0 8px 0;font-size:16px;line-height:1.3;font-weight:600;color:${h};">${R}</h3>
1
+ import{a as f,b as k}from"./chunk-BDWQ6J4V.js";import{e as _,f as S}from"./chunk-MHLHLJ5T.js";import{a as o}from"./chunk-ZLLER3HP.js";import*as m from"node:fs/promises";import*as $ from"node:path";import{eq as j}from"drizzle-orm";import{randomBytes as Y}from"node:crypto";var C="#0d9488",h="#1a1a1a",x="#666666",A="#f5f5f7",N="#ffffff",D="#e5e5e9",I=["Added","Changed","Fixed","Removed","Deprecated","Security"];function U(e){let t=["January","February","March","April","May","June","July","August","September","October","November","December"],[n,r,a]=e.split("-").map(d=>parseInt(d,10));return!n||!r||!a||r<1||r>12?e:`${t[r-1]} ${a}, ${n}`}o(U,"formatIsoDate");function c(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}o(c,"escapeHtml");function z(e){let t=[];for(let n of I){let r=e[n];r&&r.length>0&&t.push({name:n,items:r})}return t}o(z,"orderedSections");function v(e){let{version:t,date:n,sections:r,unsubscribeUrl:a,productUrl:d,recipientName:u}=e,l=U(n),s=`What's new in RuleMetric \u2014 ${l}`,y=u?`Hi ${u},`:"Hi there,",i=z(r),p=new Date().getUTCFullYear(),b=i.map(({name:w,items:R})=>{let E=R.map(O=>` <li style="margin:0 0 6px 0;font-size:15px;line-height:1.5;color:${h};">${c(O)}</li>`).join(`
2
+ `);return` <h3 style="margin:24px 0 8px 0;font-size:16px;line-height:1.3;font-weight:600;color:${h};">${w}</h3>
3
3
  <ul style="margin:0 0 8px 0;padding-left:20px;">
4
- ${w}
4
+ ${E}
5
5
  </ul>`}).join(`
6
- `),k=`<!doctype html>
6
+ `),M=`<!doctype html>
7
7
  <html lang="en">
8
8
  <head>
9
9
  <meta charset="utf-8" />
10
10
  <meta name="viewport" content="width=device-width, initial-scale=1" />
11
- <title>${l(s)}</title>
11
+ <title>${c(s)}</title>
12
12
  </head>
13
- <body style="margin:0;padding:0;background:${C};font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;color:${h};">
14
- <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="background:${C};padding:32px 16px;">
13
+ <body style="margin:0;padding:0;background:${A};font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;color:${h};">
14
+ <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="background:${A};padding:32px 16px;">
15
15
  <tr>
16
16
  <td align="center">
17
17
  <table role="presentation" width="560" cellspacing="0" cellpadding="0" border="0" style="max-width:560px;background:${N};border:1px solid ${D};border-radius:8px;overflow:hidden;">
18
18
  <tr>
19
19
  <td style="padding:24px 32px 8px 32px;">
20
- <a href="${l(d)}" style="text-decoration:none;color:${A};font-size:14px;font-weight:600;">RuleMetric</a>
20
+ <a href="${c(d)}" style="text-decoration:none;color:${C};font-size:14px;font-weight:600;">RuleMetric</a>
21
21
  </td>
22
22
  </tr>
23
23
  <tr>
24
24
  <td style="padding:8px 32px 8px 32px;">
25
25
  <h1 style="margin:0 0 8px 0;font-size:22px;line-height:1.3;font-weight:600;color:${h};">
26
- What's new \u2014 ${l(c)}
26
+ What's new \u2014 ${c(l)}
27
27
  </h1>
28
- <p style="margin:0 0 8px 0;font-size:13px;line-height:1.5;color:${$};">
29
- Release ${l(t)}
28
+ <p style="margin:0 0 8px 0;font-size:13px;line-height:1.5;color:${x};">
29
+ Release ${c(t)}
30
30
  </p>
31
31
  <p style="margin:16px 0 0 0;font-size:15px;line-height:1.5;color:${h};">
32
- ${l(y)}
32
+ ${c(y)}
33
33
  </p>
34
34
  <p style="margin:8px 0 0 0;font-size:15px;line-height:1.5;color:${h};">
35
35
  Here's what shipped in the latest RuleMetric release.
@@ -43,16 +43,16 @@ ${b}
43
43
  </tr>
44
44
  <tr>
45
45
  <td style="padding:16px 32px 24px 32px;border-top:1px solid ${D};">
46
- <p style="margin:0 0 8px 0;font-size:12px;line-height:1.5;color:${$};">
46
+ <p style="margin:0 0 8px 0;font-size:12px;line-height:1.5;color:${x};">
47
47
  You're receiving this because you signed up for RuleMetric product updates. If you'd rather not hear about new releases, you can unsubscribe at any time.
48
48
  </p>
49
49
  <p style="margin:0 0 4px 0;font-size:12px;line-height:1.5;">
50
- <a href="${l(a)}" style="color:${A};text-decoration:underline;">Unsubscribe</a>
50
+ <a href="${c(a)}" style="color:${C};text-decoration:underline;">Unsubscribe</a>
51
51
  </p>
52
- <p style="margin:0 0 12px 0;font-size:12px;line-height:1.5;color:${$};word-break:break-all;">
53
- ${l(a)}
52
+ <p style="margin:0 0 12px 0;font-size:12px;line-height:1.5;color:${x};word-break:break-all;">
53
+ ${c(a)}
54
54
  </p>
55
- <p style="margin:0;font-size:11px;line-height:1.5;color:${$};">
55
+ <p style="margin:0;font-size:11px;line-height:1.5;color:${x};">
56
56
  RuleMetric \u2022 ${p}
57
57
  </p>
58
58
  </td>
@@ -62,5 +62,5 @@ ${b}
62
62
  </tr>
63
63
  </table>
64
64
  </body>
65
- </html>`,g=[`What's new in RuleMetric \u2014 ${c}`,`Release ${t}`,"",y,"","Here's what shipped in the latest RuleMetric release.",""];for(let{name:R,items:E}of i){g.push(`${R}:`);for(let w of E)g.push(` - ${w}`);g.push("")}g.push("--","You're receiving this because you signed up for RuleMetric product updates.",`Unsubscribe: ${a}`,"",`RuleMetric \u2022 ${p}`);let T=g.join(`
66
- `);return{subject:s,html:k,text:T}}o(v,"renderChangelogAnnouncement");async function P(e){let t=e;for(let n=0;n<50;n++){try{return await m.stat(x.join(t,"pnpm-workspace.yaml")),t}catch{}let r=x.dirname(t);if(r===t)return null;t=r}return null}o(P,"findRepoRoot");async function L(e){if(e)try{return await m.readFile(e,"utf-8")}catch{return null}let t=await P(process.cwd())??process.cwd(),n=x.join(t,"CHANGELOG.md");try{return await m.readFile(n,"utf-8")}catch{return null}}o(L,"readChangelog");var B="https://rulemetric.com";function F(e){let t=e.date??new Date().toISOString().slice(0,10),n=v({version:e.version,date:t,sections:e.sections,unsubscribeUrl:"{{unsubscribe_url}}",recipientName:"{{recipient_name}}",productUrl:B});return{version:e.version,releaseDate:t,subject:n.subject,htmlBody:n.html,textBody:n.text,sections:e.sections}}o(F,"renderRow");async function Re(e={}){let t=e.db??M(),n=e.logger??{info:o(s=>console.log(s),"info"),warn:o(s=>console.warn(s),"warn")},r=await L(e.changelogPath);if(r===null)return n.info("[cron_check_changelog] CHANGELOG.md not found; nothing to do"),{createdCount:0,skippedCount:0};let a=_(r),d=S(a);if(d.length===0)return n.info("[cron_check_changelog] No announceable entries; nothing to do"),{createdCount:0,skippedCount:0};let u=0,c=0;for(let s of d){if((await t.select({id:f.id}).from(f).where(j(f.version,s.version)).limit(1)).length>0){c++;continue}let i=F(s);try{await t.insert(f).values({version:i.version,releaseDate:i.releaseDate,subject:i.subject,htmlBody:i.htmlBody,textBody:i.textBody,sections:i.sections,status:"draft"}),u++,n.info(`[cron_check_changelog] Created draft announcement for ${i.version}`)}catch(p){let b=p instanceof Error?p.message:String(p);if(/duplicate key|unique/i.test(b)){c++;continue}throw p}}return n.info(`[cron_check_changelog] Done: created ${u}, skipped ${c}`),{createdCount:u,skippedCount:c}}o(Re,"processChangelog");export{Re as a};
65
+ </html>`,g=[`What's new in RuleMetric \u2014 ${l}`,`Release ${t}`,"",y,"","Here's what shipped in the latest RuleMetric release.",""];for(let{name:w,items:R}of i){g.push(`${w}:`);for(let E of R)g.push(` - ${E}`);g.push("")}g.push("--","You're receiving this because you signed up for RuleMetric product updates.",`Unsubscribe: ${a}`,"",`RuleMetric \u2022 ${p}`);let T=g.join(`
66
+ `);return{subject:s,html:M,text:T}}o(v,"renderChangelogAnnouncement");async function L(e){let t=e;for(let n=0;n<50;n++){try{return await m.stat($.join(t,"pnpm-workspace.yaml")),t}catch{}let r=$.dirname(t);if(r===t)return null;t=r}return null}o(L,"findRepoRoot");async function P(e){if(e)try{return await m.readFile(e,"utf-8")}catch{return null}let t=await L(process.cwd())??process.cwd(),n=$.join(t,"CHANGELOG.md");try{return await m.readFile(n,"utf-8")}catch{return null}}o(P,"readChangelog");var B="https://rulemetric.com";function F(e){let t=e.date??new Date().toISOString().slice(0,10),n=v({version:e.version,date:t,sections:e.sections,unsubscribeUrl:"{{unsubscribe_url}}",recipientName:"{{recipient_name}}",productUrl:B});return{version:e.version,releaseDate:t,subject:n.subject,htmlBody:n.html,textBody:n.text,sections:e.sections}}o(F,"renderRow");async function we(e={}){let t=e.db??k(),n=e.logger??{info:o(s=>console.log(s),"info"),warn:o(s=>console.warn(s),"warn")},r=await P(e.changelogPath);if(r===null)return n.info("[cron_check_changelog] CHANGELOG.md not found; nothing to do"),{createdCount:0,skippedCount:0};let a=_(r),d=S(a);if(d.length===0)return n.info("[cron_check_changelog] No announceable entries; nothing to do"),{createdCount:0,skippedCount:0};let u=0,l=0;for(let s of d){if((await t.select({id:f.id}).from(f).where(j(f.version,s.version)).limit(1)).length>0){l++;continue}let i=F(s);try{await t.insert(f).values({version:i.version,releaseDate:i.releaseDate,subject:i.subject,htmlBody:i.htmlBody,textBody:i.textBody,sections:i.sections,status:"draft"}),u++,n.info(`[cron_check_changelog] Created draft announcement for ${i.version}`)}catch(p){let b=p instanceof Error?p.message:String(p);if(/duplicate key|unique/i.test(b)){l++;continue}throw p}}return n.info(`[cron_check_changelog] Done: created ${u}, skipped ${l}`),{createdCount:u,skippedCount:l}}o(we,"processChangelog");export{we as a};
@@ -1,4 +1,4 @@
1
- import{a as N}from"./chunk-5RBLIVBF.js";import{b as Z,d as X}from"./chunk-K65DDLTZ.js";import{a as se}from"./chunk-LELSVLNK.js";import{c as ee}from"./chunk-A2JFQUDW.js";import{a as K,b as Y}from"./chunk-LZPE6424.js";import{a as A,d as F}from"./chunk-3UKZJAFS.js";import{a as O,b as M,c as Q,d as G}from"./chunk-77FH6UZP.js";import{b as B,e as V,g as R}from"./chunk-GWQ24FQP.js";import{e as $,f as U,h as f}from"./chunk-5VWVQCNR.js";import{a as q,b as W}from"./chunk-MHLHLJ5T.js";import{a as _}from"./chunk-ZLLER3HP.js";var te=_((c,{limit:i,sort:n,eventTypes:e})=>$(`/api/sessions/${c}/events?limit=${i}&sort=${n}&eventType=${encodeURIComponent(e.join(","))}&hasContent=true`),"fetchTranscriptTurns");async function _e(c,i){let{mirrorId:n,projectPath:e,projectId:r,config:u}=c,s=_(t=>i.logger.info(t),"log");if(u?.sessionId)return re({mirrorId:n,sessionId:u.sessionId},s);s(`Processing insights job ${n}...`),await f(`/api/insights-jobs/${n}/progress`,{status:"running",progress:{step:"reading_data"}});try{let{repaired:t}=await U("/api/sessions/repair-analyzed-at",{});t>0&&s(` Repaired analyzed_at on ${t} orphan session(s).`)}catch(t){s(` Warning: analyzed_at repair failed: ${t instanceof Error?t.message:String(t)}`)}let y=20,w=200,x=15*6e4,J=3,v=Date.now()+x,C=V()==="none"?"no-llm-backend":null,g={attempted:0,generated:0,failed:0,ungradeable:0,stopReason:C??"queue-exhausted"};if(C&&i.logger.warn?.("[process-insights] no LLM backend (no claude/codex CLI and no ANTHROPIC_API_KEY) \u2014 facet grading SKIPPED for this run; the summary below is computed from already-graded sessions only"),!C){let t=0,a=0;try{for(;t<w&&Date.now()<v;){let d=await $(`/api/sessions?needsFacets=true&graderVersion=${2}&limit=${y}&offset=${a}`);if(d.length===0)break;s(` Generating facets for ${d.length} un-analyzed sessions (drained ${t} so far)...`);for(let I=0;I<d.length&&!(t>=w||Date.now()>=v);I+=J){let j=d.slice(I,I+J);await Promise.all(j.map(async p=>{if(!(t>=w||Date.now()>=v)){g.attempted++;try{let l=await F(oe=>te(p.id,oe));if(l.turnCount<2){g.ungradeable++,t++,a++;return}let D=await R(G,l.text,4096);D&&typeof D.outcome=="string"?(await f(`/api/sessions/${p.id}/enrich`,{analysis:{source:"generated_facets",...D,graderVersion:2},...p.eventCount!=null?{analyzedEventCount:p.eventCount}:{},analyzedTurnCount:l.turnCount}),s(` Generated facets for session ${p.id} (${p.tool}, ${l.turnCount} turns)`),g.generated++):(a++,g.failed++),t++}catch(l){g.failed++,s(` Failed to generate facets for session ${p.id}: ${l instanceof Error?l.message:String(l)}`),t++,a++}}}))}if(d.length<y)break}}catch(d){g.stopReason="read-failed",s(` Warning: facet generation failed after ${t} sessions: ${d instanceof Error?d.message:String(d)}`)}if(g.stopReason!=="read-failed"&&(g.stopReason=Date.now()>=v?"time-budget":t>=w?"hard-cap":"queue-exhausted"),t>0||g.stopReason==="read-failed"){let d=g.stopReason==="read-failed"?"database read failure":Date.now()>=v?`time budget (${Math.round(x/6e4)}m)`:t>=w?`hard cap (${w})`:"end of queue scan";s(` Facet drain stopped on ${d} after ${t} session(s); the rest resume next run.`)}}let b=await ie(e,r);if(!b)throw new N("No session data found \u2014 ensure sessions are captured and enriched.");s(` Found ${b.stats.sessions} sessions, generating recommendations...`);let m=await Y({projectId:r,projectPath:e},$);b.summary+=`
1
+ import{a as N}from"./chunk-5RBLIVBF.js";import{a as O,b as M,c as Q,d as G}from"./chunk-77FH6UZP.js";import{b as Z,d as X}from"./chunk-K65DDLTZ.js";import{a as se}from"./chunk-LELSVLNK.js";import{c as ee}from"./chunk-A2JFQUDW.js";import{a as K,b as Y}from"./chunk-LZPE6424.js";import{a as A,d as F}from"./chunk-3UKZJAFS.js";import{b as B,e as V,g as R}from"./chunk-GWQ24FQP.js";import{e as $,f as U,h as f}from"./chunk-5VWVQCNR.js";import{a as q,b as W}from"./chunk-MHLHLJ5T.js";import{a as _}from"./chunk-ZLLER3HP.js";var te=_((c,{limit:i,sort:n,eventTypes:e})=>$(`/api/sessions/${c}/events?limit=${i}&sort=${n}&eventType=${encodeURIComponent(e.join(","))}&hasContent=true`),"fetchTranscriptTurns");async function _e(c,i){let{mirrorId:n,projectPath:e,projectId:r,config:u}=c,s=_(t=>i.logger.info(t),"log");if(u?.sessionId)return re({mirrorId:n,sessionId:u.sessionId},s);s(`Processing insights job ${n}...`),await f(`/api/insights-jobs/${n}/progress`,{status:"running",progress:{step:"reading_data"}});try{let{repaired:t}=await U("/api/sessions/repair-analyzed-at",{});t>0&&s(` Repaired analyzed_at on ${t} orphan session(s).`)}catch(t){s(` Warning: analyzed_at repair failed: ${t instanceof Error?t.message:String(t)}`)}let y=20,w=200,x=15*6e4,J=3,v=Date.now()+x,C=V()==="none"?"no-llm-backend":null,g={attempted:0,generated:0,failed:0,ungradeable:0,stopReason:C??"queue-exhausted"};if(C&&i.logger.warn?.("[process-insights] no LLM backend (no claude/codex CLI and no ANTHROPIC_API_KEY) \u2014 facet grading SKIPPED for this run; the summary below is computed from already-graded sessions only"),!C){let t=0,a=0;try{for(;t<w&&Date.now()<v;){let d=await $(`/api/sessions?needsFacets=true&graderVersion=${2}&limit=${y}&offset=${a}`);if(d.length===0)break;s(` Generating facets for ${d.length} un-analyzed sessions (drained ${t} so far)...`);for(let I=0;I<d.length&&!(t>=w||Date.now()>=v);I+=J){let j=d.slice(I,I+J);await Promise.all(j.map(async p=>{if(!(t>=w||Date.now()>=v)){g.attempted++;try{let l=await F(oe=>te(p.id,oe));if(l.turnCount<2){g.ungradeable++,t++,a++;return}let D=await R(G,l.text,4096);D&&typeof D.outcome=="string"?(await f(`/api/sessions/${p.id}/enrich`,{analysis:{source:"generated_facets",...D,graderVersion:2},...p.eventCount!=null?{analyzedEventCount:p.eventCount}:{},analyzedTurnCount:l.turnCount}),s(` Generated facets for session ${p.id} (${p.tool}, ${l.turnCount} turns)`),g.generated++):(a++,g.failed++),t++}catch(l){g.failed++,s(` Failed to generate facets for session ${p.id}: ${l instanceof Error?l.message:String(l)}`),t++,a++}}}))}if(d.length<y)break}}catch(d){g.stopReason="read-failed",s(` Warning: facet generation failed after ${t} sessions: ${d instanceof Error?d.message:String(d)}`)}if(g.stopReason!=="read-failed"&&(g.stopReason=Date.now()>=v?"time-budget":t>=w?"hard-cap":"queue-exhausted"),t>0||g.stopReason==="read-failed"){let d=g.stopReason==="read-failed"?"database read failure":Date.now()>=v?`time budget (${Math.round(x/6e4)}m)`:t>=w?`hard cap (${w})`:"end of queue scan";s(` Facet drain stopped on ${d} after ${t} session(s); the rest resume next run.`)}}let b=await ie(e,r);if(!b)throw new N("No session data found \u2014 ensure sessions are captured and enriched.");s(` Found ${b.stats.sessions} sessions, generating recommendations...`);let m=await Y({projectId:r,projectPath:e},$);b.summary+=`
2
2
 
3
3
  ${m.text}`,s(` Session evidence: ${m.sessionIds.length} usable, ${m.failedSessionIds.length} unavailable`);let P=await ae(e,s);P&&s(` Generator memory: ${P.split(`
4
4
  `).length} lines of prior-advice context`);let o={},E=[],h=M.length+1;for(let t=0;t<M.length;t++){let a=M[t];s(` [${t+1}/${h}] Generating ${a.name}...`);try{await f(`/api/insights-jobs/${n}/progress`,{status:"running",progress:{step:a.name,current:t+1,total:h,partial:{...o}}})}catch(l){s(` Warning: progress update failed for ${a.name}: ${l instanceof Error?l.message:String(l)}`)}s(` Running LLM prompt for ${a.name}...`);let d=a.usesGeneratorMemory&&P?`${b.summary}
@@ -0,0 +1 @@
1
+ import{e as y,f as o,h as f}from"./chunk-NJ5UED3H.js";import{a as n}from"./chunk-ZLLER3HP.js";import{Box as p,Text as r}from"ink";import{jsx as x,jsxs as l}from"react/jsx-runtime";function T({checks:t,width:a}){let m=t?.filter(e=>e.severity!=="ok")??[];return!t||m.length===0?null:l(p,{flexDirection:"column",borderStyle:"round",borderColor:o,paddingX:1,width:a,children:[x(r,{bold:!0,color:o,children:"Telemetry"}),m.map(e=>l(p,{flexDirection:"column",children:[l(r,{color:e.severity==="fail"?f:o,children:[e.label,": ",e.message]}),e.hints.map(i=>x(r,{color:y,children:i},i))]},e.label))]})}n(T,"TelemetryPanel");export{T as a};
@@ -1 +1 @@
1
- import{b as m}from"./chunk-BTKVLLV2.js";import{a as g}from"./chunk-ZLLER3HP.js";var p=5;function b(t){let r=g((e,f)=>({retire:[],survivingCases:0,replacementsRequired:!1,refused:e,summary:f}),"none");if(!t||t.cases.length===0&&t.unpairedCases.length===0)return r("no-discrimination-data","No case-discrimination data yet \u2014 the target needs runs in BOTH cohorts before any case can be judged dead.");let c=[...t.cases.filter(e=>!e.discriminating).map(e=>({evalId:e.evalId,name:e.name,feedback:{name:e.name,withPassRate:e.withPassRate,withoutPassRate:e.withoutPassRate,reason:e.note}})),...t.unpairedCases.map(e=>({evalId:e.evalId,name:e.name,feedback:{name:e.name,withPassRate:e.withPassRate??0,withoutPassRate:e.withoutPassRate,reason:"runs in only one cohort (no with-vs-without comparison possible)"}}))];if(c.length===0)return r("all-discriminating","Every case discriminates \u2014 nothing to retire.");let s=new Map(t.cases.map(e=>[e.evalId,e.separation])),o=[...c].sort((e,f)=>(s.get(e.evalId)??-1)-(s.get(f.evalId)??-1)).slice(0,p),u=c.length-o.length,d=t.total+t.unpaired,l=d-o.length,i=l<m,n=`${o.length} of ${d} live case(s) carry no treatment signal`+(u>0?` (${u} more over the ${p}-per-run cap)`:"")+(i?`; retiring them leaves ${l}, below the ${m}-case evolution floor, so replacements must be generated first`:"");return{retire:o,survivingCases:l,replacementsRequired:i,refused:null,summary:n}}g(b,"planCaseRefinement");async function v(t,r){let h=r.log??(()=>{}),c=g((n,e)=>({retired:0,generated:0,skipped:n,summary:e,retiredNames:[],generatedNames:[]}),"empty");if(t.refused)return c(t.refused,t.summary);let s=await r.generate(t.retire.map(n=>n.feedback)),a=[];for(let n of s??[]){let e=await r.createCase(n);a.push(e.name),h(` + ${e.name} (${e.id})`)}let o=t.survivingCases+t.retire.length+a.length,u=Math.max(0,o-m),d=t.retire.slice(0,Math.min(t.retire.length,u)),l=t.retire.length-d.length;if(d.length===0)return{retired:0,generated:a.length,skipped:s===null?"no-llm-backend":"no-replacements-generated",summary:`${t.summary}. `+(s===null?"No local LLM backend available, so nothing was retired":`The generator produced ${a.length} usable replacement(s), not enough to retire anything`)+` \u2014 dropping below the ${m}-case floor would silently disenrol the target from the nightly loop.`,retiredNames:[],generatedNames:a};let i=[];for(let n of d)await r.retireCase(n.evalId,n.feedback.reason),i.push(n.name),h(` retired ${n.name}`);return{retired:i.length,generated:a.length,skipped:null,summary:`Retired ${i.length} non-discriminating case(s), added ${a.length} replacement(s)`+(l>0?`; held ${l} back to stay at the ${m}-case floor (they remain condemned and will be retired once replacements exist)`:"")+". The replacements have no runs yet \u2014 the next autorun batch builds their depth.",retiredNames:i,generatedNames:a}}g(v,"executeCaseRefinement");export{p as a,b,v as c};
1
+ import{b as m}from"./chunk-FLJTAD2R.js";import{a as g}from"./chunk-ZLLER3HP.js";var p=5;function b(t){let r=g((e,f)=>({retire:[],survivingCases:0,replacementsRequired:!1,refused:e,summary:f}),"none");if(!t||t.cases.length===0&&t.unpairedCases.length===0)return r("no-discrimination-data","No case-discrimination data yet \u2014 the target needs runs in BOTH cohorts before any case can be judged dead.");let c=[...t.cases.filter(e=>!e.discriminating).map(e=>({evalId:e.evalId,name:e.name,feedback:{name:e.name,withPassRate:e.withPassRate,withoutPassRate:e.withoutPassRate,reason:e.note}})),...t.unpairedCases.map(e=>({evalId:e.evalId,name:e.name,feedback:{name:e.name,withPassRate:e.withPassRate??0,withoutPassRate:e.withoutPassRate,reason:"runs in only one cohort (no with-vs-without comparison possible)"}}))];if(c.length===0)return r("all-discriminating","Every case discriminates \u2014 nothing to retire.");let s=new Map(t.cases.map(e=>[e.evalId,e.separation])),o=[...c].sort((e,f)=>(s.get(e.evalId)??-1)-(s.get(f.evalId)??-1)).slice(0,p),u=c.length-o.length,d=t.total+t.unpaired,l=d-o.length,i=l<m,n=`${o.length} of ${d} live case(s) carry no treatment signal`+(u>0?` (${u} more over the ${p}-per-run cap)`:"")+(i?`; retiring them leaves ${l}, below the ${m}-case evolution floor, so replacements must be generated first`:"");return{retire:o,survivingCases:l,replacementsRequired:i,refused:null,summary:n}}g(b,"planCaseRefinement");async function v(t,r){let h=r.log??(()=>{}),c=g((n,e)=>({retired:0,generated:0,skipped:n,summary:e,retiredNames:[],generatedNames:[]}),"empty");if(t.refused)return c(t.refused,t.summary);let s=await r.generate(t.retire.map(n=>n.feedback)),a=[];for(let n of s??[]){let e=await r.createCase(n);a.push(e.name),h(` + ${e.name} (${e.id})`)}let o=t.survivingCases+t.retire.length+a.length,u=Math.max(0,o-m),d=t.retire.slice(0,Math.min(t.retire.length,u)),l=t.retire.length-d.length;if(d.length===0)return{retired:0,generated:a.length,skipped:s===null?"no-llm-backend":"no-replacements-generated",summary:`${t.summary}. `+(s===null?"No local LLM backend available, so nothing was retired":`The generator produced ${a.length} usable replacement(s), not enough to retire anything`)+` \u2014 dropping below the ${m}-case floor would silently disenrol the target from the nightly loop.`,retiredNames:[],generatedNames:a};let i=[];for(let n of d)await r.retireCase(n.evalId,n.feedback.reason),i.push(n.name),h(` retired ${n.name}`);return{retired:i.length,generated:a.length,skipped:null,summary:`Retired ${i.length} non-discriminating case(s), added ${a.length} replacement(s)`+(l>0?`; held ${l} back to stay at the ${m}-case floor (they remain condemned and will be retired once replacements exist)`:"")+". The replacements have no runs yet \u2014 the next autorun batch builds their depth.",retiredNames:i,generatedNames:a}}g(v,"executeCaseRefinement");export{p as a,b,v as c};
@@ -0,0 +1,7 @@
1
+ import{c as a,d as y}from"./chunk-5VWVQCNR.js";import{l as m}from"./chunk-PZNWH4VQ.js";import{a as s}from"./chunk-ZLLER3HP.js";import{createHash as h}from"node:crypto";import{mkdirSync as O,readFileSync as x,writeFileSync as U,renameSync as $}from"node:fs";import{join as S}from"node:path";function _(n){if(process.env.RULEMETRIC_HOOK_TOOL&&process.env.RULEMETRIC_HOOK_TOOL!=="claude_code")return null;try{let e=JSON.parse(n);return e.hook_event_name==="SessionStart"&&typeof e.session_id=="string"&&typeof e.cwd=="string"?{cwd:e.cwd}:null}catch{return null}}s(_,"claudeSessionStart");function j(n,e){return JSON.stringify({...e?{systemMessage:e}:{},hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:n}})+`
2
+ `}s(j,"sessionStartOutput");function w(n,e,o){let p=o.toISOString().slice(0,10);return[...n.blockers.map(t=>({item:t,key:`${t.id}:${p}`})).filter(({key:t})=>!e[t]).slice(0,1),...n.events.map(t=>({item:t,key:t.id}))].filter(({key:t})=>!e[t]).slice(0,3)}s(w,"selectSessionUpdates");async function A(n){try{let e=await y(`/api/experiment-updates?projectPath=${encodeURIComponent(n)}`,{timeoutMs:2500});if(!e.userId||!Array.isArray(e.events)||!Array.isArray(e.blockers))return null;let o=new Date,p=h("sha256").update(`${a()}
3
+ ${e.userId}
4
+ ${n}`).digest("hex"),d=S(m(),"experiment-notices"),t=S(d,`${p}.json`),i={};try{i=JSON.parse(x(t,"utf8"))}catch{}(!i||typeof i!="object"||Array.isArray(i))&&(i={});let l=w(e,i,o);if(!l.length)return null;let g=s(r=>r.replace(/[\x00-\x1f\x7f]/g," ").slice(0,650),"text"),f=l.map(({item:r})=>{let c=new URL(r.url,a());if(c.origin!==new URL(a()).origin)throw new Error("Unexpected evidence origin");return`\u2022 ${g(r.title)}: ${g(r.body)}
5
+ ${c.href}`});return e.total-l.filter(({key:r})=>!r.startsWith("waiting:")).length>0&&f.push(`More experiment history: ${a()}/loop`),{message:`RuleMetric \u2014 experiment updates
6
+ ${f.join(`
7
+ `)}`,emitted:s(()=>{try{O(d,{recursive:!0,mode:448});let r=Object.fromEntries(Object.entries(i).filter(([,u])=>Date.parse(u)>o.getTime()-14*864e5));for(let{key:u}of l)r[u]=o.toISOString();let c=`${t}.${process.pid}.tmp`;U(c,JSON.stringify(r),{mode:384}),$(c,t)}catch{}},"emitted")}}catch{return null}}s(A,"sessionExperimentNotice");export{_ as a,j as b,w as c,A as d};
@@ -1 +1 @@
1
- import{a as o}from"../chunk-TQFHRD5B.js";import"../chunk-IZTIYR5Q.js";import"../chunk-5LTJNYCP.js";import"../chunk-3EZZGA72.js";import"../chunk-XAGNGQL3.js";import"../chunk-3AV3GTMP.js";import"../chunk-5VWVQCNR.js";import"../chunk-MHLHLJ5T.js";import"../chunk-XQYAVSUQ.js";import"../chunk-PZNWH4VQ.js";import{a as i}from"../chunk-ZLLER3HP.js";import{Flags as r}from"@oclif/core";var a=class s extends o{static{i(this,"Dashboard")}static description="Interactive TUI dashboard showing session analytics, outcomes, friction, and insights";static examples=["<%= config.bin %> dashboard","<%= config.bin %> dashboard --period 30days","<%= config.bin %> dashboard --launcher"];static flags={period:r.string({char:"p",default:"week",options:["today","week","30days","month","all"],description:"Initial time period"}),launcher:r.boolean({char:"l",default:!1,description:"Open the launcher overlay immediately"})};async run(){let{flags:e}=await this.parse(s),{renderDashboard:t}=await import("../dashboard/Dashboard.js");await t(e.period,{openLauncher:e.launcher})}};export{a as default};
1
+ import{a as o}from"../chunk-TQFHRD5B.js";import"../chunk-IZTIYR5Q.js";import"../chunk-5LTJNYCP.js";import"../chunk-3EZZGA72.js";import"../chunk-XAGNGQL3.js";import"../chunk-3AV3GTMP.js";import"../chunk-5VWVQCNR.js";import"../chunk-MHLHLJ5T.js";import"../chunk-XQYAVSUQ.js";import"../chunk-PZNWH4VQ.js";import{a as i}from"../chunk-ZLLER3HP.js";import{Flags as r}from"@oclif/core";var a=class s extends o{static{i(this,"Dashboard")}static description="Interactive TUI dashboard showing session analytics, outcomes, friction, and insights";static examples=["<%= config.bin %> dashboard","<%= config.bin %> dashboard --period 30days"];static flags={period:r.string({char:"p",default:"week",options:["today","week","30days","month","all"],description:"Initial time period"})};async run(){let{flags:e}=await this.parse(s),{renderDashboard:t}=await import("../dashboard/Dashboard.js");await t(e.period)}};export{a as default};
@@ -1 +1 @@
1
- import{c as q,d as K}from"../chunk-TYFEWLYZ.js";import{b as L,c as W}from"../chunk-V5U3E4BZ.js";import{a as J}from"../chunk-2TJ7Q2OU.js";import{e as O,f as _,g as M}from"../chunk-QWCEZEDO.js";import"../chunk-KKDHD4XA.js";import"../chunk-SZ62CP55.js";import{d as oe,e as ne}from"../chunk-MGT5FZJ4.js";import"../chunk-M7QSC64D.js";import"../chunk-DZRBB34J.js";import"../chunk-KR32Y5Q5.js";import"../chunk-RITL4NU3.js";import{i as z,j as Q,k as Z,m as ee,n as te}from"../chunk-GYKYJJNF.js";import"../chunk-G7V4ZZZ3.js";import"../chunk-AHLVY52I.js";import"../chunk-PPQFN62M.js";import"../chunk-V6L25LFD.js";import"../chunk-GWQ24FQP.js";import"../chunk-PPAHIVG5.js";import"../chunk-CT7FWSIU.js";import"../chunk-5MXZJWQS.js";import"../chunk-N7ODX6PO.js";import{a as V}from"../chunk-OZQNSELV.js";import"../chunk-HFGO5762.js";import"../chunk-VS5ROGDP.js";import"../chunk-NAS7FIGM.js";import"../chunk-VZYNZS5U.js";import"../chunk-U2NT5OSQ.js";import"../chunk-KGURGIZ2.js";import"../chunk-GYNZ3OZF.js";import"../chunk-UPFH72PF.js";import"../chunk-3HJT572X.js";import"../chunk-CDY7TQFZ.js";import"../chunk-KFNFLMUR.js";import"../chunk-FLP6WIJV.js";import"../chunk-JP6ULOEX.js";import"../chunk-SVZYRGO5.js";import"../chunk-WULEBQPI.js";import{d as F}from"../chunk-GPBN4ROE.js";import"../chunk-6XTLP2G7.js";import"../chunk-PJ3WHQ67.js";import{a as X,b as D,c as Y,g as j,h as G}from"../chunk-QI3FJKGK.js";import{a as B}from"../chunk-TQFHRD5B.js";import"../chunk-IZTIYR5Q.js";import"../chunk-5LTJNYCP.js";import"../chunk-3EZZGA72.js";import"../chunk-XAGNGQL3.js";import"../chunk-3AV3GTMP.js";import{a as U,e as y}from"../chunk-5VWVQCNR.js";import"../chunk-MHLHLJ5T.js";import"../chunk-XQYAVSUQ.js";import{a as N,g as v,l as x}from"../chunk-PZNWH4VQ.js";import{a as S}from"../chunk-ZLLER3HP.js";import{spawnSync as le}from"node:child_process";import{existsSync as ce,readFileSync as ue}from"node:fs";import{join as se}from"node:path";var I=class h extends B{static{S(this,"Diagnostics")}static description='Diagnose capture / proxy / connectivity problems (e.g. a client-side "502 Bad Gateway")';static examples=["<%= config.bin %> diagnostics"];baseUrl(){return process.env.RULEMETRIC_API_URL??N().apiUrl??U}async checkDirect(){let r=process.env.HTTPS_PROXY,i=process.env.HTTP_PROXY;delete process.env.HTTPS_PROXY,delete process.env.HTTP_PROXY;let s=new AbortController,l=setTimeout(()=>s.abort(),8e3);try{return(await globalThis.fetch(`${this.baseUrl()}/health`,{signal:s.signal})).ok}catch{return!1}finally{clearTimeout(l),r!==void 0&&(process.env.HTTPS_PROXY=r),i!==void 0&&(process.env.HTTP_PROXY=i)}}configuredProxy(){if(process.env.HTTPS_PROXY)return process.env.HTTPS_PROXY;for(let r of["settings.local.json","settings.json"]){let i=se(process.cwd(),".claude",r);if(ce(i))try{let s=JSON.parse(ue(i,"utf8"));if(s.env?.HTTPS_PROXY)return s.env.HTTPS_PROXY}catch{}}return null}checkThroughProxy(r){let i=le("curl",["-sS","-x",r,"--max-time","8","-o","/dev/null","-w","%{http_code}",`${this.baseUrl()}/health`],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return i.error||typeof i.stdout!="string"?null:i.stdout.trim()==="200"}async run(){await this.parse(h);let r=process.version,i=this.configuredProxy(),s=i!=null,[l,m,d]=await Promise.all([this.checkDirect(),M(O),M(_)]),p=s&&i?this.checkThroughProxy(i):null,t=S((e,c,T)=>{let u=c===null?"\u2013":c?"[OK]":"[!!]";this.log(` ${u} ${e.padEnd(22)} ${T}`)},"line");this.log("RuleMetric diagnostics"),this.log(""),t("Node",!L(r),`${r}${L(r)?" (< 20.11 \u2014 breaks the bundled proxy)":""}`),t("API (direct)",l,`${this.baseUrl()}/health ${l?"reachable":"UNREACHABLE"}`),t("Authenticated",v(),v()?"yes":"no \u2014 run `rulemetric auth login`"),t("Proxy configured",s?!0:null,s?i:"no HTTPS_PROXY set"),s&&(t("Gateway :"+O,m,m?"listening":"NOT listening"),t("mitmproxy :"+_,d,d?"listening":"not listening (gateway should route direct)"),t("API (via proxy)",p,p===null?"inconclusive (curl unavailable)":p?"reachable":"FAILED \u2014 502/blocked through your proxy"));let a=F();t("claude CLI",a.claudeBin!=null,a.claudeBin??"not found \u2014 LLM features (grading, distill) will no-op"),t("codex CLI",a.codexBin!=null?!0:null,a.codexBin?`${a.codexBin}${a.codexConfiguredModel?` (model ${a.codexConfiguredModel})`:""}`:"not found \u2014 optional; enables the cross-vendor reviewer (evals validate-judge)");let o=null;if(v()&&l)try{o=await y("/api/workers/health")}catch{o=null}if(o){let e=o.worker;t("Worker",!!e.active,e.present?e.active?`online (last heartbeat ${e.ageSeconds??"?"}s ago${e.clientVersion?`, v${e.clientVersion}`:""})`:`NOT RUNNING \u2014 last heartbeat ${A(e.ageSeconds)} ago`:"never connected \u2014 no worker has ever reported in");let c=o.worker.engines;if(c!=null){let u=[c.claude&&"claude",c.codex&&"codex"].filter(Boolean);t("LLM engine",u.length>0,u.length>0?`${u.join(" + ")} available to the worker`:"NONE \u2014 the worker found no `claude` and no `codex`. LLM jobs will complete with empty output rather than failing.")}let T=o.pending.reduce((u,E)=>u+E.count,0);if(T>0){let u=o.verdict.stuck.reduce(($,k)=>$+k.count,0),E=o.verdict.unclaimable.reduce(($,k)=>$+k.count,0),R=(o.verdict.engineBlocked??[]).reduce(($,k)=>$+k.count,0);t("Job queue",u===0&&R===0,`${T} pending`+(u>0?` \u2014 ${u} waiting on this worker`:"")+(R>0?` \u2014 ${R} need a local LLM engine`:"")+(E>0?` \u2014 ${E} need a worker with DATABASE_URL`:""))}else t("Job queue",!0,"empty")}else v()&&l&&t("Worker",null,"could not read /workers/health (older API?)");let n=o?.worker.machine;if(n){let e=n.suspends+n.stalls,c=n.lastPause;t("Worker pauses",e===0?!0:null,e===0?`none since ${n.since} \u2014 no sleep or stall seen by the worker`:`${n.suspends} suspend${n.suspends===1?"":"s"}`+(n.stalls>0?` + ${n.stalls} event-loop stall${n.stalls===1?"":"s"}`:"")+` since ${n.since}, ${A(Math.round(n.pausedMs/1e3))} paused total`+(c?`; last: ${c.kind} of ${A(Math.round(c.wallGapMs/1e3))} ending ${c.detectedAt}`:"")+" \u2014 jobs in flight during a suspend lose their lease and are redone on wake")}let f=await q();if(f){t("Machine sleep (pmset)",f.sleeps===0?!0:null,K(f));for(let e of f.recent.slice(-3)){let c=e.seconds!=null?` (${A(e.seconds)})`:"";this.log(` \u21B3 ${e.at.toISOString()} ${e.kind}${c}: ${e.reason.slice(0,80)}`)}}let C=V(process.cwd()),g=await D({configDir:x()}),re=await Y({configDir:x()}),w=` \u2014 ${G(re)}`,b=J(process.cwd()),H=[b.user&&`user hooks (${b.user})`,b.workspace&&`workspace hooks (${b.workspace})`].filter(Boolean),ie={claude_code:`session hooks (+ proxy for instruction linking)${w}`,codex:`worker transcript sync of ~/.codex/sessions \u2014 ${j(g)}`,cursor:`user hooks (~/.cursor/hooks.json)${w}`,copilot_agent:`workspace hooks${w}`,antigravity:H.length>0?`${H.join(" + ")}${w}`:"NOT CAPTURED \u2014 no rulemetric block in ~/.gemini/config/hooks.json or .agents/hooks.json; run `rulemetric hooks install` (user hooks are on by default)"};this.log(""),this.log(" Capture coverage (agents found on this machine):");for(let e of C)this.log(` \u2022 ${e.padEnd(15)} ${ie[e]??"captured"}`);if(C.includes("codex"))if(g.error)this.log(` ! ${g.error}`);else if(g.mode==="allowlist")for(let e of g.roots)this.log(` \u21B3 ${e}`);else g.mode==="all"&&this.log(` \u21B3 scope it with ${se(x(),X)} ({"codex":{"roots":["/path/to/repo"]}}) or RULEMETRIC_CODEX_CAPTURE=off`);o&&!o.worker.active&&C.includes("codex")&&g.mode!=="off"&&this.log(" ! Codex capture runs INSIDE the worker \u2014 it is stopped while the worker is down."),v()&&l&&await this.reportEvolutionSpend();let P=W({nodeVersion:r,directApiOk:l,httpsProxySet:s,gatewayAlive:m,mitmproxyAlive:d,proxyPathOk:p});this.log("");let ae=P.severity==="ok"?"[OK]":P.severity==="warn"?"[!!]":"[XX]";this.log(`${ae} ${P.headline}`);for(let e of P.hints)this.log(` \u2022 ${e}`);if(o&&o.verdict.severity!=="ok"){let e=o.verdict.severity==="warn"?"[!!]":"[XX]";this.log(""),this.log(`${e} ${o.verdict.headline}`);for(let c of o.verdict.hints)this.log(` \u2022 ${c}`)}}async reportEvolutionSpend(){let r;try{r=await y("/api/eval-targets?type=instruction&limit=200")}catch{return}let i=r.filter(s=>{let l=s.metadata??{};return l.autoEvolveEnabled===!0||l.autoEvolveEnabled==="true"});if(i.length!==0){this.log(""),this.log(" Nightly instruction evolution (cron_instruction_evolution, 07:30 UTC):");for(let s of i){let l=s.metadata??{},m=Q(l),d=z(l);if(m){this.log(` \u2022 ${s.name} \u2014 PAUSED (metadata.autoEvolvePaused). Opt-in preserved.`),this.log(" \u21B3 resume: set autoEvolvePaused=false");continue}let p=null;try{p=(await y(`/api/eval-targets/${s.id}/evals`)).filter(a=>!a.retiredAt).length}catch{}if(this.log(` \u2022 ${s.name}`),p!=null){let t=ne(p,d.minPairs,oe(d,p));if(!t.feasible)this.log(` \u21B3 cannot reach a verdict \u2014 ${t.reason}`);else{let a=Z({liveCases:p,passes:t.passes});this.log(` \u21B3 each night: ${te(a)}`)}}this.log(` \u21B3 pairs budget ${d.minPairs}`+(d.configured?" (metadata.autoEvolvePairs)":" (default)")+` \xB7 writes ${l.autoEvolveApply===!0||l.autoEvolveApply==="true"?"ENABLED":"off (dry run)"}`),d.note&&this.log(` ! ${d.note}`);try{let t=await y(`/api/eval-targets/${s.id}/promotions?limit=1`),a=t.promotions[0];if(a){let n=a.gates?.cost,f=n?.modelCalls?`${n.modelCalls} model calls, ${n.usablePairs??"?"} usable pair(s)`+(n.mde!=null?`, resolved +/-${ee(n.mde)}`:"")+(n.wallMs?`, ${(n.wallMs/6e4).toFixed(0)} min`:""):"cost not recorded (decision predates cost tracking)";this.log(` \u21B3 last run ${new Date(a.createdAt).toISOString().slice(0,10)}: ${a.decision}${a.applied?" (APPLIED)":""} \u2014 ${f}`)}let o=t.counts??{};this.log(` \u21B3 lifetime: ${o.promote??0} promote / ${o.revert??0} revert / ${o.refuse??0} refuse`)}catch{}}this.log(" \u21B3 pause the spend: metadata.autoEvolvePaused=true (keeps the opt-in)")}}};function A(h){if(h===null)return"never";if(h<90)return`${Math.round(h)}s`;let r=Math.round(h/60);return r<90?`${r}m`:`${Math.round(r/60)}h`}S(A,"formatAge");export{I as default};
1
+ import{c as q,d as K}from"../chunk-TYFEWLYZ.js";import{b as L,c as W}from"../chunk-V5U3E4BZ.js";import{a as J}from"../chunk-2TJ7Q2OU.js";import{e as O,f as _,g as M}from"../chunk-QWCEZEDO.js";import"../chunk-KKDHD4XA.js";import"../chunk-SZ62CP55.js";import{d as oe,e as ne}from"../chunk-L5ILEWHH.js";import"../chunk-M7QSC64D.js";import"../chunk-DZRBB34J.js";import"../chunk-KR32Y5Q5.js";import"../chunk-G7V4ZZZ3.js";import"../chunk-RITL4NU3.js";import{i as z,j as Q,k as Z,m as ee,n as te}from"../chunk-GYKYJJNF.js";import"../chunk-V6L25LFD.js";import"../chunk-GWQ24FQP.js";import"../chunk-PPAHIVG5.js";import"../chunk-CT7FWSIU.js";import"../chunk-5MXZJWQS.js";import"../chunk-AHLVY52I.js";import"../chunk-PPQFN62M.js";import"../chunk-N7ODX6PO.js";import{a as V}from"../chunk-OZQNSELV.js";import"../chunk-HFGO5762.js";import"../chunk-VS5ROGDP.js";import"../chunk-NAS7FIGM.js";import"../chunk-VZYNZS5U.js";import"../chunk-U2NT5OSQ.js";import"../chunk-KGURGIZ2.js";import"../chunk-GYNZ3OZF.js";import"../chunk-UPFH72PF.js";import"../chunk-3HJT572X.js";import"../chunk-CDY7TQFZ.js";import"../chunk-KFNFLMUR.js";import"../chunk-FLP6WIJV.js";import"../chunk-JP6ULOEX.js";import"../chunk-SVZYRGO5.js";import"../chunk-WULEBQPI.js";import{d as F}from"../chunk-GPBN4ROE.js";import"../chunk-6XTLP2G7.js";import"../chunk-PJ3WHQ67.js";import{a as X,b as D,c as Y,g as j,h as G}from"../chunk-QI3FJKGK.js";import{a as B}from"../chunk-TQFHRD5B.js";import"../chunk-IZTIYR5Q.js";import"../chunk-5LTJNYCP.js";import"../chunk-3EZZGA72.js";import"../chunk-XAGNGQL3.js";import"../chunk-3AV3GTMP.js";import{a as U,e as y}from"../chunk-5VWVQCNR.js";import"../chunk-MHLHLJ5T.js";import"../chunk-XQYAVSUQ.js";import{a as N,g as v,l as x}from"../chunk-PZNWH4VQ.js";import{a as S}from"../chunk-ZLLER3HP.js";import{spawnSync as le}from"node:child_process";import{existsSync as ce,readFileSync as ue}from"node:fs";import{join as se}from"node:path";var I=class h extends B{static{S(this,"Diagnostics")}static description='Diagnose capture / proxy / connectivity problems (e.g. a client-side "502 Bad Gateway")';static examples=["<%= config.bin %> diagnostics"];baseUrl(){return process.env.RULEMETRIC_API_URL??N().apiUrl??U}async checkDirect(){let r=process.env.HTTPS_PROXY,i=process.env.HTTP_PROXY;delete process.env.HTTPS_PROXY,delete process.env.HTTP_PROXY;let s=new AbortController,l=setTimeout(()=>s.abort(),8e3);try{return(await globalThis.fetch(`${this.baseUrl()}/health`,{signal:s.signal})).ok}catch{return!1}finally{clearTimeout(l),r!==void 0&&(process.env.HTTPS_PROXY=r),i!==void 0&&(process.env.HTTP_PROXY=i)}}configuredProxy(){if(process.env.HTTPS_PROXY)return process.env.HTTPS_PROXY;for(let r of["settings.local.json","settings.json"]){let i=se(process.cwd(),".claude",r);if(ce(i))try{let s=JSON.parse(ue(i,"utf8"));if(s.env?.HTTPS_PROXY)return s.env.HTTPS_PROXY}catch{}}return null}checkThroughProxy(r){let i=le("curl",["-sS","-x",r,"--max-time","8","-o","/dev/null","-w","%{http_code}",`${this.baseUrl()}/health`],{encoding:"utf8",stdio:["ignore","pipe","ignore"]});return i.error||typeof i.stdout!="string"?null:i.stdout.trim()==="200"}async run(){await this.parse(h);let r=process.version,i=this.configuredProxy(),s=i!=null,[l,m,d]=await Promise.all([this.checkDirect(),M(O),M(_)]),p=s&&i?this.checkThroughProxy(i):null,t=S((e,c,T)=>{let u=c===null?"\u2013":c?"[OK]":"[!!]";this.log(` ${u} ${e.padEnd(22)} ${T}`)},"line");this.log("RuleMetric diagnostics"),this.log(""),t("Node",!L(r),`${r}${L(r)?" (< 20.11 \u2014 breaks the bundled proxy)":""}`),t("API (direct)",l,`${this.baseUrl()}/health ${l?"reachable":"UNREACHABLE"}`),t("Authenticated",v(),v()?"yes":"no \u2014 run `rulemetric auth login`"),t("Proxy configured",s?!0:null,s?i:"no HTTPS_PROXY set"),s&&(t("Gateway :"+O,m,m?"listening":"NOT listening"),t("mitmproxy :"+_,d,d?"listening":"not listening (gateway should route direct)"),t("API (via proxy)",p,p===null?"inconclusive (curl unavailable)":p?"reachable":"FAILED \u2014 502/blocked through your proxy"));let a=F();t("claude CLI",a.claudeBin!=null,a.claudeBin??"not found \u2014 LLM features (grading, distill) will no-op"),t("codex CLI",a.codexBin!=null?!0:null,a.codexBin?`${a.codexBin}${a.codexConfiguredModel?` (model ${a.codexConfiguredModel})`:""}`:"not found \u2014 optional; enables the cross-vendor reviewer (evals validate-judge)");let o=null;if(v()&&l)try{o=await y("/api/workers/health")}catch{o=null}if(o){let e=o.worker;t("Worker",!!e.active,e.present?e.active?`online (last heartbeat ${e.ageSeconds??"?"}s ago${e.clientVersion?`, v${e.clientVersion}`:""})`:`NOT RUNNING \u2014 last heartbeat ${A(e.ageSeconds)} ago`:"never connected \u2014 no worker has ever reported in");let c=o.worker.engines;if(c!=null){let u=[c.claude&&"claude",c.codex&&"codex"].filter(Boolean);t("LLM engine",u.length>0,u.length>0?`${u.join(" + ")} available to the worker`:"NONE \u2014 the worker found no `claude` and no `codex`. LLM jobs will complete with empty output rather than failing.")}let T=o.pending.reduce((u,E)=>u+E.count,0);if(T>0){let u=o.verdict.stuck.reduce(($,k)=>$+k.count,0),E=o.verdict.unclaimable.reduce(($,k)=>$+k.count,0),R=(o.verdict.engineBlocked??[]).reduce(($,k)=>$+k.count,0);t("Job queue",u===0&&R===0,`${T} pending`+(u>0?` \u2014 ${u} waiting on this worker`:"")+(R>0?` \u2014 ${R} need a local LLM engine`:"")+(E>0?` \u2014 ${E} need a worker with DATABASE_URL`:""))}else t("Job queue",!0,"empty")}else v()&&l&&t("Worker",null,"could not read /workers/health (older API?)");let n=o?.worker.machine;if(n){let e=n.suspends+n.stalls,c=n.lastPause;t("Worker pauses",e===0?!0:null,e===0?`none since ${n.since} \u2014 no sleep or stall seen by the worker`:`${n.suspends} suspend${n.suspends===1?"":"s"}`+(n.stalls>0?` + ${n.stalls} event-loop stall${n.stalls===1?"":"s"}`:"")+` since ${n.since}, ${A(Math.round(n.pausedMs/1e3))} paused total`+(c?`; last: ${c.kind} of ${A(Math.round(c.wallGapMs/1e3))} ending ${c.detectedAt}`:"")+" \u2014 jobs in flight during a suspend lose their lease and are redone on wake")}let f=await q();if(f){t("Machine sleep (pmset)",f.sleeps===0?!0:null,K(f));for(let e of f.recent.slice(-3)){let c=e.seconds!=null?` (${A(e.seconds)})`:"";this.log(` \u21B3 ${e.at.toISOString()} ${e.kind}${c}: ${e.reason.slice(0,80)}`)}}let C=V(process.cwd()),g=await D({configDir:x()}),re=await Y({configDir:x()}),w=` \u2014 ${G(re)}`,b=J(process.cwd()),H=[b.user&&`user hooks (${b.user})`,b.workspace&&`workspace hooks (${b.workspace})`].filter(Boolean),ie={claude_code:`session hooks (+ proxy for instruction linking)${w}`,codex:`worker transcript sync of ~/.codex/sessions \u2014 ${j(g)}`,cursor:`user hooks (~/.cursor/hooks.json)${w}`,copilot_agent:`workspace hooks${w}`,antigravity:H.length>0?`${H.join(" + ")}${w}`:"NOT CAPTURED \u2014 no rulemetric block in ~/.gemini/config/hooks.json or .agents/hooks.json; run `rulemetric hooks install` (user hooks are on by default)"};this.log(""),this.log(" Capture coverage (agents found on this machine):");for(let e of C)this.log(` \u2022 ${e.padEnd(15)} ${ie[e]??"captured"}`);if(C.includes("codex"))if(g.error)this.log(` ! ${g.error}`);else if(g.mode==="allowlist")for(let e of g.roots)this.log(` \u21B3 ${e}`);else g.mode==="all"&&this.log(` \u21B3 scope it with ${se(x(),X)} ({"codex":{"roots":["/path/to/repo"]}}) or RULEMETRIC_CODEX_CAPTURE=off`);o&&!o.worker.active&&C.includes("codex")&&g.mode!=="off"&&this.log(" ! Codex capture runs INSIDE the worker \u2014 it is stopped while the worker is down."),v()&&l&&await this.reportEvolutionSpend();let P=W({nodeVersion:r,directApiOk:l,httpsProxySet:s,gatewayAlive:m,mitmproxyAlive:d,proxyPathOk:p});this.log("");let ae=P.severity==="ok"?"[OK]":P.severity==="warn"?"[!!]":"[XX]";this.log(`${ae} ${P.headline}`);for(let e of P.hints)this.log(` \u2022 ${e}`);if(o&&o.verdict.severity!=="ok"){let e=o.verdict.severity==="warn"?"[!!]":"[XX]";this.log(""),this.log(`${e} ${o.verdict.headline}`);for(let c of o.verdict.hints)this.log(` \u2022 ${c}`)}}async reportEvolutionSpend(){let r;try{r=await y("/api/eval-targets?type=instruction&limit=200")}catch{return}let i=r.filter(s=>{let l=s.metadata??{};return l.autoEvolveEnabled===!0||l.autoEvolveEnabled==="true"});if(i.length!==0){this.log(""),this.log(" Nightly instruction evolution (cron_instruction_evolution, 07:30 UTC):");for(let s of i){let l=s.metadata??{},m=Q(l),d=z(l);if(m){this.log(` \u2022 ${s.name} \u2014 PAUSED (metadata.autoEvolvePaused). Opt-in preserved.`),this.log(" \u21B3 resume: set autoEvolvePaused=false");continue}let p=null;try{p=(await y(`/api/eval-targets/${s.id}/evals`)).filter(a=>!a.retiredAt).length}catch{}if(this.log(` \u2022 ${s.name}`),p!=null){let t=ne(p,d.minPairs,oe(d,p));if(!t.feasible)this.log(` \u21B3 cannot reach a verdict \u2014 ${t.reason}`);else{let a=Z({liveCases:p,passes:t.passes});this.log(` \u21B3 each night: ${te(a)}`)}}this.log(` \u21B3 pairs budget ${d.minPairs}`+(d.configured?" (metadata.autoEvolvePairs)":" (default)")+` \xB7 writes ${l.autoEvolveApply===!0||l.autoEvolveApply==="true"?"ENABLED":"off (dry run)"}`),d.note&&this.log(` ! ${d.note}`);try{let t=await y(`/api/eval-targets/${s.id}/promotions?limit=1`),a=t.promotions[0];if(a){let n=a.gates?.cost,f=n?.modelCalls?`${n.modelCalls} model calls, ${n.usablePairs??"?"} usable pair(s)`+(n.mde!=null?`, resolved +/-${ee(n.mde)}`:"")+(n.wallMs?`, ${(n.wallMs/6e4).toFixed(0)} min`:""):"cost not recorded (decision predates cost tracking)";this.log(` \u21B3 last run ${new Date(a.createdAt).toISOString().slice(0,10)}: ${a.decision}${a.applied?" (APPLIED)":""} \u2014 ${f}`)}let o=t.counts??{};this.log(` \u21B3 lifetime: ${o.promote??0} promote / ${o.revert??0} revert / ${o.refuse??0} refuse`)}catch{}}this.log(" \u21B3 pause the spend: metadata.autoEvolvePaused=true (keeps the opt-in)")}}};function A(h){if(h===null)return"never";if(h<90)return`${Math.round(h)}s`;let r=Math.round(h/60);return r<90?`${r}m`:`${Math.round(r/60)}h`}S(A,"formatAge");export{I as default};
@@ -1,3 +1,3 @@
1
- import{a as G,b as V,c as j,d as q}from"../../chunk-4LVSD2XZ.js";import{b as M}from"../../chunk-GH4EZK2O.js";import{c as g}from"../../chunk-BDWQ6J4V.js";import{e as D}from"../../chunk-JLX2D3QL.js";import"../../chunk-5U5SHJJA.js";import"../../chunk-IEQDLURA.js";import"../../chunk-KINIFUZQ.js";import"../../chunk-QRKMRG6W.js";import"../../chunk-D7L7IMJQ.js";import"../../chunk-MRQIYIQE.js";import"../../chunk-R26SQ3BE.js";import"../../chunk-PMMHMRFS.js";import"../../chunk-IYX65N6T.js";import"../../chunk-GHUW7P55.js";import"../../chunk-JU5ZNXPK.js";import"../../chunk-MBP5OJKE.js";import"../../chunk-BRYURAUN.js";import"../../chunk-NLUHMHPM.js";import"../../chunk-DTTR4EUJ.js";import"../../chunk-WLLIFRRE.js";import"../../chunk-RRBFKVCI.js";import"../../chunk-ZYGBABMZ.js";import"../../chunk-5RBLIVBF.js";import"../../chunk-NSO2EBYE.js";import"../../chunk-3ZHVP3KE.js";import"../../chunk-2C7CFCMM.js";import"../../chunk-HOQPVOMF.js";import"../../chunk-WSUKOU3X.js";import"../../chunk-A6XQSO62.js";import"../../chunk-MOJY6S5J.js";import"../../chunk-CJ2WSSHD.js";import"../../chunk-KOIFFSYW.js";import"../../chunk-IPNBW7ZW.js";import"../../chunk-P577DWWL.js";import"../../chunk-7MQZPDDZ.js";import"../../chunk-ANLPPIMS.js";import"../../chunk-AZRGURHR.js";import"../../chunk-TG4C4ENM.js";import"../../chunk-MJLW5KN2.js";import"../../chunk-SW24KZ5C.js";import"../../chunk-K65DDLTZ.js";import"../../chunk-LELSVLNK.js";import"../../chunk-A2JFQUDW.js";import"../../chunk-LZPE6424.js";import"../../chunk-3UKZJAFS.js";import"../../chunk-77FH6UZP.js";import"../../chunk-FGGESTXG.js";import"../../chunk-PX2E644Q.js";import"../../chunk-GIRPEMTW.js";import"../../chunk-DQYYHX6K.js";import"../../chunk-RWQG25JU.js";import"../../chunk-3ZHBOILE.js";import"../../chunk-PIVEJTNF.js";import"../../chunk-BOYWPUV2.js";import"../../chunk-ENW5SUQJ.js";import"../../chunk-C3XWDYZJ.js";import"../../chunk-CAQLSYOK.js";import"../../chunk-RQBN7WNS.js";import"../../chunk-ZJABRHIP.js";import"../../chunk-XFOG2PDJ.js";import"../../chunk-SIGZEQ3K.js";import"../../chunk-AZWY2DOT.js";import"../../chunk-LJRE3LZ2.js";import"../../chunk-EQ2O6DSN.js";import"../../chunk-BTKVLLV2.js";import"../../chunk-UQJNUESP.js";import"../../chunk-FLXWL4F4.js";import"../../chunk-KIQK7NVF.js";import"../../chunk-6UEFCMR2.js";import"../../chunk-MODXEGCU.js";import"../../chunk-MHVHGKDK.js";import"../../chunk-RBSEE2Z6.js";import"../../chunk-NBTH6ZKD.js";import"../../chunk-MGT5FZJ4.js";import"../../chunk-M7QSC64D.js";import"../../chunk-DZRBB34J.js";import"../../chunk-KR32Y5Q5.js";import"../../chunk-RITL4NU3.js";import"../../chunk-GYKYJJNF.js";import"../../chunk-G7V4ZZZ3.js";import"../../chunk-AHLVY52I.js";import"../../chunk-PPQFN62M.js";import"../../chunk-V6L25LFD.js";import"../../chunk-GWQ24FQP.js";import"../../chunk-PPAHIVG5.js";import"../../chunk-CT7FWSIU.js";import"../../chunk-5MXZJWQS.js";import"../../chunk-N7ODX6PO.js";import"../../chunk-OZQNSELV.js";import"../../chunk-HFGO5762.js";import"../../chunk-VS5ROGDP.js";import"../../chunk-NAS7FIGM.js";import"../../chunk-VZYNZS5U.js";import"../../chunk-U2NT5OSQ.js";import"../../chunk-KGURGIZ2.js";import"../../chunk-GYNZ3OZF.js";import"../../chunk-UPFH72PF.js";import"../../chunk-3HJT572X.js";import"../../chunk-CDY7TQFZ.js";import"../../chunk-KFNFLMUR.js";import"../../chunk-FLP6WIJV.js";import"../../chunk-JP6ULOEX.js";import"../../chunk-SVZYRGO5.js";import"../../chunk-WULEBQPI.js";import"../../chunk-GPBN4ROE.js";import"../../chunk-6XTLP2G7.js";import"../../chunk-PJ3WHQ67.js";import{b as A,d as C,g as S,i as E,j as L,k as $}from"../../chunk-QI3FJKGK.js";import{a as O}from"../../chunk-TQFHRD5B.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-5LTJNYCP.js";import"../../chunk-3EZZGA72.js";import"../../chunk-XAGNGQL3.js";import"../../chunk-3AV3GTMP.js";import{f as m}from"../../chunk-5VWVQCNR.js";import"../../chunk-MHLHLJ5T.js";import"../../chunk-XQYAVSUQ.js";import{e as I,l as p}from"../../chunk-PZNWH4VQ.js";import{a as e}from"../../chunk-ZLLER3HP.js";import{trace as de,context as me}from"@opentelemetry/api";import{NodeSDK as W}from"@opentelemetry/sdk-node";import{OTLPTraceExporter as Y}from"@opentelemetry/exporter-trace-otlp-http";import{BatchSpanProcessor as J,ConsoleSpanExporter as z,SimpleSpanProcessor as Q}from"@opentelemetry/sdk-trace-node";import{Resource as Z}from"@opentelemetry/resources";import{ATTR_SERVICE_NAME as ee,ATTR_SERVICE_VERSION as te}from"@opentelemetry/semantic-conventions";function F(r){if(!r)return{};let n={};for(let o of r.split(",")){let s=o.indexOf("=");if(s===-1)continue;let i=o.slice(0,s).trim(),c=o.slice(s+1).trim();i&&(n[i]=c)}return n}e(F,"parseOtlpHeaders");var u=null;function T(){return process.env.TELEMETRY_ENABLED!=="false"}e(T,"isTelemetryEnabled");function x(r){if(!T()||u!==null)return"off";let n=new Z({[ee]:r.serviceName,[te]:r.serviceVersion??"0.1.0"}),o=process.env.OTEL_EXPORTER_OTLP_ENDPOINT,s,i;if(o){let c=F(process.env.OTEL_EXPORTER_OTLP_HEADERS),l=new Y({url:`${o}/v1/traces`,headers:c});i=new J(l),s="otlp"}else if(process.env.OTEL_SPAN_EXPORT==="none")i=void 0,s="silent";else{let c=new z;i=new Q(c),s="console"}return u=new W({resource:n,spanProcessors:i?[i]:[]}),u.start(),s}e(x,"initTelemetry");async function h(){u&&(await u.shutdown(),u=null)}e(h,"shutdownTelemetry");import{SpanKind as Pe,SpanStatusCode as Re}from"@opentelemetry/api";import{trace as Ie,context as Oe}from"@opentelemetry/api";import*as f from"@sentry/node";var v=!1;function w(r){if(v)return!1;let n=process.env.SENTRY_DSN;return n?(f.init({dsn:n,serverName:r.serviceName,environment:process.env.NODE_ENV??"development",tracesSampleRate:0}),v=!0,!0):!1}e(w,"initSentry");async function y(r){v&&await f.flush(r)}e(y,"flushSentry");import{existsSync as ne,mkdirSync as oe,readFileSync as k,unlinkSync as X,writeFileSync as U}from"node:fs";import{dirname as se,join as R}from"node:path";import{execFileSync as ie}from"node:child_process";var a=R(p(),"evals-agent.lock");function ce(r){try{return process.kill(r,0),!0}catch(n){return n.code==="EPERM"}}e(ce,"pidAlive");function ae(r){if(!ce(r))return!1;try{let n=ie("ps",["-p",String(r),"-o","command="],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]});return/run\.js\s+evals\s+agent|evals\s+agent/.test(n)}catch{return!0}}e(ae,"isLiveAgent");function le(){try{oe(se(a),{recursive:!0})}catch{}for(let r=0;r<2;r++)try{return U(a,String(process.pid),{flag:"wx"}),{ok:!0}}catch(n){if(n.code!=="EEXIST")throw n;let o=0;try{o=Number(k(a,"utf-8").trim())}catch{}if(o&&o!==process.pid&&ae(o))return{ok:!1,holder:o};try{X(a)}catch{}}try{U(a,String(process.pid))}catch{}return{ok:!0}}e(le,"acquireAgentLock");function P(){try{ne(a)&&Number(k(a,"utf-8").trim())===process.pid&&X(a)}catch{}}e(P,"releaseAgentLock");var N=class r extends O{static{e(this,"EvalAgentCommand")}static description="The worker daemon: long-polls /api/work/next, claims jobs, and runs them locally. Installed as a launchd service by `rulemetric service install`.";static examples=["<%= config.bin %> evals agent"];async run(){await this.parse(r),this.requireAuth();let n=le();if(!n.ok){this.log(`Another rulemetric evals agent is already running (pid ${n.holder}). Refusing to start a second instance.`);return}process.env.PG_APPLICATION_NAME||="rulemetric-agent",w({serviceName:"rulemetric-agent"})&&this.log("[sentry] error capture enabled");let s=x({serviceName:"rulemetric-agent"});s==="otlp"?this.log(`[otel] traces exporting to ${process.env.OTEL_EXPORTER_OTLP_ENDPOINT}`):s==="console"?this.log("[otel] cron spans printing to stdout (set OTEL_EXPORTER_OTLP_ENDPOINT to ship to a backend)"):this.log("[otel] disabled (TELEMETRY_ENABLED=false)"),!I()&&!process.env.RULEMETRIC_API_KEY&&this.error("No auth token found. Run `rulemetric auth login` first."),this.log("Starting thin agent (Phase 4b parallel-run)..."),this.log(`Long-polling /api/work/next. Press Ctrl+C to stop.
1
+ import{a as G,b as V,c as j,d as q}from"../../chunk-4LVSD2XZ.js";import{b as M}from"../../chunk-GH4EZK2O.js";import{c as g}from"../../chunk-BDWQ6J4V.js";import{e as D}from"../../chunk-NVOYP4HX.js";import"../../chunk-5U5SHJJA.js";import"../../chunk-IEQDLURA.js";import"../../chunk-KINIFUZQ.js";import"../../chunk-ZYGBABMZ.js";import"../../chunk-QRKMRG6W.js";import"../../chunk-D7L7IMJQ.js";import"../../chunk-MRQIYIQE.js";import"../../chunk-R26SQ3BE.js";import"../../chunk-PMMHMRFS.js";import"../../chunk-IYX65N6T.js";import"../../chunk-GHUW7P55.js";import"../../chunk-JU5ZNXPK.js";import"../../chunk-RAMQVEJB.js";import"../../chunk-BRYURAUN.js";import"../../chunk-NLUHMHPM.js";import"../../chunk-DTTR4EUJ.js";import"../../chunk-WLLIFRRE.js";import"../../chunk-RRBFKVCI.js";import"../../chunk-5RBLIVBF.js";import"../../chunk-SW24KZ5C.js";import"../../chunk-NSO2EBYE.js";import"../../chunk-3ZHVP3KE.js";import"../../chunk-2C7CFCMM.js";import"../../chunk-HOQPVOMF.js";import"../../chunk-WSUKOU3X.js";import"../../chunk-A6XQSO62.js";import"../../chunk-MOJY6S5J.js";import"../../chunk-CJ2WSSHD.js";import"../../chunk-KOIFFSYW.js";import"../../chunk-IPNBW7ZW.js";import"../../chunk-P577DWWL.js";import"../../chunk-7MQZPDDZ.js";import"../../chunk-ANLPPIMS.js";import"../../chunk-AZRGURHR.js";import"../../chunk-CXENLSMR.js";import"../../chunk-MJLW5KN2.js";import"../../chunk-77FH6UZP.js";import"../../chunk-K65DDLTZ.js";import"../../chunk-LELSVLNK.js";import"../../chunk-A2JFQUDW.js";import"../../chunk-LZPE6424.js";import"../../chunk-3UKZJAFS.js";import"../../chunk-FGGESTXG.js";import"../../chunk-PX2E644Q.js";import"../../chunk-DQYYHX6K.js";import"../../chunk-GIRPEMTW.js";import"../../chunk-RWQG25JU.js";import"../../chunk-3ZHBOILE.js";import"../../chunk-PIVEJTNF.js";import"../../chunk-BOYWPUV2.js";import"../../chunk-ENW5SUQJ.js";import"../../chunk-C3XWDYZJ.js";import"../../chunk-CAQLSYOK.js";import"../../chunk-RQBN7WNS.js";import"../../chunk-ZJABRHIP.js";import"../../chunk-XFOG2PDJ.js";import"../../chunk-SIGZEQ3K.js";import"../../chunk-AZWY2DOT.js";import"../../chunk-LJRE3LZ2.js";import"../../chunk-YZQZD2E6.js";import"../../chunk-FLJTAD2R.js";import"../../chunk-UQJNUESP.js";import"../../chunk-FLXWL4F4.js";import"../../chunk-KIQK7NVF.js";import"../../chunk-6UEFCMR2.js";import"../../chunk-MODXEGCU.js";import"../../chunk-MHVHGKDK.js";import"../../chunk-RBSEE2Z6.js";import"../../chunk-NBTH6ZKD.js";import"../../chunk-L5ILEWHH.js";import"../../chunk-M7QSC64D.js";import"../../chunk-DZRBB34J.js";import"../../chunk-KR32Y5Q5.js";import"../../chunk-G7V4ZZZ3.js";import"../../chunk-RITL4NU3.js";import"../../chunk-GYKYJJNF.js";import"../../chunk-V6L25LFD.js";import"../../chunk-GWQ24FQP.js";import"../../chunk-PPAHIVG5.js";import"../../chunk-CT7FWSIU.js";import"../../chunk-5MXZJWQS.js";import"../../chunk-AHLVY52I.js";import"../../chunk-PPQFN62M.js";import"../../chunk-N7ODX6PO.js";import"../../chunk-OZQNSELV.js";import"../../chunk-HFGO5762.js";import"../../chunk-VS5ROGDP.js";import"../../chunk-NAS7FIGM.js";import"../../chunk-VZYNZS5U.js";import"../../chunk-U2NT5OSQ.js";import"../../chunk-KGURGIZ2.js";import"../../chunk-GYNZ3OZF.js";import"../../chunk-UPFH72PF.js";import"../../chunk-3HJT572X.js";import"../../chunk-CDY7TQFZ.js";import"../../chunk-KFNFLMUR.js";import"../../chunk-FLP6WIJV.js";import"../../chunk-JP6ULOEX.js";import"../../chunk-SVZYRGO5.js";import"../../chunk-WULEBQPI.js";import"../../chunk-GPBN4ROE.js";import"../../chunk-6XTLP2G7.js";import"../../chunk-PJ3WHQ67.js";import{b as A,d as C,g as S,i as E,j as L,k as $}from"../../chunk-QI3FJKGK.js";import{a as O}from"../../chunk-TQFHRD5B.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-5LTJNYCP.js";import"../../chunk-3EZZGA72.js";import"../../chunk-XAGNGQL3.js";import"../../chunk-3AV3GTMP.js";import{f as m}from"../../chunk-5VWVQCNR.js";import"../../chunk-MHLHLJ5T.js";import"../../chunk-XQYAVSUQ.js";import{e as I,l as p}from"../../chunk-PZNWH4VQ.js";import{a as e}from"../../chunk-ZLLER3HP.js";import{trace as de,context as me}from"@opentelemetry/api";import{NodeSDK as W}from"@opentelemetry/sdk-node";import{OTLPTraceExporter as Y}from"@opentelemetry/exporter-trace-otlp-http";import{BatchSpanProcessor as J,ConsoleSpanExporter as z,SimpleSpanProcessor as Q}from"@opentelemetry/sdk-trace-node";import{Resource as Z}from"@opentelemetry/resources";import{ATTR_SERVICE_NAME as ee,ATTR_SERVICE_VERSION as te}from"@opentelemetry/semantic-conventions";function F(r){if(!r)return{};let n={};for(let o of r.split(",")){let s=o.indexOf("=");if(s===-1)continue;let i=o.slice(0,s).trim(),c=o.slice(s+1).trim();i&&(n[i]=c)}return n}e(F,"parseOtlpHeaders");var u=null;function T(){return process.env.TELEMETRY_ENABLED!=="false"}e(T,"isTelemetryEnabled");function x(r){if(!T()||u!==null)return"off";let n=new Z({[ee]:r.serviceName,[te]:r.serviceVersion??"0.1.0"}),o=process.env.OTEL_EXPORTER_OTLP_ENDPOINT,s,i;if(o){let c=F(process.env.OTEL_EXPORTER_OTLP_HEADERS),l=new Y({url:`${o}/v1/traces`,headers:c});i=new J(l),s="otlp"}else if(process.env.OTEL_SPAN_EXPORT==="none")i=void 0,s="silent";else{let c=new z;i=new Q(c),s="console"}return u=new W({resource:n,spanProcessors:i?[i]:[]}),u.start(),s}e(x,"initTelemetry");async function h(){u&&(await u.shutdown(),u=null)}e(h,"shutdownTelemetry");import{SpanKind as Pe,SpanStatusCode as Re}from"@opentelemetry/api";import{trace as Ie,context as Oe}from"@opentelemetry/api";import*as f from"@sentry/node";var v=!1;function w(r){if(v)return!1;let n=process.env.SENTRY_DSN;return n?(f.init({dsn:n,serverName:r.serviceName,environment:process.env.NODE_ENV??"development",tracesSampleRate:0}),v=!0,!0):!1}e(w,"initSentry");async function y(r){v&&await f.flush(r)}e(y,"flushSentry");import{existsSync as ne,mkdirSync as oe,readFileSync as k,unlinkSync as X,writeFileSync as U}from"node:fs";import{dirname as se,join as R}from"node:path";import{execFileSync as ie}from"node:child_process";var a=R(p(),"evals-agent.lock");function ce(r){try{return process.kill(r,0),!0}catch(n){return n.code==="EPERM"}}e(ce,"pidAlive");function ae(r){if(!ce(r))return!1;try{let n=ie("ps",["-p",String(r),"-o","command="],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]});return/run\.js\s+evals\s+agent|evals\s+agent/.test(n)}catch{return!0}}e(ae,"isLiveAgent");function le(){try{oe(se(a),{recursive:!0})}catch{}for(let r=0;r<2;r++)try{return U(a,String(process.pid),{flag:"wx"}),{ok:!0}}catch(n){if(n.code!=="EEXIST")throw n;let o=0;try{o=Number(k(a,"utf-8").trim())}catch{}if(o&&o!==process.pid&&ae(o))return{ok:!1,holder:o};try{X(a)}catch{}}try{U(a,String(process.pid))}catch{}return{ok:!0}}e(le,"acquireAgentLock");function P(){try{ne(a)&&Number(k(a,"utf-8").trim())===process.pid&&X(a)}catch{}}e(P,"releaseAgentLock");var N=class r extends O{static{e(this,"EvalAgentCommand")}static description="The worker daemon: long-polls /api/work/next, claims jobs, and runs them locally. Installed as a launchd service by `rulemetric service install`.";static examples=["<%= config.bin %> evals agent"];async run(){await this.parse(r),this.requireAuth();let n=le();if(!n.ok){this.log(`Another rulemetric evals agent is already running (pid ${n.holder}). Refusing to start a second instance.`);return}process.env.PG_APPLICATION_NAME||="rulemetric-agent",w({serviceName:"rulemetric-agent"})&&this.log("[sentry] error capture enabled");let s=x({serviceName:"rulemetric-agent"});s==="otlp"?this.log(`[otel] traces exporting to ${process.env.OTEL_EXPORTER_OTLP_ENDPOINT}`):s==="console"?this.log("[otel] cron spans printing to stdout (set OTEL_EXPORTER_OTLP_ENDPOINT to ship to a backend)"):this.log("[otel] disabled (TELEMETRY_ENABLED=false)"),!I()&&!process.env.RULEMETRIC_API_KEY&&this.error("No auth token found. Run `rulemetric auth login` first."),this.log("Starting thin agent (Phase 4b parallel-run)..."),this.log(`Long-polling /api/work/next. Press Ctrl+C to stop.
2
2
  `);let c=new AbortController,l=await A({configDir:p()});if(this.log(`[transcript-sync] Codex capture: ${S(l)}`),l.error)this.log(`[transcript-sync] WARNING: ${l.error}`);else if(l.mode==="allowlist")for(let t of l.roots)this.log(`[transcript-sync] \u2022 ${t}`);let d=await C({configDir:p()});if(this.log(`[transcript-sync] Pi capture: ${E(d)}`),d.error)this.log(`[transcript-sync] WARNING: ${d.error}`);else if(d.mode==="allowlist")for(let t of d.roots)this.log(`[transcript-sync] \u2022 ${t}`);let B=new M({postSnapshot:e((t,K)=>m(`/api/sessions/${t}/context-snapshots`,K),"postSnapshot"),linkInstructions:e(t=>m("/api/sessions/link-instructions",{sessionId:t}),"linkInstructions"),log:e(t=>this.log(`[transcript-sync] ${t}`),"log")}),H=new G({providers:[V(void 0,void 0,L({configDir:p(),onChange:e(t=>this.log(`[transcript-sync] Codex capture changed: ${S(t)}`),"onChange")})),j(void 0,void 0,$({configDir:p(),onChange:e(t=>this.log(`[transcript-sync] Pi capture changed: ${E(t)}`),"onChange")}))],statePath:R(p(),"transcript-sync-state.json"),importTranscript:e(t=>m("/api/sessions/import",t),"importTranscript"),emitInstructions:e(t=>B.emit(t),"emitInstructions"),log:e(t=>this.log(`[transcript-sync] ${t}`),"log")});q(H,{signal:c.signal,log:e(t=>this.log(`[transcript-sync] ${t}`),"log")});let _=e(async t=>{this.log(`
3
3
  [${t}] shutting down agent...`),c.abort(),await Promise.allSettled([y(2e3),h(),g()]),P(),process.exit(0)},"shutdown");process.on("SIGINT",()=>{_("SIGINT")}),process.on("SIGTERM",()=>{_("SIGTERM")});let b=!1;try{await D({signal:c.signal,log:e(t=>this.log(t),"log"),version:this.config.version,readInstalledVersion:e(()=>{try{return JSON.parse(k(R(this.config.root,"package.json"),"utf-8")).version??null}catch{return null}},"readInstalledVersion"),onVersionDrift:e(()=>{b=!0},"onVersionDrift")}),b&&(this.log("[upgrade] Installed CLI version changed \u2014 restarting worker onto the new code."),await Promise.allSettled([y(2e3),h(),g()]),P(),process.exit(1))}finally{P(),await g()}}};export{N as default};
@@ -1,4 +1,4 @@
1
- import{b as w,c as $}from"../../chunk-EQ2O6DSN.js";import"../../chunk-BTKVLLV2.js";import{b as v}from"../../chunk-UQJNUESP.js";import"../../chunk-FLXWL4F4.js";import"../../chunk-MGT5FZJ4.js";import"../../chunk-M7QSC64D.js";import"../../chunk-DZRBB34J.js";import"../../chunk-KR32Y5Q5.js";import"../../chunk-RITL4NU3.js";import"../../chunk-GYKYJJNF.js";import"../../chunk-G7V4ZZZ3.js";import"../../chunk-AHLVY52I.js";import"../../chunk-PPQFN62M.js";import"../../chunk-V6L25LFD.js";import"../../chunk-GWQ24FQP.js";import"../../chunk-PPAHIVG5.js";import"../../chunk-CT7FWSIU.js";import"../../chunk-5MXZJWQS.js";import"../../chunk-N7ODX6PO.js";import"../../chunk-NAS7FIGM.js";import"../../chunk-VZYNZS5U.js";import"../../chunk-U2NT5OSQ.js";import"../../chunk-KGURGIZ2.js";import"../../chunk-GYNZ3OZF.js";import"../../chunk-UPFH72PF.js";import"../../chunk-3HJT572X.js";import"../../chunk-CDY7TQFZ.js";import"../../chunk-KFNFLMUR.js";import"../../chunk-FLP6WIJV.js";import"../../chunk-JP6ULOEX.js";import"../../chunk-SVZYRGO5.js";import"../../chunk-WULEBQPI.js";import"../../chunk-GPBN4ROE.js";import"../../chunk-6XTLP2G7.js";import"../../chunk-PJ3WHQ67.js";import{a as f}from"../../chunk-TQFHRD5B.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-5LTJNYCP.js";import"../../chunk-3EZZGA72.js";import"../../chunk-XAGNGQL3.js";import"../../chunk-3AV3GTMP.js";import{e as d,f as p,h}from"../../chunk-5VWVQCNR.js";import"../../chunk-MHLHLJ5T.js";import"../../chunk-XQYAVSUQ.js";import"../../chunk-PZNWH4VQ.js";import{a}from"../../chunk-ZLLER3HP.js";import{Args as P,Flags as y}from"@oclif/core";var c=a(s=>s==null?"n/a":`${Math.round(s*100)}%`,"pct"),g=class s extends f{static{a(this,"EvalRefineCases")}static description="Retire non-discriminating eval cases and regenerate discriminating replacements (\xA76e)";static examples=["<%= config.bin %> evals refine-cases <target-id> # preview","<%= config.bin %> evals refine-cases <target-id> --yes # apply: retire + regenerate","<%= config.bin %> evals refine-cases <target-id> --yes --no-generate"];static args={targetId:P.string({description:"Eval target ID",required:!0})};static flags={yes:y.boolean({char:"y",description:"Apply (retire + regenerate). Without this, only previews."}),"no-generate":y.boolean({description:"Retire dead cases but do not regenerate replacements."})};async run(){let{args:b,flags:l}=await this.parse(s);this.requireAuth();let n=b.targetId,o=await d(`/api/eval-targets/${n}`),m=await d(`/api/eval-targets/${n}/judge-calibration`),i=m.caseDiscrimination,t=w(i);if(this.log(`Target "${o.name}" v${o.version} \u2014 judge ${m.judge.currentModel??"(unstamped)"}`),t.refused==="no-discrimination-data"){this.log("No case-discrimination data yet \u2014 run some evals with AND without the target first (`evals run` / the web Run Evals button), then refine.");return}if(this.log(`${i.total} diagnosable case(s): ${i.discriminating} discriminate, ${i.nonDiscriminating} flat/wrong-sign, ${i.unpaired} unpaired.`),t.refused==="all-discriminating"){this.log("Every case discriminates \u2014 nothing to retire. \u{1F389}");return}let C=i.cases.filter(e=>!e.discriminating),u=new Set(t.retire.map(e=>e.evalId));this.log(`
1
+ import{b as w,c as $}from"../../chunk-YZQZD2E6.js";import"../../chunk-FLJTAD2R.js";import{b as v}from"../../chunk-UQJNUESP.js";import"../../chunk-FLXWL4F4.js";import"../../chunk-L5ILEWHH.js";import"../../chunk-M7QSC64D.js";import"../../chunk-DZRBB34J.js";import"../../chunk-KR32Y5Q5.js";import"../../chunk-G7V4ZZZ3.js";import"../../chunk-RITL4NU3.js";import"../../chunk-GYKYJJNF.js";import"../../chunk-V6L25LFD.js";import"../../chunk-GWQ24FQP.js";import"../../chunk-PPAHIVG5.js";import"../../chunk-CT7FWSIU.js";import"../../chunk-5MXZJWQS.js";import"../../chunk-AHLVY52I.js";import"../../chunk-PPQFN62M.js";import"../../chunk-N7ODX6PO.js";import"../../chunk-NAS7FIGM.js";import"../../chunk-VZYNZS5U.js";import"../../chunk-U2NT5OSQ.js";import"../../chunk-KGURGIZ2.js";import"../../chunk-GYNZ3OZF.js";import"../../chunk-UPFH72PF.js";import"../../chunk-3HJT572X.js";import"../../chunk-CDY7TQFZ.js";import"../../chunk-KFNFLMUR.js";import"../../chunk-FLP6WIJV.js";import"../../chunk-JP6ULOEX.js";import"../../chunk-SVZYRGO5.js";import"../../chunk-WULEBQPI.js";import"../../chunk-GPBN4ROE.js";import"../../chunk-6XTLP2G7.js";import"../../chunk-PJ3WHQ67.js";import{a as f}from"../../chunk-TQFHRD5B.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-5LTJNYCP.js";import"../../chunk-3EZZGA72.js";import"../../chunk-XAGNGQL3.js";import"../../chunk-3AV3GTMP.js";import{e as d,f as p,h}from"../../chunk-5VWVQCNR.js";import"../../chunk-MHLHLJ5T.js";import"../../chunk-XQYAVSUQ.js";import"../../chunk-PZNWH4VQ.js";import{a}from"../../chunk-ZLLER3HP.js";import{Args as P,Flags as y}from"@oclif/core";var c=a(s=>s==null?"n/a":`${Math.round(s*100)}%`,"pct"),g=class s extends f{static{a(this,"EvalRefineCases")}static description="Retire non-discriminating eval cases and regenerate discriminating replacements (\xA76e)";static examples=["<%= config.bin %> evals refine-cases <target-id> # preview","<%= config.bin %> evals refine-cases <target-id> --yes # apply: retire + regenerate","<%= config.bin %> evals refine-cases <target-id> --yes --no-generate"];static args={targetId:P.string({description:"Eval target ID",required:!0})};static flags={yes:y.boolean({char:"y",description:"Apply (retire + regenerate). Without this, only previews."}),"no-generate":y.boolean({description:"Retire dead cases but do not regenerate replacements."})};async run(){let{args:b,flags:l}=await this.parse(s);this.requireAuth();let n=b.targetId,o=await d(`/api/eval-targets/${n}`),m=await d(`/api/eval-targets/${n}/judge-calibration`),i=m.caseDiscrimination,t=w(i);if(this.log(`Target "${o.name}" v${o.version} \u2014 judge ${m.judge.currentModel??"(unstamped)"}`),t.refused==="no-discrimination-data"){this.log("No case-discrimination data yet \u2014 run some evals with AND without the target first (`evals run` / the web Run Evals button), then refine.");return}if(this.log(`${i.total} diagnosable case(s): ${i.discriminating} discriminate, ${i.nonDiscriminating} flat/wrong-sign, ${i.unpaired} unpaired.`),t.refused==="all-discriminating"){this.log("Every case discriminates \u2014 nothing to retire. \u{1F389}");return}let C=i.cases.filter(e=>!e.discriminating),u=new Set(t.retire.map(e=>e.evalId));this.log(`
2
2
  Would retire ${t.retire.length} non-discriminating case(s):`);for(let e of C)u.has(e.evalId)&&this.log(` \u2717 ${e.name} \u2014 ${c(e.withPassRate)} with vs ${c(e.withoutPassRate)} without (\u0394${(e.separation*100).toFixed(0)}pp) \u2014 ${e.note}`);for(let e of i.unpairedCases)u.has(e.evalId)&&this.log(` \u2717 ${e.name} \u2014 ${c(e.withPassRate)} with vs ${c(e.withoutPassRate)} without \u2014 unpaired`);if(t.replacementsRequired&&this.log(`
3
3
  ${t.summary}. Replacements are generated and created BEFORE anything is retired \u2014 a target left under the floor drops out of the nightly evolution rotation with no error anywhere.`),!l.yes){this.log(`
4
4
  Preview only. Re-run with --yes to retire ${t.retire.length} case(s)${l["no-generate"]?"":" and generate replacements"}.`);return}let r=await $(t,{generate:a(e=>l["no-generate"]?Promise.resolve([]):v({content:o.content,name:o.name,feedback:e}),"generate"),createCase:a(e=>p(`/api/eval-targets/${n}/evals`,{name:e.name,prompt:e.prompt,expectations:e.expectations}),"createCase"),retireCase:a(async(e,R)=>{await h(`/api/eval-targets/${n}/evals/${e}`,{retire:!0,retiredReason:R})},"retireCase"),log:a(e=>this.log(e),"log")});if(r.skipped==="no-llm-backend"){this.warn(r.summary+" Install the `claude` CLI (or set ANTHROPIC_API_KEY), then run `evals refine-cases` again.");return}if(r.skipped==="no-replacements-generated"){this.warn(r.summary);return}this.log(`
@@ -1,3 +1,3 @@
1
- import{a as p}from"../../chunk-TQFHRD5B.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-5LTJNYCP.js";import"../../chunk-3EZZGA72.js";import"../../chunk-XAGNGQL3.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-5VWVQCNR.js";import"../../chunk-MHLHLJ5T.js";import"../../chunk-XQYAVSUQ.js";import"../../chunk-PZNWH4VQ.js";import{a as c}from"../../chunk-ZLLER3HP.js";import{Args as m}from"@oclif/core";import{execFileSync as f}from"node:child_process";import{existsSync as g}from"node:fs";import{join as h,delimiter as l}from"node:path";var v=["session-start","session-end","user-prompt","post-tool-use","assistant-response"],a=class d extends p{static{c(this,"HooksRun")}static description="Execute a hook script (called by AI tool hooks, not for direct use)";static hidden=!0;static args={hook:m.string({description:"Hook name to run",required:!0,options:[...v]})};async run(){let{args:e}=await this.parse(d),t=e.hook,{scriptsDir:o}=await import("@rulemetric/hooks/scripts-dir"),i=h(o,`${t}.sh`);g(i)||this.error(`Hook script not found: ${i}`);try{let s=await this.readStdin();try{let{evaluateHookCaptureGate:r}=await import("../../lib/hooks-capture-gate.js"),{getDefaultConfigDir:u}=await import("../../lib/auth.js");if(!(await r({stdin:s,configDir:u()})).allowed)return}catch{}let n=`${process.env.PATH??""}${l}${o}`;if(f("bash",[i],{input:s,stdio:["pipe","inherit","inherit"],timeout:t==="session-end"?3e4:1e4,env:{...process.env,PATH:n}}),process.env.RULEMETRIC_HOOK_TOOL==="antigravity"&&t==="post-tool-use")try{let{tailAntigravityTranscript:r}=await import("../../lib/antigravity-transcript.js");await r(s)}catch(r){process.stderr.write(`[antigravity-tailer] ${r.message}
2
- `)}}catch(s){let n=s.status;process.env.RULEMETRIC_HOOK_DEBUG&&process.stderr.write(`[rulemetric hooks run ${t}] non-fatal exit ${n??"?"}: ${s.message??""}
3
- `)}}readStdin(){return new Promise(e=>{let t=[];process.stdin.on("data",o=>t.push(o)),process.stdin.on("end",()=>e(Buffer.concat(t).toString("utf-8"))),process.stdin.readableEnded&&e(Buffer.concat(t).toString("utf-8"))})}};export{a as default};
1
+ import{a as m,b as f,d as g}from"../../chunk-ZFEDOPRU.js";import{a as d}from"../../chunk-TQFHRD5B.js";import"../../chunk-IZTIYR5Q.js";import"../../chunk-5LTJNYCP.js";import"../../chunk-3EZZGA72.js";import"../../chunk-XAGNGQL3.js";import"../../chunk-3AV3GTMP.js";import"../../chunk-5VWVQCNR.js";import"../../chunk-MHLHLJ5T.js";import"../../chunk-XQYAVSUQ.js";import"../../chunk-PZNWH4VQ.js";import{a as u}from"../../chunk-ZLLER3HP.js";import{Args as v}from"@oclif/core";import{execFileSync as S}from"node:child_process";import{existsSync as y}from"node:fs";import{join as k,delimiter as E}from"node:path";var O=["session-start","session-end","user-prompt","post-tool-use","assistant-response"],p=class h extends d{static{u(this,"HooksRun")}static description="Execute a hook script (called by AI tool hooks, not for direct use)";static hidden=!0;static args={hook:v.string({description:"Hook name to run",required:!0,options:[...O]})};async run(){let{args:o}=await this.parse(h),s=o.hook,{scriptsDir:r}=await import("@rulemetric/hooks/scripts-dir"),n=k(r,`${s}.sh`);y(n)||this.error(`Hook script not found: ${n}`);try{let e=await this.readStdin();try{let{evaluateHookCaptureGate:t}=await import("../../lib/hooks-capture-gate.js"),{getDefaultConfigDir:w}=await import("../../lib/auth.js");if(!(await t({stdin:e,configDir:w()})).allowed)return}catch{}let a=`${process.env.PATH??""}${E}${r}`,l=s==="session-end"?3e4:1e4,i=s==="session-start"?m(e):null,c="";try{c=S("bash",[n],{input:e,stdio:["pipe",i?"pipe":"inherit","inherit"],timeout:l,env:{...process.env,PATH:a}})?.toString()??""}catch(t){if(!i)throw t;c=t.stdout?.toString()??""}if(i){let t=await g(i.cwd);process.stdout.write(f(c,t?.message??null)),t?.emitted()}if(process.env.RULEMETRIC_HOOK_TOOL==="antigravity"&&s==="post-tool-use")try{let{tailAntigravityTranscript:t}=await import("../../lib/antigravity-transcript.js");await t(e)}catch(t){process.stderr.write(`[antigravity-tailer] ${t.message}
2
+ `)}}catch(e){let a=e.status;process.env.RULEMETRIC_HOOK_DEBUG&&process.stderr.write(`[rulemetric hooks run ${s}] non-fatal exit ${a??"?"}: ${e.message??""}
3
+ `)}}readStdin(){return new Promise(o=>{let s=[];process.stdin.on("data",r=>s.push(r)),process.stdin.on("end",()=>o(Buffer.concat(s).toString("utf-8"))),process.stdin.readableEnded&&o(Buffer.concat(s).toString("utf-8"))})}};export{p as default};
@@ -1 +1 @@
1
- import{a as o}from"../chunk-TQFHRD5B.js";import"../chunk-IZTIYR5Q.js";import"../chunk-5LTJNYCP.js";import"../chunk-3EZZGA72.js";import"../chunk-XAGNGQL3.js";import"../chunk-3AV3GTMP.js";import"../chunk-5VWVQCNR.js";import"../chunk-MHLHLJ5T.js";import"../chunk-XQYAVSUQ.js";import"../chunk-PZNWH4VQ.js";import{a as e}from"../chunk-ZLLER3HP.js";import{Flags as s}from"@oclif/core";var a=class r extends o{static{e(this,"Launcher")}static description="Open the launcher overlay (alias for `dashboard --launcher`)";static examples=["<%= config.bin %> launcher","<%= config.bin %> launcher --period today"];static flags={period:s.string({char:"p",default:"week",options:["today","week","30days","month","all"],description:"Initial time period for the dashboard panels behind the overlay"})};async run(){let{flags:i}=await this.parse(r),{renderDashboard:t}=await import("../dashboard/Dashboard.js");await t(i.period,{openLauncher:!0})}};export{a as default};
1
+ import{a as r}from"../chunk-TQFHRD5B.js";import"../chunk-IZTIYR5Q.js";import"../chunk-5LTJNYCP.js";import"../chunk-3EZZGA72.js";import"../chunk-XAGNGQL3.js";import"../chunk-3AV3GTMP.js";import"../chunk-5VWVQCNR.js";import"../chunk-MHLHLJ5T.js";import"../chunk-XQYAVSUQ.js";import"../chunk-PZNWH4VQ.js";import{a as i}from"../chunk-ZLLER3HP.js";var e=class extends r{static{i(this,"Launcher")}static hidden=!0;static description="Manual session launching is currently unavailable";async run(){this.error("Manual session launching has been shelved. Start your coding tool directly, or use `rulemetric dashboard` to view activity.")}};export{e as default};
@@ -1,3 +1,3 @@
1
- import{c as l,d as h,f as m,g as p,h as f,i as y,j as r}from"../chunk-YLEXR62G.js";import"../chunk-QWCEZEDO.js";import"../chunk-KKDHD4XA.js";import"../chunk-SZ62CP55.js";import"../chunk-OZQNSELV.js";import"../chunk-HFGO5762.js";import"../chunk-VS5ROGDP.js";import"../chunk-GPBN4ROE.js";import"../chunk-6XTLP2G7.js";import"../chunk-PJ3WHQ67.js";import{a as g}from"../chunk-TQFHRD5B.js";import"../chunk-IZTIYR5Q.js";import"../chunk-5LTJNYCP.js";import"../chunk-3EZZGA72.js";import"../chunk-XAGNGQL3.js";import"../chunk-3AV3GTMP.js";import"../chunk-5VWVQCNR.js";import"../chunk-MHLHLJ5T.js";import"../chunk-XQYAVSUQ.js";import"../chunk-PZNWH4VQ.js";import{a as u}from"../chunk-ZLLER3HP.js";import{Args as b,Flags as c}from"@oclif/core";import*as w from"node:readline/promises";var d=class v extends g{static{u(this,"Setup")}static description="Agentic, transparent setup: plan / show diffs / apply the four core onboarding steps";static examples=["<%= config.bin %> setup # interactive walk (TTY)","<%= config.bin %> setup plan # read-only: every remaining artifact + diff","<%= config.bin %> setup hooks --show # print one step's diff","<%= config.bin %> setup hooks --apply # apply one step","<%= config.bin %> setup --json # machine-readable status (exit 0 iff complete)"];static args={target:b.string({description:`"plan" or a step id (${l.join(", ")})`,required:!1})};static flags={json:c.boolean({description:"Machine-readable output",default:!1}),show:c.boolean({description:"Print the step diff (read-only)",default:!1}),apply:c.boolean({description:"Apply the step",default:!1})};async run(){let{args:t,flags:e}=await this.parse(v),i=h();if(t.target==="plan"){await this.runPlan(i,e.json);return}if(t.target&&y(t.target)){if(e.apply){await f(t.target).apply(i);return}let n=await f(t.target).plan(i);this.printPlan(n);return}if(t.target&&this.error(`Unknown target "${t.target}". Use "plan" or one of: ${l.join(", ")}.`),e.json){let n=await r(i);this.log(JSON.stringify(n,null,2)),n.coreComplete||this.exit(1);return}await this.runInteractive(i)}async runPlan(t,e){let i=await r(t),n=p.filter(s=>!i.steps.find(a=>a.id===s.id)?.done),o=[];for(let s of n)o.push(await s.plan(t));if(e){this.log(JSON.stringify({...i,plans:o},null,2));return}if(o.length===0){this.log("[OK] All core steps complete \u2014 nothing to install.");return}this.log(`The following steps would be applied:
1
+ import{c as l,d as h,f as m,g as p,h as f,i as y,j as r}from"../chunk-LSZ32DUR.js";import"../chunk-QWCEZEDO.js";import"../chunk-KKDHD4XA.js";import"../chunk-SZ62CP55.js";import"../chunk-OZQNSELV.js";import"../chunk-HFGO5762.js";import"../chunk-VS5ROGDP.js";import"../chunk-GPBN4ROE.js";import"../chunk-6XTLP2G7.js";import"../chunk-PJ3WHQ67.js";import{a as g}from"../chunk-TQFHRD5B.js";import"../chunk-IZTIYR5Q.js";import"../chunk-5LTJNYCP.js";import"../chunk-3EZZGA72.js";import"../chunk-XAGNGQL3.js";import"../chunk-3AV3GTMP.js";import"../chunk-5VWVQCNR.js";import"../chunk-MHLHLJ5T.js";import"../chunk-XQYAVSUQ.js";import"../chunk-PZNWH4VQ.js";import{a as u}from"../chunk-ZLLER3HP.js";import{Args as b,Flags as c}from"@oclif/core";import*as w from"node:readline/promises";var d=class v extends g{static{u(this,"Setup")}static description="Agentic, transparent setup: plan / show diffs / apply the four core onboarding steps";static examples=["<%= config.bin %> setup # interactive walk (TTY)","<%= config.bin %> setup plan # read-only: every remaining artifact + diff","<%= config.bin %> setup hooks --show # print one step's diff","<%= config.bin %> setup hooks --apply # apply one step","<%= config.bin %> setup --json # machine-readable status (exit 0 iff complete)"];static args={target:b.string({description:`"plan" or a step id (${l.join(", ")})`,required:!1})};static flags={json:c.boolean({description:"Machine-readable output",default:!1}),show:c.boolean({description:"Print the step diff (read-only)",default:!1}),apply:c.boolean({description:"Apply the step",default:!1})};async run(){let{args:t,flags:e}=await this.parse(v),i=h();if(t.target==="plan"){await this.runPlan(i,e.json);return}if(t.target&&y(t.target)){if(e.apply){await f(t.target).apply(i);return}let n=await f(t.target).plan(i);this.printPlan(n);return}if(t.target&&this.error(`Unknown target "${t.target}". Use "plan" or one of: ${l.join(", ")}.`),e.json){let n=await r(i);this.log(JSON.stringify(n,null,2)),n.coreComplete||this.exit(1);return}await this.runInteractive(i)}async runPlan(t,e){let i=await r(t),n=p.filter(s=>!i.steps.find(a=>a.id===s.id)?.done),o=[];for(let s of n)o.push(await s.plan(t));if(e){this.log(JSON.stringify({...i,plans:o},null,2));return}if(o.length===0){this.log("[OK] All core steps complete \u2014 nothing to install.");return}this.log(`The following steps would be applied:
2
2
  `);for(let s of o)this.printPlan(s),this.log("")}printPlan(t){this.log(`[..] ${t.title} (${t.id})`),t.command&&this.log(` command: ${t.command}`);for(let e of t.artifacts){this.log(` ${e.kind}: ${e.path}${e.masked?" (secret masked)":""}`);let i=m(e.before,e.after);for(let n of i.split(`
3
3
  `))this.log(` ${n}`)}}async runInteractive(t){if(!process.stdin.isTTY){this.log("Not a TTY \u2014 interactive walk needs a terminal."),this.log("Use one of:"),this.log(" rulemetric setup plan \u2014 see every remaining artifact + diff"),this.log(" rulemetric setup <step> --show \u2014 print one step diff"),this.log(" rulemetric setup <step> --apply \u2014 apply one step"),this.log(" rulemetric setup --json \u2014 machine-readable status");return}let e=await r(t),i=p.filter(o=>!e.steps.find(s=>s.id===o.id)?.done);if(i.length===0){this.log("[OK] All core steps complete.");return}let n=w.createInterface({input:process.stdin,output:process.stdout});try{for(let o of i){let s=await o.plan(t);this.printPlan(s);let a=(await n.question(`Apply "${s.title}"? [y/N] `)).trim().toLowerCase();a==="y"||a==="yes"?(await o.apply(t),this.log(`[OK] Applied ${s.title}.`)):this.log(`[..] Skipped ${s.title}.`),this.log("")}}finally{n.close()}}};export{d as default};