@kynver-app/runtime 0.2.99 → 0.2.100
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.
- package/README.md +1 -1
- package/dist/cli.js +121 -117
- package/dist/desktop-entry.js +85 -81
- package/dist/index.js +144 -140
- package/dist/local-run-store/index.js +12 -12
- package/dist/server/cleanup.js +14 -14
- package/dist/server/default-repo.js +1 -1
- package/dist/server/dispatch-routing.js +3 -3
- package/dist/server/model-routing.js +3 -3
- package/dist/server/monitor.js +7 -7
- package/dist/server/worker-policy.js +2 -2
- package/package.json +1 -1
package/dist/server/cleanup.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),
|
|
1
|
+
var g=(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 Vt}from"node:os";import zt from"node:path";function Gs(e){return e==="~"?Vt():e.startsWith("~/")||e.startsWith("~\\")?zt.join(Vt(),e.slice(2)):e}function Q(e){return zt.resolve(Gs(e))}var se=g(()=>{"use strict"});var Jt=g(()=>{"use strict"});import{existsSync as Ys,mkdirSync as Vs,readFileSync as qt,readdirSync as Ol,renameSync as zs,rmSync as Js,statSync as Xt,writeFileSync as qs}from"node:fs";import{randomBytes as Xs}from"node:crypto";import Zs from"node:path";function qe(e){console.error(e),process.exit(1)}function zr(e){return process.platform!=="win32"?e:{windowsHide:!0,...e}}function Xe(e){try{return JSON.parse(e)}catch{return null}}function x(e,r){try{return JSON.parse(qt(e,"utf8"))}catch(t){if(arguments.length>1)return r;qe(`failed to read ${e}: ${t.message}`)}}function Jr(e,r){Vs(Zs.dirname(e),{recursive:!0});let t=`${e}.${process.pid}.${Xs(4).toString("hex")}.tmp`;try{qs(t,`${JSON.stringify(r,null,2)}
|
|
2
|
+
`),zs(t,e)}catch(n){try{Js(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 Xt(e).size}catch{return 0}}function Qe(e){try{return Xt(e).mtime.toISOString()}catch{return null}}function Zt(e,r){return Ys(e)?qt(e,"utf8").split(`
|
|
3
3
|
`).slice(-r).join(`
|
|
4
|
-
`):""}function ee(e){if(!e)return!1;try{return process.kill(e,0),!0}catch{return!1}}function
|
|
5
|
-
`).map(r=>r.trim()).filter(Boolean)}function w(e,r){try{let t=en("git",r,zr({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 Qt(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 er(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 Xr(n,"missing worktree path");let s=w(e,["rev-parse","HEAD"]);if(s.status!==0)return Xr(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 Xr(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=Qt(e,i,a),l=Qt(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 p=u.isAncestor?"ahead":l.isAncestor?"merged":"diverged";return{checked:!0,base:n,head:a,baseHead:i,baseIsAncestorOfHead:u.isAncestor,headIsAncestorOfBase:l.isAncestor,relation:p,...c?{error:c}:{}}}function Xr(e,r,t=null){return{checked:!1,base:e,head:t,baseHead:null,baseIsAncestorOfHead:null,headIsAncestorOfBase:null,relation:"unknown",error:r}}var K=f(()=>{"use strict";se();b();Zt()});var Zr=f(()=>{"use strict";K()});var rr=f(()=>{"use strict";K();se();Zr()});var Qr=f(()=>{"use strict";b()});function ie(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 tr(e,r){return e[r]?.trim()||null}function rn(e){let r=e?.split(":")[0]?.trim();return r?ie(r):null}function ve(e=process.env,r={}){let t=[],n=rn(r.boxId),o=rn(tr(e,"KYNVER_BOX_ID")),s=r.boxKind?.trim();if(s)return n&&n!==ie(s)&&t.push(`config.boxId=${r.boxId} conflicts with boxKind=${s}; using explicit boxKind=${s}`),{boxKind:ie(s),source:"config",slugInferenceBlocked:!1,warnings:t};let i=tr(e,"KYNVER_BOX_KIND");if(i)return o&&o!==ie(i)&&t.push(`KYNVER_BOX_ID=${tr(e,"KYNVER_BOX_ID")} conflicts with KYNVER_BOX_KIND=${i}; using explicit KYNVER_BOX_KIND=${i}`),{boxKind:ie(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=tr(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 ae=f(()=>{"use strict"});function et(e,r){return e==="forge"?4:Math.max(1,r)}function nr(e,r){return e==="forge"?Math.min(Math.max(1,r),4):Math.max(1,r)}var or=f(()=>{"use strict"});var tn=f(()=>{"use strict"});import{existsSync as Js,readFileSync as qs,statfsSync as Xs}from"node:fs";function rt(){if(process.platform!=="linux")return!1;for(let e of["/proc/sys/kernel/osrelease","/proc/version"])try{if(!Js(e))continue;let r=qs(e,"utf8");if(/microsoft|wsl/i.test(r))return!0}catch{}return!1}function nn(e={}){if(!(e.forceWsl===void 0?rt():e.forceWsl))return null;let t=e.wslHostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||xe,n=e.wslHostFreeWarnBytes??Zs,o=e.wslHostFreeCriticalBytes??Qs,s=e.statfs??Xs,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,p=a<o,m=!c&&!p,g=(a/(1024*1024*1024)).toFixed(1),d=null;return m||(d=`Windows host disk ${t} at ${p?"critical":"warning"}: ${g} GiB free (<${(p?o:n)/1024/1024/1024} GiB); WSL VHDX cannot grow safely. ${ei()}`),{ok:m,path:t,freeBytes:a,totalBytes:u,usedPercent:l,warnBelowBytes:n,criticalBelowBytes:o,reason:d,probeError:null}}function ei(){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`. More help: https://www.kynver.com/help."}var Zs,Qs,xe,tt=f(()=>{"use strict";Zs=25*1024*1024*1024,Qs=12*1024*1024*1024,xe="/mnt/c"});import{execFileSync as on}from"node:child_process";import{existsSync as ir,readFileSync as sn,readdirSync as ri,statSync as ti}from"node:fs";import nt from"node:path";function sr(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function an(){let e=process.env.KYNVER_WSL_WIN_USER?.trim();if(e)return e;try{let n=on("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()||xe;return r&&ir(nt.join(t,"Users",r))?r:null}function ai(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()||xe,n=e.windowsUser??an();return n?`${t.replace(/\\/g,"/").replace(/\/$/,"")}/Users/${n}/AppData/Local/Temp/wsl-crashes`:null}function ui(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 li(){try{if(ir("/proc/sys/kernel/core_pattern"))return sn("/proc/sys/kernel/core_pattern","utf8").trim()}catch{}try{return on("sysctl",["-n","kernel.core_pattern"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function ci(e){return!!(e&&/wsl-capture-crash/i.test(e))}function di(e,r=xe){let t=nt.join(r,"Users",e,".wslconfig");if(!ir(t))return{maxCrashDumpCount:null,crashDumpFolder:null};let n;try{n=sn(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 p=Number(c);o=Number.isFinite(p)?p:null}else l==="crashdumpfolder"&&(s=c.replace(/^["']|["']$/g,"")||null)}return{maxCrashDumpCount:o,crashDumpFolder:s}}function pi(e){if(!ir(e))return[];let r=ri(e,{withFileTypes:!0}),t=[];for(let n of r){if(!n.isFile()||!n.name.toLowerCase().endsWith(".dmp"))continue;let o=nt.join(e,n.name);try{let s=ti(o),i=ui(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 _e(e={}){if(!(e.forceWsl===void 0?rt():e.forceWsl))return null;let t=e.hostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||xe,n=e.windowsUser??an(),o=e.warnBelowBytes??sr("KYNVER_WSL_CRASH_DUMP_WARN_BYTES",ni),s=e.criticalBelowBytes??sr("KYNVER_WSL_CRASH_DUMP_CRITICAL_BYTES",oi),i=e.warnCount??sr("KYNVER_WSL_CRASH_DUMP_WARN_COUNT",si),a=e.criticalCount??sr("KYNVER_WSL_CRASH_DUMP_CRITICAL_COUNT",ii),u=(e.readCorePattern??li)(),l=ci(u),c=null;n&&(c=(e.readWslConfig??di)(n,t));let p=c?.maxCrashDumpCount??null,m=p===-1,g=ai({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:p,dumpsDisabledInWslConfig:m,reason:null,probeError:"windows_user_unresolved"};let d;try{d=(e.listDumps??pi)(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:p,dumpsDisabledInWslConfig:m,reason:`WSL crash dump probe failed at ${g}: ${P.message}`,probeError:P.message}}let R=d.reduce((P,h)=>P+h.bytes,0),S=d.length,y=[...new Set(d.map(P=>P.executableHint).filter(P=>!!P))],A=R>=s,L=R>=o,B=S>=a,Ve=S>=i,ne=!(A||B||L||Ve),oe=null;if(!ne){let P=A||B?"critical":"warning",h=(R/1024**3).toFixed(1),X=y.length>0?y.join(", "):"unknown";oe=`WSL crash dumps ${P}: ${S} file(s), ${h} GiB at ${g} (executables: ${X}). `+mi({wslCaptureEnabled:l,dumpsDisabledInWslConfig:m})}return{ok:ne,path:g,windowsUser:n,dumpCount:S,totalBytes:R,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:d,executables:y,corePattern:u,wslCaptureEnabled:l,maxCrashDumpCount:p,dumpsDisabledInWslConfig:m,reason:oe,probeError:null}}function mi(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);"),r.push("More help: https://www.kynver.com/help."),r.join(" ")}var ni,oi,si,ii,ar=f(()=>{"use strict";tt();ni=5*1024*1024*1024,oi=10*1024*1024*1024,si=2,ii=4});import{statfsSync as fi}from"node:fs";function ur(e={}){let r=e.diskPath?.trim()||"/",t=e.diskFreeWarnBytes??gi,n=e.diskFreeCriticalBytes??hi,o=e.diskMaxUsedPercent??ki,s=e.diskHardMaxUsedPercent??Ri,i=fi(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,p=a<n,m=a<t*2,g=m&&l>o,d=m&&l>s,R=!c&&!p&&!g&&!d,S=e.skipWslHostCheck?null:nn(e.wslHost),y=e.skipWslCrashDumpCheck?null:_e(e.wslCrashDumps),A=R&&(S?S.ok:!0)&&(y?y.ok:!0),L=null;return A||(L=[p?`free space below critical ${n} bytes`:null,c?`free space below warning ${t} bytes`:null,d?`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("; ")),yi({ok:A,path:r,freeBytes:a,totalBytes:u,usedPercent:l,warnBelowBytes:t,criticalBelowBytes:n,maxUsedPercent:o,hardMaxUsedPercent:s,reason:L,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 yi(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 gi,hi,ki,Ri,lr=f(()=>{"use strict";ar();tt();gi=30*1024*1024*1024,hi=15*1024*1024*1024,ki=80,Ri=90});import{existsSync as bi,readdirSync as Si,statSync as vi}from"node:fs";import ot from"node:path";function cr(){return ln()}function st(){let{runsDir:e}=cr();return un(e)}function dr(e){return un(G(e))}function xi(e){try{return vi(e).isDirectory()}catch{return!1}}function un(e){if(!bi(e))return[];let r=[];for(let t of Si(e,{withFileTypes:!0})){if(t.name==="runs")continue;let n=ot.join(e,t.name);if(!xi(n))continue;let o=x(ot.join(n,"run.json"),void 0);o?.id&&r.push(o)}return r}function it(e){let{runsDir:r}=cr();Jr(ot.join(at(r,e.id),"run.json"),e)}function We(e){let{harnessRoot:r}=cr();return Te(r,e)}function Te(e,r){return at(G(e),v(r))}var ue=f(()=>{"use strict";Y();b()});import{existsSync as _i,readdirSync as Ei}from"node:fs";import Ci from"node:path";function ut(e){let r=new Set;for(let n of Object.keys(e.workers||{}))r.add(v(n));let t=Ci.join(We(e.id),"workers");if(!_i(t))return[...r];for(let n of Ei(t,{withFileTypes:!0}))n.isDirectory()&&r.add(v(n.name));return[...r]}var lt=f(()=>{"use strict";ue();b()});function ct(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.trim();if(!r)return null;let t=ct(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let u=ct(s[1]??"");u&&n.push(u)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let u=ct(r.slice(i,a+1));u&&n.push(u)}return n.length>0?n[n.length-1]:null}function dn(e){let r=e.finalResult??e.final_result;if(r!=null)return typeof r=="string"?cn(r)??(r.trim()||null):r;let t=typeof e.summary=="string"?e.summary.trim():"";if(!t)return null;let n=cn(t);return n||t}var pn=f(()=>{"use strict"});import{existsSync as wi,readFileSync as Ai}from"node:fs";function mn(e){return e==="complete"}function fn(e){return mn(e.lastHeartbeatPhase)?e.terminalFinalResult!==void 0&&e.terminalFinalResult!==null?e.terminalFinalResult:e.lastHeartbeatSummary?.trim()||"completed":null}function Ee(e){let r={heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,terminalFinalResult:null,heartbeatBlocker:null,timestampAnomalies:[],lastBoxResourceSnapshot:null,lastPrEvidence:[]};if(!wi(e))return r;let t=Date.now()+Pi,n=new Date(t).toISOString(),o=Ai(e,"utf8").split(`
|
|
6
|
-
`).filter(Boolean);for(let s of o){let i=Xe(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)),
|
|
7
|
-
`).find(Boolean)??o,160):"npm audit failed"}function
|
|
8
|
-
${e.stderr}`.trim(),t=
|
|
9
|
-
`).filter(Boolean),n=null;for(let o of t){let s=Xe(o);if(!s||typeof s!="object"||Array.isArray(s))continue;if(s.type==="turn.started"&&(n=null,r.finalResult=null),s.type==="item.completed"){let u=s.item;if(u&&typeof u=="object"&&!Array.isArray(u)){let l=u;l.type==="agent_message"&&typeof l.text=="string"&&l.text.trim()&&(n=l.text)}}s.type==="turn.completed"&&n&&!r.providerTerminalError&&(r.finalResult=n,n=null);let i=ta(s);if(i&&(r.firstEventAt||=i,r.lastEventAt=i),s.type==="stream_event"&&s.event&&typeof s.event=="object"&&s.event.type==="content_block_start"){let u=s.event.content_block;u?.type==="tool_use"&&(r.currentTool=String(u.name||"tool"))}if(s.type==="assistant"&&s.message&&typeof s.message=="object"){let u=s.message.content;if(Array.isArray(u)){let l=u.find(c=>c?.type==="tool_use");l&&(r.currentTool=String(l.name||r.currentTool))}}if(s.type==="tool_call"&&s.subtype==="started"){let u=s.tool_call&&typeof s.tool_call=="object"&&!Array.isArray(s.tool_call)?s.tool_call:void 0,l=na(u);l&&(r.currentTool=l)}let a=ua(s);if(a&&la(r,_n({command:a.command,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr,interleavedOutput:a.interleaved})),s.type==="result"&&oa(r,s),s.type==="turn.failed"){n=null,r.finalResult=null,r.providerTerminalError=!0;let u=s.error;r.error=typeof u?.message=="string"?u.message:"provider turn failed"}aa(r,s)}return r}var wn=f(()=>{"use strict";En();b();hr()});function An(e,r=240){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function ft(e){let r=(e??"").trim();if(!r)return null;if(Ke(r))return{blocked:!0,reason:`provider authentication failed: ${An(r)}`};for(let t of ca)if(t.test.test(r))return{blocked:!0,reason:`${t.label}: ${An(r)}`};return null}var ca,Pn=f(()=>{"use strict";hr();ca=[{test:/(?:claude provider refuses to spawn: worker prompt is empty after argv assembly|Input must be provided (?:either )?through stdin or as a prompt argument)/i,label:"provider prompt delivery failed"},{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 In(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function da(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 pa(e){return!e?.checked||e.headIsAncestorOfBase!==!1?null:In(e.head)}function ma(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 On(e){if(e.alive||da(e.finalResult))return null;let r=(e.changedFiles??[]).filter(i=>i.trim()).length,t=In(e.headCommit)??pa(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:ma(s,r,t)}}var Dn=f(()=>{"use strict"});function Be(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function fa(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 ga(e){if(Be(e.headCommit)||Be(e.prUrl)||Be(e.artifactBundlePath)||Be(e.patchPath))return!0;let r=e.gitAncestry;return!!(r?.checked&&r.headIsAncestorOfBase===!1&&Be(r.head))}function we(e){return fa(e.finalResult)?e.changedFiles.length===0?{blocked:!1}:ga(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 Nn(e){if(e.blocked)return e.detail??e.reason??"dirty_worktree_no_pr"}var kr=f(()=>{"use strict"});function gt(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 Wn(e){let r=e.targetPrReconciliation??e.target_pr_reconciliation??e.targetPrs??e.target_prs;return Array.isArray(r)?r.length:0}function Rr(e){let r=e.trim();if(!r)return null;let t=gt(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let c=gt(s[1]??"");c&&n.push(c)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let c=gt(r.slice(i,a+1));c&&n.push(c)}if(n.length===0)return null;let u=n[n.length-1],l=Wn(u);for(let c of n){let p=Wn(c);p>l&&(u=c,l=p)}return u}var ht=f(()=>{"use strict"});function Tn(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 Mn(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function ha(e){return new Set(e.map(r=>Mn(Tn(r)??r)).filter(Boolean))}function Un(e,r,t){let n=Tn(e)??e;if(!n)return"unrelated";let o=Mn(n);return ha(r).has(o)?"contract":t?(t.outcome==="skipped"||t.outcome==="blocked")&&t.reason?.trim()?"support":(t.outcome==="merged","unrelated"):"unrelated"}var Kn=f(()=>{"use strict"});function Ae(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function ka(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"?Object.keys(e).length>0:!0}function le(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`https://github.com/${r[1]}/pull/${r[2]}`:Ae(e)}function yr(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function Bn(e){let r=null;if(typeof e=="string"){let o=Rr(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=le(String(s.prUrl??s.pr_url??"")),a=Ae(s.outcome);!i||a!=="merged"&&a!=="skipped"&&a!=="blocked"||n.push({prUrl:i,outcome:a,mergeCommit:Ae(s.mergeCommit??s.merge_commit),reason:Ae(s.reason)})}return n}function Fn(e,r){let t=[],n=le(Ae(e.prUrl)??"");if(n&&t.push(n),r&&typeof r=="object"&&!Array.isArray(r)){let o=r,s=le(String(o.prUrl??o.pr_url??""));s&&t.push(s)}return[...new Set(t)]}function Hn(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(!ka(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?le(Ae(r.targetPrUrl)??"")??(r.targetPrUrls.length===1?le(r.targetPrUrls[0]):null):null;if(s){let p=Fn(t,n);if(!(n&&typeof n=="object"&&!Array.isArray(n)&&n.supersedesOriginalTargetPr===!0)){for(let R of p)if(R!==s)return{blocked:!0,reason:"duplicate_repair_pr",detail:`Repair worker opened or attached PR ${R} instead of canonical target ${s}`}}let d=Bn(n).find(R=>R.prUrl===s);if(!d||d.outcome!=="merged"&&!(d.reason?.trim()&&(d.outcome==="skipped"||d.outcome==="blocked")))return{blocked:!0,reason:"missing_repair_target_reconciliation",detail:`Repair worker must reconcile target PR ${s}`}}let i=Bn(n),a=new Map(i.map(p=>[yr(p.prUrl),p])),u=new Set(r.targetPrUrls.map(p=>yr(le(p)??p)).filter(Boolean)),l=Fn(t,n);if(r.landingOnly)for(let p of l){let m=a.get(yr(p)),g=Un(p,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 ${p}`}:{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 p of r.targetPrUrls){let m=yr(le(p)??p),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(p=>a.has(p))?"incomplete_target_pr_landing":"missing_target_pr_reconciliation",detail:`Target PR reconciliation incomplete: ${c.join(", ")}`}:{blocked:!1}}function Ln(e){if(e.blocked)return e.detail??e.reason}var jn=f(()=>{"use strict";ht();Kn()});function ba(e){let r=Date.now();if(e.providerTerminalError||gr(e.finalResult)||e.finalResult&&e.error?.trim()||Ke(e.error)||Ke(e.finalResult)){let o=e.error||(typeof e.finalResult=="string"?e.finalResult:"provider terminal error");return{state:"blocked",reason:ft(o)?.reason??`provider terminal error: ${o}`}}if(e.completionBlocker&&!$n(e.completionBlocker))return{state:"blocked",reason:e.completionBlocker};if(e.finalResult){if(e.localOnly&&va(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=we(o);if(s.blocked){let i=Nn(s);return{state:"needs_attention",reason:s.reason?`landing blocked (${s.reason}): ${i}`:`landing blocked: ${i}`}}if(e.landingContract){let i=Hn({contract:e.landingContract,snapshot:o,finalResult:e.finalResult}),a=Ln(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(Sa(e))return{state:"done",reason:"empty abandoned worker record"};let o=ft(e.error);if(o)return{state:"blocked",reason:o.reason};let s=On({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>Ra)return{state:"needs_attention",reason:`no first stream event ${qr(t)}s after start`};let n=e.lastActivityAt?Date.parse(e.lastActivityAt):NaN;return Number.isFinite(n)&&r-n>ya?{state:"stale",reason:`no log/event/heartbeat activity for ${qr(n)}s`}:{state:"ok",reason:"recent activity"}}function $n(e){let r=e?.trim();return r?/completion acknowledged but board not advanced/i.test(r)&&/task already terminal/i.test(r):!1}function Sa(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 va(e){let r=null;if(typeof e=="string"?r=Rr(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 xa(e,r,t){let n=e.completionSnapshot?.finalResult;return e.completionAckSource==="local-pr-merged-reconcile"&&n!==void 0&&n!==null?n:r||(n??fn(t))}function Fe(e,r={}){let t=Cn(e.stdoutPath),n=Ee(e.heartbeatPath),o=typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim().length>0,s=xa(e,t.finalResult,n),i=o?!1:ee(e.pid),a=Ze(e.stdoutPath),u=Ze(e.stderrPath),l=Ze(e.heartbeatPath),c=Ne(e.worktreePath),p=er(e.worktreePath,{base:r.base,baseCommit:r.baseCommit}),m=Xt([t.lastEventAt,n.lastHeartbeatAt,Qe(e.stdoutPath),Qe(e.stderrPath),Qe(e.heartbeatPath)]),g=t.error||!i&&!s&&qt(e.stderrPath,10).trim()||void 0,d=typeof e.completionBlocker=="string"&&e.completionBlocker.trim()?e.completionBlocker.trim():null,R=$n(d)?null:d,S=e.repairTargetPrUrl?{landingOnly:!1,targetPrUrls:[e.repairTargetPrUrl],targetPrUrl:e.repairTargetPrUrl,repairEnforceOriginalPr:!0}:null,y=ba({alive:i,finalResult:s,firstEventAt:t.firstEventAt,stdoutBytes:a,stderrBytes:u,heartbeatBytes:l,lastActivityAt:m,heartbeatBlocker:n.heartbeatBlocker,startedAt:e.startedAt,error:g,providerTerminalError:t.providerTerminalError,changedFiles:c,gitAncestry:p,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,providerTerminalError:t.providerTerminalError,changedFiles:c,gitAncestry:p,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 ce(e){return!!(e.finalResult||e.alive===!1||e.status==="exited"||e.status==="done")}function Gn(e){return e.finalResult?e.attention.state==="needs_attention"||e.attention.state==="blocked":!1}var Ra,ya,de=f(()=>{"use strict";pr();wn();hr();Pn();Dn();K();kr();jn();ht();b();Ra=18e4,ya=6e5});var Yn=f(()=>{"use strict";de()});function Vn(e,r={}){let t=r.perWorkerMemBytes??kt,n=r.memReserveBytes??Rt,o=r.memUtilization??yt,s=Math.max(0,Math.floor(e*o)-n),i=Math.max(1,Math.floor(s/t));return Math.min(i,br)}var kt,Rt,yt,br,zn=f(()=>{"use strict";tn();me();ae();or();Sr();lr();ue();lt();Yn();b();kt=500*1024*1024,Rt=4*1024*1024*1024,yt=.85,br=64});function He(e,r){let t=Number(e);return!Number.isFinite(t)||t<=0?r:Math.floor(t)}function bt(e){let r=e.config??{},t=e.env??process.env,n=He(r.perWorkerMemBytes,kt),o=He(r.memReserveBytes,Rt),s=Math.min(1,Math.max(.1,Number(r.memUtilization)>0?Number(r.memUtilization):yt)),i=Vn(e.totalMemBytes,{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s});if(e.configuredMaxWorkersOverride!==void 0&&e.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:He(e.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(r.maxConcurrentWorkers!==void 0&&r.maxConcurrentWorkers!==null){let l=He(r.maxConcurrentWorkers,0)||null;if(l)return{configuredMaxWorkers:Math.min(l,br),autoCap:i,workerCapSource:"config"}}let u=(t.KYNVER_MAX_WORKERS_INTENTIONAL==="1"||t.KYNVER_MAX_WORKERS_INTENTIONAL==="true")&&t.KYNVER_MAX_WORKERS&&He(t.KYNVER_MAX_WORKERS,0)||null;return u?{configuredMaxWorkers:Math.min(u,br),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var Sr=f(()=>{"use strict";zn()});import{homedir as _a}from"node:os";import Ea from"node:path";var Jn,St=f(()=>{"use strict";Jn=Ea.join(_a(),".kynver",".env")});var qn=f(()=>{"use strict"});var Xn=f(()=>{"use strict";qn()});var Zn=f(()=>{"use strict"});var Qn=f(()=>{"use strict";b()});var vt=f(()=>{"use strict";Xn();Zn();Qn()});var eo=f(()=>{"use strict"});var ro=f(()=>{"use strict";eo()});var vr=f(()=>{"use strict";St();se();me();vt();ro()});var oo=f(()=>{"use strict";ae();ae()});var so=f(()=>{"use strict";St();vt();vr()});var xt=f(()=>{"use strict"});import{existsSync as V,mkdirSync as wa,readdirSync as xr,renameSync as io,statSync as Aa}from"node:fs";import z from"node:path";function uo(e){try{return Aa(e).isDirectory()}catch{return!1}}function Pa(e){if(!V(e))return!0;for(let r of ao){let t=z.join(e,r);if(V(t)&&(!uo(t)||xr(t).length>0))return!1}return!0}function Ia(e){let r=z.join(e,"runs");if(!V(r)||!uo(r))return!1;for(let t of xr(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 Oa(e){let r=z.join(e,"runs");if(!V(r))return!1;for(let t of xr(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 Da(e){let r=z.join(e,"ghost");return V(r)?!V(z.join(r,"runs")):Oa(e)}function lo(e){return Ia(e.sharedRoot)?Pa(e.forgeRoot)?Da(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 co(e,r){wa(r,{recursive:!0});for(let t of ao){let n=z.join(e,t),o=z.join(r,t);if(V(n)){if(V(o)&&xr(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(V(o)){io(n,o);continue}io(n,o)}}}var ao,po=f(()=>{"use strict";b();ao=["runs","worktrees"]});import{existsSync as C}from"node:fs";import{homedir as Na}from"node:os";import E from"node:path";function _t(e=process.env){return e.HOME?.trim()||Na()}function Et(e=process.env){return E.join(_t(e),".kynver","harness")}function _r(e){let r=E.resolve(Q(e.trim()));for(;Wa.has(E.basename(r));)r=E.dirname(r);return r}function Ta(e,r=process.env){return E.join(Et(r),e)}function Ma(e=process.env){let r=Et(e);if(C(E.join(r,"runs")))return!0;if(C(r)&&!C(E.join(r,"ghost"))&&!C(E.join(r,"forge")))return C(r);let t=E.join(_t(e),mo);return C(t)}function Er(e){let r=e.env??process.env,t=r.KYNVER_HARNESS_ROOT?.trim()||r.OPUS_HARNESS_ROOT?.trim();if(t)return{harnessRoot:_r(t),source:"env"};let n=e.configuredHarnessRoot?.trim();if(n)return{harnessRoot:_r(n),source:"config"};let o=Ta(e.boxKind,r);if(C(E.join(o,"runs"))||C(o)&&!Ua(o))return{harnessRoot:o,source:"box_scoped"};let i=Et(r);if(e.boxKind==="forge"){let a=lo({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&&co(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(e.boxKind==="ghost"&&Ma(r)){if(C(E.join(i,"runs")))return{harnessRoot:i,source:"legacy_shared"};if(C(i)&&!C(E.join(i,"ghost"))&&!C(E.join(i,"forge")))return{harnessRoot:i,source:"legacy_shared"};let u=E.join(_t(r),mo);if(C(u))return{harnessRoot:u,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function Ua(e){if(!C(e))return!0;for(let r of["runs","worktrees"]){let t=E.join(e,r);if(C(t))return!1}return!0}var mo,Wa,Ct=f(()=>{"use strict";se();po();mo=E.join(".openclaw","harness");Wa=new Set(["runs","worktrees"])});import fo from"node:os";function Cr(e){return e?.trim()?e.trim():null}function Ka(e,r){let t=r.trim().toLowerCase()||"host";return`${e}-${t}`.replace(/[^a-z0-9._-]+/g,"-")}function Ba(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 wr(e=pe(),r=process.env,t={}){let n=ve(r,e),o=[...n.warnings],s=[],i=!!(e.boxKind?.trim()||Cr(r.KYNVER_BOX_KIND)),a=t.strict===!0||Ba(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=Cr(e.runnerId),l=Cr(r.KYNVER_RUNTIME_ID)??Cr(r.OPENCLAW_RUNTIME_ID),c=u??l??Ka(n.boxKind,fo.hostname()),p=u?"config":l?"env":"derived";p==="derived"&&o.push(`runnerId not persisted \u2014 using derived id "${c}"; run \`kynver setup --box-kind ${n.boxKind}\` to persist runner identity`);let m=bt({config:e,env:r,totalMemBytes:fo.totalmem()}),g=nr(n.boxKind,m.configuredMaxWorkers??et(n.boxKind,m.autoCap)),d=Er({boxKind:n.boxKind,configuredHarnessRoot:e.harnessRoot,env:r});return d.migrationBlocker&&s.push(d.migrationBlocker),s.length>0?{ok:!1,identity:null,errors:s,warnings:o}:{ok:!0,identity:{boxKind:n.boxKind,boxKindSource:n.source,runnerId:c,runnerIdSource:p,maxConcurrentWorkers:g,workerCapSource:m.workerCapSource,harnessRoot:d.harnessRoot,harnessRootSource:d.source},errors:s,warnings:o}}var Ar=f(()=>{"use strict";me();ae();or();Sr();Ct()});var ho=f(()=>{"use strict";rr();ae();oo();me();vr();so();Qr();xt();Ar()});var La,Tp,ko=f(()=>{"use strict";La=["claude","cursor","codex","gemini","gemini-api","openai-compatible"],Tp=La.join("|")});import{existsSync as $a,mkdirSync as Yp,readFileSync as Ga,writeFileSync as Vp}from"node:fs";import{homedir as Ya,totalmem as Jp}from"node:os";import wt from"node:path";function Va(e){return{...e,...e.harnessRoot?.trim()?{harnessRoot:Q(e.harnessRoot.trim())}:{},...e.defaultRepo?.trim()?{defaultRepo:Q(e.defaultRepo.trim())}:{}}}function pe(){if(!$a(Ro))return{};try{return Va(JSON.parse(Ga(Ro,"utf8")))}catch{return{}}}var yo,Ro,lm,cm,dm,me=f(()=>{"use strict";rr();se();Qr();ae();or();Sr();lr();vr();ho();ko();Ar();xt();yo=wt.join(Ya(),".kynver"),Ro=wt.join(yo,"config.json"),lm=wt.join(yo,"credentials");cm=500*1024*1024,dm=4*1024*1024*1024});import At from"node:path";function O(e){return _r(e)}function re(){let e=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(e)return O(e);let r=pe(),t=r.harnessRoot?.trim();if(t)return O(t);let n=wr(r,process.env);return n.identity?n.identity.harnessRoot:Er({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function G(e){return At.join(O(e),"runs")}function Pe(e){return At.join(O(e),"worktrees")}function ln(){let e=re();return{harnessRoot:e,runsDir:G(e),worktreesDir:Pe(e)}}function at(e,r){return At.join(e,v(r))}var Y=f(()=>{"use strict";me();Ct();Ar();b()});Y();import T from"node:path";kr();import Or from"node:path";K();de();var Pt=[".next",".turbo","dist","build",".cache","node_modules/.cache"];function bo(e){let r=e.replace(/\\/g,"/").replace(/\/+$/,"");if(r==="node_modules"||r.startsWith("node_modules/"))return!0;for(let t of Pt)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!bo(n)})}function fe(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 Le(e){let r=e.gitAncestry?.relation;return r==="merged"||r==="synced"?D(e.changedFiles).length>0:!!(fe(e.finalResult)||r==="ahead"||r==="diverged"||e.changedFiles.length>0&&e.finalResult)}b();function je(e){return e.status||(e.status=Fe(e.worker,{base:e.run.base,baseCommit:e.run.baseCommit})),e.status}function It(e,r){if(e.status)return D(e.status.changedFiles).length>0;let t=r?r.porcelain(e.worktreePath):Ne(e.worktreePath);return D(t).length>0}function za(e){let r=e.worker.completionSnapshot?.finalResult;return r??(e.worker.taskPrUrl?{prUrl:e.worker.taskPrUrl}:null)}function Ot(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=za(e);if(o&&!ee(t.pid)){let i=r?.gitStatusCache?r.gitStatusCache.porcelain(e.worktreePath):Ne(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"}:er(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??fe(s)};return e.status=c,c}return je(e)}de();ue();lt();de();b();import Ja from"node:path";var qa=new Set(["running","dispatching","pending","queued","needs_attention"]),ge=new Set(["completed","failed","cancelled","done"]);function he(e){let r=ut(e);if(r.length===0)return"failed";let t=!1,n=!1,o=!1,s=!1;for(let i of r){let a=x(Ja.join(We(e.id),"workers",v(i),"worker.json"),void 0);if(!a)continue;let u=Fe(a,{base:e.base,baseCommit:e.baseCommit});if(u.alive&&!u.finalResult){t=!0;break}typeof a.completionBlocker=="string"&&a.completionBlocker&&(o=!0),Gn(u)&&(s=!0),u.finalResult&&u.attention.state==="done"&&(n=!0)}return t||o||s?null:n?"completed":"failed"}function So(){let e=[];for(let r of st()){if(!qa.has(r.status))continue;let t=he(r);if(!t||t===r.status)continue;let n=r.status;r.status=t,it(r),e.push({runId:r.id,from:n,to:t})}return e}de();pr();import{existsSync as Pr,mkdirSync as qm,readdirSync as _o,renameSync as Xm,statSync as Xa}from"node:fs";import ke from"node:path";me();rr();se();Zr();K();pr();Y();ue();Y();b();import te from"node:path";var Gm=`${te.sep}runs${te.sep}runs${te.sep}`;function vo(e){return{workerJsonPath:te.join(e,"worker.json"),stdoutPath:te.join(e,"stdout.jsonl"),stderrPath:te.join(e,"stderr.log"),heartbeatPath:te.join(e,"heartbeat.jsonl"),lastStatusPath:te.join(e,"last-status.json")}}b();var $e=900*1e3,af=3600*1e3;function Eo(e,r){let t=ke.resolve(e),n=ke.resolve(G(r)),o=ke.relative(n,t);return o!==".."&&!o.startsWith("..")&&!ke.isAbsolute(o)}function Za(e){if(!Pr(e))return[];try{return _o(e,{withFileTypes:!0}).filter(r=>r.isDirectory()&&r.name!=="runs").map(r=>r.name)}catch{return[]}}function Qa(e){let r=ke.join(e,"workers");if(!Pr(r))return[];try{return _o(r,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}}function xo(e,r,t){if(!Pr(e))return!1;try{let n=r-Xa(e).mtimeMs;return Number.isFinite(n)&&n>=0&&n<t}catch{return!1}}function eu(e,r=Date.now(),t=$e){if(!Pr(e))return!1;let n=vo(e),o=x(n.workerJsonPath,void 0);if(o?.status==="running"&&ee(o.pid))return!0;let s=Ee(n.heartbeatPath);if(s.lastHeartbeatAt){let i=r-Date.parse(s.lastHeartbeatAt);if(Number.isFinite(i)&&i>=0&&i<t)return!0}return!!(xo(n.stdoutPath,r,t)||xo(n.heartbeatPath,r,t))}function ru(e,r=Date.now(),t=$e){for(let n of Qa(e))if(eu(ke.join(e,"workers",n),r,t))return!0;return!1}function Co(e,r=Date.now()){let t=new Set,n=G(e);for(let o of Za(n)){let s=ke.join(n,o);ru(s,r)&&t.add(`${e}\0${o}`)}return t}b();function tu(e,r=Date.now(),t=$e){let n=Ee(e.heartbeatPath);if(!n.lastHeartbeatAt)return!1;let o=r-Date.parse(n.lastHeartbeatAt);return Number.isFinite(o)&&o>=0&&o<t}function Ie(e,r=Date.now(),t=$e){return ee(e.pid)?!0:tu(e,r,t)}function nu(e,r){return r?r.runTerminalCache.derive(e.run):he(e.run)}function J(e,r=Date.now()){return Ie(e.worker,r)}function Dt(e,r){return ge.has(e.run.status)?!1:nu(e,r)!==null}function wo(e,r,t=Date.now()){if(J(e,t))return!0;if(ge.has(e.run.status)||Dt(e,r))return!1;let n=je(e);return ce(n)?!1:!!J(e,t)}kr();de();function Ao(e,r){if(!(typeof e.worker.completionBlocker=="string"?e.worker.completionBlocker.trim():""))return!1;if(J(e))return!0;let n=r??je(e);return!!(!ce(n)||Le(n)||D(n.changedFiles).length>0||we({finalResult:n.finalResult,changedFiles:n.changedFiles,gitAncestry:n.gitAncestry,prUrl:fe(n.finalResult)}).blocked)}K();b();import{existsSync as Io,mkdirSync as ou,writeFileSync as Po}from"node:fs";import Ir from"node:path";function Oo(e,r,t){return Ir.join(e,"salvage",v(r),v(t))}function Do(e){return Io(Ir.join(Oo(e.harnessRoot,e.runId,e.workerName),"evidence.json"))}function No(e){let r=Oo(e.harnessRoot,e.indexed.runId,e.indexed.workerName);ou(r,{recursive:!0});let t=Ir.join(r,"salvage.patch"),n=!1;if(Io(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
|
-
`);a.trim()&&(
|
|
4
|
+
`):""}function ee(e){if(!e)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Qt(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 qr(e){return Math.max(0,Math.round((Date.now()-e)/1e3))}var b=g(()=>{"use strict";Jt()});var Qs,Ml,ei,Ul,en=g(()=>{"use strict";Qs=["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"],Ml=new Set(Qs),ei=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY","GEMINI_API_KEY"],Ul=new Set(ei)});import{spawnSync as tn}from"node:child_process";function Se(e,r,t={}){let n=tn("git",r,zr({cwd:e,encoding:"utf8"}));if(n.status!==0&&!t.allowFailure){let o=ri(e,r,n);if(t.throwError)throw new Error(o);qe(o)}return n.stdout||""}function ri(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 Ne(e){return Se(e,["status","--short"],{allowFailure:!0}).split(`
|
|
5
|
+
`).map(r=>r.trim()).filter(Boolean)}function w(e,r){try{let t=tn("git",r,zr({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 rn(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 er(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 Xr(n,"missing worktree path");let s=w(e,["rev-parse","HEAD"]);if(s.status!==0)return Xr(n,s.error||s.stderr||s.stdout||"failed to resolve HEAD");let i;if(o)i=o;else{let p=w(e,["rev-parse",n]);if(p.status!==0)return Xr(n,p.error||p.stderr||p.stdout||`failed to resolve ${n}`,s.stdout.trim());i=p.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=rn(e,i,a),l=rn(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 Xr(e,r,t=null){return{checked:!1,base:e,head:t,baseHead:null,baseIsAncestorOfHead:null,headIsAncestorOfBase:null,relation:"unknown",error:r}}var K=g(()=>{"use strict";se();b();en()});var Zr=g(()=>{"use strict";K()});var rr=g(()=>{"use strict";K();se();Zr()});var Qr=g(()=>{"use strict";b()});function ie(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 tr(e,r){return e[r]?.trim()||null}function nn(e){let r=e?.split(":")[0]?.trim();return r?ie(r):null}function ve(e=process.env,r={}){let t=[],n=nn(r.boxId),o=nn(tr(e,"KYNVER_BOX_ID")),s=r.boxKind?.trim();if(s)return n&&n!==ie(s)&&t.push(`config.boxId=${r.boxId} conflicts with boxKind=${s}; using explicit boxKind=${s}`),{boxKind:ie(s),source:"config",slugInferenceBlocked:!1,warnings:t};let i=tr(e,"KYNVER_BOX_KIND");if(i)return o&&o!==ie(i)&&t.push(`KYNVER_BOX_ID=${tr(e,"KYNVER_BOX_ID")} conflicts with KYNVER_BOX_KIND=${i}; using explicit KYNVER_BOX_KIND=${i}`),{boxKind:ie(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=tr(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 ae=g(()=>{"use strict"});function et(e,r){return e==="forge"?4:Math.max(1,r)}function nr(e,r){return e==="forge"?Math.min(Math.max(1,r),4):Math.max(1,r)}var or=g(()=>{"use strict"});var on=g(()=>{"use strict"});import{existsSync as ti,readFileSync as ni,statfsSync as oi}from"node:fs";function rt(){if(process.platform!=="linux")return!1;for(let e of["/proc/sys/kernel/osrelease","/proc/version"])try{if(!ti(e))continue;let r=ni(e,"utf8");if(/microsoft|wsl/i.test(r))return!0}catch{}return!1}function sn(e={}){if(!(e.forceWsl===void 0?rt():e.forceWsl))return null;let t=e.wslHostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||xe,n=e.wslHostFreeWarnBytes??si,o=e.wslHostFreeCriticalBytes??ii,s=e.statfs??oi,i;try{i=s(t)}catch(y){return{ok:!1,path:t,freeBytes:0,totalBytes:0,usedPercent:100,warnBelowBytes:n,criticalBelowBytes:o,reason:`Windows host disk probe failed at ${t}: ${y.message}`,probeError:y.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,p=!c&&!d,f=(a/(1024*1024*1024)).toFixed(1),m=null;return p||(m=`Windows host disk ${t} at ${d?"critical":"warning"}: ${f} GiB free (<${(d?o:n)/1024/1024/1024} GiB); WSL VHDX cannot grow safely. ${ai()}`),{ok:p,path:t,freeBytes:a,totalBytes:u,usedPercent:l,warnBelowBytes:n,criticalBelowBytes:o,reason:m,probeError:null}}function ai(){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`. More help: https://www.kynver.com/help."}var si,ii,xe,tt=g(()=>{"use strict";si=25*1024*1024*1024,ii=12*1024*1024*1024,xe="/mnt/c"});import{execFileSync as an}from"node:child_process";import{existsSync as ir,readFileSync as un,readdirSync as ui,statSync as li}from"node:fs";import nt from"node:path";function sr(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function ln(){let e=process.env.KYNVER_WSL_WIN_USER?.trim();if(e)return e;try{let n=an("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()||xe;return r&&ir(nt.join(t,"Users",r))?r:null}function fi(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()||xe,n=e.windowsUser??ln();return n?`${t.replace(/\\/g,"/").replace(/\/$/,"")}/Users/${n}/AppData/Local/Temp/wsl-crashes`:null}function gi(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 hi(){try{if(ir("/proc/sys/kernel/core_pattern"))return un("/proc/sys/kernel/core_pattern","utf8").trim()}catch{}try{return an("sysctl",["-n","kernel.core_pattern"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function ki(e){return!!(e&&/wsl-capture-crash/i.test(e))}function yi(e,r=xe){let t=nt.join(r,"Users",e,".wslconfig");if(!ir(t))return{maxCrashDumpCount:null,crashDumpFolder:null};let n;try{n=un(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 Ri(e){if(!ir(e))return[];let r=ui(e,{withFileTypes:!0}),t=[];for(let n of r){if(!n.isFile()||!n.name.toLowerCase().endsWith(".dmp"))continue;let o=nt.join(e,n.name);try{let s=li(o),i=gi(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 _e(e={}){if(!(e.forceWsl===void 0?rt():e.forceWsl))return null;let t=e.hostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||xe,n=e.windowsUser??ln(),o=e.warnBelowBytes??sr("KYNVER_WSL_CRASH_DUMP_WARN_BYTES",ci),s=e.criticalBelowBytes??sr("KYNVER_WSL_CRASH_DUMP_CRITICAL_BYTES",di),i=e.warnCount??sr("KYNVER_WSL_CRASH_DUMP_WARN_COUNT",pi),a=e.criticalCount??sr("KYNVER_WSL_CRASH_DUMP_CRITICAL_COUNT",mi),u=(e.readCorePattern??hi)(),l=ki(u),c=null;n&&(c=(e.readWslConfig??yi)(n,t));let d=c?.maxCrashDumpCount??null,p=d===-1,f=fi({hostMount:t,windowsUser:n,crashDumpDir:e.crashDumpDir});if(!f)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:p,reason:null,probeError:"windows_user_unresolved"};let m;try{m=(e.listDumps??Ri)(f)}catch(P){return{ok:!1,path:f,windowsUser:n,dumpCount:0,totalBytes:0,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:[],executables:[],corePattern:u,wslCaptureEnabled:l,maxCrashDumpCount:d,dumpsDisabledInWslConfig:p,reason:`WSL crash dump probe failed at ${f}: ${P.message}`,probeError:P.message}}let y=m.reduce((P,h)=>P+h.bytes,0),S=m.length,R=[...new Set(m.map(P=>P.executableHint).filter(P=>!!P))],A=y>=s,L=y>=o,B=S>=a,Ve=S>=i,ne=!(A||B||L||Ve),oe=null;if(!ne){let P=A||B?"critical":"warning",h=(y/1024**3).toFixed(1),X=R.length>0?R.join(", "):"unknown";oe=`WSL crash dumps ${P}: ${S} file(s), ${h} GiB at ${f} (executables: ${X}). `+bi({wslCaptureEnabled:l,dumpsDisabledInWslConfig:p})}return{ok:ne,path:f,windowsUser:n,dumpCount:S,totalBytes:y,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:m,executables:R,corePattern:u,wslCaptureEnabled:l,maxCrashDumpCount:d,dumpsDisabledInWslConfig:p,reason:oe,probeError:null}}function bi(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);"),r.push("More help: https://www.kynver.com/help."),r.join(" ")}var ci,di,pi,mi,ar=g(()=>{"use strict";tt();ci=5*1024*1024*1024,di=10*1024*1024*1024,pi=2,mi=4});import{statfsSync as Si}from"node:fs";function ur(e={}){let r=e.diskPath?.trim()||"/",t=e.diskFreeWarnBytes??vi,n=e.diskFreeCriticalBytes??xi,o=e.diskMaxUsedPercent??_i,s=e.diskHardMaxUsedPercent??Ei,i=Si(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,p=a<t*2,f=p&&l>o,m=p&&l>s,y=!c&&!d&&!f&&!m,S=e.skipWslHostCheck?null:sn(e.wslHost),R=e.skipWslCrashDumpCheck?null:_e(e.wslCrashDumps),A=y&&(S?S.ok:!0)&&(R?R.ok:!0),L=null;return A||(L=[d?`free space below critical ${n} bytes`:null,c?`free space below warning ${t} bytes`:null,m?`used percent above hard cap ${s}%`:null,f?`used percent above cap ${o}%`:null,S&&!S.ok?S.reason:null,R&&!R.ok?R.reason:null].filter(Boolean).join("; ")),Ci({ok:A,path:r,freeBytes:a,totalBytes:u,usedPercent:l,warnBelowBytes:t,criticalBelowBytes:n,maxUsedPercent:o,hardMaxUsedPercent:s,reason:L,wslHost:S,wslCrashDumps:R?{ok:R.ok,path:R.path,dumpCount:R.dumpCount,totalBytes:R.totalBytes,executables:R.executables,wslCaptureEnabled:R.wslCaptureEnabled,dumpsDisabledInWslConfig:R.dumpsDisabledInWslConfig,reason:R.reason,probeError:R.probeError}:null})}function Ci(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 vi,xi,_i,Ei,lr=g(()=>{"use strict";ar();tt();vi=30*1024*1024*1024,xi=15*1024*1024*1024,_i=80,Ei=90});import{existsSync as wi,readdirSync as Ai,statSync as Pi}from"node:fs";import ot from"node:path";function cr(){return dn()}function st(){let{runsDir:e}=cr();return cn(e)}function dr(e){return cn(G(e))}function Ii(e){try{return Pi(e).isDirectory()}catch{return!1}}function cn(e){if(!wi(e))return[];let r=[];for(let t of Ai(e,{withFileTypes:!0})){if(t.name==="runs")continue;let n=ot.join(e,t.name);if(!Ii(n))continue;let o=x(ot.join(n,"run.json"),void 0);o?.id&&r.push(o)}return r}function it(e){let{runsDir:r}=cr();Jr(ot.join(at(r,e.id),"run.json"),e)}function We(e){let{harnessRoot:r}=cr();return Te(r,e)}function Te(e,r){return at(G(e),v(r))}var ue=g(()=>{"use strict";Y();b()});import{existsSync as Oi,readdirSync as Di}from"node:fs";import Ni from"node:path";function ut(e){let r=new Set;for(let n of Object.keys(e.workers||{}))r.add(v(n));let t=Ni.join(We(e.id),"workers");if(!Oi(t))return[...r];for(let n of Di(t,{withFileTypes:!0}))n.isDirectory()&&r.add(v(n.name));return[...r]}var lt=g(()=>{"use strict";ue();b()});function ct(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 pn(e){let r=e.trim();if(!r)return null;let t=ct(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let u=ct(s[1]??"");u&&n.push(u)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let u=ct(r.slice(i,a+1));u&&n.push(u)}return n.length>0?n[n.length-1]:null}function mn(e){let r=e.finalResult??e.final_result;if(r!=null)return typeof r=="string"?pn(r)??(r.trim()||null):r;let t=typeof e.summary=="string"?e.summary.trim():"";if(!t)return null;let n=pn(t);return n||t}var fn=g(()=>{"use strict"});import{existsSync as Wi,readFileSync as Ti}from"node:fs";function gn(e){return e==="complete"}function hn(e){return gn(e.lastHeartbeatPhase)?e.terminalFinalResult!==void 0&&e.terminalFinalResult!==null?e.terminalFinalResult:e.lastHeartbeatSummary?.trim()||"completed":null}function Ee(e){let r={heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,terminalFinalResult:null,heartbeatBlocker:null,timestampAnomalies:[],lastBoxResourceSnapshot:null,lastPrEvidence:[]};if(!Wi(e))return r;let t=Date.now()+Mi,n=new Date(t).toISOString(),o=Ti(e,"utf8").split(`
|
|
6
|
+
`).filter(Boolean);for(let s of o){let i=Xe(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)),gn(r.lastHeartbeatPhase)&&(r.terminalFinalResult=mn(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 Mi,pr=g(()=>{"use strict";fn();b();Mi=6e4});function yn(e){return e?(e.split("/").pop()??e).replace(/\.exe$/i,"").toLowerCase():null}function mr(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 Rn(e){let r=yn(e[0]);return!!(r&&Ui.has(r))}function Bi(e){let r=e.trim();return r.includes("/")?r.split("/").pop()??r:r}function Fi(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 bn(e){return!e||e.includes("/")||e.includes("*")?!1:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(e)}function dt(e){if(!e)return!1;let r=e.trim();return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")}function Hi(e){if(!e.startsWith("--glob="))return e;let r=e.slice(7);return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")?`--glob=${r}/**`:e}function Li(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;kn.has(n)&&(t+=1);continue}r.push(n)}}return r}function ji(e){let r=!1,t=e.map((o,s)=>{let i=Hi(o),a=e[s-1];return a&&kn.has(a)&&o.startsWith("!")&&!o.includes("/")&&!o.endsWith("/**")&&(i=`${o}/**`),i!==o&&(r=!0),i}),n=Li(t);if(n.length===2){let[o,s]=n;if(dt(s))return{argv:[t[0]??"rg",o,"-g",`${s}/**`,"."],changed:!0};let i=Fi(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 Sn(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 fr(e){let r=e.trim();if(!r)return{command:r,wrapped:!1};let t=mr(r);if(!t.length)return{command:r,wrapped:!1};let n=yn(t[0]);if(!n||!Ki.has(n))return{command:r,wrapped:!1};let o=Sn(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 $i(e,r){let t=e.trim(),n=mr(t),o=Sn(n);if(o<0)return r;let s=n.slice(0,o).join(" "),i=r.includes("'")?`"${r.replace(/"/g,'\\"')}"`:`'${r}'`;return`${s} ${i}`}function Gi(e){let r=e.trim(),t=fr(r),n=mr(t.command);if(!n.length||!Rn(n))return{segment:r,changed:!1};let o=ji(n);if(!o.changed)return{segment:r,changed:!1};let s=o.argv.join(" ");return t.wrapped?{segment:$i(r,s),changed:!0}:{segment:s,changed:!0}}function pt(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=Gi(i);return a.changed&&(o=!0),a.segment});return o?{command:s.join(t),changed:!0}:{command:r,changed:!1}}function vn(e){let r=fr(e).command,t=mr(r.trim());return t.length&&Rn(t)?!0:/\b(rg|ripgrep)\b/i.test(r)}function xn(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 Yi(e){let{pattern:r,target:t}=xn(e);return r?dt(t)?{kind:"rg_exclude_syntax",pattern:r,target:t}:bn(t)?{kind:"bad_scope",pattern:r,target:t}:{kind:"not_repo_search",pattern:r,target:t}:{kind:"not_repo_search"}}function Vi(e){let{pattern:r,target:t}=xn(e);if(!r)return null;if(dt(t)){let n=`${t.trim()}/**`;return{command:`rg "${r}" -g '${n}' .`,changed:!0}}return t&&bn(t)?{command:`rg -g ${t} "${r}" .`,changed:!0}:null}function zi(e){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 Ji(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 mt(e){let r=e.meta?.trim()||(e.command?Ji(e.command):null)||null;if(r){let t=Yi(r),n=zi(t);if(n)return n;let o=Vi(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=pt(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 Ui,Ki,kn,_n=g(()=>{"use strict";Ui=new Set(["rg","ripgrep","grep"]),Ki=new Set(["bash","sh","dash","zsh"]),kn=new Set(["-e","--regexp","-f","--file","-m","--max-count","-A","--after-context","-B","--before-context","-C","--context","-g","--glob","--iglob"])});function Me(e,r=200){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function Zi(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 Ue(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Qi(e){let r=e.metadata;if(!Ue(r))return null;let t=r.vulnerabilities;if(!Ue(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 ea(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 ra(e,r){let t=e.error;if(Ue(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?Me(o.split(`
|
|
7
|
+
`).find(Boolean)??o,160):"npm audit failed"}function ta(e){let r=`${e.stdout}
|
|
8
|
+
${e.stderr}`.trim(),t=Zi(r);if(!t||!Ue(t)){let o=Me(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(Ue(t.error))return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit command failed: ${ra(t,e.stderr)}`};let n=Qi(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:ea(n),audit:n}:{kind:"command_failure",exitCode:e.exitCode,summary:"npm audit failed: JSON response missing vulnerability metadata",parseError:"missing_metadata"}}function na(e){return qi.test(e)}function oa(e){let r=fr(e).command;return En.test(e)||En.test(r)||vn(e)}function sa(e){let r=mt({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&&Xi.test(n)){let i=Me(n,160);return{kind:"command_failure",exitCode:1,summary:r??`ripgrep failed (exit 1): ${i}`}}let o=pt(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=Me(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 Cn(e){let r=e.stdout??"",t=e.stderr??"",n=e.interleavedOutput??"";if(na(e.command)){let i=r.trim()||n.trim()||t.trim();return ta({exitCode:e.exitCode,stdout:i,stderr:t})}if(oa(e.command))return sa({command:e.command,exitCode:e.exitCode,stdout:r,stderr:t,interleaved:n});let o=mt({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=Me(n||r||t||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:`command failed (exit ${e.exitCode}): ${s}`}}var qi,En,Xi,wn=g(()=>{"use strict";_n();qi=/\bnpm\s+audit\b/i,En=/\b(rg|ripgrep)\b/i,Xi=/\b(error|invalid|unknown|panic|not found)\b/i});function Ke(e){return typeof e=="string"&&ia.test(e.trim())}function gr(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let r=e;return r.is_error===!0||r.providerTerminalError===!0||typeof r.subtype=="string"&&/^error(?:_|$)/.test(r.subtype)}var ia,hr=g(()=>{"use strict";ia=/^(?:provider authentication failed:\s*)?(?:(?:Failed to authenticate|authentication (?:failed|error))(?::\s*[^\n.!?]+)?|OAuth session expired and could not be refreshed)[.!]?$/i});function ft(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function aa(e){if(!e)return;let r=typeof e.input_tokens=="number"?e.input_tokens:void 0,t=typeof e.output_tokens=="number"?e.output_tokens:void 0;if(!((r===void 0||r<0)&&(t===void 0||t<0)))return{...r!==void 0&&r>=0?{inputTokens:r}:{},...t!==void 0&&t>=0?{outputTokens:t}:{}}}function An(e){if(e.event==="step_update"&&ft(e.step_update)){let s=e.step_update;return s.step_type==="tool"&&typeof s.tool_name=="string"&&s.tool_name.trim()?{currentTool:s.tool_name.trim()}:null}if(e.event!=="result"||!ft(e.result))return null;let r=e.result,t=typeof r.status=="string"?r.status.toUpperCase():"";if(t!=="SUCCESS"&&t!=="ERROR")return null;let n=ft(r.usage)?aa(r.usage):void 0;if(t==="ERROR"){let s=typeof r.error=="string"&&r.error.trim()?r.error.trim():"antigravity cli result error";return{...n?{usage:n}:{},terminal:{ok:!1,finalResult:null,error:s}}}let o=typeof r.response=="string"?r.response.trim():"";return{...n?{usage:n}:{},terminal:{ok:!0,finalResult:o||"completed",error:null}}}var Pn=g(()=>{"use strict"});function gt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function In(){return{assistantText:""}}function ua(e,r){if(!(r.role!=="assistant"||typeof r.content!="string")){if(r.delta===!0){e.assistantText+=r.content;return}e.assistantText=r.content}}function la(e){let r=typeof e.input_tokens=="number"?e.input_tokens:void 0,t=typeof e.output_tokens=="number"?e.output_tokens:void 0,o=(gt(e.models)?Object.keys(e.models):[]).find(s=>s.trim())?.trim();if(!(r===void 0&&t===void 0&&!o))return{...r!==void 0&&r>=0?{inputTokens:r}:{},...t!==void 0&&t>=0?{outputTokens:t}:{},...o?{model:o}:{}}}function ca(e){return e.type!=="result"||e.status!=="success"&&e.status!=="error"?!1:typeof e.result!="string"}function On(e,r){if(e.type==="message"&&(e.role==="assistant"||e.role==="user"))return ua(r,e),{};if(e.type==="tool_use"&&typeof e.tool_name=="string"&&e.tool_name.trim())return{currentTool:e.tool_name.trim()};if(!ca(e))return null;let t=gt(e.stats)?la(e.stats):void 0;if(e.status==="error"){let o=gt(e.error)&&typeof e.error.message=="string"?e.error.message:"gemini cli result error";return{...t?{usage:t}:{},terminal:{ok:!1,finalResult:null,error:o}}}let n=r.assistantText.trim();return{...t?{usage:t}:{},terminal:{ok:!0,finalResult:n||"completed",error:null}}}var Dn=g(()=>{"use strict"});import{existsSync as da,readFileSync as pa}from"node:fs";function ma(e){let r=e.timestamp_ms;return e.timestamp||e.ts||(r?new Date(r).toISOString():void 0)}function fa(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 ga(e,r){e.finalResult=r.result||r.subtype||r.terminal_reason||"completed",gr(r)&&(e.providerTerminalError=!0,e.error=String(r.result||r.api_error_status||"stream result error"))}function Ce(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function ha(e){let r=e.usage;return r&&typeof r=="object"&&!Array.isArray(r)?r:null}function ka(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 ya(e,r){let t=ha(r);if(!t)return;let n=Ce(t.input_tokens)??Ce(t.inputTokens)??Ce(t.prompt_tokens),o=Ce(t.output_tokens)??Ce(t.outputTokens)??Ce(t.completion_tokens);if(n===void 0&&o===void 0)return;let s=ka(r)??e.usage?.model;e.usage={...n!==void 0?{inputTokens:n}:{},...o!==void 0?{outputTokens:o}:{},...s?{model:s}:{}}}function Ra(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 ba(e,r){r.kind==="success"||r.kind==="search_no_matches"||(e.lastShellOutcome=r)}function Nn(e){let r={firstEventAt:null,lastEventAt:null,currentTool:null,finalResult:null,error:null,lastShellOutcome:null,usage:null};if(!da(e))return r;let t=pa(e,"utf8").split(`
|
|
9
|
+
`).filter(Boolean),n=null,o=In();for(let s of t){let i=Xe(s);if(!i||typeof i!="object"||Array.isArray(i))continue;if(i.type==="turn.started"&&(n=null,r.finalResult=null),i.type==="item.completed"){let p=i.item;if(p&&typeof p=="object"&&!Array.isArray(p)){let f=p;f.type==="agent_message"&&typeof f.text=="string"&&f.text.trim()&&(n=f.text)}}i.type==="turn.completed"&&n&&!r.providerTerminalError&&(r.finalResult=n,n=null);let a=ma(i);if(a&&(r.firstEventAt||=a,r.lastEventAt=a),i.type==="stream_event"&&i.event&&typeof i.event=="object"&&i.event.type==="content_block_start"){let p=i.event.content_block;p?.type==="tool_use"&&(r.currentTool=String(p.name||"tool"))}if(i.type==="assistant"&&i.message&&typeof i.message=="object"){let p=i.message.content;if(Array.isArray(p)){let f=p.find(m=>m?.type==="tool_use");f&&(r.currentTool=String(f.name||r.currentTool))}}if(i.type==="tool_call"&&i.subtype==="started"){let p=i.tool_call&&typeof i.tool_call=="object"&&!Array.isArray(i.tool_call)?i.tool_call:void 0,f=fa(p);f&&(r.currentTool=f)}let u=Ra(i);u&&ba(r,Cn({command:u.command,exitCode:u.exitCode,stdout:u.stdout,stderr:u.stderr,interleavedOutput:u.interleaved}));let l=An(i),c=l?null:On(i,o),d=l??c;if(d?.currentTool&&(r.currentTool=d.currentTool),d?.usage&&(r.usage={...r.usage??{},...d.usage}),d?.terminal?d.terminal.ok?r.finalResult=d.terminal.finalResult:(r.finalResult=null,r.providerTerminalError=!0,r.error=d.terminal.error):i.type==="result"&&ga(r,i),i.type==="turn.failed"){n=null,r.finalResult=null,r.providerTerminalError=!0;let p=i.error;r.error=typeof p?.message=="string"?p.message:"provider turn failed"}ya(r,i)}return r}var Wn=g(()=>{"use strict";wn();b();hr();Pn();Dn()});function Tn(e,r=240){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function ht(e){let r=(e??"").trim();if(!r)return null;if(Ke(r))return{blocked:!0,reason:`provider authentication failed: ${Tn(r)}`};for(let t of Sa)if(t.test.test(r))return{blocked:!0,reason:`${t.label}: ${Tn(r)}`};return null}var Sa,Mn=g(()=>{"use strict";hr();Sa=[{test:/(?:claude provider refuses to spawn: worker prompt is empty after argv assembly|Input must be provided (?:either )?through stdin or as a prompt argument)/i,label:"provider prompt delivery failed"},{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 Un(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function va(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 xa(e){return!e?.checked||e.headIsAncestorOfBase!==!1?null:Un(e.head)}function _a(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 Kn(e){if(e.alive||va(e.finalResult))return null;let r=(e.changedFiles??[]).filter(i=>i.trim()).length,t=Un(e.headCommit)??xa(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:_a(s,r,t)}}var Bn=g(()=>{"use strict"});function Be(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function Ea(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 Ca(e){if(Be(e.headCommit)||Be(e.prUrl)||Be(e.artifactBundlePath)||Be(e.patchPath))return!0;let r=e.gitAncestry;return!!(r?.checked&&r.headIsAncestorOfBase===!1&&Be(r.head))}function we(e){return Ea(e.finalResult)?e.changedFiles.length===0?{blocked:!1}:Ca(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 Fn(e){if(e.blocked)return e.detail??e.reason??"dirty_worktree_no_pr"}var kr=g(()=>{"use strict"});function kt(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 Hn(e){let r=e.targetPrReconciliation??e.target_pr_reconciliation??e.targetPrs??e.target_prs;return Array.isArray(r)?r.length:0}function yr(e){let r=e.trim();if(!r)return null;let t=kt(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let c=kt(s[1]??"");c&&n.push(c)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let c=kt(r.slice(i,a+1));c&&n.push(c)}if(n.length===0)return null;let u=n[n.length-1],l=Hn(u);for(let c of n){let d=Hn(c);d>l&&(u=c,l=d)}return u}var yt=g(()=>{"use strict"});function Ln(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 jn(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function wa(e){return new Set(e.map(r=>jn(Ln(r)??r)).filter(Boolean))}function $n(e,r,t){let n=Ln(e)??e;if(!n)return"unrelated";let o=jn(n);return wa(r).has(o)?"contract":t?(t.outcome==="skipped"||t.outcome==="blocked")&&t.reason?.trim()?"support":(t.outcome==="merged","unrelated"):"unrelated"}var Gn=g(()=>{"use strict"});function Ae(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function Aa(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"?Object.keys(e).length>0:!0}function le(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`https://github.com/${r[1]}/pull/${r[2]}`:Ae(e)}function Rr(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function Yn(e){let r=null;if(typeof e=="string"){let o=yr(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=le(String(s.prUrl??s.pr_url??"")),a=Ae(s.outcome);!i||a!=="merged"&&a!=="skipped"&&a!=="blocked"||n.push({prUrl:i,outcome:a,mergeCommit:Ae(s.mergeCommit??s.merge_commit),reason:Ae(s.reason)})}return n}function Vn(e,r){let t=[],n=le(Ae(e.prUrl)??"");if(n&&t.push(n),r&&typeof r=="object"&&!Array.isArray(r)){let o=r,s=le(String(o.prUrl??o.pr_url??""));s&&t.push(s)}return[...new Set(t)]}function zn(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(!Aa(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?le(Ae(r.targetPrUrl)??"")??(r.targetPrUrls.length===1?le(r.targetPrUrls[0]):null):null;if(s){let d=Vn(t,n);if(!(n&&typeof n=="object"&&!Array.isArray(n)&&n.supersedesOriginalTargetPr===!0)){for(let y of d)if(y!==s)return{blocked:!0,reason:"duplicate_repair_pr",detail:`Repair worker opened or attached PR ${y} instead of canonical target ${s}`}}let m=Yn(n).find(y=>y.prUrl===s);if(!m||m.outcome!=="merged"&&!(m.reason?.trim()&&(m.outcome==="skipped"||m.outcome==="blocked")))return{blocked:!0,reason:"missing_repair_target_reconciliation",detail:`Repair worker must reconcile target PR ${s}`}}let i=Yn(n),a=new Map(i.map(d=>[Rr(d.prUrl),d])),u=new Set(r.targetPrUrls.map(d=>Rr(le(d)??d)).filter(Boolean)),l=Vn(t,n);if(r.landingOnly)for(let d of l){let p=a.get(Rr(d)),f=$n(d,r.targetPrUrls,p);if(!(f==="contract"||f==="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 p=Rr(le(d)??d),f=a.get(p);if(!f){c.push(p);continue}f.outcome!=="merged"&&!f.reason?.trim()&&c.push(p)}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 Jn(e){if(e.blocked)return e.detail??e.reason}var qn=g(()=>{"use strict";yt();Gn()});function Oa(e){let r=Date.now();if(e.providerTerminalError||gr(e.finalResult)||e.finalResult&&e.error?.trim()||Ke(e.error)||Ke(e.finalResult)){let o=e.error||(typeof e.finalResult=="string"?e.finalResult:"provider terminal error");return{state:"blocked",reason:ht(o)?.reason??`provider terminal error: ${o}`}}if(e.completionBlocker&&!Xn(e.completionBlocker))return{state:"blocked",reason:e.completionBlocker};if(e.finalResult){if(e.localOnly&&Na(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=we(o);if(s.blocked){let i=Fn(s);return{state:"needs_attention",reason:s.reason?`landing blocked (${s.reason}): ${i}`:`landing blocked: ${i}`}}if(e.landingContract){let i=zn({contract:e.landingContract,snapshot:o,finalResult:e.finalResult}),a=Jn(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(Da(e))return{state:"done",reason:"empty abandoned worker record"};let o=ht(e.error);if(o)return{state:"blocked",reason:o.reason};let s=Kn({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>Pa)return{state:"needs_attention",reason:`no first stream event ${qr(t)}s after start`};let n=e.lastActivityAt?Date.parse(e.lastActivityAt):NaN;return Number.isFinite(n)&&r-n>Ia?{state:"stale",reason:`no log/event/heartbeat activity for ${qr(n)}s`}:{state:"ok",reason:"recent activity"}}function Xn(e){let r=e?.trim();return r?/completion acknowledged but board not advanced/i.test(r)&&/task already terminal/i.test(r):!1}function Da(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 Na(e){let r=null;if(typeof e=="string"?r=yr(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 Wa(e,r,t){let n=e.completionSnapshot?.finalResult;return e.completionAckSource==="local-pr-merged-reconcile"&&n!==void 0&&n!==null?n:r||(n??hn(t))}function Fe(e,r={}){let t=Nn(e.stdoutPath),n=Ee(e.heartbeatPath),o=typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim().length>0,s=Wa(e,t.finalResult,n),i=o?!1:ee(e.pid),a=Ze(e.stdoutPath),u=Ze(e.stderrPath),l=Ze(e.heartbeatPath),c=Ne(e.worktreePath),d=er(e.worktreePath,{base:r.base,baseCommit:r.baseCommit}),p=Qt([t.lastEventAt,n.lastHeartbeatAt,Qe(e.stdoutPath),Qe(e.stderrPath),Qe(e.heartbeatPath)]),f=t.error||!i&&!s&&Zt(e.stderrPath,10).trim()||void 0,m=typeof e.completionBlocker=="string"&&e.completionBlocker.trim()?e.completionBlocker.trim():null,y=Xn(m)?null:m,S=e.repairTargetPrUrl?{landingOnly:!1,targetPrUrls:[e.repairTargetPrUrl],targetPrUrl:e.repairTargetPrUrl,repairEnforceOriginalPr:!0}:null,R=Oa({alive:i,finalResult:s,firstEventAt:t.firstEventAt,stdoutBytes:a,stderrBytes:u,heartbeatBytes:l,lastActivityAt:p,heartbeatBlocker:n.heartbeatBlocker,startedAt:e.startedAt,error:f,providerTerminalError:t.providerTerminalError,changedFiles:c,gitAncestry:d,completionBlocker:y,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=y||R.state==="blocked"?"blocked":o||R.state==="done"?"done":s?"exited":i?"running":"exited";return{runId:e.runId,worker:e.name,pid:e.pid,alive:i,status:A,attention:R,branch:e.branch,worktreePath:e.worktreePath,ownedPaths:e.ownedPaths,stdoutBytes:a,stderrBytes:u,heartbeatBytes:l,firstEventAt:t.firstEventAt,lastEventAt:t.lastEventAt,lastActivityAt:p,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:f,providerTerminalError:t.providerTerminalError,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 ce(e){return!!(e.finalResult||e.alive===!1||e.status==="exited"||e.status==="done")}function Zn(e){return e.finalResult?e.attention.state==="needs_attention"||e.attention.state==="blocked":!1}var Pa,Ia,de=g(()=>{"use strict";pr();Wn();hr();Mn();Bn();K();kr();qn();yt();b();Pa=18e4,Ia=6e5});var Qn=g(()=>{"use strict";de()});function eo(e,r={}){let t=r.perWorkerMemBytes??Rt,n=r.memReserveBytes??bt,o=r.memUtilization??St,s=Math.max(0,Math.floor(e*o)-n),i=Math.max(1,Math.floor(s/t));return Math.min(i,br)}var Rt,bt,St,br,ro=g(()=>{"use strict";on();me();ae();or();Sr();lr();ue();lt();Qn();b();Rt=500*1024*1024,bt=4*1024*1024*1024,St=.85,br=64});function He(e,r){let t=Number(e);return!Number.isFinite(t)||t<=0?r:Math.floor(t)}function vt(e){let r=e.config??{},t=e.env??process.env,n=He(r.perWorkerMemBytes,Rt),o=He(r.memReserveBytes,bt),s=Math.min(1,Math.max(.1,Number(r.memUtilization)>0?Number(r.memUtilization):St)),i=eo(e.totalMemBytes,{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s});if(e.configuredMaxWorkersOverride!==void 0&&e.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:He(e.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(r.maxConcurrentWorkers!==void 0&&r.maxConcurrentWorkers!==null){let l=He(r.maxConcurrentWorkers,0)||null;if(l)return{configuredMaxWorkers:Math.min(l,br),autoCap:i,workerCapSource:"config"}}let u=(t.KYNVER_MAX_WORKERS_INTENTIONAL==="1"||t.KYNVER_MAX_WORKERS_INTENTIONAL==="true")&&t.KYNVER_MAX_WORKERS&&He(t.KYNVER_MAX_WORKERS,0)||null;return u?{configuredMaxWorkers:Math.min(u,br),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var Sr=g(()=>{"use strict";ro()});import{homedir as Ta}from"node:os";import Ma from"node:path";var to,xt=g(()=>{"use strict";to=Ma.join(Ta(),".kynver",".env")});var no=g(()=>{"use strict"});var oo=g(()=>{"use strict";no()});var so=g(()=>{"use strict"});var io=g(()=>{"use strict";b()});var _t=g(()=>{"use strict";oo();so();io()});var ao=g(()=>{"use strict"});var uo=g(()=>{"use strict";ao()});var vr=g(()=>{"use strict";xt();se();me();_t();uo()});var po=g(()=>{"use strict";ae();ae()});var mo=g(()=>{"use strict";xt();_t();vr()});var Et=g(()=>{"use strict"});import{existsSync as V,mkdirSync as Ka,readdirSync as xr,renameSync as fo,statSync as Ba}from"node:fs";import z from"node:path";function ho(e){try{return Ba(e).isDirectory()}catch{return!1}}function Fa(e){if(!V(e))return!0;for(let r of go){let t=z.join(e,r);if(V(t)&&(!ho(t)||xr(t).length>0))return!1}return!0}function Ha(e){let r=z.join(e,"runs");if(!V(r)||!ho(r))return!1;for(let t of xr(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 La(e){let r=z.join(e,"runs");if(!V(r))return!1;for(let t of xr(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 ja(e){let r=z.join(e,"ghost");return V(r)?!V(z.join(r,"runs")):La(e)}function ko(e){return Ha(e.sharedRoot)?Fa(e.forgeRoot)?ja(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 yo(e,r){Ka(r,{recursive:!0});for(let t of go){let n=z.join(e,t),o=z.join(r,t);if(V(n)){if(V(o)&&xr(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(V(o)){fo(n,o);continue}fo(n,o)}}}var go,Ro=g(()=>{"use strict";b();go=["runs","worktrees"]});import{existsSync as C}from"node:fs";import{homedir as $a}from"node:os";import E from"node:path";function Ct(e=process.env){return e.HOME?.trim()||$a()}function wt(e=process.env){return E.join(Ct(e),".kynver","harness")}function _r(e){let r=E.resolve(Q(e.trim()));for(;Ga.has(E.basename(r));)r=E.dirname(r);return r}function Ya(e,r=process.env){return E.join(wt(r),e)}function Va(e=process.env){let r=wt(e);if(C(E.join(r,"runs")))return!0;if(C(r)&&!C(E.join(r,"ghost"))&&!C(E.join(r,"forge")))return C(r);let t=E.join(Ct(e),bo);return C(t)}function Er(e){let r=e.env??process.env,t=r.KYNVER_HARNESS_ROOT?.trim()||r.OPUS_HARNESS_ROOT?.trim();if(t)return{harnessRoot:_r(t),source:"env"};let n=e.configuredHarnessRoot?.trim();if(n)return{harnessRoot:_r(n),source:"config"};let o=Ya(e.boxKind,r);if(C(E.join(o,"runs"))||C(o)&&!za(o))return{harnessRoot:o,source:"box_scoped"};let i=wt(r);if(e.boxKind==="forge"){let a=ko({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&&yo(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(e.boxKind==="ghost"&&Va(r)){if(C(E.join(i,"runs")))return{harnessRoot:i,source:"legacy_shared"};if(C(i)&&!C(E.join(i,"ghost"))&&!C(E.join(i,"forge")))return{harnessRoot:i,source:"legacy_shared"};let u=E.join(Ct(r),bo);if(C(u))return{harnessRoot:u,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function za(e){if(!C(e))return!0;for(let r of["runs","worktrees"]){let t=E.join(e,r);if(C(t))return!1}return!0}var bo,Ga,At=g(()=>{"use strict";se();Ro();bo=E.join(".openclaw","harness");Ga=new Set(["runs","worktrees"])});import So from"node:os";function Cr(e){return e?.trim()?e.trim():null}function Ja(e,r){let t=r.trim().toLowerCase()||"host";return`${e}-${t}`.replace(/[^a-z0-9._-]+/g,"-")}function qa(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 wr(e=pe(),r=process.env,t={}){let n=ve(r,e),o=[...n.warnings],s=[],i=!!(e.boxKind?.trim()||Cr(r.KYNVER_BOX_KIND)),a=t.strict===!0||qa(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 y="ambiguous box identity: KYNVER_AGENT_OS_SLUG is set without KYNVER_BOX_KIND or config.boxKind";a||t.requireExplicitBoxKind?s.push(y):o.push(`${y} \u2014 defaulting box kind to box (customer), not forge/ghost`)}let u=Cr(e.runnerId),l=Cr(r.KYNVER_RUNTIME_ID)??Cr(r.OPENCLAW_RUNTIME_ID),c=u??l??Ja(n.boxKind,So.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 p=vt({config:e,env:r,totalMemBytes:So.totalmem()}),f=nr(n.boxKind,p.configuredMaxWorkers??et(n.boxKind,p.autoCap)),m=Er({boxKind:n.boxKind,configuredHarnessRoot:e.harnessRoot,env:r});return m.migrationBlocker&&s.push(m.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:f,workerCapSource:p.workerCapSource,harnessRoot:m.harnessRoot,harnessRootSource:m.source},errors:s,warnings:o}}var Ar=g(()=>{"use strict";me();ae();or();Sr();At()});var xo=g(()=>{"use strict";rr();ae();po();me();vr();mo();Qr();Et();Ar()});var Qa,Zp,_o=g(()=>{"use strict";Qa=["claude","cursor","codex","gemini","gemini-api","openai-compatible"],Zp=Qa.join("|")});import{existsSync as ru,mkdirSync as lm,readFileSync as tu,writeFileSync as cm}from"node:fs";import{homedir as nu,totalmem as pm}from"node:os";import Pt from"node:path";function ou(e){return{...e,...e.harnessRoot?.trim()?{harnessRoot:Q(e.harnessRoot.trim())}:{},...e.defaultRepo?.trim()?{defaultRepo:Q(e.defaultRepo.trim())}:{}}}function pe(){if(!ru(Eo))return{};try{return ou(JSON.parse(tu(Eo,"utf8")))}catch{return{}}}var Co,Eo,Cm,wm,Am,me=g(()=>{"use strict";rr();se();Qr();ae();or();Sr();lr();vr();xo();_o();Ar();Et();Co=Pt.join(nu(),".kynver"),Eo=Pt.join(Co,"config.json"),Cm=Pt.join(Co,"credentials");wm=500*1024*1024,Am=4*1024*1024*1024});import It from"node:path";function O(e){return _r(e)}function re(){let e=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(e)return O(e);let r=pe(),t=r.harnessRoot?.trim();if(t)return O(t);let n=wr(r,process.env);return n.identity?n.identity.harnessRoot:Er({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function G(e){return It.join(O(e),"runs")}function Pe(e){return It.join(O(e),"worktrees")}function dn(){let e=re();return{harnessRoot:e,runsDir:G(e),worktreesDir:Pe(e)}}function at(e,r){return It.join(e,v(r))}var Y=g(()=>{"use strict";me();At();Ar();b()});Y();import T from"node:path";kr();import Or from"node:path";K();de();var Ot=[".next",".turbo","dist","build",".cache","node_modules/.cache"];function wo(e){let r=e.replace(/\\/g,"/").replace(/\/+$/,"");if(r==="node_modules"||r.startsWith("node_modules/"))return!0;for(let t of Ot)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!wo(n)})}function fe(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 Le(e){let r=e.gitAncestry?.relation;return r==="merged"||r==="synced"?D(e.changedFiles).length>0:!!(fe(e.finalResult)||r==="ahead"||r==="diverged"||e.changedFiles.length>0&&e.finalResult)}b();function je(e){return e.status||(e.status=Fe(e.worker,{base:e.run.base,baseCommit:e.run.baseCommit})),e.status}function Dt(e,r){if(e.status)return D(e.status.changedFiles).length>0;let t=r?r.porcelain(e.worktreePath):Ne(e.worktreePath);return D(t).length>0}function su(e){let r=e.worker.completionSnapshot?.finalResult;return r??(e.worker.taskPrUrl?{prUrl:e.worker.taskPrUrl}:null)}function Nt(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=su(e);if(o&&!ee(t.pid)){let i=r?.gitStatusCache?r.gitStatusCache.porcelain(e.worktreePath):Ne(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"}:er(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??fe(s)};return e.status=c,c}return je(e)}de();ue();lt();de();b();import iu from"node:path";var au=new Set(["running","dispatching","pending","queued","needs_attention"]),ge=new Set(["completed","failed","cancelled","done"]);function he(e){let r=ut(e);if(r.length===0)return"failed";let t=!1,n=!1,o=!1,s=!1;for(let i of r){let a=x(iu.join(We(e.id),"workers",v(i),"worker.json"),void 0);if(!a)continue;let u=Fe(a,{base:e.base,baseCommit:e.baseCommit});if(u.alive&&!u.finalResult){t=!0;break}typeof a.completionBlocker=="string"&&a.completionBlocker&&(o=!0),Zn(u)&&(s=!0),u.finalResult&&u.attention.state==="done"&&(n=!0)}return t||o||s?null:n?"completed":"failed"}function Ao(){let e=[];for(let r of st()){if(!au.has(r.status))continue;let t=he(r);if(!t||t===r.status)continue;let n=r.status;r.status=t,it(r),e.push({runId:r.id,from:n,to:t})}return e}de();pr();import{existsSync as Pr,mkdirSync as ff,readdirSync as Oo,renameSync as gf,statSync as uu}from"node:fs";import ke from"node:path";me();rr();se();Zr();K();pr();Y();ue();Y();b();import te from"node:path";var lf=`${te.sep}runs${te.sep}runs${te.sep}`;function Po(e){return{workerJsonPath:te.join(e,"worker.json"),stdoutPath:te.join(e,"stdout.jsonl"),stderrPath:te.join(e,"stderr.log"),heartbeatPath:te.join(e,"heartbeat.jsonl"),lastStatusPath:te.join(e,"last-status.json")}}b();var $e=900*1e3,_f=3600*1e3;function Do(e,r){let t=ke.resolve(e),n=ke.resolve(G(r)),o=ke.relative(n,t);return o!==".."&&!o.startsWith("..")&&!ke.isAbsolute(o)}function lu(e){if(!Pr(e))return[];try{return Oo(e,{withFileTypes:!0}).filter(r=>r.isDirectory()&&r.name!=="runs").map(r=>r.name)}catch{return[]}}function cu(e){let r=ke.join(e,"workers");if(!Pr(r))return[];try{return Oo(r,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}}function Io(e,r,t){if(!Pr(e))return!1;try{let n=r-uu(e).mtimeMs;return Number.isFinite(n)&&n>=0&&n<t}catch{return!1}}function du(e,r=Date.now(),t=$e){if(!Pr(e))return!1;let n=Po(e),o=x(n.workerJsonPath,void 0);if(o?.status==="running"&&ee(o.pid))return!0;let s=Ee(n.heartbeatPath);if(s.lastHeartbeatAt){let i=r-Date.parse(s.lastHeartbeatAt);if(Number.isFinite(i)&&i>=0&&i<t)return!0}return!!(Io(n.stdoutPath,r,t)||Io(n.heartbeatPath,r,t))}function pu(e,r=Date.now(),t=$e){for(let n of cu(e))if(du(ke.join(e,"workers",n),r,t))return!0;return!1}function No(e,r=Date.now()){let t=new Set,n=G(e);for(let o of lu(n)){let s=ke.join(n,o);pu(s,r)&&t.add(`${e}\0${o}`)}return t}b();function mu(e,r=Date.now(),t=$e){let n=Ee(e.heartbeatPath);if(!n.lastHeartbeatAt)return!1;let o=r-Date.parse(n.lastHeartbeatAt);return Number.isFinite(o)&&o>=0&&o<t}function Ie(e,r=Date.now(),t=$e){return ee(e.pid)?!0:mu(e,r,t)}function fu(e,r){return r?r.runTerminalCache.derive(e.run):he(e.run)}function J(e,r=Date.now()){return Ie(e.worker,r)}function Wt(e,r){return ge.has(e.run.status)?!1:fu(e,r)!==null}function Wo(e,r,t=Date.now()){if(J(e,t))return!0;if(ge.has(e.run.status)||Wt(e,r))return!1;let n=je(e);return ce(n)?!1:!!J(e,t)}kr();de();function To(e,r){if(!(typeof e.worker.completionBlocker=="string"?e.worker.completionBlocker.trim():""))return!1;if(J(e))return!0;let n=r??je(e);return!!(!ce(n)||Le(n)||D(n.changedFiles).length>0||we({finalResult:n.finalResult,changedFiles:n.changedFiles,gitAncestry:n.gitAncestry,prUrl:fe(n.finalResult)}).blocked)}K();b();import{existsSync as Uo,mkdirSync as gu,writeFileSync as Mo}from"node:fs";import Ir from"node:path";function Ko(e,r,t){return Ir.join(e,"salvage",v(r),v(t))}function Bo(e){return Uo(Ir.join(Ko(e.harnessRoot,e.runId,e.workerName),"evidence.json"))}function Fo(e){let r=Ko(e.harnessRoot,e.indexed.runId,e.indexed.workerName);gu(r,{recursive:!0});let t=Ir.join(r,"salvage.patch"),n=!1;if(Uo(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
|
+
`);a.trim()&&(Mo(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
|
|
13
|
-
`),o}var su=new Set(["completion_blocked","dirty_worktree","pr_or_unmerged_commits","landing_blocked"]);function iu(e){e.writeSalvageEvidence&&su.has(e.skipReason)&&(J(e.indexed,e.now)||Do({harnessRoot:e.harnessRoot,runId:e.indexed.runId,workerName:e.indexed.workerName})||No({harnessRoot:e.harnessRoot,indexed:e.indexed,skipReason:e.skipReason,status:e.status,now:e.now}))}function au(e){let{indexed:r,worktreesAgeMs:t,terminalWorktreesAgeMs:n}=e;return r&&(ge.has(r.run.status)||e.liveness&&Dt(r,e.liveness)||e.liveness&&ce(Ot(r,e.liveness))&&!J(r))?n:t}function uu(e){return!e.indexed||e.includeOrphans&&e.worktreesAgeMs<=0?0:au(e)}function lu(e,r){if(e.harnessRoot?.trim())return Or.resolve(e.harnessRoot);let t=r.worker.workerDir;if(!t)return null;let n=`${Or.sep}runs${Or.sep}`,o=t.indexOf(n);return o<0?null:t.slice(0,o+n.length-1)}function Wo(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=uu(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=Ot(r,e.liveness),c=lu(e,r),p=d=>{if(c)try{iu({indexed:r,harnessRoot:c,skipReason:d,status:l,now:a,writeSalvageEvidence:e.writeSalvageEvidence===!0})}catch{}return d};if(Ao(r,l)){let d=p("completion_blocked");if(d)return d}if(It(r,e.liveness?.gitStatusCache)){let d=p("dirty_worktree");if(d)return d}let m=e.liveness?.gitRevCache?.countAheadOfMain(e.worktreePath);if(m!=null&&m>0){let d=p("pr_or_unmerged_commits");if(d)return d}if(wo(r,e.liveness,a)||!ce(l))return"run_still_active";if(Le(l)){let d=p("pr_or_unmerged_commits");if(d)return d}if(D(l.changedFiles).length>0){let d=p("dirty_worktree");if(d)return d}if(we({finalResult:l.finalResult,changedFiles:l.changedFiles,gitAncestry:l.gitAncestry,prUrl:fe(l.finalResult)}).blocked){let d=p("landing_blocked");if(d)return d}if(i&&e.worktreePath){let d=i({worktreePath:e.worktreePath,indexed:!!r,runId:r?.runId,worker:r?.workerName});if(d)return d.detail?{reason:d.reason,detail:d.detail}:d.reason}return null}function Nt(e){let{indexed:r,nodeModulesAgeMs:t,ageMs:n,worktreePath:o,activeWorktreePaths:s,workerFilesystemLive:i,diskPressure:a}=e;return!a&&n<t?"below_age_threshold":i||s.has(Or.resolve(o))||r&&J(r)?"active_worker":r&&It(r,e.gitStatusCache)?"dirty_worktree":null}function To(e){return Nt(e)}var Wt=216e5,Dr=6048e5;var Tt=36e5,Nr=120;var Mo=new Set(["active_worker","run_still_active","completion_blocked","landing_blocked"]);function Uo(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)Mo.has(s.reason)&&o(s.path,s.reason,s.detail);for(let s of e)!s.skipped||!s.skipReason||Mo.has(s.skipReason)&&o(s.path,s.skipReason);return t}import{existsSync as Ho,readdirSync as Lo,statSync as pu}from"node:fs";import jo from"node:path";ue();Y();import Ko from"node:path";b();function du(e,r){return Ie(e,r)}function Bo(e,r=Date.now()){let t=new Set,n=new Set;for(let o of e){for(let s of dr(o)){let i=!1;for(let a of Object.keys(s.workers||{})){let u=x(Ko.join(Te(o,s.id),"workers",v(a),"worker.json"),void 0);if(!u?.worktreePath)continue;let l=Ko.resolve(u.worktreePath);du(u,r)&&(i=!0,t.add(l))}i&&n.add(`${o}\0${s.id}`)}for(let s of Co(o))n.add(s)}return{activeWorktreePaths:t,liveRunKeys:n}}function Fo(e,r,t,n){return t?n.has(`${r}\0${t}`):!1}b();function mu(e,r){try{let t=pu(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function fu(e,r){let t=jo.join(e,"runs",r,"run.json");return Ho(t)?x(t,null):null}function $o(e){try{return Lo(e).length===0}catch{return!1}}function Go(e){let{harnessRoot:r,runId:t,runPath:n,ageMs:o,runDirectoriesAgeMs:s,activeGuards:i}=e;if(Fo(n,r,t,i.liveRunKeys)||!$o(n))return"run_still_active";let a=fu(r,t);return a&&!ge.has(a.status)&&!he(a)?"run_still_active":s>0&&o<s?"below_age_threshold":null}function Yo(e){if(!Ho(e.worktreesDir))return[];let r=[],t;try{t=Lo(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=jo.join(e.worktreesDir,o);$o(s)&&r.push({kind:"remove_run_directory",path:s,bytes:null,harnessRoot:e.harnessRoot,runId:o,ageMs:mu(s,e.now)})}return r}K();import{existsSync as Ut,rmSync as ns}from"node:fs";import{execFileSync as gu}from"node:child_process";import{existsSync as Vo,readdirSync as hu,statSync as ku}from"node:fs";import Ru from"node:path";var yu=2500;function bu(e,r=yu){if(!Vo(e))return 0;try{let n=gu("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 q(e,r=5e4){if(!Vo(e))return 0;let t=bu(e);if(t!==null)return t;let n=0,o=0,s=[e];for(;s.length>0;){let i=s.pop(),a;try{a=hu(i)}catch{continue}for(let u of a){if(o++>r)return null;let l=Ru.join(i,u),c;try{c=ku(l)}catch{continue}c.isDirectory()?s.push(l):n+=c.size}}return n}import{existsSync as _u,rmSync as Eu}from"node:fs";Y();import{lstatSync as Su,readdirSync as vu}from"node:fs";function zo(e){try{let r=Su(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 Jo(e,r=32){let t=zo(e);if(!t)return!1;if(t.foreign)return!0;try{let n=vu(e),o=0;for(let s of n){if(o>=r)break;let i=`${e.replace(/\/$/,"")}/${s}`,a=zo(i);if(o+=1,a?.foreign)return!0}}catch{}return!1}import{spawnSync as xu}from"node:child_process";import Zo from"node:path";import N from"node:path";function qo(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 Wr(e,r,t){return qo(e,r,t,"node_modules")}function Tr(e,r,t){return qo(e,r,t,".next")}function Mr(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 Xo(e,r,t){let n=N.resolve(e);return Wr(n,r,t)===null||Tr(n,r,t)===null||Mr(n,r,t)===null}function es(){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 Qo(e){let r=xu("sudo",["-n",...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{ok:r.status===0,stderr:`${r.stderr??""}${r.stdout??""}`.trim()}}function rs(e,r,t){if(!Xo(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=Qo(["chown","-R",`${n}:${o}`,Zo.resolve(e)]);if(s.ok)return{ok:!0,method:"chown_then_rm"};let i=Qo(["rm","-rf",Zo.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 Mt="Root-owned harness caches require operator reclaim: configure passwordless sudo for chown/rm under ~/.kynver/harness/worktrees, or remove them as the harness owner with sudo available. More help: https://www.kynver.com/help.";function Cu(e){let r=e?.code;return r==="EACCES"||r==="EPERM"}function ts(e,r,t={}){if(!_u(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?Pe(n):null,i=e.bytes??q(e.path)??void 0,a=t.removePath??Eu,u=t.hasForeignOwnedEntry??Jo;try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i}}catch(l){if(!Cu(l)||!n||!o)return{executed:!1,skipped:!0,skipReason:"remove_failed",error:l.message};let c=u(e.path),p=es();if(!(p==="force"||p==="auto"&&c))return c?{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${l.message}; ${Mt}`}:{executed:!1,skipped:!0,skipReason:"remove_failed",error:l.message};let g=rs(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(d){return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${d.message}; privileged chown succeeded but rm still failed`}}return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${l.message}; privileged reclaim failed: ${g.error}; ${Mt}`}}}function Kt(e){let r=e.harnessRoot;return!r||!Eo(e.path,r)?null:{...e,executed:!1,skipped:!0,skipReason:"run_metadata_protected"}}function Bt(e,r){let t=Kt(e);if(t)return t;let n=ts(e,r);return{...e,bytes:n.bytes??e.bytes,executed:n.executed,skipped:n.skipped,skipReason:n.skipReason,error:n.error}}function os(e,r){return Bt(e,r)}function ss(e,r){return Bt(e,r)}function is(e,r){return Bt(e,r)}function as(e,r){let t=Kt(e);if(t)return t;if(!Ut(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??q(e.path);return ns(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 us(e,r){let t=Kt(e);if(t)return t;if(!Ut(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??q(e.path);return n&&Se(n,["worktree","remove","--force",e.path],{allowFailure:!0}),Ut(e.path)&&ns(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 Ur,readdirSync as Kr,statSync as wu}from"node:fs";import F from"node:path";function Ft(e,r){try{let t=wu(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function cs(e,r){let t=F.relative(r,e);return t===""||!t.startsWith("..")&&!F.isAbsolute(t)}function ls(e,r,t,n){let o=[];for(let s of Pt){if(s===".next")continue;let i=F.join(e,s);if(!Ur(i))continue;let a=F.resolve(i);t.has(a)||cs(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:Ft(a,r.now)}))}return o}function ds(e){let r=[],t=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||r.push(...ls(n.worktreePath,e,t,{runId:n.runId,worker:n.workerName,repo:n.run.repo}));if(!e.includeOrphans||!Ur(e.worktreesDir))return r;for(let n of Kr(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=F.join(e.worktreesDir,n.name);for(let s of Kr(o,{withFileTypes:!0})){if(!s.isDirectory())continue;let i=F.join(o,s.name);r.push(...ls(i,e,t,{runId:n.name,worker:s.name}))}}return r}function ps(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;Ur(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:Ft(a,e.now)})))}if(!t||!Ur(e.worktreesDir))return n;let s=new Set;for(let i of e.index.values())s.add(F.resolve(i.worktreePath));for(let i of Kr(e.worktreesDir,{withFileTypes:!0})){if(!i.isDirectory()||e.runIdFilter&&i.name!==e.runIdFilter)continue;let a=F.join(e.worktreesDir,i.name),u;try{u=Kr(a,{withFileTypes:!0})}catch{continue}for(let l of u){if(!l.isDirectory())continue;let c=F.resolve(F.join(a,l.name));o.has(c)||s.has(c)||cs(c,e.harnessRoot)&&(o.add(c),n.push({kind:"remove_worktree",path:c,bytes:null,runId:i.name,worker:l.name,ageMs:Ft(c,e.now)}))}}return n}import{existsSync as gs,readdirSync as ms,statSync as Au}from"node:fs";import Oe from"node:path";var Pu=[{dirName:"node_modules",kind:"remove_node_modules"},{dirName:".next",kind:"remove_next_cache"}];function Iu(e,r){try{let t=Au(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function Ou(e,r){let t=Oe.relative(r,e);return t===""||!t.startsWith("..")&&!Oe.isAbsolute(t)}function Du(e,r,t,n,o,s){if(!gs(n))return;let i=Oe.resolve(n);r.has(i)||Ou(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:Iu(i,t.now)}))}function fs(e,r,t,n,o){for(let s of Pu)Du(e,r,t,Oe.join(n,s.dirName),s.kind,o)}function hs(e){let r=[],t=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||fs(r,t,e,n.worktreePath,{runId:n.runId,worker:n.workerName,repo:n.run.repo});if(!e.includeOrphans||!gs(e.worktreesDir))return r;for(let n of ms(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory()||e.runIdFilter&&n.name!==e.runIdFilter)continue;let o=Oe.join(e.worktreesDir,n.name),s;try{s=ms(o,{withFileTypes:!0})}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=Oe.join(o,i.name);fs(r,t,e,a,{runId:n.name,worker:i.name})}}return r}K();import{existsSync as ks,statSync as Nu}from"node:fs";import H from"node:path";function Wu(e,r){try{let t=Nu(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function Tu(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
|
|
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
|
|
16
|
-
`).map(t=>t.trim()).filter(Boolean)}var Hr=class{cache=new Map;porcelain(r){let t=r,n=this.cache.get(t);if(n!==void 0)return n;let o=
|
|
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 Mo(Ir.join(r,"evidence.json"),`${JSON.stringify(o,null,2)}
|
|
13
|
+
`),o}var hu=new Set(["completion_blocked","dirty_worktree","pr_or_unmerged_commits","landing_blocked"]);function ku(e){e.writeSalvageEvidence&&hu.has(e.skipReason)&&(J(e.indexed,e.now)||Bo({harnessRoot:e.harnessRoot,runId:e.indexed.runId,workerName:e.indexed.workerName})||Fo({harnessRoot:e.harnessRoot,indexed:e.indexed,skipReason:e.skipReason,status:e.status,now:e.now}))}function yu(e){let{indexed:r,worktreesAgeMs:t,terminalWorktreesAgeMs:n}=e;return r&&(ge.has(r.run.status)||e.liveness&&Wt(r,e.liveness)||e.liveness&&ce(Nt(r,e.liveness))&&!J(r))?n:t}function Ru(e){return!e.indexed||e.includeOrphans&&e.worktreesAgeMs<=0?0:yu(e)}function bu(e,r){if(e.harnessRoot?.trim())return Or.resolve(e.harnessRoot);let t=r.worker.workerDir;if(!t)return null;let n=`${Or.sep}runs${Or.sep}`,o=t.indexOf(n);return o<0?null:t.slice(0,o+n.length-1)}function Ho(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=Ru(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=Nt(r,e.liveness),c=bu(e,r),d=m=>{if(c)try{ku({indexed:r,harnessRoot:c,skipReason:m,status:l,now:a,writeSalvageEvidence:e.writeSalvageEvidence===!0})}catch{}return m};if(To(r,l)){let m=d("completion_blocked");if(m)return m}if(Dt(r,e.liveness?.gitStatusCache)){let m=d("dirty_worktree");if(m)return m}let p=e.liveness?.gitRevCache?.countAheadOfMain(e.worktreePath);if(p!=null&&p>0){let m=d("pr_or_unmerged_commits");if(m)return m}if(Wo(r,e.liveness,a)||!ce(l))return"run_still_active";if(Le(l)){let m=d("pr_or_unmerged_commits");if(m)return m}if(D(l.changedFiles).length>0){let m=d("dirty_worktree");if(m)return m}if(we({finalResult:l.finalResult,changedFiles:l.changedFiles,gitAncestry:l.gitAncestry,prUrl:fe(l.finalResult)}).blocked){let m=d("landing_blocked");if(m)return m}if(i&&e.worktreePath){let m=i({worktreePath:e.worktreePath,indexed:!!r,runId:r?.runId,worker:r?.workerName});if(m)return m.detail?{reason:m.reason,detail:m.detail}:m.reason}return null}function Tt(e){let{indexed:r,nodeModulesAgeMs:t,ageMs:n,worktreePath:o,activeWorktreePaths:s,workerFilesystemLive:i,diskPressure:a}=e;return!a&&n<t?"below_age_threshold":i||s.has(Or.resolve(o))||r&&J(r)?"active_worker":r&&Dt(r,e.gitStatusCache)?"dirty_worktree":null}function Lo(e){return Tt(e)}var Mt=216e5,Dr=6048e5;var Ut=36e5,Nr=120;var jo=new Set(["active_worker","run_still_active","completion_blocked","landing_blocked"]);function $o(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)jo.has(s.reason)&&o(s.path,s.reason,s.detail);for(let s of e)!s.skipped||!s.skipReason||jo.has(s.skipReason)&&o(s.path,s.skipReason);return t}import{existsSync as zo,readdirSync as Jo,statSync as xu}from"node:fs";import qo from"node:path";ue();Y();import Go from"node:path";b();function vu(e,r){return Ie(e,r)}function Yo(e,r=Date.now()){let t=new Set,n=new Set;for(let o of e){for(let s of dr(o)){let i=!1;for(let a of Object.keys(s.workers||{})){let u=x(Go.join(Te(o,s.id),"workers",v(a),"worker.json"),void 0);if(!u?.worktreePath)continue;let l=Go.resolve(u.worktreePath);vu(u,r)&&(i=!0,t.add(l))}i&&n.add(`${o}\0${s.id}`)}for(let s of No(o))n.add(s)}return{activeWorktreePaths:t,liveRunKeys:n}}function Vo(e,r,t,n){return t?n.has(`${r}\0${t}`):!1}b();function _u(e,r){try{let t=xu(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function Eu(e,r){let t=qo.join(e,"runs",r,"run.json");return zo(t)?x(t,null):null}function Xo(e){try{return Jo(e).length===0}catch{return!1}}function Zo(e){let{harnessRoot:r,runId:t,runPath:n,ageMs:o,runDirectoriesAgeMs:s,activeGuards:i}=e;if(Vo(n,r,t,i.liveRunKeys)||!Xo(n))return"run_still_active";let a=Eu(r,t);return a&&!ge.has(a.status)&&!he(a)?"run_still_active":s>0&&o<s?"below_age_threshold":null}function Qo(e){if(!zo(e.worktreesDir))return[];let r=[],t;try{t=Jo(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=qo.join(e.worktreesDir,o);Xo(s)&&r.push({kind:"remove_run_directory",path:s,bytes:null,harnessRoot:e.harnessRoot,runId:o,ageMs:_u(s,e.now)})}return r}K();import{existsSync as Bt,rmSync as cs}from"node:fs";import{execFileSync as Cu}from"node:child_process";import{existsSync as es,readdirSync as wu,statSync as Au}from"node:fs";import Pu from"node:path";var Iu=2500;function Ou(e,r=Iu){if(!es(e))return 0;try{let n=Cu("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 q(e,r=5e4){if(!es(e))return 0;let t=Ou(e);if(t!==null)return t;let n=0,o=0,s=[e];for(;s.length>0;){let i=s.pop(),a;try{a=wu(i)}catch{continue}for(let u of a){if(o++>r)return null;let l=Pu.join(i,u),c;try{c=Au(l)}catch{continue}c.isDirectory()?s.push(l):n+=c.size}}return n}import{existsSync as Tu,rmSync as Mu}from"node:fs";Y();import{lstatSync as Du,readdirSync as Nu}from"node:fs";function rs(e){try{let r=Du(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 ts(e,r=32){let t=rs(e);if(!t)return!1;if(t.foreign)return!0;try{let n=Nu(e),o=0;for(let s of n){if(o>=r)break;let i=`${e.replace(/\/$/,"")}/${s}`,a=rs(i);if(o+=1,a?.foreign)return!0}}catch{}return!1}import{spawnSync as Wu}from"node:child_process";import ss from"node:path";import N from"node:path";function ns(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 Wr(e,r,t){return ns(e,r,t,"node_modules")}function Tr(e,r,t){return ns(e,r,t,".next")}function Mr(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 os(e,r,t){let n=N.resolve(e);return Wr(n,r,t)===null||Tr(n,r,t)===null||Mr(n,r,t)===null}function as(){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 is(e){let r=Wu("sudo",["-n",...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{ok:r.status===0,stderr:`${r.stderr??""}${r.stdout??""}`.trim()}}function us(e,r,t){if(!os(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=is(["chown","-R",`${n}:${o}`,ss.resolve(e)]);if(s.ok)return{ok:!0,method:"chown_then_rm"};let i=is(["rm","-rf",ss.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 Kt="Root-owned harness caches require operator reclaim: configure passwordless sudo for chown/rm under ~/.kynver/harness/worktrees, or remove them as the harness owner with sudo available. More help: https://www.kynver.com/help.";function Uu(e){let r=e?.code;return r==="EACCES"||r==="EPERM"}function ls(e,r,t={}){if(!Tu(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?Pe(n):null,i=e.bytes??q(e.path)??void 0,a=t.removePath??Mu,u=t.hasForeignOwnedEntry??ts;try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i}}catch(l){if(!Uu(l)||!n||!o)return{executed:!1,skipped:!0,skipReason:"remove_failed",error:l.message};let c=u(e.path),d=as();if(!(d==="force"||d==="auto"&&c))return c?{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${l.message}; ${Kt}`}:{executed:!1,skipped:!0,skipReason:"remove_failed",error:l.message};let f=us(e.path,n,o);if(f.ok&&f.method==="sudo_rm")return{executed:!0,skipped:!1,bytes:i,privilegedReclaim:!0};if(f.ok)try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i,privilegedReclaim:!0}}catch(m){return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${m.message}; privileged chown succeeded but rm still failed`}}return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${l.message}; privileged reclaim failed: ${f.error}; ${Kt}`}}}function Ft(e){let r=e.harnessRoot;return!r||!Do(e.path,r)?null:{...e,executed:!1,skipped:!0,skipReason:"run_metadata_protected"}}function Ht(e,r){let t=Ft(e);if(t)return t;let n=ls(e,r);return{...e,bytes:n.bytes??e.bytes,executed:n.executed,skipped:n.skipped,skipReason:n.skipReason,error:n.error}}function ds(e,r){return Ht(e,r)}function ps(e,r){return Ht(e,r)}function ms(e,r){return Ht(e,r)}function fs(e,r){let t=Ft(e);if(t)return t;if(!Bt(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??q(e.path);return cs(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 gs(e,r){let t=Ft(e);if(t)return t;if(!Bt(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??q(e.path);return n&&Se(n,["worktree","remove","--force",e.path],{allowFailure:!0}),Bt(e.path)&&cs(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 Ur,readdirSync as Kr,statSync as Ku}from"node:fs";import F from"node:path";function Lt(e,r){try{let t=Ku(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function ks(e,r){let t=F.relative(r,e);return t===""||!t.startsWith("..")&&!F.isAbsolute(t)}function hs(e,r,t,n){let o=[];for(let s of Ot){if(s===".next")continue;let i=F.join(e,s);if(!Ur(i))continue;let a=F.resolve(i);t.has(a)||ks(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:Lt(a,r.now)}))}return o}function ys(e){let r=[],t=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||r.push(...hs(n.worktreePath,e,t,{runId:n.runId,worker:n.workerName,repo:n.run.repo}));if(!e.includeOrphans||!Ur(e.worktreesDir))return r;for(let n of Kr(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=F.join(e.worktreesDir,n.name);for(let s of Kr(o,{withFileTypes:!0})){if(!s.isDirectory())continue;let i=F.join(o,s.name);r.push(...hs(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;Ur(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:Lt(a,e.now)})))}if(!t||!Ur(e.worktreesDir))return n;let s=new Set;for(let i of e.index.values())s.add(F.resolve(i.worktreePath));for(let i of Kr(e.worktreesDir,{withFileTypes:!0})){if(!i.isDirectory()||e.runIdFilter&&i.name!==e.runIdFilter)continue;let a=F.join(e.worktreesDir,i.name),u;try{u=Kr(a,{withFileTypes:!0})}catch{continue}for(let l of u){if(!l.isDirectory())continue;let c=F.resolve(F.join(a,l.name));o.has(c)||s.has(c)||ks(c,e.harnessRoot)&&(o.add(c),n.push({kind:"remove_worktree",path:c,bytes:null,runId:i.name,worker:l.name,ageMs:Lt(c,e.now)}))}}return n}import{existsSync as vs,readdirSync as bs,statSync as Bu}from"node:fs";import Oe from"node:path";var Fu=[{dirName:"node_modules",kind:"remove_node_modules"},{dirName:".next",kind:"remove_next_cache"}];function Hu(e,r){try{let t=Bu(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function Lu(e,r){let t=Oe.relative(r,e);return t===""||!t.startsWith("..")&&!Oe.isAbsolute(t)}function ju(e,r,t,n,o,s){if(!vs(n))return;let i=Oe.resolve(n);r.has(i)||Lu(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 Ss(e,r,t,n,o){for(let s of Fu)ju(e,r,t,Oe.join(n,s.dirName),s.kind,o)}function xs(e){let r=[],t=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||Ss(r,t,e,n.worktreePath,{runId:n.runId,worker:n.workerName,repo:n.run.repo});if(!e.includeOrphans||!vs(e.worktreesDir))return r;for(let n of bs(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory()||e.runIdFilter&&n.name!==e.runIdFilter)continue;let o=Oe.join(e.worktreesDir,n.name),s;try{s=bs(o,{withFileTypes:!0})}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=Oe.join(o,i.name);Ss(r,t,e,a,{runId:n.name,worker:i.name})}}return r}K();import{existsSync as _s,statSync as $u}from"node:fs";import H from"node:path";function Gu(e,r){try{let t=$u(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function Yu(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=H.relative(H.resolve(r),H.resolve(e));return t!==""&&!t.startsWith("..")&&!H.isAbsolute(t)}var zu=200;function Es(e){if(!e.includeOrphans||!_s(e.worktreesDir))return[];let r=new Set;for(let s of e.index.values())s.run.repo&&r.add(H.resolve(s.run.repo));let t=new Set;for(let s of e.index.values())t.add(H.resolve(s.worktreePath));let n=[],o=new Set;for(let s of r){let i=0,a;try{a=Se(s,["worktree","list","--porcelain"],{allowFailure:!0})}catch{continue}let u=Yu(a);for(let l of u){if(i>=zu)break;let c=H.resolve(l.path);if(c===H.resolve(s)||!Vu(c,e.worktreesDir)||t.has(c)||o.has(c)||!_s(c))continue;let p=H.relative(e.worktreesDir,c).split(H.sep),f=p[0],m=p[1]??"unknown";o.add(c),i+=1,n.push({kind:"remove_worktree",path:c,bytes:null,runId:f,worker:m,repo:s,ageMs:Gu(c,e.now)})}}return n}ue();b();import Ge from"node:path";function Cs(e,r){let t=Ge.resolve(r),n=new Map;for(let[o,s]of e){let i=s.harnessRoot?Ge.resolve(s.harnessRoot):null;i&&i!==t||n.set(o,s)}return n}function ws(e){let r=new Map;for(let t of dr(e))for(let n of Object.keys(t.workers||{})){let o=Ge.join(Te(e,t.id),"workers",v(n),"worker.json"),s=x(o,void 0);s?.worktreePath&&r.set(Ge.resolve(s.worktreePath),{harnessRoot:e,worktreePath:Ge.resolve(s.worktreePath),runId:t.id,workerName:n,run:t,worker:s})}return r}function Ye(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function ye(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)&&n>=0?n:r}function As(e={}){let r=e.execute===!0||e.execute!==!1&&Ye("KYNVER_CLEANUP_EXECUTE"),t=e.finalizeStaleRuns!==!1&&!Ye("KYNVER_CLEANUP_SKIP_FINALIZE"),n=e.nodeModulesAgeMs??ye("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??ye("KYNVER_CLEANUP_WORKTREES_AGE_MS",0),i=e.terminalWorktreesAgeMs??ye("KYNVER_CLEANUP_TERMINAL_WORKTREES_AGE_MS",216e5),a=e.runDirectoriesAgeMs??ye("KYNVER_CLEANUP_RUN_DIRECTORIES_AGE_MS",36e5),u=e.maxActionsPerSweep??ye("KYNVER_CLEANUP_MAX_ACTIONS_PER_SWEEP",120),l=e.includeOrphans===!0||Ye("KYNVER_CLEANUP_INCLUDE_ORPHANS"),d=Ye("KYNVER_CLEANUP_SCOPE_ALL")||process.env.KYNVER_CLEANUP_SCOPE==="all"?e.runIdFilter:e.runIdFilter??(process.env.KYNVER_CLEANUP_RUN_ID||void 0),p=e.accountBytes!==!1&&!Ye("KYNVER_CLEANUP_SKIP_BYTE_ACCOUNTING"),f=ye("KYNVER_CLEANUP_STORAGE_ENTRY_CAP",2e3),m=e.storagePerRunEntryCap!==void 0?e.storagePerRunEntryCap:p&&f>0?f:null,y=ye("KYNVER_CLEANUP_BYTE_ENTRY_CAP",2e3),S=e.byteAccountingEntryCap??(Number.isFinite(y)&&y>0?Math.floor(y):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:p,storagePerRunEntryCap:m,byteAccountingEntryCap:S}}K();import{existsSync as jt,statSync as qu}from"node:fs";import Re from"node:path";b();var Ps=1800*1e3;function Xu(e,r){let t=Re.relative(r,e);return t===""||!t.startsWith("..")&&!Re.isAbsolute(t)}function Zu(e,r,t){if(!jt(e))return!1;try{let n=r-qu(e).mtimeMs;return Number.isFinite(n)&&n>=0&&n<t}catch{return!1}}function $t(e){if(!e.runId||!e.workerName)return!1;let r=e.now??Date.now(),t=e.heartbeatFreshMs??Ps,n=Re.resolve(e.harnessRoot,"runs"),o=Re.resolve(n,e.runId,"workers",e.workerName);if(!Xu(o,n))return!1;let s=x(Re.join(o,"worker.json"),void 0);return s&&Ie(s,r,t)?!0:s?!1:Zu(Re.join(o,"heartbeat.jsonl"),r,t)}function Is(e){let r=e.now??Date.now(),t=e.heartbeatFreshMs??Ps;if(!jt(e.worktreePath))return null;if(e.runId&&e.workerName&&$t(e))return"active_worker";let n=Re.join(e.worktreePath,".git");if(!jt(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 Qu,readdirSync as Os,statSync as el}from"node:fs";import rl from"node:path";function Ds(e={}){let r=O(e.harnessRoot??re()),t=Pe(r),n=e.now??Date.now(),o=new Date(n).toISOString();if(!Qu(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=Os(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=rl.join(t,c.name);try{let p=el(d);u=u===null?p.mtimeMs:Math.min(u,p.mtimeMs)}catch{}try{for(let p of Os(d,{withFileTypes:!0}))p.isDirectory()&&(a+=1)}catch{}if(s!==null&&e.perRunEntryCap!==null){let p=e.perRunEntryCap??5e4;if(p<=0)s=null;else{let f=q(d,p);f===null?s=null:s+=f}}}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 tl}from"node:fs";import{homedir as nl}from"node:os";import Ns from"node:path";var ol=["/var/tmp/kynver-harness",Ns.join(nl(),".openclaw","harness")];function Gt(e,r,t){if(!t?.trim())return;let n=O(t.trim());e.has(n)||(e.add(n),r.push(n))}function sl(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 Ws(e={}){let r=new Set,t=[];Gt(r,t,e.harnessRoot??re());let n=process.env.KYNVER_CLEANUP_EXTRA_ROOTS?.split(",").map(o=>o.trim()).filter(Boolean);for(let o of n??[])Gt(r,t,o);if(sl(e))for(let o of ol){let s=Ns.resolve(o);!r.has(s)&&tl(s)&&Gt(r,t,s)}return t}lr();function il(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function al(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function Ts(e={}){let r=e.diskPath?.trim()||process.env.KYNVER_DISK_GUARD_PATH?.trim()||"/",t=al("KYNVER_DISK_GUARD_MAX_USED_PERCENT",75),n=ur({...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 Ms(e,r){if(!r.pressured)return e;let t=e.execute||!il("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}}ar();import{unlinkSync as ul}from"node:fs";function Br(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function Us(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function ll(e,r,t){return e.length===0?[]:t?[...e]:e.length<=r?[]:e.slice(r)}function Ks(e={}){let r=e.execute===!0||Br("KYNVER_WSL_CRASH_DUMP_EXECUTE")||Br("KYNVER_CLEANUP_EXECUTE"),t=e.purgeAll===!0||Br("KYNVER_WSL_CRASH_DUMP_PURGE_ALL"),n=Math.max(0,e.keepNewest??Us("KYNVER_WSL_CRASH_DUMP_KEEP_NEWEST",t?0:1)),o=_e({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=ll(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{ul(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?Br("KYNVER_WSL_CRASH_DUMP_CLEANUP")||!e.ok?!0:e.dumpCount>Us("KYNVER_WSL_CRASH_DUMP_KEEP_NEWEST",1):!1}ar();function W(e,r){if(process.env.KYNVER_CLEANUP_QUIET==="1")return;let t=r?`: ${r}`:"";console.error(`[kynver cleanup] ${e}${t}`)}K();var Fr=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 cl}from"node:child_process";import{existsSync as dl}from"node:fs";import pl from"node:path";var ml=5e3;function fl(e,r){if(!dl(pl.join(e,".git")))return{status:null,stdout:"",stderr:"",error:"not_a_git_repo"};try{let t=cl("git",r,{windowsHide:!0,cwd:e,encoding:"utf8",timeout:ml}),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 Fs(e){let r=fl(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 Hr=class{cache=new Map;porcelain(r){let t=r,n=this.cache.get(t);if(n!==void 0)return n;let o=Fs(t)??[];return this.cache.set(t,o),o}};var Lr=class{cache=new Map;derive(r){let t=this.cache.get(r.id);if(t!==void 0)return t;let n=he(r);return this.cache.set(r.id,n),n}};function gl(e){let r={};for(let t of e)r[t.kind]=(r[t.kind]??0)+1;return r}function Hs(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:gl(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 hl(e={}){let r=e.harnessRoot?O(e.harnessRoot):re(),t=Ws({harnessRoot:r}),n=e.now??Date.now();return{harnessRoot:r,scanRoots:t,now:n}}function kl(e){return typeof e=="string"?{reason:e}:e}function De(e,r,t,n){e.push({path:r,reason:t,...n?{detail:n}:{}})}function jr(e,r,t){return!r||e.bytes!=null?e:{...e,bytes:q(e.path,t)}}function Ls(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 yl(e,r){return e.kind==="remove_next_cache"?ps(e,r):ds(e,r)}function Rl(e,r,t){return e.kind==="remove_next_cache"?Tr(e.path,r,t):Wr(e.path,r,t)}function bl(e){let r=new Map;for(let t of e)for(let[n,o]of ws(t))r.set(n,o);return r}function js(e,r){return e.runId&&e.worker?T.join(r,e.runId,e.worker):T.resolve(e.path,"..")}function $s(e){return e.indexed?!1:$t({harnessRoot:e.harnessRoot,runId:e.candidate.runId,workerName:e.candidate.worker,now:e.now})}function Sl(e={}){let r=As(e),t=Ts();r=Ms(r,t);let n=hl(e);W("scan",`${n.scanRoots.length} harness root(s)`);let o=Yo(n.scanRoots,n.now),s=r.finalizeStaleRuns?Ao().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=bl(n.scanRoots);W("index",`${i.size} indexed worktree(s)`);let a={runTerminalCache:new Lr,gitStatusCache:new Hr,gitRevCache:new Fr},u=[],l=[],c=new Set,d=r.maxActionsPerSweep,p=()=>l.length>=d;for(let h of n.scanRoots){if(p())break;W("root",h);let X=T.join(h,"worktrees"),ze=Cs(i,h),Je={harnessRoot:h,worktreesDir:X,nodeModulesAgeMs:r.nodeModulesAgeMs,worktreesAgeMs:r.worktreesAgeMs,includeOrphans:r.includeOrphans,runIdFilter:r.runIdFilter,index:ze,now:n.now},$r=r.scanDependencyCaches?xs(Je):[];W("dependency",r.scanDependencyCaches?`${$r.length} cache candidate(s) at ${h}`:"skipped (worktree-only sweep)");let Gr=0;for(let M of $r){if(p())break;Gr+=1,Gr%50===0&&W("dependency",`${Gr}/${$r.length} evaluated`);let _=T.resolve(M.path);if(c.has(_))continue;c.add(_);let k={...M,path:_},I=Rl(k,h,X);if(I){De(u,k.path,I),l.push({...k,executed:!1,skipped:!0,skipReason:I});continue}let U=js(k,X),Z=ze.get(T.resolve(U))??null,be=$s({candidate:k,indexed:Z,harnessRoot:h,now:n.now}),$=Tt({indexed:Z,includeOrphans:!0,nodeModulesAgeMs:r.nodeModulesAgeMs,ageMs:k.ageMs,worktreePath:U,activeWorktreePaths:o.activeWorktreePaths,workerFilesystemLive:be,diskPressure:r.diskPressure,gitStatusCache:a.gitStatusCache});if($){De(u,k.path,$),l.push({...k,executed:!1,skipped:!0,skipReason:$});continue}l.push(yl(jr(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}if(r.scanDependencyCaches)for(let M of ys(Je)){if(p())break;let _=T.resolve(M.path);if(c.has(_))continue;c.add(_);let k={...M,path:_},I=Mr(k.path,h,X);if(I){De(u,k.path,I),l.push({...k,executed:!1,skipped:!0,skipReason:I});continue}let U=js(k,X),Z=ze.get(T.resolve(U))??null,be=$s({candidate:k,indexed:Z,harnessRoot:h,now:n.now}),$=Lo({indexed:Z,includeOrphans:!0,nodeModulesAgeMs:r.nodeModulesAgeMs,ageMs:k.ageMs,worktreePath:U,activeWorktreePaths:o.activeWorktreePaths,workerFilesystemLive:be,diskPressure:r.diskPressure,gitStatusCache:a.gitStatusCache});if($){De(u,k.path,$),l.push({...k,executed:!1,skipped:!0,skipReason:$});continue}l.push(ms(jr(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}let Yr=[...Rs(Je),...Es(Je)];W("worktrees",`${Yr.length} candidate(s) at ${h}`);let Yt=new Set,Vr=0;for(let M of Yr){if(p())break;Vr+=1,Vr%50===0&&W("worktrees",`${Vr}/${Yr.length} evaluated`);let _=T.resolve(M.path);if(Yt.has(_))continue;Yt.add(_);let k={...M,path:_},I=ze.get(T.resolve(k.path))??null,U=I?null:Is({worktreePath:k.path,harnessRoot:h,runId:k.runId,workerName:k.worker,now:n.now}),Z=Ho({indexed:I,worktreePath:T.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(Z){let{reason:be,detail:$}=kl(Z);De(u,k.path,be,$),l.push({...k,executed:!1,skipped:!0,skipReason:be});continue}l.push(gs(jr(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}if(!p()&&r.runDirectoriesAgeMs>=0)for(let M of Qo({harnessRoot:h,worktreesDir:X,runDirectoriesAgeMs:r.runDirectoriesAgeMs,runIdFilter:r.runIdFilter,activeGuards:o,now:n.now})){if(p())break;let _=T.resolve(M.path);if(c.has(_))continue;c.add(_);let k={...M,path:_},I=k.runId??T.basename(_),U=Zo({harnessRoot:h,runId:I,runPath:_,ageMs:k.ageMs,runDirectoriesAgeMs:r.runDirectoriesAgeMs,activeGuards:o});if(U){De(u,k.path,U),l.push({...k,executed:!1,skipped:!0,skipReason:U});continue}l.push(fs(jr(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}}let f=0,m=0,y=0,S=0,R=0,A=0;for(let h of l)h.bytes&&(f+=h.bytes),!h.skipped&&!h.executed&&h.bytes&&(y+=h.bytes),h.executed?(R+=1,S+=h.bytes??0,h.kind==="remove_run_directory"&&(m+=1)):h.skipped&&(A+=1,h.skipReason==="dry_run"&&h.bytes&&(y+=h.bytes));let L=r.accountBytes?Ds({harnessRoot:n.harnessRoot,now:n.now,perRunEntryCap:r.storagePerRunEntryCap}):void 0,B=_e(),Ve=r.execute&&Bs(B),j=Ve?Ks({execute:!0}):null,ne=B?{observed:!0,execute:Ve,dumpCount:B.dumpCount,totalBytes:B.totalBytes,removedCount:j?.removed.length??0,removedBytes:j?.removedBytes??0,executables:B.executables,path:B.path,reason:B.reason}:void 0;j&&j.removed.length>0&&(S+=j.removedBytes,R+=j.removed.length,W("wsl-crashes",`removed ${j.removed.length} dump(s), ${j.removedBytes} bytes`)),W("complete",`${l.length} action(s), ${A} skipped, ${R} removed`);let oe=$o(l,u),P=Hs({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:f,reclaimableBytes:y,removedBytes:S,removedPaths:R,skippedPaths:A,skipReasons:Ls(l,u)},...L?{storage:L}:{},...oe.length>0?{preservedLivePaths:oe}:{},...m>0?{removedRunDirectories:m}:{},...ne?{wslCrashDumps:ne}:{}});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:f,reclaimableBytes:y,removedBytes:S,removedPaths:R,skippedPaths:A,skipReasons:Ls(l,u)},...L?{storage:L}:{},...oe.length>0?{preservedLivePaths:oe}:{},...m>0?{removedRunDirectories:m}:{},...ne?{wslCrashDumps:ne}:{},compactSummary:P}}export{Nr as DEFAULT_MAX_ACTIONS_PER_SWEEP,Mt as DEFAULT_NODE_MODULES_AGE_MS,Ut as DEFAULT_RUN_DIRECTORIES_AGE_MS,Dr as DEFAULT_WORKTREES_AGE_MS,Sl as runHarnessCleanup};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var e=(r,n,t)=>()=>{if(t)throw t[0];try{return r&&(n=r(r=0)),n}catch(o){throw t=[o],o}};import{homedir as $}from"node:os";import H from"node:path";function Ue(r){return r==="~"?$():r.startsWith("~/")||r.startsWith("~\\")?H.join($(),r.slice(2)):r}function l(r){return H.resolve(Ue(r))}var c=e(()=>{"use strict"});var j=e(()=>{"use strict"});function Y(r){return process.platform!=="win32"?r:{windowsHide:!0,...r}}var s=e(()=>{"use strict";j()});var De,Pr,We,Ir,V=e(()=>{"use strict";De=["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"],Pr=new Set(De),We=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY","GEMINI_API_KEY"],Ir=new Set(We)});import{spawnSync as Me}from"node:child_process";function _(r,n){try{let t=Me("git",n,Y({cwd:r,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}}}var g=e(()=>{"use strict";c();s();V()});var v=e(()=>{"use strict";g()});import{existsSync as C,readFileSync as z}from"node:fs";import{homedir as Fe}from"node:os";import i from"node:path";import{fileURLToPath as Le}from"node:url";function He(r){let n=i.join(r,"package.json");if(!C(n))return null;try{let t=JSON.parse(z(n,"utf8"));return typeof t.name=="string"?t.name.trim():null}catch{return null}}function J(r){return He(r)==="kynver"}function G(r){let n=i.resolve(r);if(!C(n))return null;let t=_(n,["rev-parse","--show-toplevel"]);if(t.status!==0)return null;let o=t.stdout.trim();return o.length?i.resolve(o):null}function je(r=import.meta.url){let n=i.dirname(Le(r));for(let t=0;t<8;t+=1){let o=i.join(n,"package.json");if(C(o))try{if(JSON.parse(z(o,"utf8")).name==="@kynver-app/runtime")return n}catch{}let a=i.dirname(n);if(a===n)break;n=a}return null}function E(r,n,t,o,a){if(!t)return;let u=i.resolve(t);r.has(u)||(a?.requireMonorepo??!0)&&!J(u)||(r.add(u),n.push({repo:u,source:o}))}function Ye(r){let n=r?.cwd??process.cwd(),t=new Set,o=[];E(t,o,G(n),"cwd_git",{requireMonorepo:!1});let a=je(r?.runtimeModuleUrl??import.meta.url);a&&E(t,o,G(a),"runtime_checkout");let u=Fe();for(let p of $e)E(t,o,l(i.join(u,p)),"well_known_path");let F=i.resolve(r?.cwd??process.cwd());return o.filter(p=>{if(p.source!=="runtime_checkout"||!J(p.repo))return!0;let L=i.resolve(p.repo);return F===L||F.startsWith(`${L}${i.sep}`)})}function A(r){return Ye(r)[0]??null}var $e,y=e(()=>{"use strict";g();c();v();$e=["Kynver","repos/Kynver","repos/kynver-source-main","code/Kynver","projects/Kynver"]});var w=e(()=>{"use strict";s()});var d=e(()=>{"use strict"});var h=e(()=>{"use strict"});var q=e(()=>{"use strict"});var nt,ot,O=e(()=>{"use strict";nt=25*1024*1024*1024,ot=12*1024*1024*1024});var lt,ct,X=e(()=>{"use strict";O();lt=5*1024*1024*1024,ct=10*1024*1024*1024});var yt,ht,P=e(()=>{"use strict";X();O();yt=30*1024*1024*1024,ht=15*1024*1024*1024});var Q=e(()=>{"use strict";s()});import Ve from"node:path";var Ct,I=e(()=>{"use strict";c();Q();Ct=Ve.join(".openclaw","harness")});var b=e(()=>{"use strict";m();d();h();k();I()});var te=e(()=>{"use strict";m();I();b();s()});var N=e(()=>{"use strict";te();s()});var ne=e(()=>{"use strict";N();s()});var oe=e(()=>{"use strict"});var se=e(()=>{"use strict";oe();s()});var ie=e(()=>{"use strict"});var ae=e(()=>{"use strict";ie()});var x=e(()=>{"use strict"});var ue=e(()=>{"use strict"});var le=e(()=>{"use strict"});var ce=e(()=>{"use strict";ae();s();x();ue();le()});var de=e(()=>{"use strict";x()});var me=e(()=>{"use strict"});var fe=e(()=>{"use strict"});var K=e(()=>{"use strict"});var pe=e(()=>{"use strict"});var ge=e(()=>{"use strict";K();pe()});var ye=e(()=>{"use strict";se();ce();x();de();me();g();fe();ge();K();s()});var he=e(()=>{"use strict";ye()});var nr,or,Re=e(()=>{"use strict";q();m();d();h();k();P();N();ne();he();s();nr=500*1024*1024,or=4*1024*1024*1024});var k=e(()=>{"use strict";Re()});import{homedir as sr}from"node:os";import ir from"node:path";var be,U=e(()=>{"use strict";be=ir.join(sr(),".kynver",".env")});var ke=e(()=>{"use strict"});var xe=e(()=>{"use strict";ke()});var Se=e(()=>{"use strict"});var _e=e(()=>{"use strict";s()});var D=e(()=>{"use strict";xe();Se();_e()});var ve=e(()=>{"use strict"});var Ee=e(()=>{"use strict";ve()});var S=e(()=>{"use strict";U();c();m();D();Ee()});var we=e(()=>{"use strict";d();d()});var Oe=e(()=>{"use strict";U();D();S()});var W=e(()=>{"use strict"});var Ie=e(()=>{"use strict";y();d();we();m();S();Oe();w();W();b()});var dr,Ws,Te=e(()=>{"use strict";dr=["claude","cursor","codex","gemini","gemini-api","openai-compatible"],Ws=dr.join("|")});import{existsSync as mr,mkdirSync as zs,readFileSync as fr,writeFileSync as Js}from"node:fs";import{homedir as pr,totalmem as Xs}from"node:os";import B from"node:path";function gr(r){return{...r,...r.harnessRoot?.trim()?{harnessRoot:l(r.harnessRoot.trim())}:{},...r.defaultRepo?.trim()?{defaultRepo:l(r.defaultRepo.trim())}:{}}}function f(){if(!mr(Ne))return{};try{return gr(JSON.parse(fr(Ne,"utf8")))}catch{return{}}}var Ke,Ne,di,mi,fi,m=e(()=>{"use strict";y();c();w();d();h();k();P();S();Ie();Te();b();W();Ke=B.join(pr(),".kynver"),Ne=B.join(Ke,"config.json"),di=B.join(Ke,"credentials");mi=500*1024*1024,fi=4*1024*1024*1024});m();y();c();v();import yr from"node:path";function hr(r){return yr.resolve(l(r.trim()))}function M(r,n,t){let o=r?.trim();return o?{repo:hr(o),source:n,persistedInConfig:t}:null}function Rr(r){return r?{repo:r.repo,source:r.source,persistedInConfig:!1}:null}function br(r={}){let n=r.env??process.env,t=r.config??f(),o=M(t.defaultRepo,"config",!0);if(o)return o;let a=M(n.KYNVER_DEFAULT_REPO,"env_default_repo",!1);if(a)return a;let u=M(n.KYNVER_HARNESS_REPO,"env_harness_repo",!1);return u||Rr(A({cwd:r.cwd,runtimeModuleUrl:r.runtimeModuleUrl}))}export{br as resolveDefaultRepo};
|