@kynver-app/runtime 0.2.37 → 0.2.41

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.
@@ -1,16 +1,16 @@
1
- var f=(e,r,t)=>()=>{if(t)throw t[0];try{return e&&(r=e(e=0)),r}catch(n){throw t=[n],n}};import{homedir as Tt}from"node:os";import Ut from"node:path";function Es(e){return e==="~"?Tt():e.startsWith("~/")||e.startsWith("~\\")?Ut.join(Tt(),e.slice(2)):e}function Z(e){return Ut.resolve(Es(e))}var oe=f(()=>{"use strict"});import{existsSync as ws,mkdirSync as As,readFileSync as Bt,readdirSync as rl,renameSync as Ps,rmSync as Os,statSync as Kt,writeFileSync as Is}from"node:fs";import{randomBytes as Ds}from"node:crypto";import Ns from"node:path";function jr(e){console.error(e),process.exit(1)}function $r(e){return process.platform!=="win32"?e:{windowsHide:!0,...e}}function Ye(e){try{return JSON.parse(e)}catch{return null}}function x(e,r){try{return JSON.parse(Bt(e,"utf8"))}catch(t){if(arguments.length>1)return r;jr(`failed to read ${e}: ${t.message}`)}}function Ft(e,r){As(Ns.dirname(e),{recursive:!0});let t=`${e}.${process.pid}.${Ds(4).toString("hex")}.tmp`;try{Is(t,`${JSON.stringify(r,null,2)}
2
- `),Ps(t,e)}catch(n){try{Os(t,{force:!0})}catch{}throw n}}function v(e){return String(e||"").toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"worker"}function Ve(e){try{return Kt(e).size}catch{return 0}}function ze(e){try{return Kt(e).mtime.toISOString()}catch{return null}}function Ht(e,r){return ws(e)?Bt(e,"utf8").split(`
1
+ var f=(e,r,t)=>()=>{if(t)throw t[0];try{return e&&(r=e(e=0)),r}catch(n){throw t=[n],n}};import{homedir as Tt}from"node:os";import Ut from"node:path";function Es(e){return e==="~"?Tt():e.startsWith("~/")||e.startsWith("~\\")?Ut.join(Tt(),e.slice(2)):e}function Z(e){return Ut.resolve(Es(e))}var oe=f(()=>{"use strict"});import{existsSync as ws,mkdirSync as As,readFileSync as Bt,readdirSync as rl,renameSync as Ps,rmSync as Os,statSync as Kt,writeFileSync as Is}from"node:fs";import{randomBytes as Ds}from"node:crypto";import Ns from"node:path";function Ye(e){console.error(e),process.exit(1)}function $r(e){return process.platform!=="win32"?e:{windowsHide:!0,...e}}function Ve(e){try{return JSON.parse(e)}catch{return null}}function x(e,r){try{return JSON.parse(Bt(e,"utf8"))}catch(t){if(arguments.length>1)return r;Ye(`failed to read ${e}: ${t.message}`)}}function Ft(e,r){As(Ns.dirname(e),{recursive:!0});let t=`${e}.${process.pid}.${Ds(4).toString("hex")}.tmp`;try{Is(t,`${JSON.stringify(r,null,2)}
2
+ `),Ps(t,e)}catch(n){try{Os(t,{force:!0})}catch{}throw n}}function v(e){return String(e||"").toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"worker"}function ze(e){try{return Kt(e).size}catch{return 0}}function Je(e){try{return Kt(e).mtime.toISOString()}catch{return null}}function Ht(e,r){return ws(e)?Bt(e,"utf8").split(`
3
3
  `).slice(-r).join(`
4
- `):""}function Q(e){if(!e)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Lt(e){let r=null,t=-1/0;for(let n of e){if(!n)continue;let o=Date.parse(n);Number.isFinite(o)&&o>t&&(t=o,r=n)}return r}function Gr(e){return Math.max(0,Math.round((Date.now()-e)/1e3))}var b=f(()=>{"use strict"});var Ws,sl,Ms,il,jt=f(()=>{"use strict";Ws=["ANTHROPIC_API_KEY","ANALYST_API_KEY","RECRUITER_API_KEY","AUTH_SECRET","NEXTAUTH_SECRET","DATABASE_URL","PRODUCTION_DATABASE_URL","KYNVER_PRODUCTION_DATABASE_URL","REDIS_URL","GOOGLE_CLIENT_SECRET","GITHUB_CLIENT_SECRET","KYNVER_API_KEY","KYNVER_SERVICE_SECRET","KYNVER_RUNTIME_SECRET","KYNVER_CRON_SECRET","OPENCLAW_CRON_SECRET","QSTASH_TOKEN","QSTASH_CURRENT_SIGNING_KEY","QSTASH_NEXT_SIGNING_KEY","TOOL_SECRETS_KEK","TOOL_EXECUTOR_DISPATCH_SECRET","CLOUDFLARE_API_TOKEN","STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_IDENTITY_WEBHOOK_SECRET","VOYAGE_API_KEY","PERPLEXITY_API_KEY","FRED_API_KEY","FMP_API_KEY","CURSOR_API_KEY","MEMORY_CONTENT_KEK","LLM_BYOK_KEK","KYNVER_COMMAND_AUTH_KEY","KYNVER_INSTRUCTION_BUNDLE_KEY","KYNVER_MEMORY_LEDGER_KEY","KYNVER_JWKS_PRIVATE_KEY_JWK"],sl=new Set(Ws),Ms=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY"],il=new Set(Ms)});import{spawnSync as Gt}from"node:child_process";function ye(e,r,t={}){let n=Gt("git",r,$r({cwd:e,encoding:"utf8"}));if(n.status!==0&&!t.allowFailure){let o=Ts(e,r,n);if(t.throwError)throw new Error(o);jr(o)}return n.stdout||""}function Ts(e,r,t){let n=typeof t.stderr=="string"&&t.stderr.trim()||typeof t.stdout=="string"&&t.stdout.trim()||t.error?.message||`exit ${t.status??"unknown"}`;return`git ${r.join(" ")} failed in ${e}: ${n}`}function Oe(e){return ye(e,["status","--short"],{allowFailure:!0}).split(`
5
- `).map(r=>r.trim()).filter(Boolean)}function w(e,r){try{let t=Gt("git",r,$r({cwd:e,encoding:"utf8"}));return{status:t.status,stdout:t.stdout||"",stderr:t.stderr||"",error:t.error?t.error.message:null}}catch(t){return{status:null,stdout:"",stderr:"",error:t.message}}}function $t(e,r,t){let n=w(e,["merge-base","--is-ancestor",r,t]);return n.status===0?{isAncestor:!0,error:null}:n.status===1?{isAncestor:!1,error:null}:{isAncestor:null,error:n.error||n.stderr||n.stdout||`git exited ${n.status}`}}function Je(e,r="origin/main"){let t=typeof r=="string"?{base:r}:r,n=t.baseCommit?.trim()||t.base?.trim()||"origin/main",o=t.baseCommit?.trim()||null;if(!e)return Yr(n,"missing worktree path");let s=w(e,["rev-parse","HEAD"]);if(s.status!==0)return Yr(n,s.error||s.stderr||s.stdout||"failed to resolve HEAD");let i;if(o)i=o;else{let m=w(e,["rev-parse",n]);if(m.status!==0)return Yr(n,m.error||m.stderr||m.stdout||`failed to resolve ${n}`,s.stdout.trim());i=m.stdout.trim()}let a=s.stdout.trim();if(a===i)return{checked:!0,base:n,head:a,baseHead:i,baseIsAncestorOfHead:!0,headIsAncestorOfBase:!0,relation:"synced"};let u=$t(e,i,a),l=$t(e,a,i),c=u.error||l.error||void 0;if(u.isAncestor==null||l.isAncestor==null)return{checked:!1,base:n,head:a,baseHead:i,baseIsAncestorOfHead:u.isAncestor,headIsAncestorOfBase:l.isAncestor,relation:"unknown",...c?{error:c}:{}};let d=u.isAncestor?"ahead":l.isAncestor?"merged":"diverged";return{checked:!0,base:n,head:a,baseHead:i,baseIsAncestorOfHead:u.isAncestor,headIsAncestorOfBase:l.isAncestor,relation:d,...c?{error:c}:{}}}function Yr(e,r,t=null){return{checked:!1,base:e,head:t,baseHead:null,baseIsAncestorOfHead:null,headIsAncestorOfBase:null,relation:"unknown",error:r}}var F=f(()=>{"use strict";oe();b();jt()});var Xe=f(()=>{"use strict";F();oe()});function se(e){let r=(e??"").trim().toLowerCase();return r==="ghost"||r==="forge"||r==="box"?r:r.includes("forge")?"forge":r.includes("ghost")||r.includes("openclaw")?"ghost":"box"}function qe(e,r){return e[r]?.trim()||null}function Yt(e){let r=e?.split(":")[0]?.trim();return r?se(r):null}function be(e=process.env,r={}){let t=[],n=Yt(r.boxId),o=Yt(qe(e,"KYNVER_BOX_ID")),s=r.boxKind?.trim();if(s)return n&&n!==se(s)&&t.push(`config.boxId=${r.boxId} conflicts with boxKind=${s}; using explicit boxKind=${s}`),{boxKind:se(s),source:"config",slugInferenceBlocked:!1,warnings:t};let i=qe(e,"KYNVER_BOX_KIND");if(i)return o&&o!==se(i)&&t.push(`KYNVER_BOX_ID=${qe(e,"KYNVER_BOX_ID")} conflicts with KYNVER_BOX_KIND=${i}; using explicit KYNVER_BOX_KIND=${i}`),{boxKind:se(i),source:"env",slugInferenceBlocked:!1,warnings:t};if(n)return{boxKind:n,source:"config",slugInferenceBlocked:!1,warnings:t};if(o)return{boxKind:o,source:"env",slugInferenceBlocked:!1,warnings:t};let a=qe(e,"KYNVER_AGENT_OS_SLUG");return a&&t.push(`KYNVER_AGENT_OS_SLUG=${a} is a workspace slug, not box identity \u2014 operators set boxKind via \`kynver setup --box-kind forge|ghost\` or KYNVER_BOX_KIND; customers default to box`),{boxKind:"box",source:"default",slugInferenceBlocked:!!a,warnings:t}}var ie=f(()=>{"use strict"});function Vr(e,r){return e==="forge"?4:Math.max(1,r)}function Ze(e,r){return e==="forge"?Math.min(Math.max(1,r),4):Math.max(1,r)}var Qe=f(()=>{"use strict"});var Vt=f(()=>{"use strict"});import{existsSync as Us,readFileSync as Bs,statfsSync as Ks}from"node:fs";function zr(){if(process.platform!=="linux")return!1;for(let e of["/proc/sys/kernel/osrelease","/proc/version"])try{if(!Us(e))continue;let r=Bs(e,"utf8");if(/microsoft|wsl/i.test(r))return!0}catch{}return!1}function zt(e={}){if(!(e.forceWsl===void 0?zr():e.forceWsl))return null;let t=e.wslHostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||Se,n=e.wslHostFreeWarnBytes??Fs,o=e.wslHostFreeCriticalBytes??Hs,s=e.statfs??Ks,i;try{i=s(t)}catch(R){return{ok:!1,path:t,freeBytes:0,totalBytes:0,usedPercent:100,warnBelowBytes:n,criticalBelowBytes:o,reason:`Windows host disk probe failed at ${t}: ${R.message}`,probeError:R.message}}let a=Number(i.bavail)*Number(i.bsize),u=Number(i.blocks)*Number(i.bsize),l=u>0?(u-a)/u*100:100,c=a<n,d=a<o,m=!c&&!d,g=(a/(1024*1024*1024)).toFixed(1),p=null;return m||(p=`Windows host disk ${t} at ${d?"critical":"warning"}: ${g} GiB free (<${(d?o:n)/1024/1024/1024} GiB); WSL VHDX cannot grow safely. ${Ls()}`),{ok:m,path:t,freeBytes:a,totalBytes:u,usedPercent:l,warnBelowBytes:n,criticalBelowBytes:o,reason:p,probeError:null}}function Ls(){return"Recovery: 1) free Windows C: (empty Recycle Bin / Storage Sense / clear %TEMP% and %LOCALAPPDATA%\\Temp\\wsl-crashes); 2) shut down WSL (`wsl --shutdown`) then compact the VHDX (`Optimize-VHD` or `diskpart compact vdisk`); 3) clear local node_modules / .next / harness worktrees before restarting workers; 4) disable recurring dumps via `%USERPROFILE%/.wslconfig` (`maxCrashDumpCount=-1`) or `kynver wsl-crashes --execute`. Full runbook: docs/runbooks/wsl-disk-pressure.md."}var Fs,Hs,Se,Jr=f(()=>{"use strict";Fs=25*1024*1024*1024,Hs=12*1024*1024*1024,Se="/mnt/c"});import{execFileSync as Jt}from"node:child_process";import{existsSync as rr,readFileSync as Xt,readdirSync as js,statSync as $s}from"node:fs";import Xr from"node:path";function er(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function qt(){let e=process.env.KYNVER_WSL_WIN_USER?.trim();if(e)return e;try{let n=Jt("cmd.exe",["/c","echo","%USERNAME%"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(n&&n!=="%USERNAME%"&&!n.includes("%"))return n}catch{}let r=process.env.USER?.trim()||process.env.LOGNAME?.trim(),t=process.env.KYNVER_WSL_HOST_MOUNT?.trim()||Se;return r&&rr(Xr.join(t,"Users",r))?r:null}function Js(e={}){let r=e.crashDumpDir?.trim()||process.env.KYNVER_WSL_CRASH_DUMP_DIR?.trim();if(r)return r;let t=e.hostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||Se,n=e.windowsUser??qt();return n?`${t.replace(/\\/g,"/").replace(/\/$/,"")}/Users/${n}/AppData/Local/Temp/wsl-crashes`:null}function Xs(e){let r=/^wsl-crash-\d+-(\d+)-(.+)-(\d+)\.dmp$/i.exec(e);if(!r)return{executableHint:null,signal:null,pid:null};let t=Number(r[1]),n=r[2]??"",o=Number(r[3]),s=n.split("_").filter(Boolean);return{executableHint:s.length>0?s[s.length-1]:null,signal:Number.isFinite(o)?o:null,pid:Number.isFinite(t)?t:null}}function qs(){try{if(rr("/proc/sys/kernel/core_pattern"))return Xt("/proc/sys/kernel/core_pattern","utf8").trim()}catch{}try{return Jt("sysctl",["-n","kernel.core_pattern"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function Zs(e){return!!(e&&/wsl-capture-crash/i.test(e))}function Qs(e,r=Se){let t=Xr.join(r,"Users",e,".wslconfig");if(!rr(t))return{maxCrashDumpCount:null,crashDumpFolder:null};let n;try{n=Xt(t,"utf8")}catch{return null}let o=null,s=null;for(let i of n.split(/\r?\n/)){let a=i.replace(/#.*$/,"").trim();if(!a||a.startsWith("["))continue;let u=a.indexOf("=");if(u<0)continue;let l=a.slice(0,u).trim().toLowerCase(),c=a.slice(u+1).trim();if(l==="maxcrashdumpcount"){let d=Number(c);o=Number.isFinite(d)?d:null}else l==="crashdumpfolder"&&(s=c.replace(/^["']|["']$/g,"")||null)}return{maxCrashDumpCount:o,crashDumpFolder:s}}function ei(e){if(!rr(e))return[];let r=js(e,{withFileTypes:!0}),t=[];for(let n of r){if(!n.isFile()||!n.name.toLowerCase().endsWith(".dmp"))continue;let o=Xr.join(e,n.name);try{let s=$s(o),i=Xs(n.name);t.push({name:n.name,path:o,bytes:s.size,mtimeMs:s.mtimeMs,executableHint:i.executableHint,signal:i.signal,pid:i.pid})}catch{}}return t.sort((n,o)=>o.mtimeMs-n.mtimeMs),t}function ve(e={}){if(!(e.forceWsl===void 0?zr():e.forceWsl))return null;let t=e.hostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||Se,n=e.windowsUser??qt(),o=e.warnBelowBytes??er("KYNVER_WSL_CRASH_DUMP_WARN_BYTES",Gs),s=e.criticalBelowBytes??er("KYNVER_WSL_CRASH_DUMP_CRITICAL_BYTES",Ys),i=e.warnCount??er("KYNVER_WSL_CRASH_DUMP_WARN_COUNT",Vs),a=e.criticalCount??er("KYNVER_WSL_CRASH_DUMP_CRITICAL_COUNT",zs),u=(e.readCorePattern??qs)(),l=Zs(u),c=null;n&&(c=(e.readWslConfig??Qs)(n,t));let d=c?.maxCrashDumpCount??null,m=d===-1,g=Js({hostMount:t,windowsUser:n,crashDumpDir:e.crashDumpDir});if(!g)return{ok:!0,path:null,windowsUser:n,dumpCount:0,totalBytes:0,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:[],executables:[],corePattern:u,wslCaptureEnabled:l,maxCrashDumpCount:d,dumpsDisabledInWslConfig:m,reason:null,probeError:"windows_user_unresolved"};let p;try{p=(e.listDumps??ei)(g)}catch(P){return{ok:!1,path:g,windowsUser:n,dumpCount:0,totalBytes:0,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:[],executables:[],corePattern:u,wslCaptureEnabled:l,maxCrashDumpCount:d,dumpsDisabledInWslConfig:m,reason:`WSL crash dump probe failed at ${g}: ${P.message}`,probeError:P.message}}let R=p.reduce((P,h)=>P+h.bytes,0),S=p.length,y=[...new Set(p.map(P=>P.executableHint).filter(P=>!!P))],A=R>=s,j=R>=o,B=S>=a,je=S>=i,te=!(A||B||j||je),ne=null;if(!te){let P=A||B?"critical":"warning",h=(R/1024**3).toFixed(1),q=y.length>0?y.join(", "):"unknown";ne=`WSL crash dumps ${P}: ${S} file(s), ${h} GiB at ${g} (executables: ${q}). `+ri({wslCaptureEnabled:l,dumpsDisabledInWslConfig:m})}return{ok:te,path:g,windowsUser:n,dumpCount:S,totalBytes:R,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:p,executables:y,corePattern:u,wslCaptureEnabled:l,maxCrashDumpCount:d,dumpsDisabledInWslConfig:m,reason:ne,probeError:null}}function ri(e={}){let r=["Recovery:","1) run `kynver wsl-crashes --execute` or scripts/cleanup-wsl-crashes.ps1 to prune old .dmp files;"];return e.dumpsDisabledInWslConfig||r.push("2) add `[wsl2]\\nmaxCrashDumpCount=-1` to %USERPROFILE%/.wslconfig then `wsl --shutdown` to disable future dumps;"),e.wslCaptureEnabled&&r.push("3) investigate crashing executables (node OOM/SIGBUS often follows Windows C: pressure \u2014 see docs/runbooks/wsl-disk-pressure.md);"),r.push("full runbook: docs/runbooks/wsl-disk-pressure.md."),r.join(" ")}var Gs,Ys,Vs,zs,tr=f(()=>{"use strict";Jr();Gs=5*1024*1024*1024,Ys=10*1024*1024*1024,Vs=2,zs=4});import{statfsSync as ti}from"node:fs";function nr(e={}){let r=e.diskPath?.trim()||"/",t=e.diskFreeWarnBytes??ni,n=e.diskFreeCriticalBytes??oi,o=e.diskMaxUsedPercent??si,s=e.diskHardMaxUsedPercent??ii,i=ti(r),a=Number(i.bavail)*Number(i.bsize),u=Number(i.blocks)*Number(i.bsize),l=u>0?(u-a)/u*100:100,c=a<t,d=a<n,m=a<t*2,g=m&&l>o,p=m&&l>s,R=!c&&!d&&!g&&!p,S=e.skipWslHostCheck?null:zt(e.wslHost),y=e.skipWslCrashDumpCheck?null:ve(e.wslCrashDumps),A=R&&(S?S.ok:!0)&&(y?y.ok:!0),j=null;return A||(j=[d?`free space below critical ${n} bytes`:null,c?`free space below warning ${t} bytes`:null,p?`used percent above hard cap ${s}%`:null,g?`used percent above cap ${o}%`:null,S&&!S.ok?S.reason:null,y&&!y.ok?y.reason:null].filter(Boolean).join("; ")),ai({ok:A,path:r,freeBytes:a,totalBytes:u,usedPercent:l,warnBelowBytes:t,criticalBelowBytes:n,maxUsedPercent:o,hardMaxUsedPercent:s,reason:j,wslHost:S,wslCrashDumps:y?{ok:y.ok,path:y.path,dumpCount:y.dumpCount,totalBytes:y.totalBytes,executables:y.executables,wslCaptureEnabled:y.wslCaptureEnabled,dumpsDisabledInWslConfig:y.dumpsDisabledInWslConfig,reason:y.reason,probeError:y.probeError}:null})}function ai(e){let r=process.env.KYNVER_DISPATCH_DISK_GATE_FORCE?.trim().toLowerCase();return r?r==="ok"||r==="open"||r==="none"?e.ok?e:{...e,ok:!0,reason:`disk gate forced open by KYNVER_DISPATCH_DISK_GATE_FORCE (suppressed: ${e.reason??"no reason"})`}:r==="block"||r==="pressured"?{...e,ok:!1,reason:`disk gate forced closed by KYNVER_DISPATCH_DISK_GATE_FORCE${e.reason?` (underlying: ${e.reason})`:""}`}:e:e}var ni,oi,si,ii,or=f(()=>{"use strict";tr();Jr();ni=30*1024*1024*1024,oi=15*1024*1024*1024,si=80,ii=90});import{existsSync as ui,readdirSync as li,statSync as ci}from"node:fs";import qr from"node:path";function sr(){return Qt()}function Zr(){let{runsDir:e}=sr();return Zt(e)}function ir(e){return Zt(G(e))}function di(e){try{return ci(e).isDirectory()}catch{return!1}}function Zt(e){if(!ui(e))return[];let r=[];for(let t of li(e,{withFileTypes:!0})){if(t.name==="runs")continue;let n=qr.join(e,t.name);if(!di(n))continue;let o=x(qr.join(n,"run.json"),void 0);o?.id&&r.push(o)}return r}function Qr(e){let{runsDir:r}=sr();Ft(qr.join(et(r,e.id),"run.json"),e)}function Ie(e){let{harnessRoot:r}=sr();return De(r,e)}function De(e,r){return et(G(e),v(r))}var ae=f(()=>{"use strict";Y();b()});import{existsSync as pi,readdirSync as mi}from"node:fs";import fi from"node:path";function rt(e){let r=new Set;for(let n of Object.keys(e.workers||{}))r.add(v(n));let t=fi.join(Ie(e.id),"workers");if(!pi(t))return[...r];for(let n of mi(t,{withFileTypes:!0}))n.isDirectory()&&r.add(v(n.name));return[...r]}var tt=f(()=>{"use strict";ae();b()});function nt(e){let r=e.trim();if(!r.startsWith("{"))return null;try{let t=JSON.parse(r);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{return null}return null}function en(e){let r=e.trim();if(!r)return null;let t=nt(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let u=nt(s[1]??"");u&&n.push(u)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let u=nt(r.slice(i,a+1));u&&n.push(u)}return n.length>0?n[n.length-1]:null}function rn(e){let r=e.finalResult??e.final_result;if(r!=null)return typeof r=="string"?en(r)??(r.trim()||null):r;let t=typeof e.summary=="string"?e.summary.trim():"";if(!t)return null;let n=en(t);return n||t}var tn=f(()=>{"use strict"});import{existsSync as gi,readFileSync as hi}from"node:fs";function nn(e){return e==="complete"}function on(e){return nn(e.lastHeartbeatPhase)?e.terminalFinalResult!==void 0&&e.terminalFinalResult!==null?e.terminalFinalResult:e.lastHeartbeatSummary?.trim()||"completed":null}function xe(e){let r={heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,terminalFinalResult:null,heartbeatBlocker:null,timestampAnomalies:[],lastBoxResourceSnapshot:null,lastPrEvidence:[]};if(!gi(e))return r;let t=Date.now()+ki,n=new Date(t).toISOString(),o=hi(e,"utf8").split(`
6
- `).filter(Boolean);for(let s of o){let i=Ye(s);if(!i||typeof i!="object"||Array.isArray(i))continue;let a=i;if(r.heartbeatCount++,a.ts){let u=String(a.ts),l=Date.parse(u);Number.isFinite(l)&&l>t?r.timestampAnomalies.push({kind:"future_heartbeat_timestamp",observedAt:u,clampedTo:n}):r.lastHeartbeatAt=u}a.phase!==void 0&&a.phase!==null&&(r.lastHeartbeatPhase=String(a.phase)),a.summary!==void 0&&a.summary!==null&&(r.lastHeartbeatSummary=String(a.summary)),nn(r.lastHeartbeatPhase)&&(r.terminalFinalResult=rn(a)),r.heartbeatBlocker=a.blocker?String(a.blocker):null,a.boxResourceSnapshot&&typeof a.boxResourceSnapshot=="object"&&!Array.isArray(a.boxResourceSnapshot)&&(r.lastBoxResourceSnapshot=a.boxResourceSnapshot),Array.isArray(a.prEvidence)&&(r.lastPrEvidence=a.prEvidence.filter(u=>!!u&&typeof u=="object"&&typeof u.prUrl=="string"))}return r}var ki,ar=f(()=>{"use strict";tn();b();ki=6e4});function an(e){return e?(e.split("/").pop()??e).replace(/\.exe$/i,"").toLowerCase():null}function ur(e){if(!e)return[];let r=[],t="",n,o=!1;for(let s of e){if(o){t+=s,o=!1;continue}if(s==="\\"){o=!0;continue}if(n){s===n?n=void 0:t+=s;continue}if(s==='"'||s==="'"){n=s;continue}if(/\s/.test(s)){t&&(r.push(t),t="");continue}t+=s}return t&&r.push(t),r}function un(e){let r=an(e[0]);return!!(r&&Ri.has(r))}function bi(e){let r=e.trim();return r.includes("/")?r.split("/").pop()??r:r}function Si(e){if(!e||e.includes("*"))return null;let r=bi(e);return!r||r.includes("/")?null:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(r)?r:null}function ln(e){return!e||e.includes("/")||e.includes("*")?!1:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(e)}function ot(e){if(!e)return!1;let r=e.trim();return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")}function vi(e){if(!e.startsWith("--glob="))return e;let r=e.slice(7);return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")?`--glob=${r}/**`:e}function xi(e){let r=[];for(let t=1;t<e.length;t+=1){let n=e[t];if(n){if(n==="--"){r.push(...e.slice(t+1));break}if(n.startsWith("-")){if(n.includes("="))continue;sn.has(n)&&(t+=1);continue}r.push(n)}}return r}function _i(e){let r=!1,t=e.map((o,s)=>{let i=vi(o),a=e[s-1];return a&&sn.has(a)&&o.startsWith("!")&&!o.includes("/")&&!o.endsWith("/**")&&(i=`${o}/**`),i!==o&&(r=!0),i}),n=xi(t);if(n.length===2){let[o,s]=n;if(ot(s))return{argv:[t[0]??"rg",o,"-g",`${s}/**`,"."],changed:!0};let i=Si(s);if(i)return{argv:[t[0]??"rg","-g",i,o,"."],changed:!0}}return r&&n.length===1?{argv:[...t,"."],changed:!0}:{argv:t,changed:r}}function cn(e){for(let r=1;r<e.length;r+=1){let t=e[r];if(t&&(t==="-c"||t==="-lc"||t==="-cl"||/^-[a-zA-Z]*c[a-zA-Z]*$/u.test(t)))return r+1}return-1}function lr(e){let r=e.trim();if(!r)return{command:r,wrapped:!1};let t=ur(r);if(!t.length)return{command:r,wrapped:!1};let n=an(t[0]);if(!n||!yi.has(n))return{command:r,wrapped:!1};let o=cn(t);if(o<0||o>=t.length)return{command:r,wrapped:!1};let s=t.slice(o).join(" ").trim();return s?{command:s,wrapped:!0}:{command:r,wrapped:!1}}function Ci(e,r){let t=e.trim(),n=ur(t),o=cn(n);if(o<0)return r;let s=n.slice(0,o).join(" "),i=r.includes("'")?`"${r.replace(/"/g,'\\"')}"`:`'${r}'`;return`${s} ${i}`}function Ei(e){let r=e.trim(),t=lr(r),n=ur(t.command);if(!n.length||!un(n))return{segment:r,changed:!1};let o=_i(n);if(!o.changed)return{segment:r,changed:!1};let s=o.argv.join(" ");return t.wrapped?{segment:Ci(r,s),changed:!0}:{segment:s,changed:!0}}function st(e){let r=e.trim();if(!r)return{command:r,changed:!1};let t=r.includes("&&")?" && ":r.includes("||")?" || ":"; ",n=r.split(/\s*(?:&&|\|\||;)\s*/u),o=!1,s=n.map(i=>{let a=Ei(i);return a.changed&&(o=!0),a.segment});return o?{command:s.join(t),changed:!0}:{command:r,changed:!1}}function dn(e){let r=lr(e).command,t=ur(r.trim());return t.length&&un(t)?!0:/\b(rg|ripgrep)\b/i.test(r)}function pn(e){if(!e)return{};let r=e.match(/search\s+"(.+)"\s+in\s+([^()]+?)(?:\s*\(|$)/iu);if(r)return{pattern:r[1],target:r[2]?.trim()};let t=e.match(/^search\s+"(.+)"\s+in\s+(.+)$/iu);return t?{pattern:t[1],target:t[2]?.trim()}:{}}function wi(e){let{pattern:r,target:t}=pn(e);return r?ot(t)?{kind:"rg_exclude_syntax",pattern:r,target:t}:ln(t)?{kind:"bad_scope",pattern:r,target:t}:{kind:"not_repo_search",pattern:r,target:t}:{kind:"not_repo_search"}}function Ai(e){let{pattern:r,target:t}=pn(e);if(!r)return null;if(ot(t)){let n=`${t.trim()}/**`;return{command:`rg "${r}" -g '${n}' .`,changed:!0}}return t&&ln(t)?{command:`rg -g ${t} "${r}" .`,changed:!0}:null}function Pi(e){if(e.kind==="bad_scope"&&e.pattern?.includes("agent-os-land-pr")&&e.target==="package.json")return"Search package.json with a glob from the repo root: `rg -g package.json agent-os-land-pr .` \u2014 or run `node scripts/agent-os-land-pr.mjs <pr-url>` directly.";if(e.kind==="bad_scope"&&e.pattern&&e.target)return`Use \`rg -g '${e.target}' ${e.pattern} .\` from the repo root instead of treating ${e.target} as a folder.`;if(e.kind==="rg_exclude_syntax"&&e.pattern){let r=e.target?`${e.target.trim()}/**`:"!node_modules/**";return`Repo search scope \`${e.target??"!node_modules"}\` is not a valid ripgrep path. Use \`rg "${e.pattern}" -g '${r}' .\` from the repo root (exclude globs need a \`/**\` suffix).`}return e.kind==="no_matches"&&e.pattern?`No matches for "${e.pattern}". Try a broader pattern, drop overly short tokens, or search from the repo root with \`rg "${e.pattern}" .\`.`:null}function Oi(e){let r=e.match(/search\s+"(.+)"\s+in\s+([^()]+?)(?:\s*\(agent\)|\s*failed|$)/iu);return r?`search "${r[1]}" in ${r[2]?.trim()}`:null}function it(e){let r=e.meta?.trim()||(e.command?Oi(e.command):null)||null;if(r){let t=wi(r),n=Pi(t);if(n)return n;let o=Ai(r);if(o?.changed)return`Repo search used an invalid scope. Retry with: \`${o.command}\`.`}if(e.command&&/\b(rg|ripgrep)\b/i.test(e.command)){let t=st(e.command);if(t.changed)return`Ripgrep scope may be invalid. Retry with: \`${t.command}\`.`;if(e.exitCode===1)return"Ripgrep returned no matches (exit 1). Try a broader pattern or search from the repo root."}return null}var Ri,yi,sn,mn=f(()=>{"use strict";Ri=new Set(["rg","ripgrep","grep"]),yi=new Set(["bash","sh","dash","zsh"]),sn=new Set(["-e","--regexp","-f","--file","-m","--max-count","-A","--after-context","-B","--before-context","-C","--context","-g","--glob","--iglob"])});function Ne(e,r=200){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function Ni(e){let r=e.trim();if(!r)return null;if(r.startsWith("{"))try{return JSON.parse(r)}catch{}let t=r.indexOf("{"),n=r.lastIndexOf("}");if(t>=0&&n>t)try{return JSON.parse(r.slice(t,n+1))}catch{return null}return null}function We(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Wi(e){let r=e.metadata;if(!We(r))return null;let t=r.vulnerabilities;if(!We(t))return null;let n=s=>typeof t[s]=="number"?t[s]:0,o={info:n("info"),low:n("low"),moderate:n("moderate"),high:n("high"),critical:n("critical"),total:n("total")};return typeof t.total!="number"&&!o.critical&&!o.high&&!o.moderate&&!o.low&&!o.info?null:o}function Mi(e){let r=[];e.critical&&r.push(`${e.critical} critical`),e.high&&r.push(`${e.high} high`),e.moderate&&r.push(`${e.moderate} moderate`),e.low&&r.push(`${e.low} low`),e.info&&r.push(`${e.info} info`);let t=r.length?r.join(", "):"see report";return`npm audit: ${e.total} vulnerabilit${e.total===1?"y":"ies"} (${t}) \u2014 remediation required`}function Ti(e,r){let t=e.error;if(We(t)){let s=typeof t.summary=="string"?t.summary.trim():"",i=typeof t.code=="string"?t.code.trim():"";if(s)return i?`${i}: ${s}`:s;if(i)return i}let n=typeof e.message=="string"?e.message.trim():"";if(n)return n;let o=r.trim();return o?Ne(o.split(`
4
+ `):""}function Q(e){if(!e)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Lt(e){let r=null,t=-1/0;for(let n of e){if(!n)continue;let o=Date.parse(n);Number.isFinite(o)&&o>t&&(t=o,r=n)}return r}function Gr(e){return Math.max(0,Math.round((Date.now()-e)/1e3))}var b=f(()=>{"use strict"});var Ws,sl,Ms,il,jt=f(()=>{"use strict";Ws=["ANTHROPIC_API_KEY","ANALYST_API_KEY","RECRUITER_API_KEY","AUTH_SECRET","NEXTAUTH_SECRET","DATABASE_URL","PRODUCTION_DATABASE_URL","KYNVER_PRODUCTION_DATABASE_URL","REDIS_URL","GOOGLE_CLIENT_SECRET","GITHUB_CLIENT_SECRET","KYNVER_API_KEY","KYNVER_SERVICE_SECRET","KYNVER_RUNTIME_SECRET","KYNVER_CRON_SECRET","OPENCLAW_CRON_SECRET","QSTASH_TOKEN","QSTASH_CURRENT_SIGNING_KEY","QSTASH_NEXT_SIGNING_KEY","TOOL_SECRETS_KEK","TOOL_EXECUTOR_DISPATCH_SECRET","CLOUDFLARE_API_TOKEN","STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_IDENTITY_WEBHOOK_SECRET","VOYAGE_API_KEY","PERPLEXITY_API_KEY","FRED_API_KEY","FMP_API_KEY","CURSOR_API_KEY","MEMORY_CONTENT_KEK","LLM_BYOK_KEK","KYNVER_COMMAND_AUTH_KEY","KYNVER_INSTRUCTION_BUNDLE_KEY","KYNVER_MEMORY_LEDGER_KEY","KYNVER_JWKS_PRIVATE_KEY_JWK"],sl=new Set(Ws),Ms=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY"],il=new Set(Ms)});import{spawnSync as Gt}from"node:child_process";function ye(e,r,t={}){let n=Gt("git",r,$r({cwd:e,encoding:"utf8"}));if(n.status!==0&&!t.allowFailure){let o=Ts(e,r,n);if(t.throwError)throw new Error(o);Ye(o)}return n.stdout||""}function Ts(e,r,t){let n=typeof t.stderr=="string"&&t.stderr.trim()||typeof t.stdout=="string"&&t.stdout.trim()||t.error?.message||`exit ${t.status??"unknown"}`;return`git ${r.join(" ")} failed in ${e}: ${n}`}function Oe(e){return ye(e,["status","--short"],{allowFailure:!0}).split(`
5
+ `).map(r=>r.trim()).filter(Boolean)}function w(e,r){try{let t=Gt("git",r,$r({cwd:e,encoding:"utf8"}));return{status:t.status,stdout:t.stdout||"",stderr:t.stderr||"",error:t.error?t.error.message:null}}catch(t){return{status:null,stdout:"",stderr:"",error:t.message}}}function $t(e,r,t){let n=w(e,["merge-base","--is-ancestor",r,t]);return n.status===0?{isAncestor:!0,error:null}:n.status===1?{isAncestor:!1,error:null}:{isAncestor:null,error:n.error||n.stderr||n.stdout||`git exited ${n.status}`}}function Xe(e,r="origin/main"){let t=typeof r=="string"?{base:r}:r,n=t.baseCommit?.trim()||t.base?.trim()||"origin/main",o=t.baseCommit?.trim()||null;if(!e)return Yr(n,"missing worktree path");let s=w(e,["rev-parse","HEAD"]);if(s.status!==0)return Yr(n,s.error||s.stderr||s.stdout||"failed to resolve HEAD");let i;if(o)i=o;else{let m=w(e,["rev-parse",n]);if(m.status!==0)return Yr(n,m.error||m.stderr||m.stdout||`failed to resolve ${n}`,s.stdout.trim());i=m.stdout.trim()}let a=s.stdout.trim();if(a===i)return{checked:!0,base:n,head:a,baseHead:i,baseIsAncestorOfHead:!0,headIsAncestorOfBase:!0,relation:"synced"};let u=$t(e,i,a),l=$t(e,a,i),c=u.error||l.error||void 0;if(u.isAncestor==null||l.isAncestor==null)return{checked:!1,base:n,head:a,baseHead:i,baseIsAncestorOfHead:u.isAncestor,headIsAncestorOfBase:l.isAncestor,relation:"unknown",...c?{error:c}:{}};let d=u.isAncestor?"ahead":l.isAncestor?"merged":"diverged";return{checked:!0,base:n,head:a,baseHead:i,baseIsAncestorOfHead:u.isAncestor,headIsAncestorOfBase:l.isAncestor,relation:d,...c?{error:c}:{}}}function Yr(e,r,t=null){return{checked:!1,base:e,head:t,baseHead:null,baseIsAncestorOfHead:null,headIsAncestorOfBase:null,relation:"unknown",error:r}}var F=f(()=>{"use strict";oe();b();jt()});var qe=f(()=>{"use strict";F();oe()});function se(e){let r=(e??"").trim().toLowerCase();return r==="ghost"||r==="forge"||r==="box"?r:r.includes("forge")?"forge":r.includes("ghost")||r.includes("openclaw")?"ghost":"box"}function Ze(e,r){return e[r]?.trim()||null}function Yt(e){let r=e?.split(":")[0]?.trim();return r?se(r):null}function be(e=process.env,r={}){let t=[],n=Yt(r.boxId),o=Yt(Ze(e,"KYNVER_BOX_ID")),s=r.boxKind?.trim();if(s)return n&&n!==se(s)&&t.push(`config.boxId=${r.boxId} conflicts with boxKind=${s}; using explicit boxKind=${s}`),{boxKind:se(s),source:"config",slugInferenceBlocked:!1,warnings:t};let i=Ze(e,"KYNVER_BOX_KIND");if(i)return o&&o!==se(i)&&t.push(`KYNVER_BOX_ID=${Ze(e,"KYNVER_BOX_ID")} conflicts with KYNVER_BOX_KIND=${i}; using explicit KYNVER_BOX_KIND=${i}`),{boxKind:se(i),source:"env",slugInferenceBlocked:!1,warnings:t};if(n)return{boxKind:n,source:"config",slugInferenceBlocked:!1,warnings:t};if(o)return{boxKind:o,source:"env",slugInferenceBlocked:!1,warnings:t};let a=Ze(e,"KYNVER_AGENT_OS_SLUG");return a&&t.push(`KYNVER_AGENT_OS_SLUG=${a} is a workspace slug, not box identity \u2014 operators set boxKind via \`kynver setup --box-kind forge|ghost\` or KYNVER_BOX_KIND; customers default to box`),{boxKind:"box",source:"default",slugInferenceBlocked:!!a,warnings:t}}var ie=f(()=>{"use strict"});function Vr(e,r){return e==="forge"?4:Math.max(1,r)}function Qe(e,r){return e==="forge"?Math.min(Math.max(1,r),4):Math.max(1,r)}var er=f(()=>{"use strict"});var Vt=f(()=>{"use strict"});import{existsSync as Us,readFileSync as Bs,statfsSync as Ks}from"node:fs";function zr(){if(process.platform!=="linux")return!1;for(let e of["/proc/sys/kernel/osrelease","/proc/version"])try{if(!Us(e))continue;let r=Bs(e,"utf8");if(/microsoft|wsl/i.test(r))return!0}catch{}return!1}function zt(e={}){if(!(e.forceWsl===void 0?zr():e.forceWsl))return null;let t=e.wslHostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||Se,n=e.wslHostFreeWarnBytes??Fs,o=e.wslHostFreeCriticalBytes??Hs,s=e.statfs??Ks,i;try{i=s(t)}catch(R){return{ok:!1,path:t,freeBytes:0,totalBytes:0,usedPercent:100,warnBelowBytes:n,criticalBelowBytes:o,reason:`Windows host disk probe failed at ${t}: ${R.message}`,probeError:R.message}}let a=Number(i.bavail)*Number(i.bsize),u=Number(i.blocks)*Number(i.bsize),l=u>0?(u-a)/u*100:100,c=a<n,d=a<o,m=!c&&!d,g=(a/(1024*1024*1024)).toFixed(1),p=null;return m||(p=`Windows host disk ${t} at ${d?"critical":"warning"}: ${g} GiB free (<${(d?o:n)/1024/1024/1024} GiB); WSL VHDX cannot grow safely. ${Ls()}`),{ok:m,path:t,freeBytes:a,totalBytes:u,usedPercent:l,warnBelowBytes:n,criticalBelowBytes:o,reason:p,probeError:null}}function Ls(){return"Recovery: 1) free Windows C: (empty Recycle Bin / Storage Sense / clear %TEMP% and %LOCALAPPDATA%\\Temp\\wsl-crashes); 2) shut down WSL (`wsl --shutdown`) then compact the VHDX (`Optimize-VHD` or `diskpart compact vdisk`); 3) clear local node_modules / .next / harness worktrees before restarting workers; 4) disable recurring dumps via `%USERPROFILE%/.wslconfig` (`maxCrashDumpCount=-1`) or `kynver wsl-crashes --execute`. Full runbook: docs/runbooks/wsl-disk-pressure.md."}var Fs,Hs,Se,Jr=f(()=>{"use strict";Fs=25*1024*1024*1024,Hs=12*1024*1024*1024,Se="/mnt/c"});import{execFileSync as Jt}from"node:child_process";import{existsSync as tr,readFileSync as Xt,readdirSync as js,statSync as $s}from"node:fs";import Xr from"node:path";function rr(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function qt(){let e=process.env.KYNVER_WSL_WIN_USER?.trim();if(e)return e;try{let n=Jt("cmd.exe",["/c","echo","%USERNAME%"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(n&&n!=="%USERNAME%"&&!n.includes("%"))return n}catch{}let r=process.env.USER?.trim()||process.env.LOGNAME?.trim(),t=process.env.KYNVER_WSL_HOST_MOUNT?.trim()||Se;return r&&tr(Xr.join(t,"Users",r))?r:null}function Js(e={}){let r=e.crashDumpDir?.trim()||process.env.KYNVER_WSL_CRASH_DUMP_DIR?.trim();if(r)return r;let t=e.hostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||Se,n=e.windowsUser??qt();return n?`${t.replace(/\\/g,"/").replace(/\/$/,"")}/Users/${n}/AppData/Local/Temp/wsl-crashes`:null}function Xs(e){let r=/^wsl-crash-\d+-(\d+)-(.+)-(\d+)\.dmp$/i.exec(e);if(!r)return{executableHint:null,signal:null,pid:null};let t=Number(r[1]),n=r[2]??"",o=Number(r[3]),s=n.split("_").filter(Boolean);return{executableHint:s.length>0?s[s.length-1]:null,signal:Number.isFinite(o)?o:null,pid:Number.isFinite(t)?t:null}}function qs(){try{if(tr("/proc/sys/kernel/core_pattern"))return Xt("/proc/sys/kernel/core_pattern","utf8").trim()}catch{}try{return Jt("sysctl",["-n","kernel.core_pattern"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function Zs(e){return!!(e&&/wsl-capture-crash/i.test(e))}function Qs(e,r=Se){let t=Xr.join(r,"Users",e,".wslconfig");if(!tr(t))return{maxCrashDumpCount:null,crashDumpFolder:null};let n;try{n=Xt(t,"utf8")}catch{return null}let o=null,s=null;for(let i of n.split(/\r?\n/)){let a=i.replace(/#.*$/,"").trim();if(!a||a.startsWith("["))continue;let u=a.indexOf("=");if(u<0)continue;let l=a.slice(0,u).trim().toLowerCase(),c=a.slice(u+1).trim();if(l==="maxcrashdumpcount"){let d=Number(c);o=Number.isFinite(d)?d:null}else l==="crashdumpfolder"&&(s=c.replace(/^["']|["']$/g,"")||null)}return{maxCrashDumpCount:o,crashDumpFolder:s}}function ei(e){if(!tr(e))return[];let r=js(e,{withFileTypes:!0}),t=[];for(let n of r){if(!n.isFile()||!n.name.toLowerCase().endsWith(".dmp"))continue;let o=Xr.join(e,n.name);try{let s=$s(o),i=Xs(n.name);t.push({name:n.name,path:o,bytes:s.size,mtimeMs:s.mtimeMs,executableHint:i.executableHint,signal:i.signal,pid:i.pid})}catch{}}return t.sort((n,o)=>o.mtimeMs-n.mtimeMs),t}function ve(e={}){if(!(e.forceWsl===void 0?zr():e.forceWsl))return null;let t=e.hostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||Se,n=e.windowsUser??qt(),o=e.warnBelowBytes??rr("KYNVER_WSL_CRASH_DUMP_WARN_BYTES",Gs),s=e.criticalBelowBytes??rr("KYNVER_WSL_CRASH_DUMP_CRITICAL_BYTES",Ys),i=e.warnCount??rr("KYNVER_WSL_CRASH_DUMP_WARN_COUNT",Vs),a=e.criticalCount??rr("KYNVER_WSL_CRASH_DUMP_CRITICAL_COUNT",zs),u=(e.readCorePattern??qs)(),l=Zs(u),c=null;n&&(c=(e.readWslConfig??Qs)(n,t));let d=c?.maxCrashDumpCount??null,m=d===-1,g=Js({hostMount:t,windowsUser:n,crashDumpDir:e.crashDumpDir});if(!g)return{ok:!0,path:null,windowsUser:n,dumpCount:0,totalBytes:0,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:[],executables:[],corePattern:u,wslCaptureEnabled:l,maxCrashDumpCount:d,dumpsDisabledInWslConfig:m,reason:null,probeError:"windows_user_unresolved"};let p;try{p=(e.listDumps??ei)(g)}catch(P){return{ok:!1,path:g,windowsUser:n,dumpCount:0,totalBytes:0,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:[],executables:[],corePattern:u,wslCaptureEnabled:l,maxCrashDumpCount:d,dumpsDisabledInWslConfig:m,reason:`WSL crash dump probe failed at ${g}: ${P.message}`,probeError:P.message}}let R=p.reduce((P,h)=>P+h.bytes,0),S=p.length,y=[...new Set(p.map(P=>P.executableHint).filter(P=>!!P))],A=R>=s,j=R>=o,B=S>=a,je=S>=i,te=!(A||B||j||je),ne=null;if(!te){let P=A||B?"critical":"warning",h=(R/1024**3).toFixed(1),q=y.length>0?y.join(", "):"unknown";ne=`WSL crash dumps ${P}: ${S} file(s), ${h} GiB at ${g} (executables: ${q}). `+ri({wslCaptureEnabled:l,dumpsDisabledInWslConfig:m})}return{ok:te,path:g,windowsUser:n,dumpCount:S,totalBytes:R,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:p,executables:y,corePattern:u,wslCaptureEnabled:l,maxCrashDumpCount:d,dumpsDisabledInWslConfig:m,reason:ne,probeError:null}}function ri(e={}){let r=["Recovery:","1) run `kynver wsl-crashes --execute` or scripts/cleanup-wsl-crashes.ps1 to prune old .dmp files;"];return e.dumpsDisabledInWslConfig||r.push("2) add `[wsl2]\\nmaxCrashDumpCount=-1` to %USERPROFILE%/.wslconfig then `wsl --shutdown` to disable future dumps;"),e.wslCaptureEnabled&&r.push("3) investigate crashing executables (node OOM/SIGBUS often follows Windows C: pressure \u2014 see docs/runbooks/wsl-disk-pressure.md);"),r.push("full runbook: docs/runbooks/wsl-disk-pressure.md."),r.join(" ")}var Gs,Ys,Vs,zs,nr=f(()=>{"use strict";Jr();Gs=5*1024*1024*1024,Ys=10*1024*1024*1024,Vs=2,zs=4});import{statfsSync as ti}from"node:fs";function or(e={}){let r=e.diskPath?.trim()||"/",t=e.diskFreeWarnBytes??ni,n=e.diskFreeCriticalBytes??oi,o=e.diskMaxUsedPercent??si,s=e.diskHardMaxUsedPercent??ii,i=ti(r),a=Number(i.bavail)*Number(i.bsize),u=Number(i.blocks)*Number(i.bsize),l=u>0?(u-a)/u*100:100,c=a<t,d=a<n,m=a<t*2,g=m&&l>o,p=m&&l>s,R=!c&&!d&&!g&&!p,S=e.skipWslHostCheck?null:zt(e.wslHost),y=e.skipWslCrashDumpCheck?null:ve(e.wslCrashDumps),A=R&&(S?S.ok:!0)&&(y?y.ok:!0),j=null;return A||(j=[d?`free space below critical ${n} bytes`:null,c?`free space below warning ${t} bytes`:null,p?`used percent above hard cap ${s}%`:null,g?`used percent above cap ${o}%`:null,S&&!S.ok?S.reason:null,y&&!y.ok?y.reason:null].filter(Boolean).join("; ")),ai({ok:A,path:r,freeBytes:a,totalBytes:u,usedPercent:l,warnBelowBytes:t,criticalBelowBytes:n,maxUsedPercent:o,hardMaxUsedPercent:s,reason:j,wslHost:S,wslCrashDumps:y?{ok:y.ok,path:y.path,dumpCount:y.dumpCount,totalBytes:y.totalBytes,executables:y.executables,wslCaptureEnabled:y.wslCaptureEnabled,dumpsDisabledInWslConfig:y.dumpsDisabledInWslConfig,reason:y.reason,probeError:y.probeError}:null})}function ai(e){let r=process.env.KYNVER_DISPATCH_DISK_GATE_FORCE?.trim().toLowerCase();return r?r==="ok"||r==="open"||r==="none"?e.ok?e:{...e,ok:!0,reason:`disk gate forced open by KYNVER_DISPATCH_DISK_GATE_FORCE (suppressed: ${e.reason??"no reason"})`}:r==="block"||r==="pressured"?{...e,ok:!1,reason:`disk gate forced closed by KYNVER_DISPATCH_DISK_GATE_FORCE${e.reason?` (underlying: ${e.reason})`:""}`}:e:e}var ni,oi,si,ii,sr=f(()=>{"use strict";nr();Jr();ni=30*1024*1024*1024,oi=15*1024*1024*1024,si=80,ii=90});import{existsSync as ui,readdirSync as li,statSync as ci}from"node:fs";import qr from"node:path";function ir(){return Qt()}function Zr(){let{runsDir:e}=ir();return Zt(e)}function ar(e){return Zt(G(e))}function di(e){try{return ci(e).isDirectory()}catch{return!1}}function Zt(e){if(!ui(e))return[];let r=[];for(let t of li(e,{withFileTypes:!0})){if(t.name==="runs")continue;let n=qr.join(e,t.name);if(!di(n))continue;let o=x(qr.join(n,"run.json"),void 0);o?.id&&r.push(o)}return r}function Qr(e){let{runsDir:r}=ir();Ft(qr.join(et(r,e.id),"run.json"),e)}function Ie(e){let{harnessRoot:r}=ir();return De(r,e)}function De(e,r){return et(G(e),v(r))}var ae=f(()=>{"use strict";Y();b()});import{existsSync as pi,readdirSync as mi}from"node:fs";import fi from"node:path";function rt(e){let r=new Set;for(let n of Object.keys(e.workers||{}))r.add(v(n));let t=fi.join(Ie(e.id),"workers");if(!pi(t))return[...r];for(let n of mi(t,{withFileTypes:!0}))n.isDirectory()&&r.add(v(n.name));return[...r]}var tt=f(()=>{"use strict";ae();b()});function nt(e){let r=e.trim();if(!r.startsWith("{"))return null;try{let t=JSON.parse(r);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{return null}return null}function en(e){let r=e.trim();if(!r)return null;let t=nt(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let u=nt(s[1]??"");u&&n.push(u)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let u=nt(r.slice(i,a+1));u&&n.push(u)}return n.length>0?n[n.length-1]:null}function rn(e){let r=e.finalResult??e.final_result;if(r!=null)return typeof r=="string"?en(r)??(r.trim()||null):r;let t=typeof e.summary=="string"?e.summary.trim():"";if(!t)return null;let n=en(t);return n||t}var tn=f(()=>{"use strict"});import{existsSync as gi,readFileSync as hi}from"node:fs";function nn(e){return e==="complete"}function on(e){return nn(e.lastHeartbeatPhase)?e.terminalFinalResult!==void 0&&e.terminalFinalResult!==null?e.terminalFinalResult:e.lastHeartbeatSummary?.trim()||"completed":null}function xe(e){let r={heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,terminalFinalResult:null,heartbeatBlocker:null,timestampAnomalies:[],lastBoxResourceSnapshot:null,lastPrEvidence:[]};if(!gi(e))return r;let t=Date.now()+ki,n=new Date(t).toISOString(),o=hi(e,"utf8").split(`
6
+ `).filter(Boolean);for(let s of o){let i=Ve(s);if(!i||typeof i!="object"||Array.isArray(i))continue;let a=i;if(r.heartbeatCount++,a.ts){let u=String(a.ts),l=Date.parse(u);Number.isFinite(l)&&l>t?r.timestampAnomalies.push({kind:"future_heartbeat_timestamp",observedAt:u,clampedTo:n}):r.lastHeartbeatAt=u}a.phase!==void 0&&a.phase!==null&&(r.lastHeartbeatPhase=String(a.phase)),a.summary!==void 0&&a.summary!==null&&(r.lastHeartbeatSummary=String(a.summary)),nn(r.lastHeartbeatPhase)&&(r.terminalFinalResult=rn(a)),r.heartbeatBlocker=a.blocker?String(a.blocker):null,a.boxResourceSnapshot&&typeof a.boxResourceSnapshot=="object"&&!Array.isArray(a.boxResourceSnapshot)&&(r.lastBoxResourceSnapshot=a.boxResourceSnapshot),Array.isArray(a.prEvidence)&&(r.lastPrEvidence=a.prEvidence.filter(u=>!!u&&typeof u=="object"&&typeof u.prUrl=="string"))}return r}var ki,ur=f(()=>{"use strict";tn();b();ki=6e4});function an(e){return e?(e.split("/").pop()??e).replace(/\.exe$/i,"").toLowerCase():null}function lr(e){if(!e)return[];let r=[],t="",n,o=!1;for(let s of e){if(o){t+=s,o=!1;continue}if(s==="\\"){o=!0;continue}if(n){s===n?n=void 0:t+=s;continue}if(s==='"'||s==="'"){n=s;continue}if(/\s/.test(s)){t&&(r.push(t),t="");continue}t+=s}return t&&r.push(t),r}function un(e){let r=an(e[0]);return!!(r&&Ri.has(r))}function bi(e){let r=e.trim();return r.includes("/")?r.split("/").pop()??r:r}function Si(e){if(!e||e.includes("*"))return null;let r=bi(e);return!r||r.includes("/")?null:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(r)?r:null}function ln(e){return!e||e.includes("/")||e.includes("*")?!1:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(e)}function ot(e){if(!e)return!1;let r=e.trim();return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")}function vi(e){if(!e.startsWith("--glob="))return e;let r=e.slice(7);return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")?`--glob=${r}/**`:e}function xi(e){let r=[];for(let t=1;t<e.length;t+=1){let n=e[t];if(n){if(n==="--"){r.push(...e.slice(t+1));break}if(n.startsWith("-")){if(n.includes("="))continue;sn.has(n)&&(t+=1);continue}r.push(n)}}return r}function _i(e){let r=!1,t=e.map((o,s)=>{let i=vi(o),a=e[s-1];return a&&sn.has(a)&&o.startsWith("!")&&!o.includes("/")&&!o.endsWith("/**")&&(i=`${o}/**`),i!==o&&(r=!0),i}),n=xi(t);if(n.length===2){let[o,s]=n;if(ot(s))return{argv:[t[0]??"rg",o,"-g",`${s}/**`,"."],changed:!0};let i=Si(s);if(i)return{argv:[t[0]??"rg","-g",i,o,"."],changed:!0}}return r&&n.length===1?{argv:[...t,"."],changed:!0}:{argv:t,changed:r}}function cn(e){for(let r=1;r<e.length;r+=1){let t=e[r];if(t&&(t==="-c"||t==="-lc"||t==="-cl"||/^-[a-zA-Z]*c[a-zA-Z]*$/u.test(t)))return r+1}return-1}function cr(e){let r=e.trim();if(!r)return{command:r,wrapped:!1};let t=lr(r);if(!t.length)return{command:r,wrapped:!1};let n=an(t[0]);if(!n||!yi.has(n))return{command:r,wrapped:!1};let o=cn(t);if(o<0||o>=t.length)return{command:r,wrapped:!1};let s=t.slice(o).join(" ").trim();return s?{command:s,wrapped:!0}:{command:r,wrapped:!1}}function Ci(e,r){let t=e.trim(),n=lr(t),o=cn(n);if(o<0)return r;let s=n.slice(0,o).join(" "),i=r.includes("'")?`"${r.replace(/"/g,'\\"')}"`:`'${r}'`;return`${s} ${i}`}function Ei(e){let r=e.trim(),t=cr(r),n=lr(t.command);if(!n.length||!un(n))return{segment:r,changed:!1};let o=_i(n);if(!o.changed)return{segment:r,changed:!1};let s=o.argv.join(" ");return t.wrapped?{segment:Ci(r,s),changed:!0}:{segment:s,changed:!0}}function st(e){let r=e.trim();if(!r)return{command:r,changed:!1};let t=r.includes("&&")?" && ":r.includes("||")?" || ":"; ",n=r.split(/\s*(?:&&|\|\||;)\s*/u),o=!1,s=n.map(i=>{let a=Ei(i);return a.changed&&(o=!0),a.segment});return o?{command:s.join(t),changed:!0}:{command:r,changed:!1}}function dn(e){let r=cr(e).command,t=lr(r.trim());return t.length&&un(t)?!0:/\b(rg|ripgrep)\b/i.test(r)}function pn(e){if(!e)return{};let r=e.match(/search\s+"(.+)"\s+in\s+([^()]+?)(?:\s*\(|$)/iu);if(r)return{pattern:r[1],target:r[2]?.trim()};let t=e.match(/^search\s+"(.+)"\s+in\s+(.+)$/iu);return t?{pattern:t[1],target:t[2]?.trim()}:{}}function wi(e){let{pattern:r,target:t}=pn(e);return r?ot(t)?{kind:"rg_exclude_syntax",pattern:r,target:t}:ln(t)?{kind:"bad_scope",pattern:r,target:t}:{kind:"not_repo_search",pattern:r,target:t}:{kind:"not_repo_search"}}function Ai(e){let{pattern:r,target:t}=pn(e);if(!r)return null;if(ot(t)){let n=`${t.trim()}/**`;return{command:`rg "${r}" -g '${n}' .`,changed:!0}}return t&&ln(t)?{command:`rg -g ${t} "${r}" .`,changed:!0}:null}function Pi(e){if(e.kind==="bad_scope"&&e.pattern?.includes("agent-os-land-pr")&&e.target==="package.json")return"Search package.json with a glob from the repo root: `rg -g package.json agent-os-land-pr .` \u2014 or run `node scripts/agent-os-land-pr.mjs <pr-url>` directly.";if(e.kind==="bad_scope"&&e.pattern&&e.target)return`Use \`rg -g '${e.target}' ${e.pattern} .\` from the repo root instead of treating ${e.target} as a folder.`;if(e.kind==="rg_exclude_syntax"&&e.pattern){let r=e.target?`${e.target.trim()}/**`:"!node_modules/**";return`Repo search scope \`${e.target??"!node_modules"}\` is not a valid ripgrep path. Use \`rg "${e.pattern}" -g '${r}' .\` from the repo root (exclude globs need a \`/**\` suffix).`}return e.kind==="no_matches"&&e.pattern?`No matches for "${e.pattern}". Try a broader pattern, drop overly short tokens, or search from the repo root with \`rg "${e.pattern}" .\`.`:null}function Oi(e){let r=e.match(/search\s+"(.+)"\s+in\s+([^()]+?)(?:\s*\(agent\)|\s*failed|$)/iu);return r?`search "${r[1]}" in ${r[2]?.trim()}`:null}function it(e){let r=e.meta?.trim()||(e.command?Oi(e.command):null)||null;if(r){let t=wi(r),n=Pi(t);if(n)return n;let o=Ai(r);if(o?.changed)return`Repo search used an invalid scope. Retry with: \`${o.command}\`.`}if(e.command&&/\b(rg|ripgrep)\b/i.test(e.command)){let t=st(e.command);if(t.changed)return`Ripgrep scope may be invalid. Retry with: \`${t.command}\`.`;if(e.exitCode===1)return"Ripgrep returned no matches (exit 1). Try a broader pattern or search from the repo root."}return null}var Ri,yi,sn,mn=f(()=>{"use strict";Ri=new Set(["rg","ripgrep","grep"]),yi=new Set(["bash","sh","dash","zsh"]),sn=new Set(["-e","--regexp","-f","--file","-m","--max-count","-A","--after-context","-B","--before-context","-C","--context","-g","--glob","--iglob"])});function Ne(e,r=200){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function Ni(e){let r=e.trim();if(!r)return null;if(r.startsWith("{"))try{return JSON.parse(r)}catch{}let t=r.indexOf("{"),n=r.lastIndexOf("}");if(t>=0&&n>t)try{return JSON.parse(r.slice(t,n+1))}catch{return null}return null}function We(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Wi(e){let r=e.metadata;if(!We(r))return null;let t=r.vulnerabilities;if(!We(t))return null;let n=s=>typeof t[s]=="number"?t[s]:0,o={info:n("info"),low:n("low"),moderate:n("moderate"),high:n("high"),critical:n("critical"),total:n("total")};return typeof t.total!="number"&&!o.critical&&!o.high&&!o.moderate&&!o.low&&!o.info?null:o}function Mi(e){let r=[];e.critical&&r.push(`${e.critical} critical`),e.high&&r.push(`${e.high} high`),e.moderate&&r.push(`${e.moderate} moderate`),e.low&&r.push(`${e.low} low`),e.info&&r.push(`${e.info} info`);let t=r.length?r.join(", "):"see report";return`npm audit: ${e.total} vulnerabilit${e.total===1?"y":"ies"} (${t}) \u2014 remediation required`}function Ti(e,r){let t=e.error;if(We(t)){let s=typeof t.summary=="string"?t.summary.trim():"",i=typeof t.code=="string"?t.code.trim():"";if(s)return i?`${i}: ${s}`:s;if(i)return i}let n=typeof e.message=="string"?e.message.trim():"";if(n)return n;let o=r.trim();return o?Ne(o.split(`
7
7
  `).find(Boolean)??o,160):"npm audit failed"}function Ui(e){let r=`${e.stdout}
8
- ${e.stderr}`.trim(),t=Ni(r);if(!t||!We(t)){let o=Ne(r||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit failed (invalid or missing JSON): ${o}`,parseError:"invalid_json"}}if(We(t.error))return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit command failed: ${Ti(t,e.stderr)}`};let n=Wi(t);return n?e.exitCode===0&&n.total===0?{kind:"success",exitCode:0,summary:"npm audit: no vulnerabilities reported",audit:n}:{kind:"audit_findings",exitCode:e.exitCode,summary:Mi(n),audit:n}:{kind:"command_failure",exitCode:e.exitCode,summary:"npm audit failed: JSON response missing vulnerability metadata",parseError:"missing_metadata"}}function Bi(e){return Ii.test(e)}function Ki(e){let r=lr(e).command;return fn.test(e)||fn.test(r)||dn(e)}function Fi(e){let r=it({command:e.command,exitCode:e.exitCode});if(e.exitCode===0)return{kind:"success",exitCode:0,summary:"ripgrep finished (exit 0)"};if(e.exitCode===1){let n=(e.stderr||e.interleaved).trim();if(n&&Di.test(n)){let i=Ne(n,160);return{kind:"command_failure",exitCode:1,summary:r??`ripgrep failed (exit 1): ${i}`}}let o=st(e.command),s=o.changed&&!r?` Retry with: \`${o.command}\`.`:"";return{kind:"search_no_matches",exitCode:1,summary:r??`ripgrep: no matches (exit 1).${s} Try a broader pattern or search from the repo root.`}}let t=Ne(e.interleaved||e.stdout||e.stderr||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:r??`ripgrep failed (exit ${e.exitCode}): ${t}`}}function gn(e){let r=e.stdout??"",t=e.stderr??"",n=e.interleavedOutput??"";if(Bi(e.command)){let i=r.trim()||n.trim()||t.trim();return Ui({exitCode:e.exitCode,stdout:i,stderr:t})}if(Ki(e.command))return Fi({command:e.command,exitCode:e.exitCode,stdout:r,stderr:t,interleaved:n});let o=it({command:e.command,exitCode:e.exitCode});if(o&&e.exitCode!==0)return{kind:"command_failure",exitCode:e.exitCode,summary:o};if(e.exitCode===0)return{kind:"success",exitCode:0,summary:"command succeeded (exit 0)"};let s=Ne(n||r||t||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:`command failed (exit ${e.exitCode}): ${s}`}}var Ii,fn,Di,hn=f(()=>{"use strict";mn();Ii=/\bnpm\s+audit\b/i,fn=/\b(rg|ripgrep)\b/i,Di=/\b(error|invalid|unknown|panic|not found)\b/i});import{existsSync as Hi,readFileSync as Li}from"node:fs";function ji(e){let r=e.timestamp_ms;return e.timestamp||e.ts||(r?new Date(r).toISOString():void 0)}function $i(e){if(!e)return null;for(let r of Object.keys(e))if(r.endsWith("ToolCall")){let t=r.slice(0,-8);return t.length?t:r}return null}function Gi(e,r){e.finalResult=r.result||r.subtype||r.terminal_reason||"completed",r.is_error&&(e.error=String(r.result||r.api_error_status||"stream result error"))}function _e(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function Yi(e){let r=e.usage;return r&&typeof r=="object"&&!Array.isArray(r)?r:null}function Vi(e){if(typeof e.model=="string"&&e.model.trim())return e.model.trim();let r=e.modelUsage;if(r&&typeof r=="object"&&!Array.isArray(r)){let t=Object.keys(r)[0];if(t?.trim())return t.trim()}}function zi(e,r){let t=Yi(r);if(!t)return;let n=_e(t.input_tokens)??_e(t.inputTokens)??_e(t.prompt_tokens),o=_e(t.output_tokens)??_e(t.outputTokens)??_e(t.completion_tokens);if(n===void 0&&o===void 0)return;let s=Vi(r)??e.usage?.model;e.usage={...n!==void 0?{inputTokens:n}:{},...o!==void 0?{outputTokens:o}:{},...s?{model:s}:{}}}function Ji(e){if(e.type!=="tool_call"||e.subtype!=="completed")return null;let t=(e.tool_call&&typeof e.tool_call=="object"&&!Array.isArray(e.tool_call)?e.tool_call:null)?.shellToolCall;if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,o=n.args,s=o&&typeof o=="object"&&!Array.isArray(o)&&typeof o.command=="string"?String(o.command):"",i=n.result;if(!i||typeof i!="object"||Array.isArray(i))return null;let a=i.success??i.failure;if(!a||typeof a!="object"||Array.isArray(a))return null;let u=a,l=typeof u.exitCode=="number"?u.exitCode:0;return{command:s,exitCode:l,stdout:typeof u.stdout=="string"?u.stdout:"",stderr:typeof u.stderr=="string"?u.stderr:"",interleaved:typeof u.interleavedOutput=="string"?u.interleavedOutput:""}}function Xi(e,r){r.kind==="success"||r.kind==="search_no_matches"||(e.lastShellOutcome=r)}function kn(e){let r={firstEventAt:null,lastEventAt:null,currentTool:null,finalResult:null,error:null,lastShellOutcome:null,usage:null};if(!Hi(e))return r;let t=Li(e,"utf8").split(`
9
- `).filter(Boolean);for(let n of t){let o=Ye(n);if(!o)continue;let s=ji(o);if(s&&(r.firstEventAt||=s,r.lastEventAt=s),o.type==="stream_event"&&o.event&&typeof o.event=="object"&&o.event.type==="content_block_start"){let a=o.event.content_block;a?.type==="tool_use"&&(r.currentTool=String(a.name||"tool"))}if(o.type==="assistant"&&o.message&&typeof o.message=="object"){let a=o.message.content;if(Array.isArray(a)){let u=a.find(l=>l?.type==="tool_use");u&&(r.currentTool=String(u.name||r.currentTool))}}if(o.type==="tool_call"&&o.subtype==="started"){let a=o.tool_call&&typeof o.tool_call=="object"&&!Array.isArray(o.tool_call)?o.tool_call:void 0,u=$i(a);u&&(r.currentTool=u)}let i=Ji(o);i&&Xi(r,gn({command:i.command,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr,interleavedOutput:i.interleaved})),o.type==="result"&&Gi(r,o),zi(r,o)}return r}var Rn=f(()=>{"use strict";hn();b()});function Zi(e,r=240){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function yn(e){let r=(e??"").trim();if(!r)return null;for(let t of qi)if(t.test.test(r))return{blocked:!0,reason:`${t.label}: ${Zi(r)}`};return null}var qi,bn=f(()=>{"use strict";qi=[{test:/\b(?:invalid|unknown|unsupported|unrecognized)\b[^.\n]*\bmodel\b/i,label:"provider rejected the requested model"},{test:/\bmodel\b[^.\n]*\b(?:not\s+(?:found|supported|available|recognized|valid)|is\s+not\s+valid|does\s+not\s+exist)/i,label:"provider rejected the requested model"},{test:/\b(?:did you mean|available models|choose (?:a|one of)|supported models)\b/i,label:"provider rejected the requested model"},{test:/model preflight failed/i,label:"model/provider preflight failed"},{test:/\b(?:command not found|ENOENT|is the .*CLI on PATH|executable not found|no such file or directory)\b/i,label:"provider CLI is missing or not on PATH"},{test:/\bfailed to spawn\b/i,label:"provider failed to spawn the worker process"},{test:/\b(?:not logged in|unauthorized|authentication (?:failed|required)|invalid api key|missing api key|401)\b/i,label:"provider authentication failed"},{test:/\b(?:out of usage|increase limits?|switch to auto|ask your admin to increase your limit|usage limits?|quota exceeded|insufficient_quota|credits? exhausted|billing|payment required)\b/i,label:"provider quota exhausted"}]});function Sn(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function Qi(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="boolean"?e:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function ea(e){return!e?.checked||e.headIsAncestorOfBase!==!1?null:Sn(e.head)}function ra(e,r,t){let n=["exited_with_changes_salvage"];if((e==="uncommitted"||e==="both")&&n.push(`${r} uncommitted change${r===1?"":"s"} with no final result`),(e==="committed_ahead"||e==="both")&&t){let o=t.length>12?t.slice(0,12):t;n.push(`commit ${o} ahead of base with no final result`)}return n.push("review worktree \u2014 commit, open a PR, or run a salvage worker before discarding"),n.join(": ")}function vn(e){if(e.alive||Qi(e.finalResult))return null;let r=(e.changedFiles??[]).filter(i=>i.trim()).length,t=Sn(e.headCommit)??ea(e.gitAncestry),n=r>0,o=!!t;if(!n&&!o)return{kind:"none",salvageable:!1,uncommittedCount:0,headCommit:null,attentionReason:"process exited without a final result"};let s=n&&o?"both":n?"uncommitted":"committed_ahead";return{kind:s,salvageable:!0,uncommittedCount:r,headCommit:t,attentionReason:ra(s,r,t)}}var xn=f(()=>{"use strict"});function Me(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function ta(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="boolean"?e:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function na(e){if(Me(e.headCommit)||Me(e.prUrl)||Me(e.artifactBundlePath)||Me(e.patchPath))return!0;let r=e.gitAncestry;return!!(r?.checked&&r.headIsAncestorOfBase===!1&&Me(r.head))}function Ce(e){return ta(e.finalResult)?e.changedFiles.length===0?{blocked:!1}:na(e)?{blocked:!0,detail:`Worktree has ${e.changedFiles.length} uncommitted change(s); commit or discard before landing`}:{blocked:!0,reason:"dirty_worktree_no_pr",detail:`Worktree has ${e.changedFiles.length} uncommitted change(s) with no commit or PR; commit, open a PR, or discard before landing`}:{blocked:!1}}function _n(e){if(e.blocked)return e.detail??e.reason??"dirty_worktree_no_pr"}var cr=f(()=>{"use strict"});function at(e){let r=e.trim();if(!r.startsWith("{"))return null;try{let t=JSON.parse(r);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{return null}return null}function Cn(e){let r=e.targetPrReconciliation??e.target_pr_reconciliation??e.targetPrs??e.target_prs;return Array.isArray(r)?r.length:0}function dr(e){let r=e.trim();if(!r)return null;let t=at(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let c=at(s[1]??"");c&&n.push(c)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let c=at(r.slice(i,a+1));c&&n.push(c)}if(n.length===0)return null;let u=n[n.length-1],l=Cn(u);for(let c of n){let d=Cn(c);d>l&&(u=c,l=d)}return u}var ut=f(()=>{"use strict"});function En(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`https://github.com/${r[1]}/pull/${r[2]}`:e.trim()||null}function wn(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function oa(e){return new Set(e.map(r=>wn(En(r)??r)).filter(Boolean))}function An(e,r,t){let n=En(e)??e;if(!n)return"unrelated";let o=wn(n);return oa(r).has(o)?"contract":t?(t.outcome==="skipped"||t.outcome==="blocked")&&t.reason?.trim()?"support":(t.outcome==="merged","unrelated"):"unrelated"}var Pn=f(()=>{"use strict"});function Ee(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function sa(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"?Object.keys(e).length>0:!0}function ue(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`https://github.com/${r[1]}/pull/${r[2]}`:Ee(e)}function pr(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function On(e){let r=null;if(typeof e=="string"){let o=dr(e);o&&(r=o)}else e&&typeof e=="object"&&!Array.isArray(e)&&(r=e);if(!r)return[];let t=r.targetPrReconciliation??r.target_pr_reconciliation;if(!Array.isArray(t))return[];let n=[];for(let o of t){if(!o||typeof o!="object"||Array.isArray(o))continue;let s=o,i=ue(String(s.prUrl??s.pr_url??"")),a=Ee(s.outcome);!i||a!=="merged"&&a!=="skipped"&&a!=="blocked"||n.push({prUrl:i,outcome:a,mergeCommit:Ee(s.mergeCommit??s.merge_commit),reason:Ee(s.reason)})}return n}function In(e,r){let t=[],n=ue(Ee(e.prUrl)??"");if(n&&t.push(n),r&&typeof r=="object"&&!Array.isArray(r)){let o=r,s=ue(String(o.prUrl??o.pr_url??""));s&&t.push(s)}return[...new Set(t)]}function Dn(e){let{contract:r,snapshot:t}=e,n=e.finalResult??t.finalResult;if(!r.landingOnly&&r.targetPrUrls.length===0&&!r.repairEnforceOriginalPr)return{blocked:!1};if(!sa(n))return(r.requiresTargetPrReconciliation??(r.landingOnly||!!r.repairEnforceOriginalPr||r.targetPrUrls.length>0))&&r.targetPrUrls.length>0?{blocked:!0,reason:"missing_target_pr_reconciliation",detail:`Final result required to reconcile target PR(s): ${r.targetPrUrls.join(", ")}`}:{blocked:!1};if(!(r.requiresTargetPrReconciliation??(r.landingOnly||!!r.repairEnforceOriginalPr||r.targetPrUrls.length>0))&&!r.repairEnforceOriginalPr)return{blocked:!1};let s=r.repairEnforceOriginalPr?ue(Ee(r.targetPrUrl)??"")??(r.targetPrUrls.length===1?ue(r.targetPrUrls[0]):null):null;if(s){let d=In(t,n);if(!(n&&typeof n=="object"&&!Array.isArray(n)&&n.supersedesOriginalTargetPr===!0)){for(let R of d)if(R!==s)return{blocked:!0,reason:"duplicate_repair_pr",detail:`Repair worker opened or attached PR ${R} instead of canonical target ${s}`}}let p=On(n).find(R=>R.prUrl===s);if(!p||p.outcome!=="merged"&&!(p.reason?.trim()&&(p.outcome==="skipped"||p.outcome==="blocked")))return{blocked:!0,reason:"missing_repair_target_reconciliation",detail:`Repair worker must reconcile target PR ${s}`}}let i=On(n),a=new Map(i.map(d=>[pr(d.prUrl),d])),u=new Set(r.targetPrUrls.map(d=>pr(ue(d)??d)).filter(Boolean)),l=In(t,n);if(r.landingOnly)for(let d of l){let m=a.get(pr(d)),g=An(d,r.targetPrUrls,m);if(!(g==="contract"||g==="support"))return u.size>0?{blocked:!0,reason:"unrelated_implementation_pr",detail:`Landing-only worker attached unrelated PR ${d}`}:{blocked:!0,reason:"unrelated_implementation_pr",detail:"Landing-only worker must not open new implementation PRs"}}if(r.targetPrUrls.length===0)return{blocked:!1};let c=[];for(let d of r.targetPrUrls){let m=pr(ue(d)??d),g=a.get(m);if(!g){c.push(m);continue}g.outcome!=="merged"&&!g.reason?.trim()&&c.push(m)}return c.length>0?{blocked:!0,reason:c.every(d=>a.has(d))?"incomplete_target_pr_landing":"missing_target_pr_reconciliation",detail:`Target PR reconciliation incomplete: ${c.join(", ")}`}:{blocked:!1}}function Nn(e){if(e.blocked)return e.detail??e.reason}var Wn=f(()=>{"use strict";ut();Pn()});function ua(e){let r=Date.now();if(e.completionBlocker&&!Mn(e.completionBlocker))return{state:"blocked",reason:e.completionBlocker};if(e.finalResult){if(e.localOnly&&ca(e.finalResult))return{state:"done",reason:"local-only worker superseded by merged PR"};let o={finalResult:e.finalResult,changedFiles:e.changedFiles??[],gitAncestry:e.gitAncestry??null,prUrl:e.prUrl??null},s=Ce(o);if(s.blocked){let i=_n(s);return{state:"needs_attention",reason:s.reason?`landing blocked (${s.reason}): ${i}`:`landing blocked: ${i}`}}if(e.landingContract){let i=Dn({contract:e.landingContract,snapshot:o,finalResult:e.finalResult}),a=Nn(i);if(a)return{state:"needs_attention",reason:i.reason?`landing contract (${i.reason}): ${a}`:`landing contract: ${a}`}}return{state:"done",reason:"final result recorded"}}if(!e.alive){if(la(e))return{state:"done",reason:"empty abandoned worker record"};let o=yn(e.error);if(o)return{state:"blocked",reason:o.reason};let s=vn({alive:!1,finalResult:null,changedFiles:e.changedFiles,gitAncestry:e.gitAncestry});if(s?.salvageable){let a=e.error?.trim();return{state:"needs_attention",reason:a?`${s.attentionReason} (${a})`:s.attentionReason}}let i=e.error?.trim();return{state:"needs_attention",reason:i?`process exited without a final result: ${i}`:s?.attentionReason??"process exited without a final result"}}if(e.heartbeatBlocker)return{state:"blocked",reason:`worker heartbeat reported blocker: ${e.heartbeatBlocker}`};let t=e.startedAt?Date.parse(e.startedAt):NaN;if(!e.firstEventAt&&e.stdoutBytes===0&&e.heartbeatBytes===0&&Number.isFinite(t)&&r-t>ia)return{state:"needs_attention",reason:`no first stream event ${Gr(t)}s after start`};let n=e.lastActivityAt?Date.parse(e.lastActivityAt):NaN;return Number.isFinite(n)&&r-n>aa?{state:"stale",reason:`no log/event/heartbeat activity for ${Gr(n)}s`}:{state:"ok",reason:"recent activity"}}function Mn(e){let r=e?.trim();return r?/completion acknowledged but board not advanced/i.test(r)&&/task already terminal/i.test(r):!1}function la(e){return e.finalResult||e.taskId||e.agentOsId||e.stdoutBytes>0||(e.stderrBytes??0)>0||e.heartbeatBytes>0||e.error?.trim()||(e.changedFiles??[]).some(r=>r.trim())?!1:/empty worker dir|marked abandoned/i.test(e.reconcileReason??"")}function ca(e){let r=null;if(typeof e=="string"?r=dr(e):e&&typeof e=="object"&&!Array.isArray(e)&&(r=e),!r)return!1;let t=r.targetPrReconciliation??r.target_pr_reconciliation;return Array.isArray(t)?t.some(n=>!n||typeof n!="object"||Array.isArray(n)?!1:String(n.outcome??"").trim()==="merged"):!1}function da(e,r,t){let n=e.completionSnapshot?.finalResult;return e.completionAckSource==="local-pr-merged-reconcile"&&n!==void 0&&n!==null?n:r||(n??on(t))}function Te(e,r={}){let t=kn(e.stdoutPath),n=xe(e.heartbeatPath),o=typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim().length>0,s=da(e,t.finalResult,n),i=o?!1:Q(e.pid),a=Ve(e.stdoutPath),u=Ve(e.stderrPath),l=Ve(e.heartbeatPath),c=Oe(e.worktreePath),d=Je(e.worktreePath,{base:r.base,baseCommit:r.baseCommit}),m=Lt([t.lastEventAt,n.lastHeartbeatAt,ze(e.stdoutPath),ze(e.stderrPath),ze(e.heartbeatPath)]),g=t.error||!i&&!s&&Ht(e.stderrPath,10).trim()||void 0,p=typeof e.completionBlocker=="string"&&e.completionBlocker.trim()?e.completionBlocker.trim():null,R=Mn(p)?null:p,S=e.repairTargetPrUrl?{landingOnly:!1,targetPrUrls:[e.repairTargetPrUrl],targetPrUrl:e.repairTargetPrUrl,repairEnforceOriginalPr:!0}:null,y=ua({alive:i,finalResult:s,firstEventAt:t.firstEventAt,stdoutBytes:a,stderrBytes:u,heartbeatBytes:l,lastActivityAt:m,heartbeatBlocker:n.heartbeatBlocker,startedAt:e.startedAt,error:g,changedFiles:c,gitAncestry:d,completionBlocker:R,landingContract:S,prUrl:e.repairTargetPrUrl??e.taskPrUrl??null,localOnly:e.localOnly===!0,taskId:e.taskId??null,agentOsId:e.agentOsId??null,reconcileReason:e.reconcileReason??null}),A=R||y.state==="blocked"?"blocked":o||y.state==="done"?"done":s?"exited":i?"running":"exited";return{runId:e.runId,worker:e.name,pid:e.pid,alive:i,status:A,attention:y,branch:e.branch,worktreePath:e.worktreePath,ownedPaths:e.ownedPaths,stdoutBytes:a,stderrBytes:u,heartbeatBytes:l,firstEventAt:t.firstEventAt,lastEventAt:t.lastEventAt,lastActivityAt:m,currentTool:o?null:t.currentTool,heartbeatCount:n.heartbeatCount,lastHeartbeatAt:n.lastHeartbeatAt,lastHeartbeatPhase:n.lastHeartbeatPhase,lastHeartbeatSummary:n.lastHeartbeatSummary,heartbeatBlocker:n.heartbeatBlocker,timestampAnomalies:n.timestampAnomalies,finalResult:s,error:g,changedFiles:c,gitAncestry:d,instructionPolicyFingerprint:e.instructionPolicyFingerprint??null,instructionPolicyEvidence:e.instructionPolicyEvidence??null,model:e.model??e.orchestrationAudit?.model??null,provider:e.provider??e.orchestrationAudit?.provider??null,usage:t.usage??null,boxKind:e.boxKind??null,boxId:e.boxId??null,runtimeId:e.runtimeId??null,personaSlug:e.personaSlug??null,dispatched:e.dispatched??null,localOnly:e.localOnly??null}}function le(e){return!!(e.finalResult||e.alive===!1||e.status==="exited"||e.status==="done")}function Tn(e){return e.finalResult?e.attention.state==="needs_attention"||e.attention.state==="blocked":!1}var ia,aa,ce=f(()=>{"use strict";ar();Rn();bn();xn();F();cr();Wn();ut();b();ia=18e4,aa=6e5});var Un=f(()=>{"use strict";ce()});function Bn(e,r={}){let t=r.perWorkerMemBytes??lt,n=r.memReserveBytes??ct,o=r.memUtilization??dt,s=Math.max(0,Math.floor(e*o)-n),i=Math.max(1,Math.floor(s/t));return Math.min(i,mr)}var lt,ct,dt,mr,Kn=f(()=>{"use strict";Vt();pe();ie();Qe();fr();or();ae();tt();Un();b();lt=500*1024*1024,ct=4*1024*1024*1024,dt=.85,mr=64});function Ue(e,r){let t=Number(e);return!Number.isFinite(t)||t<=0?r:Math.floor(t)}function pt(e){let r=e.config??{},t=e.env??process.env,n=Ue(r.perWorkerMemBytes,lt),o=Ue(r.memReserveBytes,ct),s=Math.min(1,Math.max(.1,Number(r.memUtilization)>0?Number(r.memUtilization):dt)),i=Bn(e.totalMemBytes,{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s});if(e.configuredMaxWorkersOverride!==void 0&&e.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:Ue(e.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(r.maxConcurrentWorkers!==void 0&&r.maxConcurrentWorkers!==null){let l=Ue(r.maxConcurrentWorkers,0)||null;if(l)return{configuredMaxWorkers:Math.min(l,mr),autoCap:i,workerCapSource:"config"}}let u=(t.KYNVER_MAX_WORKERS_INTENTIONAL==="1"||t.KYNVER_MAX_WORKERS_INTENTIONAL==="true")&&t.KYNVER_MAX_WORKERS&&Ue(t.KYNVER_MAX_WORKERS,0)||null;return u?{configuredMaxWorkers:Math.min(u,mr),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var fr=f(()=>{"use strict";Kn()});import{homedir as pa}from"node:os";import ma from"node:path";var Fn,mt=f(()=>{"use strict";Fn=ma.join(pa(),".kynver",".env")});var Hn=f(()=>{"use strict"});var Ln=f(()=>{"use strict";Hn()});var jn=f(()=>{"use strict"});var ft=f(()=>{"use strict";Ln();jn()});var $n=f(()=>{"use strict"});var Gn=f(()=>{"use strict";$n()});var gr=f(()=>{"use strict";mt();oe();pe();ft();Gn()});var zn=f(()=>{"use strict";ie();ie()});var Jn=f(()=>{"use strict";mt();ft();gr()});import{existsSync as V,mkdirSync as ga,readdirSync as hr,renameSync as Xn,statSync as ha}from"node:fs";import z from"node:path";function Zn(e){try{return ha(e).isDirectory()}catch{return!1}}function ka(e){if(!V(e))return!0;for(let r of qn){let t=z.join(e,r);if(V(t)&&(!Zn(t)||hr(t).length>0))return!1}return!0}function Ra(e){let r=z.join(e,"runs");if(!V(r)||!Zn(r))return!1;for(let t of hr(r,{withFileTypes:!0})){if(!t.isDirectory()||t.name==="runs")continue;let n=z.join(r,t.name,"run.json");if(x(n,void 0)?.id)return!0}return!1}function ya(e){let r=z.join(e,"runs");if(!V(r))return!1;for(let t of hr(r,{withFileTypes:!0})){if(!t.isDirectory())continue;if(x(z.join(r,t.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function ba(e){let r=z.join(e,"ghost");return V(r)?!V(z.join(r,"runs")):ya(e)}function Qn(e){return Ra(e.sharedRoot)?ka(e.forgeRoot)?ba(e.sharedRoot)?{action:"blocked",blocker:"Forge legacy harness migration blocked: Ghost pool is co-hosted on this host (ghost namespace or ghost-attributed runs under ~/.kynver/harness). Drain in-flight Ghost runs from the shared root, or get operator sign-off for a fresh Forge cutover before enabling box-scoped isolation."}:{action:"migrate"}:{action:"none"}:{action:"none"}}function eo(e,r){ga(r,{recursive:!0});for(let t of qn){let n=z.join(e,t),o=z.join(r,t);if(V(n)){if(V(o)&&hr(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(V(o)){Xn(n,o);continue}Xn(n,o)}}}var qn,ro=f(()=>{"use strict";b();qn=["runs","worktrees"]});import{existsSync as E}from"node:fs";import{homedir as Sa}from"node:os";import C from"node:path";function gt(e=process.env){return e.HOME?.trim()||Sa()}function ht(e=process.env){return C.join(gt(e),".kynver","harness")}function kr(e){let r=C.resolve(Z(e.trim()));for(;va.has(C.basename(r));)r=C.dirname(r);return r}function xa(e,r=process.env){return C.join(ht(r),e)}function _a(e=process.env){let r=ht(e);if(E(C.join(r,"runs")))return!0;if(E(r)&&!E(C.join(r,"ghost"))&&!E(C.join(r,"forge")))return E(r);let t=C.join(gt(e),to);return E(t)}function Rr(e){let r=e.env??process.env,t=r.KYNVER_HARNESS_ROOT?.trim()||r.OPUS_HARNESS_ROOT?.trim();if(t)return{harnessRoot:kr(t),source:"env"};let n=e.configuredHarnessRoot?.trim();if(n)return{harnessRoot:kr(n),source:"config"};let o=xa(e.boxKind,r);if(E(C.join(o,"runs"))||E(o)&&!Ca(o))return{harnessRoot:o,source:"box_scoped"};let i=ht(r);if(e.boxKind==="forge"){let a=Qn({sharedRoot:i,forgeRoot:o});if(a.action==="blocked")return{harnessRoot:o,source:"box_scoped",migrationBlocker:a.blocker};if(a.action==="migrate")return e.allowForgeLegacyMigration!==!1&&eo(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(e.boxKind==="ghost"&&_a(r)){if(E(C.join(i,"runs")))return{harnessRoot:i,source:"legacy_shared"};if(E(i)&&!E(C.join(i,"ghost"))&&!E(C.join(i,"forge")))return{harnessRoot:i,source:"legacy_shared"};let u=C.join(gt(r),to);if(E(u))return{harnessRoot:u,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function Ca(e){if(!E(e))return!0;for(let r of["runs","worktrees"]){let t=C.join(e,r);if(E(t))return!1}return!0}var to,va,kt=f(()=>{"use strict";oe();ro();to=C.join(".openclaw","harness");va=new Set(["runs","worktrees"])});import no from"node:os";function yr(e){return e?.trim()?e.trim():null}function Ea(e,r){let t=r.trim().toLowerCase()||"host";return`${e}-${t}`.replace(/[^a-z0-9._-]+/g,"-")}function wa(e){return e.KYNVER_DISPATCH_STRICT_IDENTITY==="1"||e.KYNVER_DISPATCH_STRICT_IDENTITY==="true"||e.KYNVER_DAEMON_STRICT_IDENTITY==="1"||e.KYNVER_DAEMON_STRICT_IDENTITY==="true"}function br(e=de(),r=process.env,t={}){let n=be(r,e),o=[...n.warnings],s=[],i=!!(e.boxKind?.trim()||yr(r.KYNVER_BOX_KIND)),a=t.strict===!0||wa(r);if((t.requireExplicitBoxKind||a)&&!i&&s.push("boxKind is not persisted in ~/.kynver/config.json and KYNVER_BOX_KIND is unset \u2014 run `kynver setup` (customers: boxKind=box) or `kynver setup --box-kind forge|ghost` for operator pools before dispatch"),n.slugInferenceBlocked&&!i){let R="ambiguous box identity: KYNVER_AGENT_OS_SLUG is set without KYNVER_BOX_KIND or config.boxKind";a||t.requireExplicitBoxKind?s.push(R):o.push(`${R} \u2014 defaulting box kind to box (customer), not forge/ghost`)}let u=yr(e.runnerId),l=yr(r.KYNVER_RUNTIME_ID)??yr(r.OPENCLAW_RUNTIME_ID),c=u??l??Ea(n.boxKind,no.hostname()),d=u?"config":l?"env":"derived";d==="derived"&&o.push(`runnerId not persisted \u2014 using derived id "${c}"; run \`kynver setup --box-kind ${n.boxKind}\` to persist runner identity`);let m=pt({config:e,env:r,totalMemBytes:no.totalmem()}),g=Ze(n.boxKind,m.configuredMaxWorkers??Vr(n.boxKind,m.autoCap)),p=Rr({boxKind:n.boxKind,configuredHarnessRoot:e.harnessRoot,env:r});return p.migrationBlocker&&s.push(p.migrationBlocker),s.length>0?{ok:!1,identity:null,errors:s,warnings:o}:{ok:!0,identity:{boxKind:n.boxKind,boxKindSource:n.source,runnerId:c,runnerIdSource:d,maxConcurrentWorkers:g,workerCapSource:m.workerCapSource,harnessRoot:p.harnessRoot,harnessRootSource:p.source},errors:s,warnings:o}}var Sr=f(()=>{"use strict";pe();ie();Qe();fr();kt()});var so=f(()=>{"use strict";Xe();ie();zn();pe();gr();Jn();b();Sr()});import{existsSync as Ia,mkdirSync as rp,readFileSync as Da,writeFileSync as tp}from"node:fs";import{homedir as Na,totalmem as op}from"node:os";import Rt from"node:path";function Wa(e){return{...e,...e.harnessRoot?.trim()?{harnessRoot:Z(e.harnessRoot.trim())}:{},...e.defaultRepo?.trim()?{defaultRepo:Z(e.defaultRepo.trim())}:{}}}function de(){if(!Ia(io))return{};try{return Wa(JSON.parse(Da(io,"utf8")))}catch{return{}}}var ao,io,hp,kp,Rp,pe=f(()=>{"use strict";Xe();oe();b();ie();Qe();fr();or();gr();so();Sr();ao=Rt.join(Na(),".kynver"),io=Rt.join(ao,"config.json"),hp=Rt.join(ao,"credentials");kp=500*1024*1024,Rp=4*1024*1024*1024});import yt from"node:path";function I(e){return kr(e)}function ee(){let e=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(e)return I(e);let r=de(),t=r.harnessRoot?.trim();if(t)return I(t);let n=br(r,process.env);return n.identity?n.identity.harnessRoot:Rr({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function G(e){return yt.join(I(e),"runs")}function we(e){return yt.join(I(e),"worktrees")}function Qt(){let e=ee();return{harnessRoot:e,runsDir:G(e),worktreesDir:we(e)}}function et(e,r){return yt.join(e,v(r))}var Y=f(()=>{"use strict";pe();kt();Sr();b()});Y();import M from"node:path";cr();import Cr from"node:path";F();ce();var bt=[".next",".turbo","dist","build",".cache","node_modules/.cache"];function uo(e){let r=e.replace(/\\/g,"/").replace(/\/+$/,"");if(r==="node_modules"||r.startsWith("node_modules/"))return!0;for(let t of bt)if(r===t||r.startsWith(`${t}/`))return!0;return!1}function D(e){return e.filter(r=>{let t=r.trim(),n=t.startsWith("??")?t.slice(2).trim():t.length>3?t.slice(3).trim():t;return!uo(n)})}function me(e){if(typeof e=="string")return e.match(/https:\/\/github\.com\/[^\s]+\/pull\/\d+/i)?.[0]??null;if(e&&typeof e=="object"){let r=e;for(let t of["prUrl","pr_url","pullRequestUrl"]){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}}return null}function Be(e){let r=e.gitAncestry?.relation;return r==="merged"||r==="synced"?D(e.changedFiles).length>0:!!(me(e.finalResult)||r==="ahead"||r==="diverged"||e.changedFiles.length>0&&e.finalResult)}b();function Ke(e){return e.status||(e.status=Te(e.worker,{base:e.run.base,baseCommit:e.run.baseCommit})),e.status}function St(e,r){if(e.status)return D(e.status.changedFiles).length>0;let t=r?r.porcelain(e.worktreePath):Oe(e.worktreePath);return D(t).length>0}function Ma(e){let r=e.worker.completionSnapshot?.finalResult;return r??(e.worker.taskPrUrl?{prUrl:e.worker.taskPrUrl}:null)}function vt(e,r){if(e.status)return e.status;let t=e.worker,n=typeof t.completionReportedAt=="string"&&t.completionReportedAt.trim().length>0,o=!!(t.status&&["done","exited","blocked","failed","abandoned"].includes(t.status))||n,s=Ma(e);if(o&&!Q(t.pid)){let i=r?.gitStatusCache?r.gitStatusCache.porcelain(e.worktreePath):Oe(e.worktreePath),a=e.run.baseCommit?.trim()||e.run.base?.trim()||"origin/main",l=r?.gitRevCache?.countAheadOfMain(e.worktreePath,a)===0?{checked:!0,base:a,relation:"synced"}:Je(e.worktreePath,{base:e.run.base,baseCommit:e.run.baseCommit}),c={runId:e.runId,worker:e.workerName,pid:t.pid,alive:!1,status:t.status??(n?"done":"exited"),attention:{state:n?"done":"stale"},branch:t.branch,worktreePath:e.worktreePath,ownedPaths:t.ownedPaths,stdoutBytes:0,stderrBytes:0,heartbeatBytes:0,firstEventAt:null,lastEventAt:null,lastActivityAt:t.completionReportedAt??null,currentTool:null,heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,heartbeatBlocker:null,changedFiles:i,gitAncestry:l,finalResult:s,completionBlocker:typeof t.completionBlocker=="string"&&t.completionBlocker.trim()||null,prUrl:t.repairTargetPrUrl??t.taskPrUrl??me(s)};return e.status=c,c}return Ke(e)}ce();ae();tt();ce();b();import Ta from"node:path";var Ua=new Set(["running","dispatching","pending","queued","needs_attention"]),fe=new Set(["completed","failed","cancelled","done"]);function ge(e){let r=rt(e);if(r.length===0)return"failed";let t=!1,n=!1,o=!1,s=!1;for(let i of r){let a=x(Ta.join(Ie(e.id),"workers",v(i),"worker.json"),void 0);if(!a)continue;let u=Te(a,{base:e.base,baseCommit:e.baseCommit});if(u.alive&&!u.finalResult){t=!0;break}typeof a.completionBlocker=="string"&&a.completionBlocker&&(o=!0),Tn(u)&&(s=!0),u.finalResult&&u.attention.state==="done"&&(n=!0)}return t||o||s?null:n?"completed":"failed"}function lo(){let e=[];for(let r of Zr()){if(!Ua.has(r.status))continue;let t=ge(r);if(!t||t===r.status)continue;let n=r.status;r.status=t,Qr(r),e.push({runId:r.id,from:n,to:t})}return e}ce();ar();import{existsSync as vr,mkdirSync as rm,readdirSync as mo,renameSync as tm,statSync as Ba}from"node:fs";import he from"node:path";pe();Xe();oe();F();ar();Y();ae();Y();b();import re from"node:path";var Xp=`${re.sep}runs${re.sep}runs${re.sep}`;function co(e){return{workerJsonPath:re.join(e,"worker.json"),stdoutPath:re.join(e,"stdout.jsonl"),stderrPath:re.join(e,"stderr.log"),heartbeatPath:re.join(e,"heartbeat.jsonl"),lastStatusPath:re.join(e,"last-status.json")}}b();var Fe=900*1e3,dm=3600*1e3;function fo(e,r){let t=he.resolve(e),n=he.resolve(G(r)),o=he.relative(n,t);return o!==".."&&!o.startsWith("..")&&!he.isAbsolute(o)}function Ka(e){if(!vr(e))return[];try{return mo(e,{withFileTypes:!0}).filter(r=>r.isDirectory()&&r.name!=="runs").map(r=>r.name)}catch{return[]}}function Fa(e){let r=he.join(e,"workers");if(!vr(r))return[];try{return mo(r,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}}function po(e,r,t){if(!vr(e))return!1;try{let n=r-Ba(e).mtimeMs;return Number.isFinite(n)&&n>=0&&n<t}catch{return!1}}function Ha(e,r=Date.now(),t=Fe){if(!vr(e))return!1;let n=co(e),o=x(n.workerJsonPath,void 0);if(o?.status==="running"&&Q(o.pid))return!0;let s=xe(n.heartbeatPath);if(s.lastHeartbeatAt){let i=r-Date.parse(s.lastHeartbeatAt);if(Number.isFinite(i)&&i>=0&&i<t)return!0}return!!(po(n.stdoutPath,r,t)||po(n.heartbeatPath,r,t))}function La(e,r=Date.now(),t=Fe){for(let n of Fa(e))if(Ha(he.join(e,"workers",n),r,t))return!0;return!1}function go(e,r=Date.now()){let t=new Set,n=G(e);for(let o of Ka(n)){let s=he.join(n,o);La(s,r)&&t.add(`${e}\0${o}`)}return t}b();function xt(e,r=Date.now(),t=Fe){let n=xe(e.heartbeatPath);if(!n.lastHeartbeatAt)return!1;let o=r-Date.parse(n.lastHeartbeatAt);return Number.isFinite(o)&&o>=0&&o<t}function xr(e,r=Date.now(),t=Fe){return Q(e.pid)?!0:xt(e,r,t)}function ja(e,r){return r?r.runTerminalCache.derive(e.run):ge(e.run)}function J(e,r=Date.now()){return xr(e.worker,r)}function _t(e,r){return fe.has(e.run.status)?!1:ja(e,r)!==null}function ho(e,r,t=Date.now()){if(J(e,t))return!0;if(fe.has(e.run.status)||_t(e,r))return!1;let n=Ke(e);return le(n)?!1:!!J(e,t)}cr();ce();function ko(e,r){if(!(typeof e.worker.completionBlocker=="string"?e.worker.completionBlocker.trim():""))return!1;if(J(e))return!0;let n=r??Ke(e);return!!(!le(n)||Be(n)||D(n.changedFiles).length>0||Ce({finalResult:n.finalResult,changedFiles:n.changedFiles,gitAncestry:n.gitAncestry,prUrl:me(n.finalResult)}).blocked)}F();b();import{existsSync as yo,mkdirSync as $a,writeFileSync as Ro}from"node:fs";import _r from"node:path";function bo(e,r,t){return _r.join(e,"salvage",v(r),v(t))}function So(e){return yo(_r.join(bo(e.harnessRoot,e.runId,e.workerName),"evidence.json"))}function vo(e){let r=bo(e.harnessRoot,e.indexed.runId,e.indexed.workerName);$a(r,{recursive:!0});let t=_r.join(r,"salvage.patch"),n=!1;if(yo(e.indexed.worktreePath)){let s=w(e.indexed.worktreePath,["diff","HEAD"]),i=w(e.indexed.worktreePath,["diff","--cached"]),a=[s.stdout,i.stdout].filter(u=>u.trim()).join(`
8
+ ${e.stderr}`.trim(),t=Ni(r);if(!t||!We(t)){let o=Ne(r||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit failed (invalid or missing JSON): ${o}`,parseError:"invalid_json"}}if(We(t.error))return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit command failed: ${Ti(t,e.stderr)}`};let n=Wi(t);return n?e.exitCode===0&&n.total===0?{kind:"success",exitCode:0,summary:"npm audit: no vulnerabilities reported",audit:n}:{kind:"audit_findings",exitCode:e.exitCode,summary:Mi(n),audit:n}:{kind:"command_failure",exitCode:e.exitCode,summary:"npm audit failed: JSON response missing vulnerability metadata",parseError:"missing_metadata"}}function Bi(e){return Ii.test(e)}function Ki(e){let r=cr(e).command;return fn.test(e)||fn.test(r)||dn(e)}function Fi(e){let r=it({command:e.command,exitCode:e.exitCode});if(e.exitCode===0)return{kind:"success",exitCode:0,summary:"ripgrep finished (exit 0)"};if(e.exitCode===1){let n=(e.stderr||e.interleaved).trim();if(n&&Di.test(n)){let i=Ne(n,160);return{kind:"command_failure",exitCode:1,summary:r??`ripgrep failed (exit 1): ${i}`}}let o=st(e.command),s=o.changed&&!r?` Retry with: \`${o.command}\`.`:"";return{kind:"search_no_matches",exitCode:1,summary:r??`ripgrep: no matches (exit 1).${s} Try a broader pattern or search from the repo root.`}}let t=Ne(e.interleaved||e.stdout||e.stderr||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:r??`ripgrep failed (exit ${e.exitCode}): ${t}`}}function gn(e){let r=e.stdout??"",t=e.stderr??"",n=e.interleavedOutput??"";if(Bi(e.command)){let i=r.trim()||n.trim()||t.trim();return Ui({exitCode:e.exitCode,stdout:i,stderr:t})}if(Ki(e.command))return Fi({command:e.command,exitCode:e.exitCode,stdout:r,stderr:t,interleaved:n});let o=it({command:e.command,exitCode:e.exitCode});if(o&&e.exitCode!==0)return{kind:"command_failure",exitCode:e.exitCode,summary:o};if(e.exitCode===0)return{kind:"success",exitCode:0,summary:"command succeeded (exit 0)"};let s=Ne(n||r||t||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:`command failed (exit ${e.exitCode}): ${s}`}}var Ii,fn,Di,hn=f(()=>{"use strict";mn();Ii=/\bnpm\s+audit\b/i,fn=/\b(rg|ripgrep)\b/i,Di=/\b(error|invalid|unknown|panic|not found)\b/i});import{existsSync as Hi,readFileSync as Li}from"node:fs";function ji(e){let r=e.timestamp_ms;return e.timestamp||e.ts||(r?new Date(r).toISOString():void 0)}function $i(e){if(!e)return null;for(let r of Object.keys(e))if(r.endsWith("ToolCall")){let t=r.slice(0,-8);return t.length?t:r}return null}function Gi(e,r){e.finalResult=r.result||r.subtype||r.terminal_reason||"completed",r.is_error&&(e.error=String(r.result||r.api_error_status||"stream result error"))}function _e(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function Yi(e){let r=e.usage;return r&&typeof r=="object"&&!Array.isArray(r)?r:null}function Vi(e){if(typeof e.model=="string"&&e.model.trim())return e.model.trim();let r=e.modelUsage;if(r&&typeof r=="object"&&!Array.isArray(r)){let t=Object.keys(r)[0];if(t?.trim())return t.trim()}}function zi(e,r){let t=Yi(r);if(!t)return;let n=_e(t.input_tokens)??_e(t.inputTokens)??_e(t.prompt_tokens),o=_e(t.output_tokens)??_e(t.outputTokens)??_e(t.completion_tokens);if(n===void 0&&o===void 0)return;let s=Vi(r)??e.usage?.model;e.usage={...n!==void 0?{inputTokens:n}:{},...o!==void 0?{outputTokens:o}:{},...s?{model:s}:{}}}function Ji(e){if(e.type!=="tool_call"||e.subtype!=="completed")return null;let t=(e.tool_call&&typeof e.tool_call=="object"&&!Array.isArray(e.tool_call)?e.tool_call:null)?.shellToolCall;if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,o=n.args,s=o&&typeof o=="object"&&!Array.isArray(o)&&typeof o.command=="string"?String(o.command):"",i=n.result;if(!i||typeof i!="object"||Array.isArray(i))return null;let a=i.success??i.failure;if(!a||typeof a!="object"||Array.isArray(a))return null;let u=a,l=typeof u.exitCode=="number"?u.exitCode:0;return{command:s,exitCode:l,stdout:typeof u.stdout=="string"?u.stdout:"",stderr:typeof u.stderr=="string"?u.stderr:"",interleaved:typeof u.interleavedOutput=="string"?u.interleavedOutput:""}}function Xi(e,r){r.kind==="success"||r.kind==="search_no_matches"||(e.lastShellOutcome=r)}function kn(e){let r={firstEventAt:null,lastEventAt:null,currentTool:null,finalResult:null,error:null,lastShellOutcome:null,usage:null};if(!Hi(e))return r;let t=Li(e,"utf8").split(`
9
+ `).filter(Boolean);for(let n of t){let o=Ve(n);if(!o)continue;let s=ji(o);if(s&&(r.firstEventAt||=s,r.lastEventAt=s),o.type==="stream_event"&&o.event&&typeof o.event=="object"&&o.event.type==="content_block_start"){let a=o.event.content_block;a?.type==="tool_use"&&(r.currentTool=String(a.name||"tool"))}if(o.type==="assistant"&&o.message&&typeof o.message=="object"){let a=o.message.content;if(Array.isArray(a)){let u=a.find(l=>l?.type==="tool_use");u&&(r.currentTool=String(u.name||r.currentTool))}}if(o.type==="tool_call"&&o.subtype==="started"){let a=o.tool_call&&typeof o.tool_call=="object"&&!Array.isArray(o.tool_call)?o.tool_call:void 0,u=$i(a);u&&(r.currentTool=u)}let i=Ji(o);i&&Xi(r,gn({command:i.command,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr,interleavedOutput:i.interleaved})),o.type==="result"&&Gi(r,o),zi(r,o)}return r}var Rn=f(()=>{"use strict";hn();b()});function Zi(e,r=240){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function yn(e){let r=(e??"").trim();if(!r)return null;for(let t of qi)if(t.test.test(r))return{blocked:!0,reason:`${t.label}: ${Zi(r)}`};return null}var qi,bn=f(()=>{"use strict";qi=[{test:/\b(?:invalid|unknown|unsupported|unrecognized)\b[^.\n]*\bmodel\b/i,label:"provider rejected the requested model"},{test:/\bmodel\b[^.\n]*\b(?:not\s+(?:found|supported|available|recognized|valid)|is\s+not\s+valid|does\s+not\s+exist)/i,label:"provider rejected the requested model"},{test:/\b(?:did you mean|available models|choose (?:a|one of)|supported models)\b/i,label:"provider rejected the requested model"},{test:/model preflight failed/i,label:"model/provider preflight failed"},{test:/\b(?:command not found|ENOENT|is the .*CLI on PATH|executable not found|no such file or directory)\b/i,label:"provider CLI is missing or not on PATH"},{test:/\bfailed to spawn\b/i,label:"provider failed to spawn the worker process"},{test:/\b(?:not logged in|unauthorized|authentication (?:failed|required)|invalid api key|missing api key|401)\b/i,label:"provider authentication failed"},{test:/\b(?:out of usage|increase limits?|switch to auto|ask your admin to increase your limit|usage limits?|quota exceeded|insufficient_quota|credits? exhausted|billing|payment required)\b/i,label:"provider quota exhausted"}]});function Sn(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function Qi(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="boolean"?e:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function ea(e){return!e?.checked||e.headIsAncestorOfBase!==!1?null:Sn(e.head)}function ra(e,r,t){let n=["exited_with_changes_salvage"];if((e==="uncommitted"||e==="both")&&n.push(`${r} uncommitted change${r===1?"":"s"} with no final result`),(e==="committed_ahead"||e==="both")&&t){let o=t.length>12?t.slice(0,12):t;n.push(`commit ${o} ahead of base with no final result`)}return n.push("review worktree \u2014 commit, open a PR, or run a salvage worker before discarding"),n.join(": ")}function vn(e){if(e.alive||Qi(e.finalResult))return null;let r=(e.changedFiles??[]).filter(i=>i.trim()).length,t=Sn(e.headCommit)??ea(e.gitAncestry),n=r>0,o=!!t;if(!n&&!o)return{kind:"none",salvageable:!1,uncommittedCount:0,headCommit:null,attentionReason:"process exited without a final result"};let s=n&&o?"both":n?"uncommitted":"committed_ahead";return{kind:s,salvageable:!0,uncommittedCount:r,headCommit:t,attentionReason:ra(s,r,t)}}var xn=f(()=>{"use strict"});function Me(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function ta(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="boolean"?e:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function na(e){if(Me(e.headCommit)||Me(e.prUrl)||Me(e.artifactBundlePath)||Me(e.patchPath))return!0;let r=e.gitAncestry;return!!(r?.checked&&r.headIsAncestorOfBase===!1&&Me(r.head))}function Ce(e){return ta(e.finalResult)?e.changedFiles.length===0?{blocked:!1}:na(e)?{blocked:!0,detail:`Worktree has ${e.changedFiles.length} uncommitted change(s); commit or discard before landing`}:{blocked:!0,reason:"dirty_worktree_no_pr",detail:`Worktree has ${e.changedFiles.length} uncommitted change(s) with no commit or PR; commit, open a PR, or discard before landing`}:{blocked:!1}}function _n(e){if(e.blocked)return e.detail??e.reason??"dirty_worktree_no_pr"}var dr=f(()=>{"use strict"});function at(e){let r=e.trim();if(!r.startsWith("{"))return null;try{let t=JSON.parse(r);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{return null}return null}function Cn(e){let r=e.targetPrReconciliation??e.target_pr_reconciliation??e.targetPrs??e.target_prs;return Array.isArray(r)?r.length:0}function pr(e){let r=e.trim();if(!r)return null;let t=at(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let c=at(s[1]??"");c&&n.push(c)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let c=at(r.slice(i,a+1));c&&n.push(c)}if(n.length===0)return null;let u=n[n.length-1],l=Cn(u);for(let c of n){let d=Cn(c);d>l&&(u=c,l=d)}return u}var ut=f(()=>{"use strict"});function En(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`https://github.com/${r[1]}/pull/${r[2]}`:e.trim()||null}function wn(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function oa(e){return new Set(e.map(r=>wn(En(r)??r)).filter(Boolean))}function An(e,r,t){let n=En(e)??e;if(!n)return"unrelated";let o=wn(n);return oa(r).has(o)?"contract":t?(t.outcome==="skipped"||t.outcome==="blocked")&&t.reason?.trim()?"support":(t.outcome==="merged","unrelated"):"unrelated"}var Pn=f(()=>{"use strict"});function Ee(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function sa(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"?Object.keys(e).length>0:!0}function ue(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`https://github.com/${r[1]}/pull/${r[2]}`:Ee(e)}function mr(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function On(e){let r=null;if(typeof e=="string"){let o=pr(e);o&&(r=o)}else e&&typeof e=="object"&&!Array.isArray(e)&&(r=e);if(!r)return[];let t=r.targetPrReconciliation??r.target_pr_reconciliation;if(!Array.isArray(t))return[];let n=[];for(let o of t){if(!o||typeof o!="object"||Array.isArray(o))continue;let s=o,i=ue(String(s.prUrl??s.pr_url??"")),a=Ee(s.outcome);!i||a!=="merged"&&a!=="skipped"&&a!=="blocked"||n.push({prUrl:i,outcome:a,mergeCommit:Ee(s.mergeCommit??s.merge_commit),reason:Ee(s.reason)})}return n}function In(e,r){let t=[],n=ue(Ee(e.prUrl)??"");if(n&&t.push(n),r&&typeof r=="object"&&!Array.isArray(r)){let o=r,s=ue(String(o.prUrl??o.pr_url??""));s&&t.push(s)}return[...new Set(t)]}function Dn(e){let{contract:r,snapshot:t}=e,n=e.finalResult??t.finalResult;if(!r.landingOnly&&r.targetPrUrls.length===0&&!r.repairEnforceOriginalPr)return{blocked:!1};if(!sa(n))return(r.requiresTargetPrReconciliation??(r.landingOnly||!!r.repairEnforceOriginalPr||r.targetPrUrls.length>0))&&r.targetPrUrls.length>0?{blocked:!0,reason:"missing_target_pr_reconciliation",detail:`Final result required to reconcile target PR(s): ${r.targetPrUrls.join(", ")}`}:{blocked:!1};if(!(r.requiresTargetPrReconciliation??(r.landingOnly||!!r.repairEnforceOriginalPr||r.targetPrUrls.length>0))&&!r.repairEnforceOriginalPr)return{blocked:!1};let s=r.repairEnforceOriginalPr?ue(Ee(r.targetPrUrl)??"")??(r.targetPrUrls.length===1?ue(r.targetPrUrls[0]):null):null;if(s){let d=In(t,n);if(!(n&&typeof n=="object"&&!Array.isArray(n)&&n.supersedesOriginalTargetPr===!0)){for(let R of d)if(R!==s)return{blocked:!0,reason:"duplicate_repair_pr",detail:`Repair worker opened or attached PR ${R} instead of canonical target ${s}`}}let p=On(n).find(R=>R.prUrl===s);if(!p||p.outcome!=="merged"&&!(p.reason?.trim()&&(p.outcome==="skipped"||p.outcome==="blocked")))return{blocked:!0,reason:"missing_repair_target_reconciliation",detail:`Repair worker must reconcile target PR ${s}`}}let i=On(n),a=new Map(i.map(d=>[mr(d.prUrl),d])),u=new Set(r.targetPrUrls.map(d=>mr(ue(d)??d)).filter(Boolean)),l=In(t,n);if(r.landingOnly)for(let d of l){let m=a.get(mr(d)),g=An(d,r.targetPrUrls,m);if(!(g==="contract"||g==="support"))return u.size>0?{blocked:!0,reason:"unrelated_implementation_pr",detail:`Landing-only worker attached unrelated PR ${d}`}:{blocked:!0,reason:"unrelated_implementation_pr",detail:"Landing-only worker must not open new implementation PRs"}}if(r.targetPrUrls.length===0)return{blocked:!1};let c=[];for(let d of r.targetPrUrls){let m=mr(ue(d)??d),g=a.get(m);if(!g){c.push(m);continue}g.outcome!=="merged"&&!g.reason?.trim()&&c.push(m)}return c.length>0?{blocked:!0,reason:c.every(d=>a.has(d))?"incomplete_target_pr_landing":"missing_target_pr_reconciliation",detail:`Target PR reconciliation incomplete: ${c.join(", ")}`}:{blocked:!1}}function Nn(e){if(e.blocked)return e.detail??e.reason}var Wn=f(()=>{"use strict";ut();Pn()});function ua(e){let r=Date.now();if(e.completionBlocker&&!Mn(e.completionBlocker))return{state:"blocked",reason:e.completionBlocker};if(e.finalResult){if(e.localOnly&&ca(e.finalResult))return{state:"done",reason:"local-only worker superseded by merged PR"};let o={finalResult:e.finalResult,changedFiles:e.changedFiles??[],gitAncestry:e.gitAncestry??null,prUrl:e.prUrl??null},s=Ce(o);if(s.blocked){let i=_n(s);return{state:"needs_attention",reason:s.reason?`landing blocked (${s.reason}): ${i}`:`landing blocked: ${i}`}}if(e.landingContract){let i=Dn({contract:e.landingContract,snapshot:o,finalResult:e.finalResult}),a=Nn(i);if(a)return{state:"needs_attention",reason:i.reason?`landing contract (${i.reason}): ${a}`:`landing contract: ${a}`}}return{state:"done",reason:"final result recorded"}}if(!e.alive){if(la(e))return{state:"done",reason:"empty abandoned worker record"};let o=yn(e.error);if(o)return{state:"blocked",reason:o.reason};let s=vn({alive:!1,finalResult:null,changedFiles:e.changedFiles,gitAncestry:e.gitAncestry});if(s?.salvageable){let a=e.error?.trim();return{state:"needs_attention",reason:a?`${s.attentionReason} (${a})`:s.attentionReason}}let i=e.error?.trim();return{state:"needs_attention",reason:i?`process exited without a final result: ${i}`:s?.attentionReason??"process exited without a final result"}}if(e.heartbeatBlocker)return{state:"blocked",reason:`worker heartbeat reported blocker: ${e.heartbeatBlocker}`};let t=e.startedAt?Date.parse(e.startedAt):NaN;if(!e.firstEventAt&&e.stdoutBytes===0&&e.heartbeatBytes===0&&Number.isFinite(t)&&r-t>ia)return{state:"needs_attention",reason:`no first stream event ${Gr(t)}s after start`};let n=e.lastActivityAt?Date.parse(e.lastActivityAt):NaN;return Number.isFinite(n)&&r-n>aa?{state:"stale",reason:`no log/event/heartbeat activity for ${Gr(n)}s`}:{state:"ok",reason:"recent activity"}}function Mn(e){let r=e?.trim();return r?/completion acknowledged but board not advanced/i.test(r)&&/task already terminal/i.test(r):!1}function la(e){return e.finalResult||e.taskId||e.agentOsId||e.stdoutBytes>0||(e.stderrBytes??0)>0||e.heartbeatBytes>0||e.error?.trim()||(e.changedFiles??[]).some(r=>r.trim())?!1:/empty worker dir|marked abandoned/i.test(e.reconcileReason??"")}function ca(e){let r=null;if(typeof e=="string"?r=pr(e):e&&typeof e=="object"&&!Array.isArray(e)&&(r=e),!r)return!1;let t=r.targetPrReconciliation??r.target_pr_reconciliation;return Array.isArray(t)?t.some(n=>!n||typeof n!="object"||Array.isArray(n)?!1:String(n.outcome??"").trim()==="merged"):!1}function da(e,r,t){let n=e.completionSnapshot?.finalResult;return e.completionAckSource==="local-pr-merged-reconcile"&&n!==void 0&&n!==null?n:r||(n??on(t))}function Te(e,r={}){let t=kn(e.stdoutPath),n=xe(e.heartbeatPath),o=typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim().length>0,s=da(e,t.finalResult,n),i=o?!1:Q(e.pid),a=ze(e.stdoutPath),u=ze(e.stderrPath),l=ze(e.heartbeatPath),c=Oe(e.worktreePath),d=Xe(e.worktreePath,{base:r.base,baseCommit:r.baseCommit}),m=Lt([t.lastEventAt,n.lastHeartbeatAt,Je(e.stdoutPath),Je(e.stderrPath),Je(e.heartbeatPath)]),g=t.error||!i&&!s&&Ht(e.stderrPath,10).trim()||void 0,p=typeof e.completionBlocker=="string"&&e.completionBlocker.trim()?e.completionBlocker.trim():null,R=Mn(p)?null:p,S=e.repairTargetPrUrl?{landingOnly:!1,targetPrUrls:[e.repairTargetPrUrl],targetPrUrl:e.repairTargetPrUrl,repairEnforceOriginalPr:!0}:null,y=ua({alive:i,finalResult:s,firstEventAt:t.firstEventAt,stdoutBytes:a,stderrBytes:u,heartbeatBytes:l,lastActivityAt:m,heartbeatBlocker:n.heartbeatBlocker,startedAt:e.startedAt,error:g,changedFiles:c,gitAncestry:d,completionBlocker:R,landingContract:S,prUrl:e.repairTargetPrUrl??e.taskPrUrl??null,localOnly:e.localOnly===!0,taskId:e.taskId??null,agentOsId:e.agentOsId??null,reconcileReason:e.reconcileReason??null}),A=R||y.state==="blocked"?"blocked":o||y.state==="done"?"done":s?"exited":i?"running":"exited";return{runId:e.runId,worker:e.name,pid:e.pid,alive:i,status:A,attention:y,branch:e.branch,worktreePath:e.worktreePath,ownedPaths:e.ownedPaths,stdoutBytes:a,stderrBytes:u,heartbeatBytes:l,firstEventAt:t.firstEventAt,lastEventAt:t.lastEventAt,lastActivityAt:m,currentTool:o?null:t.currentTool,heartbeatCount:n.heartbeatCount,lastHeartbeatAt:n.lastHeartbeatAt,lastHeartbeatPhase:n.lastHeartbeatPhase,lastHeartbeatSummary:n.lastHeartbeatSummary,heartbeatBlocker:n.heartbeatBlocker,timestampAnomalies:n.timestampAnomalies,finalResult:s,error:g,changedFiles:c,gitAncestry:d,instructionPolicyFingerprint:e.instructionPolicyFingerprint??null,instructionPolicyEvidence:e.instructionPolicyEvidence??null,model:e.model??e.orchestrationAudit?.model??null,provider:e.provider??e.orchestrationAudit?.provider??null,usage:t.usage??null,boxKind:e.boxKind??null,boxId:e.boxId??null,runtimeId:e.runtimeId??null,personaSlug:e.personaSlug??null,dispatched:e.dispatched??null,localOnly:e.localOnly??null}}function le(e){return!!(e.finalResult||e.alive===!1||e.status==="exited"||e.status==="done")}function Tn(e){return e.finalResult?e.attention.state==="needs_attention"||e.attention.state==="blocked":!1}var ia,aa,ce=f(()=>{"use strict";ur();Rn();bn();xn();F();dr();Wn();ut();b();ia=18e4,aa=6e5});var Un=f(()=>{"use strict";ce()});function Bn(e,r={}){let t=r.perWorkerMemBytes??lt,n=r.memReserveBytes??ct,o=r.memUtilization??dt,s=Math.max(0,Math.floor(e*o)-n),i=Math.max(1,Math.floor(s/t));return Math.min(i,fr)}var lt,ct,dt,fr,Kn=f(()=>{"use strict";Vt();pe();ie();er();gr();sr();ae();tt();Un();b();lt=500*1024*1024,ct=4*1024*1024*1024,dt=.85,fr=64});function Ue(e,r){let t=Number(e);return!Number.isFinite(t)||t<=0?r:Math.floor(t)}function pt(e){let r=e.config??{},t=e.env??process.env,n=Ue(r.perWorkerMemBytes,lt),o=Ue(r.memReserveBytes,ct),s=Math.min(1,Math.max(.1,Number(r.memUtilization)>0?Number(r.memUtilization):dt)),i=Bn(e.totalMemBytes,{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s});if(e.configuredMaxWorkersOverride!==void 0&&e.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:Ue(e.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(r.maxConcurrentWorkers!==void 0&&r.maxConcurrentWorkers!==null){let l=Ue(r.maxConcurrentWorkers,0)||null;if(l)return{configuredMaxWorkers:Math.min(l,fr),autoCap:i,workerCapSource:"config"}}let u=(t.KYNVER_MAX_WORKERS_INTENTIONAL==="1"||t.KYNVER_MAX_WORKERS_INTENTIONAL==="true")&&t.KYNVER_MAX_WORKERS&&Ue(t.KYNVER_MAX_WORKERS,0)||null;return u?{configuredMaxWorkers:Math.min(u,fr),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var gr=f(()=>{"use strict";Kn()});import{homedir as pa}from"node:os";import ma from"node:path";var Fn,mt=f(()=>{"use strict";Fn=ma.join(pa(),".kynver",".env")});var Hn=f(()=>{"use strict"});var Ln=f(()=>{"use strict";Hn()});var jn=f(()=>{"use strict"});var ft=f(()=>{"use strict";Ln();jn()});var $n=f(()=>{"use strict"});var Gn=f(()=>{"use strict";$n()});var hr=f(()=>{"use strict";mt();oe();pe();ft();Gn()});var zn=f(()=>{"use strict";ie();ie()});var Jn=f(()=>{"use strict";mt();ft();hr()});import{existsSync as V,mkdirSync as ga,readdirSync as kr,renameSync as Xn,statSync as ha}from"node:fs";import z from"node:path";function Zn(e){try{return ha(e).isDirectory()}catch{return!1}}function ka(e){if(!V(e))return!0;for(let r of qn){let t=z.join(e,r);if(V(t)&&(!Zn(t)||kr(t).length>0))return!1}return!0}function Ra(e){let r=z.join(e,"runs");if(!V(r)||!Zn(r))return!1;for(let t of kr(r,{withFileTypes:!0})){if(!t.isDirectory()||t.name==="runs")continue;let n=z.join(r,t.name,"run.json");if(x(n,void 0)?.id)return!0}return!1}function ya(e){let r=z.join(e,"runs");if(!V(r))return!1;for(let t of kr(r,{withFileTypes:!0})){if(!t.isDirectory())continue;if(x(z.join(r,t.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function ba(e){let r=z.join(e,"ghost");return V(r)?!V(z.join(r,"runs")):ya(e)}function Qn(e){return Ra(e.sharedRoot)?ka(e.forgeRoot)?ba(e.sharedRoot)?{action:"blocked",blocker:"Forge legacy harness migration blocked: Ghost pool is co-hosted on this host (ghost namespace or ghost-attributed runs under ~/.kynver/harness). Drain in-flight Ghost runs from the shared root, or get operator sign-off for a fresh Forge cutover before enabling box-scoped isolation."}:{action:"migrate"}:{action:"none"}:{action:"none"}}function eo(e,r){ga(r,{recursive:!0});for(let t of qn){let n=z.join(e,t),o=z.join(r,t);if(V(n)){if(V(o)&&kr(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(V(o)){Xn(n,o);continue}Xn(n,o)}}}var qn,ro=f(()=>{"use strict";b();qn=["runs","worktrees"]});import{existsSync as E}from"node:fs";import{homedir as Sa}from"node:os";import C from"node:path";function gt(e=process.env){return e.HOME?.trim()||Sa()}function ht(e=process.env){return C.join(gt(e),".kynver","harness")}function Rr(e){let r=C.resolve(Z(e.trim()));for(;va.has(C.basename(r));)r=C.dirname(r);return r}function xa(e,r=process.env){return C.join(ht(r),e)}function _a(e=process.env){let r=ht(e);if(E(C.join(r,"runs")))return!0;if(E(r)&&!E(C.join(r,"ghost"))&&!E(C.join(r,"forge")))return E(r);let t=C.join(gt(e),to);return E(t)}function yr(e){let r=e.env??process.env,t=r.KYNVER_HARNESS_ROOT?.trim()||r.OPUS_HARNESS_ROOT?.trim();if(t)return{harnessRoot:Rr(t),source:"env"};let n=e.configuredHarnessRoot?.trim();if(n)return{harnessRoot:Rr(n),source:"config"};let o=xa(e.boxKind,r);if(E(C.join(o,"runs"))||E(o)&&!Ca(o))return{harnessRoot:o,source:"box_scoped"};let i=ht(r);if(e.boxKind==="forge"){let a=Qn({sharedRoot:i,forgeRoot:o});if(a.action==="blocked")return{harnessRoot:o,source:"box_scoped",migrationBlocker:a.blocker};if(a.action==="migrate")return e.allowForgeLegacyMigration!==!1&&eo(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(e.boxKind==="ghost"&&_a(r)){if(E(C.join(i,"runs")))return{harnessRoot:i,source:"legacy_shared"};if(E(i)&&!E(C.join(i,"ghost"))&&!E(C.join(i,"forge")))return{harnessRoot:i,source:"legacy_shared"};let u=C.join(gt(r),to);if(E(u))return{harnessRoot:u,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function Ca(e){if(!E(e))return!0;for(let r of["runs","worktrees"]){let t=C.join(e,r);if(E(t))return!1}return!0}var to,va,kt=f(()=>{"use strict";oe();ro();to=C.join(".openclaw","harness");va=new Set(["runs","worktrees"])});import no from"node:os";function br(e){return e?.trim()?e.trim():null}function Ea(e,r){let t=r.trim().toLowerCase()||"host";return`${e}-${t}`.replace(/[^a-z0-9._-]+/g,"-")}function wa(e){return e.KYNVER_DISPATCH_STRICT_IDENTITY==="1"||e.KYNVER_DISPATCH_STRICT_IDENTITY==="true"||e.KYNVER_DAEMON_STRICT_IDENTITY==="1"||e.KYNVER_DAEMON_STRICT_IDENTITY==="true"}function Sr(e=de(),r=process.env,t={}){let n=be(r,e),o=[...n.warnings],s=[],i=!!(e.boxKind?.trim()||br(r.KYNVER_BOX_KIND)),a=t.strict===!0||wa(r);if((t.requireExplicitBoxKind||a)&&!i&&s.push("boxKind is not persisted in ~/.kynver/config.json and KYNVER_BOX_KIND is unset \u2014 run `kynver setup` (customers: boxKind=box) or `kynver setup --box-kind forge|ghost` for operator pools before dispatch"),n.slugInferenceBlocked&&!i){let R="ambiguous box identity: KYNVER_AGENT_OS_SLUG is set without KYNVER_BOX_KIND or config.boxKind";a||t.requireExplicitBoxKind?s.push(R):o.push(`${R} \u2014 defaulting box kind to box (customer), not forge/ghost`)}let u=br(e.runnerId),l=br(r.KYNVER_RUNTIME_ID)??br(r.OPENCLAW_RUNTIME_ID),c=u??l??Ea(n.boxKind,no.hostname()),d=u?"config":l?"env":"derived";d==="derived"&&o.push(`runnerId not persisted \u2014 using derived id "${c}"; run \`kynver setup --box-kind ${n.boxKind}\` to persist runner identity`);let m=pt({config:e,env:r,totalMemBytes:no.totalmem()}),g=Qe(n.boxKind,m.configuredMaxWorkers??Vr(n.boxKind,m.autoCap)),p=yr({boxKind:n.boxKind,configuredHarnessRoot:e.harnessRoot,env:r});return p.migrationBlocker&&s.push(p.migrationBlocker),s.length>0?{ok:!1,identity:null,errors:s,warnings:o}:{ok:!0,identity:{boxKind:n.boxKind,boxKindSource:n.source,runnerId:c,runnerIdSource:d,maxConcurrentWorkers:g,workerCapSource:m.workerCapSource,harnessRoot:p.harnessRoot,harnessRootSource:p.source},errors:s,warnings:o}}var vr=f(()=>{"use strict";pe();ie();er();gr();kt()});var so=f(()=>{"use strict";qe();ie();zn();pe();hr();Jn();b();vr()});import{existsSync as Ia,mkdirSync as rp,readFileSync as Da,writeFileSync as tp}from"node:fs";import{homedir as Na,totalmem as op}from"node:os";import Rt from"node:path";function Wa(e){return{...e,...e.harnessRoot?.trim()?{harnessRoot:Z(e.harnessRoot.trim())}:{},...e.defaultRepo?.trim()?{defaultRepo:Z(e.defaultRepo.trim())}:{}}}function de(){if(!Ia(io))return{};try{return Wa(JSON.parse(Da(io,"utf8")))}catch{return{}}}var ao,io,hp,kp,Rp,pe=f(()=>{"use strict";qe();oe();b();ie();er();gr();sr();hr();so();vr();ao=Rt.join(Na(),".kynver"),io=Rt.join(ao,"config.json"),hp=Rt.join(ao,"credentials");kp=500*1024*1024,Rp=4*1024*1024*1024});import yt from"node:path";function I(e){return Rr(e)}function ee(){let e=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(e)return I(e);let r=de(),t=r.harnessRoot?.trim();if(t)return I(t);let n=Sr(r,process.env);return n.identity?n.identity.harnessRoot:yr({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function G(e){return yt.join(I(e),"runs")}function we(e){return yt.join(I(e),"worktrees")}function Qt(){let e=ee();return{harnessRoot:e,runsDir:G(e),worktreesDir:we(e)}}function et(e,r){return yt.join(e,v(r))}var Y=f(()=>{"use strict";pe();kt();vr();b()});Y();import M from"node:path";dr();import Er from"node:path";F();ce();var bt=[".next",".turbo","dist","build",".cache","node_modules/.cache"];function uo(e){let r=e.replace(/\\/g,"/").replace(/\/+$/,"");if(r==="node_modules"||r.startsWith("node_modules/"))return!0;for(let t of bt)if(r===t||r.startsWith(`${t}/`))return!0;return!1}function D(e){return e.filter(r=>{let t=r.trim(),n=t.startsWith("??")?t.slice(2).trim():t.length>3?t.slice(3).trim():t;return!uo(n)})}function me(e){if(typeof e=="string")return e.match(/https:\/\/github\.com\/[^\s]+\/pull\/\d+/i)?.[0]??null;if(e&&typeof e=="object"){let r=e;for(let t of["prUrl","pr_url","pullRequestUrl"]){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}}return null}function Be(e){let r=e.gitAncestry?.relation;return r==="merged"||r==="synced"?D(e.changedFiles).length>0:!!(me(e.finalResult)||r==="ahead"||r==="diverged"||e.changedFiles.length>0&&e.finalResult)}b();function Ke(e){return e.status||(e.status=Te(e.worker,{base:e.run.base,baseCommit:e.run.baseCommit})),e.status}function St(e,r){if(e.status)return D(e.status.changedFiles).length>0;let t=r?r.porcelain(e.worktreePath):Oe(e.worktreePath);return D(t).length>0}function Ma(e){let r=e.worker.completionSnapshot?.finalResult;return r??(e.worker.taskPrUrl?{prUrl:e.worker.taskPrUrl}:null)}function vt(e,r){if(e.status)return e.status;let t=e.worker,n=typeof t.completionReportedAt=="string"&&t.completionReportedAt.trim().length>0,o=!!(t.status&&["done","exited","blocked","failed","abandoned"].includes(t.status))||n,s=Ma(e);if(o&&!Q(t.pid)){let i=r?.gitStatusCache?r.gitStatusCache.porcelain(e.worktreePath):Oe(e.worktreePath),a=e.run.baseCommit?.trim()||e.run.base?.trim()||"origin/main",l=r?.gitRevCache?.countAheadOfMain(e.worktreePath,a)===0?{checked:!0,base:a,relation:"synced"}:Xe(e.worktreePath,{base:e.run.base,baseCommit:e.run.baseCommit}),c={runId:e.runId,worker:e.workerName,pid:t.pid,alive:!1,status:t.status??(n?"done":"exited"),attention:{state:n?"done":"stale"},branch:t.branch,worktreePath:e.worktreePath,ownedPaths:t.ownedPaths,stdoutBytes:0,stderrBytes:0,heartbeatBytes:0,firstEventAt:null,lastEventAt:null,lastActivityAt:t.completionReportedAt??null,currentTool:null,heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,heartbeatBlocker:null,changedFiles:i,gitAncestry:l,finalResult:s,completionBlocker:typeof t.completionBlocker=="string"&&t.completionBlocker.trim()||null,prUrl:t.repairTargetPrUrl??t.taskPrUrl??me(s)};return e.status=c,c}return Ke(e)}ce();ae();tt();ce();b();import Ta from"node:path";var Ua=new Set(["running","dispatching","pending","queued","needs_attention"]),fe=new Set(["completed","failed","cancelled","done"]);function ge(e){let r=rt(e);if(r.length===0)return"failed";let t=!1,n=!1,o=!1,s=!1;for(let i of r){let a=x(Ta.join(Ie(e.id),"workers",v(i),"worker.json"),void 0);if(!a)continue;let u=Te(a,{base:e.base,baseCommit:e.baseCommit});if(u.alive&&!u.finalResult){t=!0;break}typeof a.completionBlocker=="string"&&a.completionBlocker&&(o=!0),Tn(u)&&(s=!0),u.finalResult&&u.attention.state==="done"&&(n=!0)}return t||o||s?null:n?"completed":"failed"}function lo(){let e=[];for(let r of Zr()){if(!Ua.has(r.status))continue;let t=ge(r);if(!t||t===r.status)continue;let n=r.status;r.status=t,Qr(r),e.push({runId:r.id,from:n,to:t})}return e}ce();ur();import{existsSync as xr,mkdirSync as rm,readdirSync as mo,renameSync as tm,statSync as Ba}from"node:fs";import he from"node:path";pe();qe();oe();F();ur();Y();ae();Y();b();import re from"node:path";var Xp=`${re.sep}runs${re.sep}runs${re.sep}`;function co(e){return{workerJsonPath:re.join(e,"worker.json"),stdoutPath:re.join(e,"stdout.jsonl"),stderrPath:re.join(e,"stderr.log"),heartbeatPath:re.join(e,"heartbeat.jsonl"),lastStatusPath:re.join(e,"last-status.json")}}b();var Fe=900*1e3,dm=3600*1e3;function fo(e,r){let t=he.resolve(e),n=he.resolve(G(r)),o=he.relative(n,t);return o!==".."&&!o.startsWith("..")&&!he.isAbsolute(o)}function Ka(e){if(!xr(e))return[];try{return mo(e,{withFileTypes:!0}).filter(r=>r.isDirectory()&&r.name!=="runs").map(r=>r.name)}catch{return[]}}function Fa(e){let r=he.join(e,"workers");if(!xr(r))return[];try{return mo(r,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}}function po(e,r,t){if(!xr(e))return!1;try{let n=r-Ba(e).mtimeMs;return Number.isFinite(n)&&n>=0&&n<t}catch{return!1}}function Ha(e,r=Date.now(),t=Fe){if(!xr(e))return!1;let n=co(e),o=x(n.workerJsonPath,void 0);if(o?.status==="running"&&Q(o.pid))return!0;let s=xe(n.heartbeatPath);if(s.lastHeartbeatAt){let i=r-Date.parse(s.lastHeartbeatAt);if(Number.isFinite(i)&&i>=0&&i<t)return!0}return!!(po(n.stdoutPath,r,t)||po(n.heartbeatPath,r,t))}function La(e,r=Date.now(),t=Fe){for(let n of Fa(e))if(Ha(he.join(e,"workers",n),r,t))return!0;return!1}function go(e,r=Date.now()){let t=new Set,n=G(e);for(let o of Ka(n)){let s=he.join(n,o);La(s,r)&&t.add(`${e}\0${o}`)}return t}b();function xt(e,r=Date.now(),t=Fe){let n=xe(e.heartbeatPath);if(!n.lastHeartbeatAt)return!1;let o=r-Date.parse(n.lastHeartbeatAt);return Number.isFinite(o)&&o>=0&&o<t}function _r(e,r=Date.now(),t=Fe){return Q(e.pid)?!0:xt(e,r,t)}function ja(e,r){return r?r.runTerminalCache.derive(e.run):ge(e.run)}function J(e,r=Date.now()){return _r(e.worker,r)}function _t(e,r){return fe.has(e.run.status)?!1:ja(e,r)!==null}function ho(e,r,t=Date.now()){if(J(e,t))return!0;if(fe.has(e.run.status)||_t(e,r))return!1;let n=Ke(e);return le(n)?!1:!!J(e,t)}dr();ce();function ko(e,r){if(!(typeof e.worker.completionBlocker=="string"?e.worker.completionBlocker.trim():""))return!1;if(J(e))return!0;let n=r??Ke(e);return!!(!le(n)||Be(n)||D(n.changedFiles).length>0||Ce({finalResult:n.finalResult,changedFiles:n.changedFiles,gitAncestry:n.gitAncestry,prUrl:me(n.finalResult)}).blocked)}F();b();import{existsSync as yo,mkdirSync as $a,writeFileSync as Ro}from"node:fs";import Cr from"node:path";function bo(e,r,t){return Cr.join(e,"salvage",v(r),v(t))}function So(e){return yo(Cr.join(bo(e.harnessRoot,e.runId,e.workerName),"evidence.json"))}function vo(e){let r=bo(e.harnessRoot,e.indexed.runId,e.indexed.workerName);$a(r,{recursive:!0});let t=Cr.join(r,"salvage.patch"),n=!1;if(yo(e.indexed.worktreePath)){let s=w(e.indexed.worktreePath,["diff","HEAD"]),i=w(e.indexed.worktreePath,["diff","--cached"]),a=[s.stdout,i.stdout].filter(u=>u.trim()).join(`
10
10
  `);a.trim()&&(Ro(t,a.endsWith(`
11
11
  `)?a:`${a}
12
- `),n=!0)}let o={capturedAt:new Date(e.now??Date.now()).toISOString(),skipReason:e.skipReason,runId:e.indexed.runId,workerName:e.indexed.workerName,worktreePath:e.indexed.worktreePath,taskId:e.indexed.worker.taskId,agentOsId:e.indexed.worker.agentOsId,branch:e.indexed.worker.branch,completionBlocker:e.indexed.worker.completionBlocker,finalResult:e.status.finalResult,changedFiles:e.status.changedFiles,gitAncestry:e.status.gitAncestry,prUrl:e.status.prUrl??null,...n?{patchPath:t}:{}};return Ro(_r.join(r,"evidence.json"),`${JSON.stringify(o,null,2)}
13
- `),o}var Ga=new Set(["completion_blocked","dirty_worktree","pr_or_unmerged_commits","landing_blocked"]);function Ya(e){return!Ga.has(e.skipReason)||J(e.indexed,e.now)?!1:So({harnessRoot:e.harnessRoot,runId:e.indexed.runId,workerName:e.indexed.workerName})?!0:e.writeSalvageEvidence?(vo({harnessRoot:e.harnessRoot,indexed:e.indexed,skipReason:e.skipReason,status:e.status,now:e.now}),!0):!1}function Va(e){let{indexed:r,worktreesAgeMs:t,terminalWorktreesAgeMs:n}=e;return r&&(fe.has(r.run.status)||e.liveness&&_t(r,e.liveness)||e.liveness&&le(vt(r,e.liveness))&&!J(r))?n:t}function za(e){return!e.indexed||e.includeOrphans&&e.worktreesAgeMs<=0?0:Va(e)}function Ja(e,r){if(e.harnessRoot?.trim())return Cr.resolve(e.harnessRoot);let t=r.worker.workerDir;if(!t)return null;let n=`${Cr.sep}runs${Cr.sep}`,o=t.indexOf(n);return o<0?null:t.slice(0,o+n.length-1)}function xo(e){let{indexed:r,includeOrphans:t,worktreesAgeMs:n,ageMs:o,orphanSafety:s,worktreeRemovalGuard:i}=e,a=e.now??Date.now();if(!r)return t?s??null:"orphan_without_flag";let u=za(e);if(n<=0&&!t&&u<=0)return"worktrees_disabled";if(u>0&&o<u)return"below_age_threshold";if(J(r,a))return"active_worker";let l=vt(r,e.liveness),c=Ja(e,r),d=p=>c&&Ya({indexed:r,harnessRoot:c,skipReason:p,status:l,now:a,writeSalvageEvidence:e.writeSalvageEvidence===!0})?null:p;if(ko(r,l)){let p=d("completion_blocked");if(p)return p}if(St(r,e.liveness?.gitStatusCache)){let p=d("dirty_worktree");if(p)return p}let m=e.liveness?.gitRevCache?.countAheadOfMain(e.worktreePath);if(m!=null&&m>0){let p=d("pr_or_unmerged_commits");if(p)return p}if(ho(r,e.liveness,a)||!le(l))return"run_still_active";if(Be(l)){let p=d("pr_or_unmerged_commits");if(p)return p}if(D(l.changedFiles).length>0){let p=d("dirty_worktree");if(p)return p}if(Ce({finalResult:l.finalResult,changedFiles:l.changedFiles,gitAncestry:l.gitAncestry,prUrl:me(l.finalResult)}).blocked){let p=d("landing_blocked");if(p)return p}if(i&&e.worktreePath){let p=i({worktreePath:e.worktreePath,indexed:!!r,runId:r?.runId,worker:r?.workerName});if(p)return p.detail?{reason:p.reason,detail:p.detail}:p.reason}return null}function Ct(e){let{indexed:r,nodeModulesAgeMs:t,ageMs:n,worktreePath:o,activeWorktreePaths:s,diskPressure:i}=e;return!i&&n<t?"below_age_threshold":s.has(Cr.resolve(o))||r&&J(r)?"active_worker":r&&St(r,e.gitStatusCache)?"dirty_worktree":null}function _o(e){return Ct(e)}var Et=216e5,Er=6048e5;var wt=36e5,wr=120;var Co=new Set(["active_worker","run_still_active","completion_blocked","landing_blocked"]);function Eo(e,r){let t=[],n=new Set,o=(s,i,a)=>{let u=`${s}\0${i}`;n.has(u)||t.length>=24||(n.add(u),t.push({path:s,reason:i,...a?{detail:a}:{}}))};for(let s of r)Co.has(s.reason)&&o(s.path,s.reason,s.detail);for(let s of e)!s.skipped||!s.skipReason||Co.has(s.skipReason)&&o(s.path,s.skipReason);return t}import{existsSync as Oo,readdirSync as Io,statSync as Za}from"node:fs";import Do from"node:path";ae();Y();import wo from"node:path";b();function qa(e,r){return xr(e,r)}function Ao(e,r=Date.now()){let t=new Set,n=new Set;for(let o of e){for(let s of ir(o)){let i=!1;for(let a of Object.keys(s.workers||{})){let u=x(wo.join(De(o,s.id),"workers",v(a),"worker.json"),void 0);if(!u?.worktreePath)continue;let l=wo.resolve(u.worktreePath);qa(u,r)&&(i=!0,t.add(l))}i&&n.add(`${o}\0${s.id}`)}for(let s of go(o))n.add(s)}return{activeWorktreePaths:t,liveRunKeys:n}}function Po(e,r,t,n){return t?n.has(`${r}\0${t}`):!1}b();function Qa(e,r){try{let t=Za(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function eu(e,r){let t=Do.join(e,"runs",r,"run.json");return Oo(t)?x(t,null):null}function No(e){try{return Io(e).length===0}catch{return!1}}function Wo(e){let{harnessRoot:r,runId:t,runPath:n,ageMs:o,runDirectoriesAgeMs:s,activeGuards:i}=e;if(Po(n,r,t,i.liveRunKeys)||!No(n))return"run_still_active";let a=eu(r,t);return a&&!fe.has(a.status)&&!ge(a)?"run_still_active":s>0&&o<s?"below_age_threshold":null}function Mo(e){if(!Oo(e.worktreesDir))return[];let r=[],t;try{t=Io(e.worktreesDir,{withFileTypes:!0})}catch{return[]}for(let n of t){if(!n.isDirectory())continue;let o=n.name;if(e.runIdFilter&&o!==e.runIdFilter)continue;let s=Do.join(e.worktreesDir,o);No(s)&&r.push({kind:"remove_run_directory",path:s,bytes:null,harnessRoot:e.harnessRoot,runId:o,ageMs:Qa(s,e.now)})}return r}F();import{existsSync as Pt,rmSync as Yo}from"node:fs";import{execFileSync as ru}from"node:child_process";import{existsSync as To,readdirSync as tu,statSync as nu}from"node:fs";import ou from"node:path";var su=2500;function iu(e,r=su){if(!To(e))return 0;try{let n=ru("du",["-sb",e],{encoding:"utf8",timeout:r,stdio:["ignore","pipe","ignore"]}).trim().split(/\s+/)[0],o=Number(n);return Number.isFinite(o)&&o>=0?o:null}catch{return null}}function X(e,r=5e4){if(!To(e))return 0;let t=iu(e);if(t!==null)return t;let n=0,o=0,s=[e];for(;s.length>0;){let i=s.pop(),a;try{a=tu(i)}catch{continue}for(let u of a){if(o++>r)return null;let l=ou.join(i,u),c;try{c=nu(l)}catch{continue}c.isDirectory()?s.push(l):n+=c.size}}return n}import{existsSync as cu,rmSync as du}from"node:fs";Y();import{lstatSync as au,readdirSync as uu}from"node:fs";function Uo(e){try{let r=au(e),t=typeof process.getuid=="function"?process.getuid():null,n=typeof process.getgid=="function"?process.getgid():null,o=t!==null&&(r.uid!==t||n!==null&&r.gid!==n);return{uid:r.uid,gid:r.gid,foreign:o}}catch{return null}}function Bo(e,r=32){let t=Uo(e);if(!t)return!1;if(t.foreign)return!0;try{let n=uu(e),o=0;for(let s of n){if(o>=r)break;let i=`${e.replace(/\/$/,"")}/${s}`,a=Uo(i);if(o+=1,a?.foreign)return!0}}catch{}return!1}import{spawnSync as lu}from"node:child_process";import Ho from"node:path";import N from"node:path";function Ko(e,r,t,n){let o=N.resolve(e),s=`${N.sep}${n}`,i=o.endsWith(s)?o:null;if(!i)return"path_outside_harness";let a=N.relative(t,i);if(a.startsWith("..")||N.isAbsolute(a))return"path_outside_harness";let u=a.split(N.sep);return u.length<3||u[u.length-1]!==n||!o.startsWith(N.resolve(r))?"path_outside_harness":null}function Ar(e,r,t){return Ko(e,r,t,"node_modules")}function Pr(e,r,t){return Ko(e,r,t,".next")}function Or(e,r,t){let n=N.resolve(e),o=N.relative(t,n);return o.startsWith("..")||N.isAbsolute(o)||o.split(N.sep).length<3||!n.startsWith(N.resolve(r))?"path_outside_harness":null}function Fo(e,r,t){let n=N.resolve(e);return Ar(n,r,t)===null||Pr(n,r,t)===null||Or(n,r,t)===null}function jo(){let e=(process.env.KYNVER_CLEANUP_PRIVILEGED??"auto").trim().toLowerCase();return e==="0"||e==="false"||e==="off"||e==="no"?"off":e==="1"||e==="true"||e==="force"||e==="yes"?"force":"auto"}function Lo(e){let r=lu("sudo",["-n",...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{ok:r.status===0,stderr:`${r.stderr??""}${r.stdout??""}`.trim()}}function $o(e,r,t){if(!Fo(e,r,t))return{ok:!1,error:"path is not an allowed harness generated cache"};let n=typeof process.getuid=="function"?process.getuid():null,o=typeof process.getgid=="function"?process.getgid():null;if(n===null||o===null)return{ok:!1,error:"privileged reclaim requires POSIX uid/gid"};let s=Lo(["chown","-R",`${n}:${o}`,Ho.resolve(e)]);if(s.ok)return{ok:!0,method:"chown_then_rm"};let i=Lo(["rm","-rf",Ho.resolve(e)]);return i.ok?{ok:!0,method:"sudo_rm"}:{ok:!1,error:s.stderr||i.stderr||"sudo -n failed (password required or not permitted)"}}var At="Root-owned harness caches require operator reclaim: configure passwordless sudo for chown/rm under ~/.kynver/harness/worktrees, or run `node scripts/reclaim-harness-root-owned-cache.mjs --execute` as the harness owner with sudo available. See docs/runbooks/harness-root-owned-cache-reclaim.md.";function pu(e){let r=e?.code;return r==="EACCES"||r==="EPERM"}function Go(e,r,t={}){if(!cu(e.path))return{executed:!1,skipped:!0,skipReason:"missing_worktree"};if(!r)return{executed:!1,skipped:!0,skipReason:"dry_run"};let n=e.harnessRoot,o=n?we(n):null,i=e.bytes??X(e.path)??void 0,a=t.removePath??du,u=t.hasForeignOwnedEntry??Bo;try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i}}catch(l){if(!pu(l)||!n||!o)return{executed:!1,skipped:!0,skipReason:"remove_failed",error:l.message};let c=u(e.path),d=jo();if(!(d==="force"||d==="auto"&&c))return c?{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${l.message}; ${At}`}:{executed:!1,skipped:!0,skipReason:"remove_failed",error:l.message};let g=$o(e.path,n,o);if(g.ok&&g.method==="sudo_rm")return{executed:!0,skipped:!1,bytes:i,privilegedReclaim:!0};if(g.ok)try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i,privilegedReclaim:!0}}catch(p){return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${p.message}; privileged chown succeeded but rm still failed`}}return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${l.message}; privileged reclaim failed: ${g.error}; ${At}`}}}function Ot(e){let r=e.harnessRoot;return!r||!fo(e.path,r)?null:{...e,executed:!1,skipped:!0,skipReason:"run_metadata_protected"}}function It(e,r){let t=Ot(e);if(t)return t;let n=Go(e,r);return{...e,bytes:n.bytes??e.bytes,executed:n.executed,skipped:n.skipped,skipReason:n.skipReason,error:n.error}}function Vo(e,r){return It(e,r)}function zo(e,r){return It(e,r)}function Jo(e,r){return It(e,r)}function Xo(e,r){let t=Ot(e);if(t)return t;if(!Pt(e.path))return{...e,executed:!1,skipped:!0,skipReason:"missing_worktree"};if(!r)return{...e,executed:!1,skipped:!0,skipReason:"dry_run"};try{let n=e.bytes??X(e.path);return Yo(e.path,{recursive:!0,force:!0}),{...e,bytes:n,executed:!0,skipped:!1}}catch(n){return{...e,executed:!1,skipped:!0,skipReason:"remove_failed",error:n.message}}}function qo(e,r){let t=Ot(e);if(t)return t;if(!Pt(e.path))return{...e,executed:!1,skipped:!0,skipReason:"missing_worktree"};if(!r)return{...e,executed:!1,skipped:!0,skipReason:"dry_run"};let n=e.repo;try{let o=e.bytes??X(e.path);return n&&ye(n,["worktree","remove","--force",e.path],{allowFailure:!0}),Pt(e.path)&&Yo(e.path,{recursive:!0,force:!0}),{...e,bytes:o,executed:!0,skipped:!1}}catch(o){return{...e,executed:!1,skipped:!0,skipReason:"remove_failed",error:o.message}}}import{existsSync as Ir,readdirSync as Dr,statSync as mu}from"node:fs";import H from"node:path";function Dt(e,r){try{let t=mu(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function Qo(e,r){let t=H.relative(r,e);return t===""||!t.startsWith("..")&&!H.isAbsolute(t)}function Zo(e,r,t,n){let o=[];for(let s of bt){if(s===".next")continue;let i=H.join(e,s);if(!Ir(i))continue;let a=H.resolve(i);t.has(a)||Qo(a,r.harnessRoot)&&(t.add(a),o.push({kind:"remove_build_cache",path:a,bytes:null,runId:n.runId,worker:n.worker,repo:n.repo,ageMs:Dt(a,r.now)}))}return o}function es(e){let r=[],t=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||r.push(...Zo(n.worktreePath,e,t,{runId:n.runId,worker:n.workerName,repo:n.run.repo}));if(!e.includeOrphans||!Ir(e.worktreesDir))return r;for(let n of Dr(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=H.join(e.worktreesDir,n.name);for(let s of Dr(o,{withFileTypes:!0})){if(!s.isDirectory())continue;let i=H.join(o,s.name);r.push(...Zo(i,e,t,{runId:n.name,worker:s.name}))}}return r}function rs(e){let r=e.worktreesAgeMs>0||e.includeOrphans,t=e.includeOrphans;if(!r&&!t)return[];let n=[],o=new Set;if(r)for(let i of e.index.values()){if(e.runIdFilter&&i.runId!==e.runIdFilter)continue;let a=i.worktreePath;Ir(a)&&(o.has(a)||(o.add(a),n.push({kind:"remove_worktree",path:a,bytes:null,runId:i.runId,worker:i.workerName,repo:i.run.repo,ageMs:Dt(a,e.now)})))}if(!t||!Ir(e.worktreesDir))return n;let s=new Set;for(let i of e.index.values())s.add(H.resolve(i.worktreePath));for(let i of Dr(e.worktreesDir,{withFileTypes:!0})){if(!i.isDirectory()||e.runIdFilter&&i.name!==e.runIdFilter)continue;let a=H.join(e.worktreesDir,i.name),u;try{u=Dr(a,{withFileTypes:!0})}catch{continue}for(let l of u){if(!l.isDirectory())continue;let c=H.resolve(H.join(a,l.name));o.has(c)||s.has(c)||Qo(c,e.harnessRoot)&&(o.add(c),n.push({kind:"remove_worktree",path:c,bytes:null,runId:i.name,worker:l.name,ageMs:Dt(c,e.now)}))}}return n}import{existsSync as os,readdirSync as ts,statSync as fu}from"node:fs";import Ae from"node:path";var gu=[{dirName:"node_modules",kind:"remove_node_modules"},{dirName:".next",kind:"remove_next_cache"}];function hu(e,r){try{let t=fu(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function ku(e,r){let t=Ae.relative(r,e);return t===""||!t.startsWith("..")&&!Ae.isAbsolute(t)}function Ru(e,r,t,n,o,s){if(!os(n))return;let i=Ae.resolve(n);r.has(i)||ku(i,t.harnessRoot)&&(r.add(i),e.push({kind:o,path:i,bytes:null,harnessRoot:t.harnessRoot,runId:s.runId,worker:s.worker,repo:s.repo,ageMs:hu(i,t.now)}))}function ns(e,r,t,n,o){for(let s of gu)Ru(e,r,t,Ae.join(n,s.dirName),s.kind,o)}function ss(e){let r=[],t=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||ns(r,t,e,n.worktreePath,{runId:n.runId,worker:n.workerName,repo:n.run.repo});if(!e.includeOrphans||!os(e.worktreesDir))return r;for(let n of ts(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory()||e.runIdFilter&&n.name!==e.runIdFilter)continue;let o=Ae.join(e.worktreesDir,n.name),s;try{s=ts(o,{withFileTypes:!0})}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=Ae.join(o,i.name);ns(r,t,e,a,{runId:n.name,worker:i.name})}}return r}F();import{existsSync as is,statSync as yu}from"node:fs";import L from"node:path";function bu(e,r){try{let t=yu(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function Su(e){let r=[],t=null;for(let n of e.split(`
14
- `)){if(!n.trim())continue;let[o,...s]=n.split(" "),i=s.join(" ");if(o==="worktree"){t&&r.push(t),t={path:i};continue}t&&(o==="branch"&&(t.branch=i),o==="HEAD"&&(t.head=i),o==="bare"&&(t.bare=!0))}return t&&r.push(t),r}function vu(e,r){let t=L.relative(L.resolve(r),L.resolve(e));return t!==""&&!t.startsWith("..")&&!L.isAbsolute(t)}var xu=200;function as(e){if(!e.includeOrphans||!is(e.worktreesDir))return[];let r=new Set;for(let s of e.index.values())s.run.repo&&r.add(L.resolve(s.run.repo));let t=new Set;for(let s of e.index.values())t.add(L.resolve(s.worktreePath));let n=[],o=new Set;for(let s of r){let i=0,a;try{a=ye(s,["worktree","list","--porcelain"],{allowFailure:!0})}catch{continue}let u=Su(a);for(let l of u){if(i>=xu)break;let c=L.resolve(l.path);if(c===L.resolve(s)||!vu(c,e.worktreesDir)||t.has(c)||o.has(c)||!is(c))continue;let m=L.relative(e.worktreesDir,c).split(L.sep),g=m[0],p=m[1]??"unknown";o.add(c),i+=1,n.push({kind:"remove_worktree",path:c,bytes:null,runId:g,worker:p,repo:s,ageMs:bu(c,e.now)})}}return n}ae();b();import He from"node:path";function us(e,r){let t=He.resolve(r),n=new Map;for(let[o,s]of e){let i=s.harnessRoot?He.resolve(s.harnessRoot):null;i&&i!==t||n.set(o,s)}return n}function ls(e){let r=new Map;for(let t of ir(e))for(let n of Object.keys(t.workers||{})){let o=He.join(De(e,t.id),"workers",v(n),"worker.json"),s=x(o,void 0);s?.worktreePath&&r.set(He.resolve(s.worktreePath),{harnessRoot:e,worktreePath:He.resolve(s.worktreePath),runId:t.id,workerName:n,run:t,worker:s})}return r}function Le(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function ke(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)&&n>=0?n:r}function cs(e={}){let r=e.execute===!0||e.execute!==!1&&Le("KYNVER_CLEANUP_EXECUTE"),t=e.finalizeStaleRuns!==!1&&!Le("KYNVER_CLEANUP_SKIP_FINALIZE"),n=e.nodeModulesAgeMs??ke("KYNVER_CLEANUP_NODE_MODULES_AGE_MS",216e5),o=e.scanDependencyCaches??(e.nodeModulesAgeMs!==void 0||process.env.KYNVER_CLEANUP_NODE_MODULES_AGE_MS!=null),s=e.worktreesAgeMs??ke("KYNVER_CLEANUP_WORKTREES_AGE_MS",0),i=e.terminalWorktreesAgeMs??ke("KYNVER_CLEANUP_TERMINAL_WORKTREES_AGE_MS",216e5),a=e.runDirectoriesAgeMs??ke("KYNVER_CLEANUP_RUN_DIRECTORIES_AGE_MS",36e5),u=e.maxActionsPerSweep??ke("KYNVER_CLEANUP_MAX_ACTIONS_PER_SWEEP",120),l=e.includeOrphans===!0||Le("KYNVER_CLEANUP_INCLUDE_ORPHANS"),d=Le("KYNVER_CLEANUP_SCOPE_ALL")||process.env.KYNVER_CLEANUP_SCOPE==="all"?e.runIdFilter:e.runIdFilter??(process.env.KYNVER_CLEANUP_RUN_ID||void 0),m=e.accountBytes!==!1&&!Le("KYNVER_CLEANUP_SKIP_BYTE_ACCOUNTING"),g=ke("KYNVER_CLEANUP_STORAGE_ENTRY_CAP",2e3),p=e.storagePerRunEntryCap!==void 0?e.storagePerRunEntryCap:m&&g>0?g:null,R=ke("KYNVER_CLEANUP_BYTE_ENTRY_CAP",2e3),S=e.byteAccountingEntryCap??(Number.isFinite(R)&&R>0?Math.floor(R):2e3);return{execute:r,finalizeStaleRuns:t,scanDependencyCaches:o,nodeModulesAgeMs:n,worktreesAgeMs:s>0?s:0,terminalWorktreesAgeMs:i>=0?i:0,runDirectoriesAgeMs:a>=0?a:0,maxActionsPerSweep:Number.isFinite(u)&&u>0?Math.floor(u):120,includeOrphans:l,runIdFilter:d?String(d):void 0,accountBytes:m,storagePerRunEntryCap:p,byteAccountingEntryCap:S}}F();import{existsSync as Nt,statSync as Cu}from"node:fs";import Nr from"node:path";b();var Eu=1800*1e3;function ds(e){let r=e.now??Date.now(),t=e.heartbeatFreshMs??Eu;if(!Nt(e.worktreePath))return null;if(e.runId&&e.workerName){let l=Nr.join(e.harnessRoot,"runs",e.runId,"workers",e.workerName),c=x(Nr.join(l,"worker.json"),void 0);if(c&&xt(c,r,t))return"active_worker";if(!c){let d=Nr.join(l,"heartbeat.jsonl");if(Nt(d))try{let m=r-Cu(d).mtimeMs;if(Number.isFinite(m)&&m>=0&&m<t)return"active_worker"}catch{}}}let n=Nr.join(e.worktreePath,".git");if(!Nt(n))return null;let o=w(e.worktreePath,["status","--porcelain"]);if(o.status!==0)return"pr_or_unmerged_commits";let s=o.stdout.split(`
15
- `).map(l=>l.trim()).filter(l=>l.length>0);if(D(s).length>0)return"dirty_worktree";let i=w(e.worktreePath,["rev-list","--count","@{u}..HEAD"]);if(i.status===0){let l=Number(i.stdout.trim());if(Number.isFinite(l)&&l>0)return"pr_or_unmerged_commits"}let a=w(e.worktreePath,["rev-list","--count","origin/main..HEAD"]);if(a.status!==0)return i.status!==0?"pr_or_unmerged_commits":null;let u=Number(a.stdout.trim());return Number.isFinite(u)&&u>0?"pr_or_unmerged_commits":null}Y();import{existsSync as wu,readdirSync as ps,statSync as Au}from"node:fs";import Pu from"node:path";function ms(e={}){let r=I(e.harnessRoot??ee()),t=we(r),n=e.now??Date.now(),o=new Date(n).toISOString();if(!wu(t))return{harnessRoot:r,worktreesDir:t,worktreesBytes:0,runCount:0,workerCount:0,oldestRunAt:null,scannedAt:o};let s=0,i=0,a=0,u=null,l;try{l=ps(t,{withFileTypes:!0})}catch{return{harnessRoot:r,worktreesDir:t,worktreesBytes:null,runCount:0,workerCount:0,oldestRunAt:null,scannedAt:o}}for(let c of l){if(!c.isDirectory())continue;i+=1;let d=Pu.join(t,c.name);try{let m=Au(d);u=u===null?m.mtimeMs:Math.min(u,m.mtimeMs)}catch{}try{for(let m of ps(d,{withFileTypes:!0}))m.isDirectory()&&(a+=1)}catch{}if(s!==null&&e.perRunEntryCap!==null){let m=e.perRunEntryCap??5e4;if(m<=0)s=null;else{let g=X(d,m);g===null?s=null:s+=g}}}return{harnessRoot:r,worktreesDir:t,worktreesBytes:s,runCount:i,workerCount:a,oldestRunAt:u===null?null:new Date(u).toISOString(),scannedAt:o}}Y();import{existsSync as Ou}from"node:fs";import{homedir as Iu}from"node:os";import fs from"node:path";var Du=["/var/tmp/kynver-harness",fs.join(Iu(),".openclaw","harness")];function Wt(e,r,t){if(!t?.trim())return;let n=I(t.trim());e.has(n)||(e.add(n),r.push(n))}function Nu(e){return e.scanWellKnown!=null?e.scanWellKnown:process.env.VITEST==="true"?!1:process.env.KYNVER_CLEANUP_SCAN_WELL_KNOWN!=="0"&&!["0","false","no"].includes((process.env.KYNVER_CLEANUP_SCAN_WELL_KNOWN??"").toLowerCase())}function gs(e={}){let r=new Set,t=[];Wt(r,t,e.harnessRoot??ee());let n=process.env.KYNVER_CLEANUP_EXTRA_ROOTS?.split(",").map(o=>o.trim()).filter(Boolean);for(let o of n??[])Wt(r,t,o);if(Nu(e))for(let o of Du){let s=fs.resolve(o);!r.has(s)&&Ou(s)&&Wt(r,t,s)}return t}or();function Wu(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function Mu(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function hs(e={}){let r=e.diskPath?.trim()||process.env.KYNVER_DISK_GUARD_PATH?.trim()||"/",t=Mu("KYNVER_DISK_GUARD_MAX_USED_PERCENT",75),n=nr({...e,diskPath:r,diskMaxUsedPercent:e.diskMaxUsedPercent??t}),o=!n.ok||n.usedPercent>=t,s=process.env.KYNVER_CLEANUP_DISK_PRESSURE_FORCE?.trim().toLowerCase();return s==="none"||s==="off"||s==="0"?o=!1:(s==="pressured"||s==="on"||s==="1")&&(o=!0),{diskGate:n,pressured:o,maxUsedPercent:t}}function ks(e,r){if(!r.pressured)return e;let t=e.execute||!Wu("KYNVER_CLEANUP_DRY_RUN_ON_PRESSURE");return{...e,execute:t,nodeModulesAgeMs:0,runIdFilter:void 0,includeOrphans:!0,terminalWorktreesAgeMs:0,runDirectoriesAgeMs:0,worktreesAgeMs:e.worktreesAgeMs>0?e.worktreesAgeMs:6048e5,diskPressure:!0,diskGate:r.diskGate}}tr();import{unlinkSync as Tu}from"node:fs";function Wr(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function Rs(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function Uu(e,r,t){return e.length===0?[]:t?[...e]:e.length<=r?[]:e.slice(r)}function ys(e={}){let r=e.execute===!0||Wr("KYNVER_WSL_CRASH_DUMP_EXECUTE")||Wr("KYNVER_CLEANUP_EXECUTE"),t=e.purgeAll===!0||Wr("KYNVER_WSL_CRASH_DUMP_PURGE_ALL"),n=Math.max(0,e.keepNewest??Rs("KYNVER_WSL_CRASH_DUMP_KEEP_NEWEST",t?0:1)),o=ve({forceWsl:e.forceWsl});if(!o?.path)return{observation:o,execute:r,keepNewest:n,removed:[],removedBytes:0,skipped:o?.probeError?[{path:o.path??"(unresolved)",reason:o.probeError}]:[]};let s=Uu(o.dumps,n,t),i=[],a=[],u=0;for(let l of s){if(!r){a.push({path:l.path,reason:"dry_run"});continue}try{Tu(l.path),i.push({path:l.path,bytes:l.bytes,name:l.name}),u+=l.bytes}catch(c){a.push({path:l.path,reason:c.message})}}return{observation:o,execute:r,keepNewest:n,removed:i,removedBytes:u,skipped:a}}function bs(e){return e?Wr("KYNVER_WSL_CRASH_DUMP_CLEANUP")||!e.ok?!0:e.dumpCount>Rs("KYNVER_WSL_CRASH_DUMP_KEEP_NEWEST",1):!1}tr();function W(e,r){if(process.env.KYNVER_CLEANUP_QUIET==="1")return;let t=r?`: ${r}`:"";console.error(`[kynver cleanup] ${e}${t}`)}F();var Mr=class{aheadOfMain=new Map;countAheadOfMain(r,t="origin/main"){let n=`${r}\0${t}`;if(this.aheadOfMain.has(n))return this.aheadOfMain.get(n)??null;let o=w(r,["rev-list","--count",`${t}..HEAD`]);if(o.status!==0)return this.aheadOfMain.set(n,null),null;let s=Number(o.stdout.trim()),i=Number.isFinite(s)?s:null;return this.aheadOfMain.set(n,i),i}};import{spawnSync as Bu}from"node:child_process";import{existsSync as Ku}from"node:fs";import Fu from"node:path";var Hu=5e3;function Lu(e,r){if(!Ku(Fu.join(e,".git")))return{status:null,stdout:"",stderr:"",error:"not_a_git_repo"};try{let t=Bu("git",r,{cwd:e,encoding:"utf8",timeout:Hu}),n=t.error?.message?.includes("ETIMEDOUT")===!0;return{status:n?null:t.status,stdout:t.stdout||"",stderr:t.stderr||"",error:n?"git_timeout":t.error?t.error.message:null}}catch(t){return{status:null,stdout:"",stderr:"",error:t.message}}}function Ss(e){let r=Lu(e,["status","--short"]);return r.error==="not_a_git_repo"?[]:r.error==="git_timeout"||r.status!==0?null:r.stdout.split(`
16
- `).map(t=>t.trim()).filter(Boolean)}var Tr=class{cache=new Map;porcelain(r){let t=r,n=this.cache.get(t);if(n!==void 0)return n;let o=Ss(t)??[];return this.cache.set(t,o),o}};var Ur=class{cache=new Map;derive(r){let t=this.cache.get(r.id);if(t!==void 0)return t;let n=ge(r);return this.cache.set(r.id,n),n}};function ju(e){let r={};for(let t of e)r[t.kind]=(r[t.kind]??0)+1;return r}function vs(e,r={}){let t=r.maxSampleActions??12,n=r.maxSampleSkips??8;return{harnessRoot:e.harnessRoot,scanRoots:e.scanRoots,dryRun:e.dryRun,execute:e.execute,scannedAt:e.scannedAt,finalizedRuns:e.finalizedRuns.length,actionCount:e.actions.length,actionKinds:ju(e.actions),totals:e.totals,...e.storage?{storage:e.storage}:{},...e.preservedLivePaths?.length?{preservedLivePaths:e.preservedLivePaths}:{},...e.removedRunDirectories!=null?{removedRunDirectories:e.removedRunDirectories}:{},sampleActions:e.actions.slice(0,t).map(o=>({kind:o.kind,path:o.path,...o.skipReason?{skipReason:o.skipReason}:{},...o.bytes!=null?{bytes:o.bytes}:{},...o.runId?{runId:o.runId}:{},...o.worker?{worker:o.worker}:{}})),sampleSkips:e.skips.slice(0,n)}}function $u(e={}){let r=e.harnessRoot?I(e.harnessRoot):ee(),t=gs({harnessRoot:r}),n=e.now??Date.now();return{harnessRoot:r,scanRoots:t,now:n}}function Gu(e){return typeof e=="string"?{reason:e}:e}function Pe(e,r,t,n){e.push({path:r,reason:t,...n?{detail:n}:{}})}function Br(e,r,t){return!r||e.bytes!=null?e:{...e,bytes:X(e.path,t)}}function xs(e,r){let t={};for(let n of r)t[n.reason]=(t[n.reason]??0)+1;for(let n of e)n.skipReason&&(t[n.skipReason]=(t[n.skipReason]??0)+1);return t}function Yu(e,r){return e.kind==="remove_next_cache"?zo(e,r):Vo(e,r)}function Vu(e,r,t){return e.kind==="remove_next_cache"?Pr(e.path,r,t):Ar(e.path,r,t)}function zu(e){let r=new Map;for(let t of e)for(let[n,o]of ls(t))r.set(n,o);return r}function _s(e,r){return e.runId&&e.worker?M.join(r,e.runId,e.worker):M.resolve(e.path,"..")}function Ju(e={}){let r=cs(e),t=hs();r=ks(r,t);let n=$u(e);W("scan",`${n.scanRoots.length} harness root(s)`);let o=Ao(n.scanRoots,n.now),s=r.finalizeStaleRuns?lo().map(h=>({runId:h.runId,from:h.from,to:h.to})):[];s.length>0&&W("finalize",`${s.length} stale run(s) marked terminal`),W("index","building worktree index");let i=zu(n.scanRoots);W("index",`${i.size} indexed worktree(s)`);let a={runTerminalCache:new Ur,gitStatusCache:new Tr,gitRevCache:new Mr},u=[],l=[],c=new Set,d=r.maxActionsPerSweep,m=()=>l.length>=d;for(let h of n.scanRoots){if(m())break;W("root",h);let q=M.join(h,"worktrees"),$e=us(i,h),Ge={harnessRoot:h,worktreesDir:q,nodeModulesAgeMs:r.nodeModulesAgeMs,worktreesAgeMs:r.worktreesAgeMs,includeOrphans:r.includeOrphans,runIdFilter:r.runIdFilter,index:$e,now:n.now},Kr=r.scanDependencyCaches?ss(Ge):[];W("dependency",r.scanDependencyCaches?`${Kr.length} cache candidate(s) at ${h}`:"skipped (worktree-only sweep)");let Fr=0;for(let T of Kr){if(m())break;Fr+=1,Fr%50===0&&W("dependency",`${Fr}/${Kr.length} evaluated`);let _=M.resolve(T.path);if(c.has(_))continue;c.add(_);let k={...T,path:_},O=Vu(k,h,q);if(O){Pe(u,k.path,O),l.push({...k,executed:!1,skipped:!0,skipReason:O});continue}let U=_s(k,q),Re=$e.get(M.resolve(U))??null,K=Ct({indexed:Re,includeOrphans:!0,nodeModulesAgeMs:r.nodeModulesAgeMs,ageMs:k.ageMs,worktreePath:U,activeWorktreePaths:o.activeWorktreePaths,diskPressure:r.diskPressure,gitStatusCache:a.gitStatusCache});if(K){Pe(u,k.path,K),l.push({...k,executed:!1,skipped:!0,skipReason:K});continue}l.push(Yu(Br(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}if(r.scanDependencyCaches)for(let T of es(Ge)){if(m())break;let _=M.resolve(T.path);if(c.has(_))continue;c.add(_);let k={...T,path:_},O=Or(k.path,h,q);if(O){Pe(u,k.path,O),l.push({...k,executed:!1,skipped:!0,skipReason:O});continue}let U=_s(k,q),Re=$e.get(M.resolve(U))??null,K=_o({indexed:Re,includeOrphans:!0,nodeModulesAgeMs:r.nodeModulesAgeMs,ageMs:k.ageMs,worktreePath:U,activeWorktreePaths:o.activeWorktreePaths,diskPressure:r.diskPressure,gitStatusCache:a.gitStatusCache});if(K){Pe(u,k.path,K),l.push({...k,executed:!1,skipped:!0,skipReason:K});continue}l.push(Jo(Br(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}let Hr=[...rs(Ge),...as(Ge)];W("worktrees",`${Hr.length} candidate(s) at ${h}`);let Mt=new Set,Lr=0;for(let T of Hr){if(m())break;Lr+=1,Lr%50===0&&W("worktrees",`${Lr}/${Hr.length} evaluated`);let _=M.resolve(T.path);if(Mt.has(_))continue;Mt.add(_);let k={...T,path:_},O=$e.get(M.resolve(k.path))??null,U=O?null:ds({worktreePath:k.path,harnessRoot:h,runId:k.runId,workerName:k.worker,now:n.now}),Re=xo({indexed:O,worktreePath:M.resolve(k.path),includeOrphans:r.includeOrphans,worktreesAgeMs:r.worktreesAgeMs,terminalWorktreesAgeMs:r.terminalWorktreesAgeMs,ageMs:k.ageMs,orphanSafety:U,worktreeRemovalGuard:e.worktreeRemovalGuard,liveness:a,now:n.now,harnessRoot:h,writeSalvageEvidence:r.execute});if(Re){let{reason:K,detail:Cs}=Gu(Re);Pe(u,k.path,K,Cs),l.push({...k,executed:!1,skipped:!0,skipReason:K});continue}l.push(qo(Br(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}if(!m()&&r.runDirectoriesAgeMs>=0)for(let T of Mo({harnessRoot:h,worktreesDir:q,runDirectoriesAgeMs:r.runDirectoriesAgeMs,runIdFilter:r.runIdFilter,activeGuards:o,now:n.now})){if(m())break;let _=M.resolve(T.path);if(c.has(_))continue;c.add(_);let k={...T,path:_},O=k.runId??M.basename(_),U=Wo({harnessRoot:h,runId:O,runPath:_,ageMs:k.ageMs,runDirectoriesAgeMs:r.runDirectoriesAgeMs,activeGuards:o});if(U){Pe(u,k.path,U),l.push({...k,executed:!1,skipped:!0,skipReason:U});continue}l.push(Xo(Br(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}}let g=0,p=0,R=0,S=0,y=0,A=0;for(let h of l)h.bytes&&(g+=h.bytes),!h.skipped&&!h.executed&&h.bytes&&(R+=h.bytes),h.executed?(y+=1,S+=h.bytes??0,h.kind==="remove_run_directory"&&(p+=1)):h.skipped&&(A+=1,h.skipReason==="dry_run"&&h.bytes&&(R+=h.bytes));let j=r.accountBytes?ms({harnessRoot:n.harnessRoot,now:n.now,perRunEntryCap:r.storagePerRunEntryCap}):void 0,B=ve(),je=r.execute&&bs(B),$=je?ys({execute:!0}):null,te=B?{observed:!0,execute:je,dumpCount:B.dumpCount,totalBytes:B.totalBytes,removedCount:$?.removed.length??0,removedBytes:$?.removedBytes??0,executables:B.executables,path:B.path,reason:B.reason}:void 0;$&&$.removed.length>0&&(S+=$.removedBytes,y+=$.removed.length,W("wsl-crashes",`removed ${$.removed.length} dump(s), ${$.removedBytes} bytes`)),W("complete",`${l.length} action(s), ${A} skipped, ${y} removed`);let ne=Eo(l,u),P=vs({harnessRoot:n.harnessRoot,scanRoots:n.scanRoots,dryRun:!r.execute,execute:r.execute,nodeModulesAgeMs:r.nodeModulesAgeMs,worktreesAgeMs:r.worktreesAgeMs,includeOrphans:r.includeOrphans,diskPressure:r.diskPressure,diskGate:r.diskGate?{ok:r.diskGate.ok,path:r.diskGate.path,freeBytes:r.diskGate.freeBytes,usedPercent:r.diskGate.usedPercent,reason:r.diskGate.reason}:void 0,scannedAt:new Date(n.now).toISOString(),finalizedRuns:s,actions:l,skips:u,totals:{candidateBytes:g,reclaimableBytes:R,removedBytes:S,removedPaths:y,skippedPaths:A,skipReasons:xs(l,u)},...j?{storage:j}:{},...ne.length>0?{preservedLivePaths:ne}:{},...p>0?{removedRunDirectories:p}:{},...te?{wslCrashDumps:te}:{}});return{harnessRoot:n.harnessRoot,scanRoots:n.scanRoots,dryRun:!r.execute,execute:r.execute,nodeModulesAgeMs:r.nodeModulesAgeMs,worktreesAgeMs:r.worktreesAgeMs,includeOrphans:r.includeOrphans,diskPressure:r.diskPressure,diskGate:r.diskGate?{ok:r.diskGate.ok,path:r.diskGate.path,freeBytes:r.diskGate.freeBytes,usedPercent:r.diskGate.usedPercent,reason:r.diskGate.reason}:void 0,scannedAt:new Date(n.now).toISOString(),finalizedRuns:s,actions:l,skips:u,totals:{candidateBytes:g,reclaimableBytes:R,removedBytes:S,removedPaths:y,skippedPaths:A,skipReasons:xs(l,u)},...j?{storage:j}:{},...ne.length>0?{preservedLivePaths:ne}:{},...p>0?{removedRunDirectories:p}:{},...te?{wslCrashDumps:te}:{},compactSummary:P}}export{wr as DEFAULT_MAX_ACTIONS_PER_SWEEP,Et as DEFAULT_NODE_MODULES_AGE_MS,wt as DEFAULT_RUN_DIRECTORIES_AGE_MS,Er as DEFAULT_WORKTREES_AGE_MS,Ju as runHarnessCleanup};
12
+ `),n=!0)}let o={capturedAt:new Date(e.now??Date.now()).toISOString(),skipReason:e.skipReason,runId:e.indexed.runId,workerName:e.indexed.workerName,worktreePath:e.indexed.worktreePath,taskId:e.indexed.worker.taskId,agentOsId:e.indexed.worker.agentOsId,branch:e.indexed.worker.branch,completionBlocker:e.indexed.worker.completionBlocker,finalResult:e.status.finalResult,changedFiles:e.status.changedFiles,gitAncestry:e.status.gitAncestry,prUrl:e.status.prUrl??null,...n?{patchPath:t}:{}};return Ro(Cr.join(r,"evidence.json"),`${JSON.stringify(o,null,2)}
13
+ `),o}var Ga=new Set(["completion_blocked","dirty_worktree","pr_or_unmerged_commits","landing_blocked"]);function Ya(e){return!Ga.has(e.skipReason)||J(e.indexed,e.now)?!1:So({harnessRoot:e.harnessRoot,runId:e.indexed.runId,workerName:e.indexed.workerName})?!0:e.writeSalvageEvidence?(vo({harnessRoot:e.harnessRoot,indexed:e.indexed,skipReason:e.skipReason,status:e.status,now:e.now}),!0):!1}function Va(e){let{indexed:r,worktreesAgeMs:t,terminalWorktreesAgeMs:n}=e;return r&&(fe.has(r.run.status)||e.liveness&&_t(r,e.liveness)||e.liveness&&le(vt(r,e.liveness))&&!J(r))?n:t}function za(e){return!e.indexed||e.includeOrphans&&e.worktreesAgeMs<=0?0:Va(e)}function Ja(e,r){if(e.harnessRoot?.trim())return Er.resolve(e.harnessRoot);let t=r.worker.workerDir;if(!t)return null;let n=`${Er.sep}runs${Er.sep}`,o=t.indexOf(n);return o<0?null:t.slice(0,o+n.length-1)}function xo(e){let{indexed:r,includeOrphans:t,worktreesAgeMs:n,ageMs:o,orphanSafety:s,worktreeRemovalGuard:i}=e,a=e.now??Date.now();if(!r)return t?s??null:"orphan_without_flag";let u=za(e);if(n<=0&&!t&&u<=0)return"worktrees_disabled";if(u>0&&o<u)return"below_age_threshold";if(J(r,a))return"active_worker";let l=vt(r,e.liveness),c=Ja(e,r),d=p=>c&&Ya({indexed:r,harnessRoot:c,skipReason:p,status:l,now:a,writeSalvageEvidence:e.writeSalvageEvidence===!0})?null:p;if(ko(r,l)){let p=d("completion_blocked");if(p)return p}if(St(r,e.liveness?.gitStatusCache)){let p=d("dirty_worktree");if(p)return p}let m=e.liveness?.gitRevCache?.countAheadOfMain(e.worktreePath);if(m!=null&&m>0){let p=d("pr_or_unmerged_commits");if(p)return p}if(ho(r,e.liveness,a)||!le(l))return"run_still_active";if(Be(l)){let p=d("pr_or_unmerged_commits");if(p)return p}if(D(l.changedFiles).length>0){let p=d("dirty_worktree");if(p)return p}if(Ce({finalResult:l.finalResult,changedFiles:l.changedFiles,gitAncestry:l.gitAncestry,prUrl:me(l.finalResult)}).blocked){let p=d("landing_blocked");if(p)return p}if(i&&e.worktreePath){let p=i({worktreePath:e.worktreePath,indexed:!!r,runId:r?.runId,worker:r?.workerName});if(p)return p.detail?{reason:p.reason,detail:p.detail}:p.reason}return null}function Ct(e){let{indexed:r,nodeModulesAgeMs:t,ageMs:n,worktreePath:o,activeWorktreePaths:s,diskPressure:i}=e;return!i&&n<t?"below_age_threshold":s.has(Er.resolve(o))||r&&J(r)?"active_worker":r&&St(r,e.gitStatusCache)?"dirty_worktree":null}function _o(e){return Ct(e)}var Et=216e5,wr=6048e5;var wt=36e5,Ar=120;var Co=new Set(["active_worker","run_still_active","completion_blocked","landing_blocked"]);function Eo(e,r){let t=[],n=new Set,o=(s,i,a)=>{let u=`${s}\0${i}`;n.has(u)||t.length>=24||(n.add(u),t.push({path:s,reason:i,...a?{detail:a}:{}}))};for(let s of r)Co.has(s.reason)&&o(s.path,s.reason,s.detail);for(let s of e)!s.skipped||!s.skipReason||Co.has(s.skipReason)&&o(s.path,s.skipReason);return t}import{existsSync as Oo,readdirSync as Io,statSync as Za}from"node:fs";import Do from"node:path";ae();Y();import wo from"node:path";b();function qa(e,r){return _r(e,r)}function Ao(e,r=Date.now()){let t=new Set,n=new Set;for(let o of e){for(let s of ar(o)){let i=!1;for(let a of Object.keys(s.workers||{})){let u=x(wo.join(De(o,s.id),"workers",v(a),"worker.json"),void 0);if(!u?.worktreePath)continue;let l=wo.resolve(u.worktreePath);qa(u,r)&&(i=!0,t.add(l))}i&&n.add(`${o}\0${s.id}`)}for(let s of go(o))n.add(s)}return{activeWorktreePaths:t,liveRunKeys:n}}function Po(e,r,t,n){return t?n.has(`${r}\0${t}`):!1}b();function Qa(e,r){try{let t=Za(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function eu(e,r){let t=Do.join(e,"runs",r,"run.json");return Oo(t)?x(t,null):null}function No(e){try{return Io(e).length===0}catch{return!1}}function Wo(e){let{harnessRoot:r,runId:t,runPath:n,ageMs:o,runDirectoriesAgeMs:s,activeGuards:i}=e;if(Po(n,r,t,i.liveRunKeys)||!No(n))return"run_still_active";let a=eu(r,t);return a&&!fe.has(a.status)&&!ge(a)?"run_still_active":s>0&&o<s?"below_age_threshold":null}function Mo(e){if(!Oo(e.worktreesDir))return[];let r=[],t;try{t=Io(e.worktreesDir,{withFileTypes:!0})}catch{return[]}for(let n of t){if(!n.isDirectory())continue;let o=n.name;if(e.runIdFilter&&o!==e.runIdFilter)continue;let s=Do.join(e.worktreesDir,o);No(s)&&r.push({kind:"remove_run_directory",path:s,bytes:null,harnessRoot:e.harnessRoot,runId:o,ageMs:Qa(s,e.now)})}return r}F();import{existsSync as Pt,rmSync as Yo}from"node:fs";import{execFileSync as ru}from"node:child_process";import{existsSync as To,readdirSync as tu,statSync as nu}from"node:fs";import ou from"node:path";var su=2500;function iu(e,r=su){if(!To(e))return 0;try{let n=ru("du",["-sb",e],{encoding:"utf8",timeout:r,stdio:["ignore","pipe","ignore"]}).trim().split(/\s+/)[0],o=Number(n);return Number.isFinite(o)&&o>=0?o:null}catch{return null}}function X(e,r=5e4){if(!To(e))return 0;let t=iu(e);if(t!==null)return t;let n=0,o=0,s=[e];for(;s.length>0;){let i=s.pop(),a;try{a=tu(i)}catch{continue}for(let u of a){if(o++>r)return null;let l=ou.join(i,u),c;try{c=nu(l)}catch{continue}c.isDirectory()?s.push(l):n+=c.size}}return n}import{existsSync as cu,rmSync as du}from"node:fs";Y();import{lstatSync as au,readdirSync as uu}from"node:fs";function Uo(e){try{let r=au(e),t=typeof process.getuid=="function"?process.getuid():null,n=typeof process.getgid=="function"?process.getgid():null,o=t!==null&&(r.uid!==t||n!==null&&r.gid!==n);return{uid:r.uid,gid:r.gid,foreign:o}}catch{return null}}function Bo(e,r=32){let t=Uo(e);if(!t)return!1;if(t.foreign)return!0;try{let n=uu(e),o=0;for(let s of n){if(o>=r)break;let i=`${e.replace(/\/$/,"")}/${s}`,a=Uo(i);if(o+=1,a?.foreign)return!0}}catch{}return!1}import{spawnSync as lu}from"node:child_process";import Ho from"node:path";import N from"node:path";function Ko(e,r,t,n){let o=N.resolve(e),s=`${N.sep}${n}`,i=o.endsWith(s)?o:null;if(!i)return"path_outside_harness";let a=N.relative(t,i);if(a.startsWith("..")||N.isAbsolute(a))return"path_outside_harness";let u=a.split(N.sep);return u.length<3||u[u.length-1]!==n||!o.startsWith(N.resolve(r))?"path_outside_harness":null}function Pr(e,r,t){return Ko(e,r,t,"node_modules")}function Or(e,r,t){return Ko(e,r,t,".next")}function Ir(e,r,t){let n=N.resolve(e),o=N.relative(t,n);return o.startsWith("..")||N.isAbsolute(o)||o.split(N.sep).length<3||!n.startsWith(N.resolve(r))?"path_outside_harness":null}function Fo(e,r,t){let n=N.resolve(e);return Pr(n,r,t)===null||Or(n,r,t)===null||Ir(n,r,t)===null}function jo(){let e=(process.env.KYNVER_CLEANUP_PRIVILEGED??"auto").trim().toLowerCase();return e==="0"||e==="false"||e==="off"||e==="no"?"off":e==="1"||e==="true"||e==="force"||e==="yes"?"force":"auto"}function Lo(e){let r=lu("sudo",["-n",...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{ok:r.status===0,stderr:`${r.stderr??""}${r.stdout??""}`.trim()}}function $o(e,r,t){if(!Fo(e,r,t))return{ok:!1,error:"path is not an allowed harness generated cache"};let n=typeof process.getuid=="function"?process.getuid():null,o=typeof process.getgid=="function"?process.getgid():null;if(n===null||o===null)return{ok:!1,error:"privileged reclaim requires POSIX uid/gid"};let s=Lo(["chown","-R",`${n}:${o}`,Ho.resolve(e)]);if(s.ok)return{ok:!0,method:"chown_then_rm"};let i=Lo(["rm","-rf",Ho.resolve(e)]);return i.ok?{ok:!0,method:"sudo_rm"}:{ok:!1,error:s.stderr||i.stderr||"sudo -n failed (password required or not permitted)"}}var At="Root-owned harness caches require operator reclaim: configure passwordless sudo for chown/rm under ~/.kynver/harness/worktrees, or run `node scripts/reclaim-harness-root-owned-cache.mjs --execute` as the harness owner with sudo available. See docs/runbooks/harness-root-owned-cache-reclaim.md.";function pu(e){let r=e?.code;return r==="EACCES"||r==="EPERM"}function Go(e,r,t={}){if(!cu(e.path))return{executed:!1,skipped:!0,skipReason:"missing_worktree"};if(!r)return{executed:!1,skipped:!0,skipReason:"dry_run"};let n=e.harnessRoot,o=n?we(n):null,i=e.bytes??X(e.path)??void 0,a=t.removePath??du,u=t.hasForeignOwnedEntry??Bo;try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i}}catch(l){if(!pu(l)||!n||!o)return{executed:!1,skipped:!0,skipReason:"remove_failed",error:l.message};let c=u(e.path),d=jo();if(!(d==="force"||d==="auto"&&c))return c?{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${l.message}; ${At}`}:{executed:!1,skipped:!0,skipReason:"remove_failed",error:l.message};let g=$o(e.path,n,o);if(g.ok&&g.method==="sudo_rm")return{executed:!0,skipped:!1,bytes:i,privilegedReclaim:!0};if(g.ok)try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i,privilegedReclaim:!0}}catch(p){return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${p.message}; privileged chown succeeded but rm still failed`}}return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${l.message}; privileged reclaim failed: ${g.error}; ${At}`}}}function Ot(e){let r=e.harnessRoot;return!r||!fo(e.path,r)?null:{...e,executed:!1,skipped:!0,skipReason:"run_metadata_protected"}}function It(e,r){let t=Ot(e);if(t)return t;let n=Go(e,r);return{...e,bytes:n.bytes??e.bytes,executed:n.executed,skipped:n.skipped,skipReason:n.skipReason,error:n.error}}function Vo(e,r){return It(e,r)}function zo(e,r){return It(e,r)}function Jo(e,r){return It(e,r)}function Xo(e,r){let t=Ot(e);if(t)return t;if(!Pt(e.path))return{...e,executed:!1,skipped:!0,skipReason:"missing_worktree"};if(!r)return{...e,executed:!1,skipped:!0,skipReason:"dry_run"};try{let n=e.bytes??X(e.path);return Yo(e.path,{recursive:!0,force:!0}),{...e,bytes:n,executed:!0,skipped:!1}}catch(n){return{...e,executed:!1,skipped:!0,skipReason:"remove_failed",error:n.message}}}function qo(e,r){let t=Ot(e);if(t)return t;if(!Pt(e.path))return{...e,executed:!1,skipped:!0,skipReason:"missing_worktree"};if(!r)return{...e,executed:!1,skipped:!0,skipReason:"dry_run"};let n=e.repo;try{let o=e.bytes??X(e.path);return n&&ye(n,["worktree","remove","--force",e.path],{allowFailure:!0}),Pt(e.path)&&Yo(e.path,{recursive:!0,force:!0}),{...e,bytes:o,executed:!0,skipped:!1}}catch(o){return{...e,executed:!1,skipped:!0,skipReason:"remove_failed",error:o.message}}}import{existsSync as Dr,readdirSync as Nr,statSync as mu}from"node:fs";import H from"node:path";function Dt(e,r){try{let t=mu(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function Qo(e,r){let t=H.relative(r,e);return t===""||!t.startsWith("..")&&!H.isAbsolute(t)}function Zo(e,r,t,n){let o=[];for(let s of bt){if(s===".next")continue;let i=H.join(e,s);if(!Dr(i))continue;let a=H.resolve(i);t.has(a)||Qo(a,r.harnessRoot)&&(t.add(a),o.push({kind:"remove_build_cache",path:a,bytes:null,runId:n.runId,worker:n.worker,repo:n.repo,ageMs:Dt(a,r.now)}))}return o}function es(e){let r=[],t=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||r.push(...Zo(n.worktreePath,e,t,{runId:n.runId,worker:n.workerName,repo:n.run.repo}));if(!e.includeOrphans||!Dr(e.worktreesDir))return r;for(let n of Nr(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=H.join(e.worktreesDir,n.name);for(let s of Nr(o,{withFileTypes:!0})){if(!s.isDirectory())continue;let i=H.join(o,s.name);r.push(...Zo(i,e,t,{runId:n.name,worker:s.name}))}}return r}function rs(e){let r=e.worktreesAgeMs>0||e.includeOrphans,t=e.includeOrphans;if(!r&&!t)return[];let n=[],o=new Set;if(r)for(let i of e.index.values()){if(e.runIdFilter&&i.runId!==e.runIdFilter)continue;let a=i.worktreePath;Dr(a)&&(o.has(a)||(o.add(a),n.push({kind:"remove_worktree",path:a,bytes:null,runId:i.runId,worker:i.workerName,repo:i.run.repo,ageMs:Dt(a,e.now)})))}if(!t||!Dr(e.worktreesDir))return n;let s=new Set;for(let i of e.index.values())s.add(H.resolve(i.worktreePath));for(let i of Nr(e.worktreesDir,{withFileTypes:!0})){if(!i.isDirectory()||e.runIdFilter&&i.name!==e.runIdFilter)continue;let a=H.join(e.worktreesDir,i.name),u;try{u=Nr(a,{withFileTypes:!0})}catch{continue}for(let l of u){if(!l.isDirectory())continue;let c=H.resolve(H.join(a,l.name));o.has(c)||s.has(c)||Qo(c,e.harnessRoot)&&(o.add(c),n.push({kind:"remove_worktree",path:c,bytes:null,runId:i.name,worker:l.name,ageMs:Dt(c,e.now)}))}}return n}import{existsSync as os,readdirSync as ts,statSync as fu}from"node:fs";import Ae from"node:path";var gu=[{dirName:"node_modules",kind:"remove_node_modules"},{dirName:".next",kind:"remove_next_cache"}];function hu(e,r){try{let t=fu(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function ku(e,r){let t=Ae.relative(r,e);return t===""||!t.startsWith("..")&&!Ae.isAbsolute(t)}function Ru(e,r,t,n,o,s){if(!os(n))return;let i=Ae.resolve(n);r.has(i)||ku(i,t.harnessRoot)&&(r.add(i),e.push({kind:o,path:i,bytes:null,harnessRoot:t.harnessRoot,runId:s.runId,worker:s.worker,repo:s.repo,ageMs:hu(i,t.now)}))}function ns(e,r,t,n,o){for(let s of gu)Ru(e,r,t,Ae.join(n,s.dirName),s.kind,o)}function ss(e){let r=[],t=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||ns(r,t,e,n.worktreePath,{runId:n.runId,worker:n.workerName,repo:n.run.repo});if(!e.includeOrphans||!os(e.worktreesDir))return r;for(let n of ts(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory()||e.runIdFilter&&n.name!==e.runIdFilter)continue;let o=Ae.join(e.worktreesDir,n.name),s;try{s=ts(o,{withFileTypes:!0})}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=Ae.join(o,i.name);ns(r,t,e,a,{runId:n.name,worker:i.name})}}return r}F();import{existsSync as is,statSync as yu}from"node:fs";import L from"node:path";function bu(e,r){try{let t=yu(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function Su(e){let r=[],t=null;for(let n of e.split(`
14
+ `)){if(!n.trim())continue;let[o,...s]=n.split(" "),i=s.join(" ");if(o==="worktree"){t&&r.push(t),t={path:i};continue}t&&(o==="branch"&&(t.branch=i),o==="HEAD"&&(t.head=i),o==="bare"&&(t.bare=!0))}return t&&r.push(t),r}function vu(e,r){let t=L.relative(L.resolve(r),L.resolve(e));return t!==""&&!t.startsWith("..")&&!L.isAbsolute(t)}var xu=200;function as(e){if(!e.includeOrphans||!is(e.worktreesDir))return[];let r=new Set;for(let s of e.index.values())s.run.repo&&r.add(L.resolve(s.run.repo));let t=new Set;for(let s of e.index.values())t.add(L.resolve(s.worktreePath));let n=[],o=new Set;for(let s of r){let i=0,a;try{a=ye(s,["worktree","list","--porcelain"],{allowFailure:!0})}catch{continue}let u=Su(a);for(let l of u){if(i>=xu)break;let c=L.resolve(l.path);if(c===L.resolve(s)||!vu(c,e.worktreesDir)||t.has(c)||o.has(c)||!is(c))continue;let m=L.relative(e.worktreesDir,c).split(L.sep),g=m[0],p=m[1]??"unknown";o.add(c),i+=1,n.push({kind:"remove_worktree",path:c,bytes:null,runId:g,worker:p,repo:s,ageMs:bu(c,e.now)})}}return n}ae();b();import He from"node:path";function us(e,r){let t=He.resolve(r),n=new Map;for(let[o,s]of e){let i=s.harnessRoot?He.resolve(s.harnessRoot):null;i&&i!==t||n.set(o,s)}return n}function ls(e){let r=new Map;for(let t of ar(e))for(let n of Object.keys(t.workers||{})){let o=He.join(De(e,t.id),"workers",v(n),"worker.json"),s=x(o,void 0);s?.worktreePath&&r.set(He.resolve(s.worktreePath),{harnessRoot:e,worktreePath:He.resolve(s.worktreePath),runId:t.id,workerName:n,run:t,worker:s})}return r}function Le(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function ke(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)&&n>=0?n:r}function cs(e={}){let r=e.execute===!0||e.execute!==!1&&Le("KYNVER_CLEANUP_EXECUTE"),t=e.finalizeStaleRuns!==!1&&!Le("KYNVER_CLEANUP_SKIP_FINALIZE"),n=e.nodeModulesAgeMs??ke("KYNVER_CLEANUP_NODE_MODULES_AGE_MS",216e5),o=e.scanDependencyCaches??(e.nodeModulesAgeMs!==void 0||process.env.KYNVER_CLEANUP_NODE_MODULES_AGE_MS!=null),s=e.worktreesAgeMs??ke("KYNVER_CLEANUP_WORKTREES_AGE_MS",0),i=e.terminalWorktreesAgeMs??ke("KYNVER_CLEANUP_TERMINAL_WORKTREES_AGE_MS",216e5),a=e.runDirectoriesAgeMs??ke("KYNVER_CLEANUP_RUN_DIRECTORIES_AGE_MS",36e5),u=e.maxActionsPerSweep??ke("KYNVER_CLEANUP_MAX_ACTIONS_PER_SWEEP",120),l=e.includeOrphans===!0||Le("KYNVER_CLEANUP_INCLUDE_ORPHANS"),d=Le("KYNVER_CLEANUP_SCOPE_ALL")||process.env.KYNVER_CLEANUP_SCOPE==="all"?e.runIdFilter:e.runIdFilter??(process.env.KYNVER_CLEANUP_RUN_ID||void 0),m=e.accountBytes!==!1&&!Le("KYNVER_CLEANUP_SKIP_BYTE_ACCOUNTING"),g=ke("KYNVER_CLEANUP_STORAGE_ENTRY_CAP",2e3),p=e.storagePerRunEntryCap!==void 0?e.storagePerRunEntryCap:m&&g>0?g:null,R=ke("KYNVER_CLEANUP_BYTE_ENTRY_CAP",2e3),S=e.byteAccountingEntryCap??(Number.isFinite(R)&&R>0?Math.floor(R):2e3);return{execute:r,finalizeStaleRuns:t,scanDependencyCaches:o,nodeModulesAgeMs:n,worktreesAgeMs:s>0?s:0,terminalWorktreesAgeMs:i>=0?i:0,runDirectoriesAgeMs:a>=0?a:0,maxActionsPerSweep:Number.isFinite(u)&&u>0?Math.floor(u):120,includeOrphans:l,runIdFilter:d?String(d):void 0,accountBytes:m,storagePerRunEntryCap:p,byteAccountingEntryCap:S}}F();import{existsSync as Nt,statSync as Cu}from"node:fs";import Wr from"node:path";b();var Eu=1800*1e3;function ds(e){let r=e.now??Date.now(),t=e.heartbeatFreshMs??Eu;if(!Nt(e.worktreePath))return null;if(e.runId&&e.workerName){let l=Wr.join(e.harnessRoot,"runs",e.runId,"workers",e.workerName),c=x(Wr.join(l,"worker.json"),void 0);if(c&&xt(c,r,t))return"active_worker";if(!c){let d=Wr.join(l,"heartbeat.jsonl");if(Nt(d))try{let m=r-Cu(d).mtimeMs;if(Number.isFinite(m)&&m>=0&&m<t)return"active_worker"}catch{}}}let n=Wr.join(e.worktreePath,".git");if(!Nt(n))return null;let o=w(e.worktreePath,["status","--porcelain"]);if(o.status!==0)return"pr_or_unmerged_commits";let s=o.stdout.split(`
15
+ `).map(l=>l.trim()).filter(l=>l.length>0);if(D(s).length>0)return"dirty_worktree";let i=w(e.worktreePath,["rev-list","--count","@{u}..HEAD"]);if(i.status===0){let l=Number(i.stdout.trim());if(Number.isFinite(l)&&l>0)return"pr_or_unmerged_commits"}let a=w(e.worktreePath,["rev-list","--count","origin/main..HEAD"]);if(a.status!==0)return i.status!==0?"pr_or_unmerged_commits":null;let u=Number(a.stdout.trim());return Number.isFinite(u)&&u>0?"pr_or_unmerged_commits":null}Y();import{existsSync as wu,readdirSync as ps,statSync as Au}from"node:fs";import Pu from"node:path";function ms(e={}){let r=I(e.harnessRoot??ee()),t=we(r),n=e.now??Date.now(),o=new Date(n).toISOString();if(!wu(t))return{harnessRoot:r,worktreesDir:t,worktreesBytes:0,runCount:0,workerCount:0,oldestRunAt:null,scannedAt:o};let s=0,i=0,a=0,u=null,l;try{l=ps(t,{withFileTypes:!0})}catch{return{harnessRoot:r,worktreesDir:t,worktreesBytes:null,runCount:0,workerCount:0,oldestRunAt:null,scannedAt:o}}for(let c of l){if(!c.isDirectory())continue;i+=1;let d=Pu.join(t,c.name);try{let m=Au(d);u=u===null?m.mtimeMs:Math.min(u,m.mtimeMs)}catch{}try{for(let m of ps(d,{withFileTypes:!0}))m.isDirectory()&&(a+=1)}catch{}if(s!==null&&e.perRunEntryCap!==null){let m=e.perRunEntryCap??5e4;if(m<=0)s=null;else{let g=X(d,m);g===null?s=null:s+=g}}}return{harnessRoot:r,worktreesDir:t,worktreesBytes:s,runCount:i,workerCount:a,oldestRunAt:u===null?null:new Date(u).toISOString(),scannedAt:o}}Y();import{existsSync as Ou}from"node:fs";import{homedir as Iu}from"node:os";import fs from"node:path";var Du=["/var/tmp/kynver-harness",fs.join(Iu(),".openclaw","harness")];function Wt(e,r,t){if(!t?.trim())return;let n=I(t.trim());e.has(n)||(e.add(n),r.push(n))}function Nu(e){return e.scanWellKnown!=null?e.scanWellKnown:process.env.VITEST==="true"?!1:process.env.KYNVER_CLEANUP_SCAN_WELL_KNOWN!=="0"&&!["0","false","no"].includes((process.env.KYNVER_CLEANUP_SCAN_WELL_KNOWN??"").toLowerCase())}function gs(e={}){let r=new Set,t=[];Wt(r,t,e.harnessRoot??ee());let n=process.env.KYNVER_CLEANUP_EXTRA_ROOTS?.split(",").map(o=>o.trim()).filter(Boolean);for(let o of n??[])Wt(r,t,o);if(Nu(e))for(let o of Du){let s=fs.resolve(o);!r.has(s)&&Ou(s)&&Wt(r,t,s)}return t}sr();function Wu(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function Mu(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function hs(e={}){let r=e.diskPath?.trim()||process.env.KYNVER_DISK_GUARD_PATH?.trim()||"/",t=Mu("KYNVER_DISK_GUARD_MAX_USED_PERCENT",75),n=or({...e,diskPath:r,diskMaxUsedPercent:e.diskMaxUsedPercent??t}),o=!n.ok||n.usedPercent>=t,s=process.env.KYNVER_CLEANUP_DISK_PRESSURE_FORCE?.trim().toLowerCase();return s==="none"||s==="off"||s==="0"?o=!1:(s==="pressured"||s==="on"||s==="1")&&(o=!0),{diskGate:n,pressured:o,maxUsedPercent:t}}function ks(e,r){if(!r.pressured)return e;let t=e.execute||!Wu("KYNVER_CLEANUP_DRY_RUN_ON_PRESSURE");return{...e,execute:t,nodeModulesAgeMs:0,runIdFilter:void 0,includeOrphans:!0,terminalWorktreesAgeMs:0,runDirectoriesAgeMs:0,worktreesAgeMs:e.worktreesAgeMs>0?e.worktreesAgeMs:6048e5,diskPressure:!0,diskGate:r.diskGate}}nr();import{unlinkSync as Tu}from"node:fs";function Mr(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function Rs(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function Uu(e,r,t){return e.length===0?[]:t?[...e]:e.length<=r?[]:e.slice(r)}function ys(e={}){let r=e.execute===!0||Mr("KYNVER_WSL_CRASH_DUMP_EXECUTE")||Mr("KYNVER_CLEANUP_EXECUTE"),t=e.purgeAll===!0||Mr("KYNVER_WSL_CRASH_DUMP_PURGE_ALL"),n=Math.max(0,e.keepNewest??Rs("KYNVER_WSL_CRASH_DUMP_KEEP_NEWEST",t?0:1)),o=ve({forceWsl:e.forceWsl});if(!o?.path)return{observation:o,execute:r,keepNewest:n,removed:[],removedBytes:0,skipped:o?.probeError?[{path:o.path??"(unresolved)",reason:o.probeError}]:[]};let s=Uu(o.dumps,n,t),i=[],a=[],u=0;for(let l of s){if(!r){a.push({path:l.path,reason:"dry_run"});continue}try{Tu(l.path),i.push({path:l.path,bytes:l.bytes,name:l.name}),u+=l.bytes}catch(c){a.push({path:l.path,reason:c.message})}}return{observation:o,execute:r,keepNewest:n,removed:i,removedBytes:u,skipped:a}}function bs(e){return e?Mr("KYNVER_WSL_CRASH_DUMP_CLEANUP")||!e.ok?!0:e.dumpCount>Rs("KYNVER_WSL_CRASH_DUMP_KEEP_NEWEST",1):!1}nr();function W(e,r){if(process.env.KYNVER_CLEANUP_QUIET==="1")return;let t=r?`: ${r}`:"";console.error(`[kynver cleanup] ${e}${t}`)}F();var Tr=class{aheadOfMain=new Map;countAheadOfMain(r,t="origin/main"){let n=`${r}\0${t}`;if(this.aheadOfMain.has(n))return this.aheadOfMain.get(n)??null;let o=w(r,["rev-list","--count",`${t}..HEAD`]);if(o.status!==0)return this.aheadOfMain.set(n,null),null;let s=Number(o.stdout.trim()),i=Number.isFinite(s)?s:null;return this.aheadOfMain.set(n,i),i}};import{spawnSync as Bu}from"node:child_process";import{existsSync as Ku}from"node:fs";import Fu from"node:path";var Hu=5e3;function Lu(e,r){if(!Ku(Fu.join(e,".git")))return{status:null,stdout:"",stderr:"",error:"not_a_git_repo"};try{let t=Bu("git",r,{cwd:e,encoding:"utf8",timeout:Hu}),n=t.error?.message?.includes("ETIMEDOUT")===!0;return{status:n?null:t.status,stdout:t.stdout||"",stderr:t.stderr||"",error:n?"git_timeout":t.error?t.error.message:null}}catch(t){return{status:null,stdout:"",stderr:"",error:t.message}}}function Ss(e){let r=Lu(e,["status","--short"]);return r.error==="not_a_git_repo"?[]:r.error==="git_timeout"||r.status!==0?null:r.stdout.split(`
16
+ `).map(t=>t.trim()).filter(Boolean)}var Ur=class{cache=new Map;porcelain(r){let t=r,n=this.cache.get(t);if(n!==void 0)return n;let o=Ss(t)??[];return this.cache.set(t,o),o}};var Br=class{cache=new Map;derive(r){let t=this.cache.get(r.id);if(t!==void 0)return t;let n=ge(r);return this.cache.set(r.id,n),n}};function ju(e){let r={};for(let t of e)r[t.kind]=(r[t.kind]??0)+1;return r}function vs(e,r={}){let t=r.maxSampleActions??12,n=r.maxSampleSkips??8;return{harnessRoot:e.harnessRoot,scanRoots:e.scanRoots,dryRun:e.dryRun,execute:e.execute,scannedAt:e.scannedAt,finalizedRuns:e.finalizedRuns.length,actionCount:e.actions.length,actionKinds:ju(e.actions),totals:e.totals,...e.storage?{storage:e.storage}:{},...e.preservedLivePaths?.length?{preservedLivePaths:e.preservedLivePaths}:{},...e.removedRunDirectories!=null?{removedRunDirectories:e.removedRunDirectories}:{},sampleActions:e.actions.slice(0,t).map(o=>({kind:o.kind,path:o.path,...o.skipReason?{skipReason:o.skipReason}:{},...o.bytes!=null?{bytes:o.bytes}:{},...o.runId?{runId:o.runId}:{},...o.worker?{worker:o.worker}:{}})),sampleSkips:e.skips.slice(0,n)}}function $u(e={}){let r=e.harnessRoot?I(e.harnessRoot):ee(),t=gs({harnessRoot:r}),n=e.now??Date.now();return{harnessRoot:r,scanRoots:t,now:n}}function Gu(e){return typeof e=="string"?{reason:e}:e}function Pe(e,r,t,n){e.push({path:r,reason:t,...n?{detail:n}:{}})}function Kr(e,r,t){return!r||e.bytes!=null?e:{...e,bytes:X(e.path,t)}}function xs(e,r){let t={};for(let n of r)t[n.reason]=(t[n.reason]??0)+1;for(let n of e)n.skipReason&&(t[n.skipReason]=(t[n.skipReason]??0)+1);return t}function Yu(e,r){return e.kind==="remove_next_cache"?zo(e,r):Vo(e,r)}function Vu(e,r,t){return e.kind==="remove_next_cache"?Or(e.path,r,t):Pr(e.path,r,t)}function zu(e){let r=new Map;for(let t of e)for(let[n,o]of ls(t))r.set(n,o);return r}function _s(e,r){return e.runId&&e.worker?M.join(r,e.runId,e.worker):M.resolve(e.path,"..")}function Ju(e={}){let r=cs(e),t=hs();r=ks(r,t);let n=$u(e);W("scan",`${n.scanRoots.length} harness root(s)`);let o=Ao(n.scanRoots,n.now),s=r.finalizeStaleRuns?lo().map(h=>({runId:h.runId,from:h.from,to:h.to})):[];s.length>0&&W("finalize",`${s.length} stale run(s) marked terminal`),W("index","building worktree index");let i=zu(n.scanRoots);W("index",`${i.size} indexed worktree(s)`);let a={runTerminalCache:new Br,gitStatusCache:new Ur,gitRevCache:new Tr},u=[],l=[],c=new Set,d=r.maxActionsPerSweep,m=()=>l.length>=d;for(let h of n.scanRoots){if(m())break;W("root",h);let q=M.join(h,"worktrees"),$e=us(i,h),Ge={harnessRoot:h,worktreesDir:q,nodeModulesAgeMs:r.nodeModulesAgeMs,worktreesAgeMs:r.worktreesAgeMs,includeOrphans:r.includeOrphans,runIdFilter:r.runIdFilter,index:$e,now:n.now},Fr=r.scanDependencyCaches?ss(Ge):[];W("dependency",r.scanDependencyCaches?`${Fr.length} cache candidate(s) at ${h}`:"skipped (worktree-only sweep)");let Hr=0;for(let T of Fr){if(m())break;Hr+=1,Hr%50===0&&W("dependency",`${Hr}/${Fr.length} evaluated`);let _=M.resolve(T.path);if(c.has(_))continue;c.add(_);let k={...T,path:_},O=Vu(k,h,q);if(O){Pe(u,k.path,O),l.push({...k,executed:!1,skipped:!0,skipReason:O});continue}let U=_s(k,q),Re=$e.get(M.resolve(U))??null,K=Ct({indexed:Re,includeOrphans:!0,nodeModulesAgeMs:r.nodeModulesAgeMs,ageMs:k.ageMs,worktreePath:U,activeWorktreePaths:o.activeWorktreePaths,diskPressure:r.diskPressure,gitStatusCache:a.gitStatusCache});if(K){Pe(u,k.path,K),l.push({...k,executed:!1,skipped:!0,skipReason:K});continue}l.push(Yu(Kr(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}if(r.scanDependencyCaches)for(let T of es(Ge)){if(m())break;let _=M.resolve(T.path);if(c.has(_))continue;c.add(_);let k={...T,path:_},O=Ir(k.path,h,q);if(O){Pe(u,k.path,O),l.push({...k,executed:!1,skipped:!0,skipReason:O});continue}let U=_s(k,q),Re=$e.get(M.resolve(U))??null,K=_o({indexed:Re,includeOrphans:!0,nodeModulesAgeMs:r.nodeModulesAgeMs,ageMs:k.ageMs,worktreePath:U,activeWorktreePaths:o.activeWorktreePaths,diskPressure:r.diskPressure,gitStatusCache:a.gitStatusCache});if(K){Pe(u,k.path,K),l.push({...k,executed:!1,skipped:!0,skipReason:K});continue}l.push(Jo(Kr(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}let Lr=[...rs(Ge),...as(Ge)];W("worktrees",`${Lr.length} candidate(s) at ${h}`);let Mt=new Set,jr=0;for(let T of Lr){if(m())break;jr+=1,jr%50===0&&W("worktrees",`${jr}/${Lr.length} evaluated`);let _=M.resolve(T.path);if(Mt.has(_))continue;Mt.add(_);let k={...T,path:_},O=$e.get(M.resolve(k.path))??null,U=O?null:ds({worktreePath:k.path,harnessRoot:h,runId:k.runId,workerName:k.worker,now:n.now}),Re=xo({indexed:O,worktreePath:M.resolve(k.path),includeOrphans:r.includeOrphans,worktreesAgeMs:r.worktreesAgeMs,terminalWorktreesAgeMs:r.terminalWorktreesAgeMs,ageMs:k.ageMs,orphanSafety:U,worktreeRemovalGuard:e.worktreeRemovalGuard,liveness:a,now:n.now,harnessRoot:h,writeSalvageEvidence:r.execute});if(Re){let{reason:K,detail:Cs}=Gu(Re);Pe(u,k.path,K,Cs),l.push({...k,executed:!1,skipped:!0,skipReason:K});continue}l.push(qo(Kr(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}if(!m()&&r.runDirectoriesAgeMs>=0)for(let T of Mo({harnessRoot:h,worktreesDir:q,runDirectoriesAgeMs:r.runDirectoriesAgeMs,runIdFilter:r.runIdFilter,activeGuards:o,now:n.now})){if(m())break;let _=M.resolve(T.path);if(c.has(_))continue;c.add(_);let k={...T,path:_},O=k.runId??M.basename(_),U=Wo({harnessRoot:h,runId:O,runPath:_,ageMs:k.ageMs,runDirectoriesAgeMs:r.runDirectoriesAgeMs,activeGuards:o});if(U){Pe(u,k.path,U),l.push({...k,executed:!1,skipped:!0,skipReason:U});continue}l.push(Xo(Kr(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}}let g=0,p=0,R=0,S=0,y=0,A=0;for(let h of l)h.bytes&&(g+=h.bytes),!h.skipped&&!h.executed&&h.bytes&&(R+=h.bytes),h.executed?(y+=1,S+=h.bytes??0,h.kind==="remove_run_directory"&&(p+=1)):h.skipped&&(A+=1,h.skipReason==="dry_run"&&h.bytes&&(R+=h.bytes));let j=r.accountBytes?ms({harnessRoot:n.harnessRoot,now:n.now,perRunEntryCap:r.storagePerRunEntryCap}):void 0,B=ve(),je=r.execute&&bs(B),$=je?ys({execute:!0}):null,te=B?{observed:!0,execute:je,dumpCount:B.dumpCount,totalBytes:B.totalBytes,removedCount:$?.removed.length??0,removedBytes:$?.removedBytes??0,executables:B.executables,path:B.path,reason:B.reason}:void 0;$&&$.removed.length>0&&(S+=$.removedBytes,y+=$.removed.length,W("wsl-crashes",`removed ${$.removed.length} dump(s), ${$.removedBytes} bytes`)),W("complete",`${l.length} action(s), ${A} skipped, ${y} removed`);let ne=Eo(l,u),P=vs({harnessRoot:n.harnessRoot,scanRoots:n.scanRoots,dryRun:!r.execute,execute:r.execute,nodeModulesAgeMs:r.nodeModulesAgeMs,worktreesAgeMs:r.worktreesAgeMs,includeOrphans:r.includeOrphans,diskPressure:r.diskPressure,diskGate:r.diskGate?{ok:r.diskGate.ok,path:r.diskGate.path,freeBytes:r.diskGate.freeBytes,usedPercent:r.diskGate.usedPercent,reason:r.diskGate.reason}:void 0,scannedAt:new Date(n.now).toISOString(),finalizedRuns:s,actions:l,skips:u,totals:{candidateBytes:g,reclaimableBytes:R,removedBytes:S,removedPaths:y,skippedPaths:A,skipReasons:xs(l,u)},...j?{storage:j}:{},...ne.length>0?{preservedLivePaths:ne}:{},...p>0?{removedRunDirectories:p}:{},...te?{wslCrashDumps:te}:{}});return{harnessRoot:n.harnessRoot,scanRoots:n.scanRoots,dryRun:!r.execute,execute:r.execute,nodeModulesAgeMs:r.nodeModulesAgeMs,worktreesAgeMs:r.worktreesAgeMs,includeOrphans:r.includeOrphans,diskPressure:r.diskPressure,diskGate:r.diskGate?{ok:r.diskGate.ok,path:r.diskGate.path,freeBytes:r.diskGate.freeBytes,usedPercent:r.diskGate.usedPercent,reason:r.diskGate.reason}:void 0,scannedAt:new Date(n.now).toISOString(),finalizedRuns:s,actions:l,skips:u,totals:{candidateBytes:g,reclaimableBytes:R,removedBytes:S,removedPaths:y,skippedPaths:A,skipReasons:xs(l,u)},...j?{storage:j}:{},...ne.length>0?{preservedLivePaths:ne}:{},...p>0?{removedRunDirectories:p}:{},...te?{wslCrashDumps:te}:{},compactSummary:P}}export{Ar as DEFAULT_MAX_ACTIONS_PER_SWEEP,Et as DEFAULT_NODE_MODULES_AGE_MS,wt as DEFAULT_RUN_DIRECTORIES_AGE_MS,wr as DEFAULT_WORKTREES_AGE_MS,Ju as runHarnessCleanup};
@@ -0,0 +1,19 @@
1
+ function g(e){return["Repair target PR policy:","- Work on the existing target PR branch \u2014 do not open a duplicate repair PR by default.",`- Canonical target PR: ${e.targetPrUrl}`,...e.targetPrBranch?[`- Canonical target branch: \`${e.targetPrBranch}\` (checkout is already on this branch).`]:[],`- Reconcile ${e.targetPrUrl} in structured finalResult.targetPrReconciliation.`,"- Only supersede the original when the branch is inaccessible: set supersedesOriginalTargetPr: true with reason and close/comment on the original PR."]}var w="embedded-1",S=[{slug:"ghost",displayName:"Ghost",description:"Orchestration persona.",dispatchLane:null,defaultRoleLane:"system"},{slug:"astra",displayName:"Astra",description:"Planning persona.",dispatchLane:"implementation",defaultRoleLane:"plan_author"},{slug:"rhea",displayName:"Rhea",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"mnemo",displayName:"Mnemo",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"sentinel",displayName:"Sentinel",description:"Review persona.",dispatchLane:"review",defaultRoleLane:"deep_reviewer"},{slug:"pixel",displayName:"Pixel",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"schema",displayName:"Schema",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"atlas",displayName:"Atlas",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"runtime_verifier"},{slug:"bridge",displayName:"Bridge",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"catalyst",displayName:"Catalyst",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"lorentz",displayName:"Lorentz",description:"Review persona.",dispatchLane:"review",defaultRoleLane:"report_reviewer"},{slug:"dalton",displayName:"Dalton",description:"Landing persona.",dispatchLane:"landing",defaultRoleLane:"implementer"}],b={"worker.prompt.core_rules":["Structured final result (recommended): record completion as JSON with summary, files, PR URLs, verification, risks, and blockers.","Completion handoff (required): before you stop, summarize the outcome in your last message and append a heartbeat line with phase `complete` and a structured finalResult object. Commit your work cleanly and open a GitHub PR (draft OK) for substantial changes \u2014 never leave uncommitted changes behind without reporting them.","Review-only workers must not open new implementation PRs \u2014 review the existing PR and record a verdict in the final result. Prefer `gh pr view` / `gh pr diff`; if a local checkout is needed, use a disposable ref or detached worktree, not a checked-out `pr-*` branch.","Keep verification targeted to touched paths; avoid full-monorepo verification unless explicitly requested.","Do not run `npm publish`.","If verification fails, append a heartbeat line immediately with the failing command, reason, and next action."].join(`
2
+ `),"worker.prompt.progress.compact":"Plan progress: when planId is set, report progress with `kynver plan progress --plan <planId> --row <rowKey> --role implementer --status in_progress|running|partial|blocked`. Do not mark rows done from the worker CLI.","worker.prompt.progress.full":["Structured plan progress (required when planId is set):","- Report checkpoints with `kynver plan progress --plan <planId> --row <rowKey> --role implementer --status in_progress|running|partial|blocked`.","- When a slice is finished, emit `partial` with evidence (`--evidence pr:<url>`, `--evidence path:<file>`, or `--evidence command:<cmd>`).","- Do not propose or confirm row `done` from the worker CLI."].join(`
3
+ `),"worker.prompt.merge_gate.compact":"Verification cost control: prefer local verification before requesting CI runs; do not push empty commits to re-trigger CI; record verification evidence on the PR.","worker.prompt.merge_gate.full":["Verification cost control:","- Prefer local verification of touched paths before requesting any CI run.","- Do not push empty commits to re-trigger CI.","- Record verification evidence on the PR before requesting review."].join(`
4
+ `),"worker.prompt.plan_artifacts.compact":"Plan artifacts: when authoring or revising plan documents, open a GitHub PR early and iterate from that PR branch; do not leave the canonical plan only in a local worktree.","worker.prompt.plan_artifacts.full":["Plan artifacts (when authoring or revising plan documents):","- Create a feature branch and open a GitHub PR (draft OK) before substantial drafting; commit and push the plan file.","- Iterate on that PR branch and link the PR URL on the related task and progress evidence."].join(`
5
+ `)},v={"harness.maxTaskAttempts":4,"harness.dispatchCooldownMs":5e3,"daemon.idleIntervalMs":5*6e4,"daemon.maxIdleStreak":10},f={version:w,generatedAt:"1970-01-01T00:00:00.000Z",personas:S,instructions:b,policyThresholds:v};var _=f;function i(e){let t=_.instructions[e];if(typeof t=="string"&&t.trim())return t;let r=f.instructions[e];return typeof r=="string"?r:""}var P="runtime-context-budget-receipt.v1",h="runtime-context-budget-receipt.v2";function R(e){return!Number.isFinite(e)||e<=0?0:Math.ceil(e/4)}function s(e,t,r){let o=t?.length??0;return{section:e,chars:o,estimatedTokens:R(o),...r}}function x(e,t){let r=e.reduce((n,a)=>n+a.chars,0),o=e.reduce((n,a)=>n+a.estimatedTokens,0),l=e.reduce((n,a)=>n+(a.omittedCount??0),0),c=e.reduce((n,a)=>n+(a.duplicatesCollapsed??0),0);return{totalChars:r,estimatedTokens:o,duplicatesCollapsed:t?.duplicatesCollapsed??c,omittedCount:t?.omittedCount??l}}function u(e){let t=x(e.sections,{duplicatesCollapsed:e.duplicatesCollapsed,omittedCount:e.omittedCount});return{schemaVersion:h,surface:e.surface,agentOsId:e.agentOsId?.trim()||null,taskId:e.taskId?.trim()||null,planId:e.planId?.trim()||null,personaSlug:e.personaSlug?.trim().toLowerCase()||null,mode:e.mode,generatedAt:e.generatedAt,...t,finalSerializedChars:e.finalSerializedChars,finalSerializedTokens:R(e.finalSerializedChars),usefulContextCoverage:e.usefulContextCoverage,budgetSatisfied:e.budgetSatisfied??!0,overBudgetReason:e.overBudgetReason??null,activeStateLookups:e.activeStateLookups??[],sections:e.sections}}function E(e,t){return u({surface:t.surface,agentOsId:t.agentOsId??e.agentOsId,taskId:t.taskId??e.taskId,planId:t.planId??e.planId,personaSlug:t.personaSlug??e.personaSlug,mode:t.mode??e.mode,generatedAt:t.generatedAt??e.generatedAt,finalSerializedChars:t.finalSerializedChars,sections:e.sections,usefulContextCoverage:t.usefulContextCoverage,activeStateLookups:t.activeStateLookups??e.activeStateLookups,duplicatesCollapsed:t.duplicatesCollapsed??e.duplicatesCollapsed,omittedCount:t.omittedCount??e.omittedCount,budgetSatisfied:t.budgetSatisfied,overBudgetReason:t.overBudgetReason})}function T(e){return e.schemaVersion===h}var p=2e5,C=500;function I(e){let t=e.ownedPaths.length?`Owned paths: ${e.ownedPaths.join(", ")}. Do not edit outside these paths without stopping and reporting why.`:"Owned paths: unrestricted for this worker, but keep edits tightly scoped.",r=!!e.model?.toLowerCase().includes("haiku"),o=r?"compact":"full",l=r?e.planId?`Active planId: ${e.planId}`:"No planId on this worker.":e.planId?`Active planId: ${e.planId}${e.taskId?` \xB7 taskId: ${e.taskId}`:""}`:"No planId on this worker \u2014 still emit progress when you touch plan-scoped work.",c=[...i(`worker.prompt.progress.${o}`).split(`
6
+ `),l],n=i(`worker.prompt.merge_gate.${o}`).split(`
7
+ `),a=i(`worker.prompt.plan_artifacts.${o}`).split(`
8
+ `);return["You are running under the Kynver AgentOS runtime.","Immediately state your plan before editing.",t,`Worktree: ${e.worktreePath}`,`Progress heartbeat file: ${e.heartbeatPath}`,"After each major step, append one JSON line to the heartbeat file with fields: ts, phase, summary, changedFiles, blocker.","Before exiting, append a terminal heartbeat with phase `complete` and a structured finalResult object; if you cannot complete, append blocker plus the recovery next action instead of exiting silently.","Final response must include files changed, verification commands, and unresolved risks.",...i("worker.prompt.core_rules").split(`
9
+ `),"",...c,"",...n,"",...a,"",...e.runtimeEnvelopeMarkdown?.trim()?[e.runtimeEnvelopeMarkdown.trim(),""]:[],...e.contextEnvelopeMarkdown?.trim()?[e.contextEnvelopeMarkdown.trim(),""]:[],...e.personaMarkdown?.trim()?[e.personaMarkdown.trim(),""]:[],...e.instructionPolicyMarkdown?.trim()?["Operating rules (from AgentOS memory policy):",e.instructionPolicyMarkdown.trim(),""]:[],...e.memoryQualityMarkdown?.trim()?[e.memoryQualityMarkdown.trim(),""]:[],...e.repairTargetPrUrl?[...g({targetPrUrl:e.repairTargetPrUrl,targetPrBranch:e.repairTargetBranch??null}),""]:[],"Task:",e.task].join(`
10
+ `)}function B(e){let t=e.ownedPaths.length?`Owned paths: ${e.ownedPaths.join(", ")}. Do not edit outside these paths without stopping and reporting why.`:"Owned paths: unrestricted for this worker, but keep edits tightly scoped.",r=!!e.model?.toLowerCase().includes("haiku"),o=r?"compact":"full",l=r?e.planId?`Active planId: ${e.planId}`:"No planId on this worker.":e.planId?`Active planId: ${e.planId}${e.taskId?` \xB7 taskId: ${e.taskId}`:""}`:"No planId on this worker \u2014 still emit progress when you touch plan-scoped work.",c=[...i(`worker.prompt.progress.${o}`).split(`
11
+ `),l],n=i(`worker.prompt.merge_gate.${o}`).split(`
12
+ `),a=i(`worker.prompt.plan_artifacts.${o}`).split(`
13
+ `),d=e.repairTargetPrUrl?g({targetPrUrl:e.repairTargetPrUrl,targetPrBranch:e.repairTargetBranch??null}).join(`
14
+ `):null;return["You are running under the Kynver AgentOS runtime.","Immediately state your plan before editing.",t,`Worktree: ${e.worktreePath}`,`Progress heartbeat file: ${e.heartbeatPath}`,"After each major step, append one JSON line to the heartbeat file with fields: ts, phase, summary, changedFiles, blocker.","Before exiting, append a terminal heartbeat with phase `complete` and a structured finalResult object; if you cannot complete, append blocker plus the recovery next action instead of exiting silently.","Final response must include files changed, verification commands, and unresolved risks.",...i("worker.prompt.core_rules").split(`
15
+ `),c.join(`
16
+ `),n.join(`
17
+ `),a.join(`
18
+ `),d,e.task].filter(m=>!!m).join(`
19
+ `)}function O(e){let t=I(e),r=B(e),o=e.surface??"runtime_prompt",l=[s("structural",r),s("memory_preview",e.runtimeEnvelopeMarkdown),s("task_envelope",e.contextEnvelopeMarkdown),s("persona",e.personaMarkdown),s("instruction_policy",e.instructionPolicyMarkdown),s("memory_quality",e.memoryQualityMarkdown)],c=e.enforcementEnabled??!1,n=t.length,a=Buffer.byteLength(t,"utf8"),d=n>p,m=d?p>=C:n>=C,k=d?`runtime_prompt exceeds hard cap: ${n} chars (${a} UTF-8 bytes) > ${p} (${c?"active":"shadow"} mode; no truncation applied)`:null,y=u({surface:o,agentOsId:e.agentOsId??null,taskId:e.taskId??null,planId:e.planId??null,personaSlug:e.personaSlug??null,mode:e.mode??"routine",generatedAt:e.generatedAt??new Date(0).toISOString(),finalSerializedChars:n,sections:l,usefulContextCoverage:{requiredOperatingRuleSlugsPresent:[],requiredOperatingRuleDenominator:0,activeTaskHandlePresent:!!e.taskId,planHandlePresent:!!e.planId,selectedHandles:[],omittedHandles:[],expansionRoutes:[],memoryQualityTraceId:null},budgetSatisfied:!d&&m,overBudgetReason:k});return{prompt:t,receipt:y}}var L={hardCapChars:p,safeFloorChars:C};export{P as RUNTIME_CONTEXT_BUDGET_RECEIPT_SCHEMA_VERSION,h as RUNTIME_CONTEXT_BUDGET_RECEIPT_V2_SCHEMA_VERSION,L as RUNTIME_PROMPT_ENFORCEMENT,u as buildContextBudgetReceiptV2,I as buildPrompt,O as buildPromptWithReceipt,R as estimateTokensFromChars,x as finalizeReceiptTotals,T as isRuntimeContextBudgetReceiptV2,s as sectionReceiptFromMarkdown,E as upgradeReceiptToV2};
@@ -1 +1 @@
1
- var r=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};import{homedir as K}from"node:os";import D from"node:path";function _e(e){return e==="~"?K():e.startsWith("~/")||e.startsWith("~\\")?D.join(K(),e.slice(2)):e}function u(e){return D.resolve(_e(e))}var c=r(()=>{"use strict"});function T(e){return process.platform!=="win32"?e:{windowsHide:!0,...e}}var s=r(()=>{"use strict"});var ve,lr,Ee,cr,W=r(()=>{"use strict";ve=["ANTHROPIC_API_KEY","ANALYST_API_KEY","RECRUITER_API_KEY","AUTH_SECRET","NEXTAUTH_SECRET","DATABASE_URL","PRODUCTION_DATABASE_URL","KYNVER_PRODUCTION_DATABASE_URL","REDIS_URL","GOOGLE_CLIENT_SECRET","GITHUB_CLIENT_SECRET","KYNVER_API_KEY","KYNVER_SERVICE_SECRET","KYNVER_RUNTIME_SECRET","KYNVER_CRON_SECRET","OPENCLAW_CRON_SECRET","QSTASH_TOKEN","QSTASH_CURRENT_SIGNING_KEY","QSTASH_NEXT_SIGNING_KEY","TOOL_SECRETS_KEK","TOOL_EXECUTOR_DISPATCH_SECRET","CLOUDFLARE_API_TOKEN","STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_IDENTITY_WEBHOOK_SECRET","VOYAGE_API_KEY","PERPLEXITY_API_KEY","FRED_API_KEY","FMP_API_KEY","CURSOR_API_KEY","MEMORY_CONTENT_KEK","LLM_BYOK_KEK","KYNVER_COMMAND_AUTH_KEY","KYNVER_INSTRUCTION_BUNDLE_KEY","KYNVER_MEMORY_LEDGER_KEY","KYNVER_JWKS_PRIVATE_KEY_JWK"],lr=new Set(ve),Ee=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY"],cr=new Set(Ee)});import{spawnSync as Ce}from"node:child_process";function B(e,t){try{let n=Ce("git",t,T({cwd:e,encoding:"utf8"}));return{status:n.status,stdout:n.stdout||"",stderr:n.stderr||"",error:n.error?n.error.message:null}}catch(n){return{status:null,stdout:"",stderr:"",error:n.message}}}var k=r(()=>{"use strict";c();s();W()});import{existsSync as S,readFileSync as F}from"node:fs";import{homedir as Ae}from"node:os";import l from"node:path";import{fileURLToPath as Oe}from"node:url";function Ie(e){let t=l.join(e,"package.json");if(!S(t))return null;try{let n=JSON.parse(F(t,"utf8"));return typeof n.name=="string"?n.name.trim():null}catch{return null}}function Pe(e){return Ie(e)==="kynver"}function M(e){let t=l.resolve(e);if(!S(t))return null;let n=B(t,["rev-parse","--show-toplevel"]);if(n.status!==0)return null;let o=n.stdout.trim();return o.length?l.resolve(o):null}function Ne(e=import.meta.url){let t=l.dirname(Oe(e));for(let n=0;n<8;n+=1){let o=l.join(t,"package.json");if(S(o))try{if(JSON.parse(F(o,"utf8")).name==="@kynver-app/runtime")return t}catch{}let i=l.dirname(t);if(i===t)break;t=i}return null}function x(e,t,n,o,i){if(!n)return;let a=l.resolve(n);e.has(a)||(i?.requireMonorepo??!0)&&!Pe(a)||(e.add(a),t.push({repo:a,source:o}))}function Ue(e){let t=e?.cwd??process.cwd(),n=new Set,o=[];x(n,o,M(t),"cwd_git",{requireMonorepo:!1});let i=Ne(e?.runtimeModuleUrl??import.meta.url);i&&x(n,o,M(i),"runtime_checkout");let a=Ae();for(let Se of we)x(n,o,u(l.join(a,Se)),"well_known_path");return o}function _(e){return Ue(e)[0]??null}var we,p=r(()=>{"use strict";k();c();we=["Kynver","repos/Kynver","repos/kynver-source-main","code/Kynver","projects/Kynver"]});var d=r(()=>{"use strict"});var g=r(()=>{"use strict"});var $=r(()=>{"use strict"});var Ir,Pr,v=r(()=>{"use strict";Ir=25*1024*1024*1024,Pr=12*1024*1024*1024});var Tr,Wr,L=r(()=>{"use strict";v();Tr=5*1024*1024*1024,Wr=10*1024*1024*1024});var Hr,jr,E=r(()=>{"use strict";L();v();Hr=30*1024*1024*1024,jr=15*1024*1024*1024});var j=r(()=>{"use strict";s()});import Ke from"node:path";var Qr,C=r(()=>{"use strict";c();j();Qr=Ke.join(".openclaw","harness")});var y=r(()=>{"use strict";m();d();g();b();C()});var G=r(()=>{"use strict";m();C();y();s()});var O=r(()=>{"use strict";G();s()});var z=r(()=>{"use strict";O();s()});var J=r(()=>{"use strict"});var q=r(()=>{"use strict";J();s()});var X=r(()=>{"use strict"});var Z=r(()=>{"use strict";X()});var Q=r(()=>{"use strict";Z();s()});var ee=r(()=>{"use strict"});var re=r(()=>{"use strict"});var ne=r(()=>{"use strict"});var w=r(()=>{"use strict"});var te=r(()=>{"use strict"});var oe=r(()=>{"use strict";w();te()});var se=r(()=>{"use strict";q();Q();ee();re();k();ne();oe();w();s()});var ie=r(()=>{"use strict";se()});var Le,He,ae=r(()=>{"use strict";$();m();d();g();b();E();O();z();ie();s();Le=500*1024*1024,He=4*1024*1024*1024});var b=r(()=>{"use strict";ae()});import{homedir as je}from"node:os";import Ye from"node:path";var ue,I=r(()=>{"use strict";ue=Ye.join(je(),".kynver",".env")});var le=r(()=>{"use strict"});var ce=r(()=>{"use strict";le()});var de=r(()=>{"use strict"});var P=r(()=>{"use strict";ce();de()});var me=r(()=>{"use strict"});var fe=r(()=>{"use strict";me()});var R=r(()=>{"use strict";I();c();m();P();fe()});var he=r(()=>{"use strict";d();d()});var ye=r(()=>{"use strict";I();P();R()});var Re=r(()=>{"use strict";p();d();he();m();R();ye();s();y()});import{existsSync as qe,mkdirSync as Jo,readFileSync as Xe,writeFileSync as qo}from"node:fs";import{homedir as Ze,totalmem as Zo}from"node:os";import N from"node:path";function Qe(e){return{...e,...e.harnessRoot?.trim()?{harnessRoot:u(e.harnessRoot.trim())}:{},...e.defaultRepo?.trim()?{defaultRepo:u(e.defaultRepo.trim())}:{}}}function f(){if(!qe(ke))return{};try{return Qe(JSON.parse(Xe(ke,"utf8")))}catch{return{}}}var xe,ke,cs,ds,ms,m=r(()=>{"use strict";p();c();s();d();g();b();E();R();Re();y();xe=N.join(Ze(),".kynver"),ke=N.join(xe,"config.json"),cs=N.join(xe,"credentials");ds=500*1024*1024,ms=4*1024*1024*1024});m();p();c();import er from"node:path";function rr(e){return er.resolve(u(e.trim()))}function U(e,t,n){let o=e?.trim();return o?{repo:rr(o),source:t,persistedInConfig:n}:null}function nr(e){return e?{repo:e.repo,source:e.source,persistedInConfig:!1}:null}function tr(e={}){let t=e.env??process.env,n=e.config??f(),o=U(n.defaultRepo,"config",!0);if(o)return o;let i=U(t.KYNVER_DEFAULT_REPO,"env_default_repo",!1);if(i)return i;let a=U(t.KYNVER_HARNESS_REPO,"env_harness_repo",!1);return a||nr(_({cwd:e.cwd,runtimeModuleUrl:e.runtimeModuleUrl}))}export{tr as resolveDefaultRepo};
1
+ var r=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(o){throw n=[o],o}};import{homedir as K}from"node:os";import D from"node:path";function _e(e){return e==="~"?K():e.startsWith("~/")||e.startsWith("~\\")?D.join(K(),e.slice(2)):e}function u(e){return D.resolve(_e(e))}var c=r(()=>{"use strict"});function T(e){return process.platform!=="win32"?e:{windowsHide:!0,...e}}var s=r(()=>{"use strict"});var ve,cr,Ee,dr,W=r(()=>{"use strict";ve=["ANTHROPIC_API_KEY","ANALYST_API_KEY","RECRUITER_API_KEY","AUTH_SECRET","NEXTAUTH_SECRET","DATABASE_URL","PRODUCTION_DATABASE_URL","KYNVER_PRODUCTION_DATABASE_URL","REDIS_URL","GOOGLE_CLIENT_SECRET","GITHUB_CLIENT_SECRET","KYNVER_API_KEY","KYNVER_SERVICE_SECRET","KYNVER_RUNTIME_SECRET","KYNVER_CRON_SECRET","OPENCLAW_CRON_SECRET","QSTASH_TOKEN","QSTASH_CURRENT_SIGNING_KEY","QSTASH_NEXT_SIGNING_KEY","TOOL_SECRETS_KEK","TOOL_EXECUTOR_DISPATCH_SECRET","CLOUDFLARE_API_TOKEN","STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_IDENTITY_WEBHOOK_SECRET","VOYAGE_API_KEY","PERPLEXITY_API_KEY","FRED_API_KEY","FMP_API_KEY","CURSOR_API_KEY","MEMORY_CONTENT_KEK","LLM_BYOK_KEK","KYNVER_COMMAND_AUTH_KEY","KYNVER_INSTRUCTION_BUNDLE_KEY","KYNVER_MEMORY_LEDGER_KEY","KYNVER_JWKS_PRIVATE_KEY_JWK"],cr=new Set(ve),Ee=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY"],dr=new Set(Ee)});import{spawnSync as Ae}from"node:child_process";function B(e,t){try{let n=Ae("git",t,T({cwd:e,encoding:"utf8"}));return{status:n.status,stdout:n.stdout||"",stderr:n.stderr||"",error:n.error?n.error.message:null}}catch(n){return{status:null,stdout:"",stderr:"",error:n.message}}}var k=r(()=>{"use strict";c();s();W()});import{existsSync as S,readFileSync as F}from"node:fs";import{homedir as Oe}from"node:os";import l from"node:path";import{fileURLToPath as we}from"node:url";function Pe(e){let t=l.join(e,"package.json");if(!S(t))return null;try{let n=JSON.parse(F(t,"utf8"));return typeof n.name=="string"?n.name.trim():null}catch{return null}}function Ne(e){return Pe(e)==="kynver"}function M(e){let t=l.resolve(e);if(!S(t))return null;let n=B(t,["rev-parse","--show-toplevel"]);if(n.status!==0)return null;let o=n.stdout.trim();return o.length?l.resolve(o):null}function Ue(e=import.meta.url){let t=l.dirname(we(e));for(let n=0;n<8;n+=1){let o=l.join(t,"package.json");if(S(o))try{if(JSON.parse(F(o,"utf8")).name==="@kynver-app/runtime")return t}catch{}let i=l.dirname(t);if(i===t)break;t=i}return null}function x(e,t,n,o,i){if(!n)return;let a=l.resolve(n);e.has(a)||(i?.requireMonorepo??!0)&&!Ne(a)||(e.add(a),t.push({repo:a,source:o}))}function Ke(e){let t=e?.cwd??process.cwd(),n=new Set,o=[];x(n,o,M(t),"cwd_git",{requireMonorepo:!1});let i=Ue(e?.runtimeModuleUrl??import.meta.url);i&&x(n,o,M(i),"runtime_checkout");let a=Oe();for(let Se of Ie)x(n,o,u(l.join(a,Se)),"well_known_path");return o}function _(e){return Ke(e)[0]??null}var Ie,p=r(()=>{"use strict";k();c();Ie=["Kynver","repos/Kynver","repos/kynver-source-main","code/Kynver","projects/Kynver"]});var d=r(()=>{"use strict"});var g=r(()=>{"use strict"});var $=r(()=>{"use strict"});var Ir,Pr,v=r(()=>{"use strict";Ir=25*1024*1024*1024,Pr=12*1024*1024*1024});var Tr,Wr,L=r(()=>{"use strict";v();Tr=5*1024*1024*1024,Wr=10*1024*1024*1024});var Hr,jr,E=r(()=>{"use strict";L();v();Hr=30*1024*1024*1024,jr=15*1024*1024*1024});var j=r(()=>{"use strict";s()});import De from"node:path";var Qr,C=r(()=>{"use strict";c();j();Qr=De.join(".openclaw","harness")});var y=r(()=>{"use strict";m();d();g();b();C()});var G=r(()=>{"use strict";m();C();y();s()});var O=r(()=>{"use strict";G();s()});var z=r(()=>{"use strict";O();s()});var J=r(()=>{"use strict"});var q=r(()=>{"use strict";J();s()});var X=r(()=>{"use strict"});var Z=r(()=>{"use strict";X()});var Q=r(()=>{"use strict";Z();s()});var ee=r(()=>{"use strict"});var re=r(()=>{"use strict"});var ne=r(()=>{"use strict"});var w=r(()=>{"use strict"});var te=r(()=>{"use strict"});var oe=r(()=>{"use strict";w();te()});var se=r(()=>{"use strict";q();Q();ee();re();k();ne();oe();w();s()});var ie=r(()=>{"use strict";se()});var He,je,ae=r(()=>{"use strict";$();m();d();g();b();E();O();z();ie();s();He=500*1024*1024,je=4*1024*1024*1024});var b=r(()=>{"use strict";ae()});import{homedir as Ye}from"node:os";import Ve from"node:path";var ue,I=r(()=>{"use strict";ue=Ve.join(Ye(),".kynver",".env")});var le=r(()=>{"use strict"});var ce=r(()=>{"use strict";le()});var de=r(()=>{"use strict"});var P=r(()=>{"use strict";ce();de()});var me=r(()=>{"use strict"});var fe=r(()=>{"use strict";me()});var R=r(()=>{"use strict";I();c();m();P();fe()});var he=r(()=>{"use strict";d();d()});var ye=r(()=>{"use strict";I();P();R()});var Re=r(()=>{"use strict";p();d();he();m();R();ye();s();y()});import{existsSync as Xe,mkdirSync as Jo,readFileSync as Ze,writeFileSync as qo}from"node:fs";import{homedir as Qe,totalmem as Zo}from"node:os";import N from"node:path";function er(e){return{...e,...e.harnessRoot?.trim()?{harnessRoot:u(e.harnessRoot.trim())}:{},...e.defaultRepo?.trim()?{defaultRepo:u(e.defaultRepo.trim())}:{}}}function f(){if(!Xe(ke))return{};try{return er(JSON.parse(Ze(ke,"utf8")))}catch{return{}}}var xe,ke,cs,ds,ms,m=r(()=>{"use strict";p();c();s();d();g();b();E();R();Re();y();xe=N.join(Qe(),".kynver"),ke=N.join(xe,"config.json"),cs=N.join(xe,"credentials");ds=500*1024*1024,ms=4*1024*1024*1024});m();p();c();import rr from"node:path";function nr(e){return rr.resolve(u(e.trim()))}function U(e,t,n){let o=e?.trim();return o?{repo:nr(o),source:t,persistedInConfig:n}:null}function tr(e){return e?{repo:e.repo,source:e.source,persistedInConfig:!1}:null}function or(e={}){let t=e.env??process.env,n=e.config??f(),o=U(n.defaultRepo,"config",!0);if(o)return o;let i=U(t.KYNVER_DEFAULT_REPO,"env_default_repo",!1);if(i)return i;let a=U(t.KYNVER_HARNESS_REPO,"env_harness_repo",!1);return a||tr(_({cwd:e.cwd,runtimeModuleUrl:e.runtimeModuleUrl}))}export{or as resolveDefaultRepo};