@kynver-app/runtime 0.1.172 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -1
- package/dist/chat/command-auth-proof.js +1 -1
- package/dist/cli.js +59 -58
- package/dist/completion-response.d.ts +1 -1
- package/dist/config.d.ts +2 -0
- package/dist/context-budget-receipt.d.ts +96 -0
- package/dist/daemon-heartbeat.d.ts +7 -0
- package/dist/daemon-supervision/setup.d.ts +10 -1
- package/dist/dispatch-model-guard.d.ts +26 -0
- package/dist/dispatch-resource-gate.d.ts +20 -0
- package/dist/doctor/context-envelope-cli.d.ts +1 -0
- package/dist/doctor/context-envelope.d.ts +13 -0
- package/dist/doctor/context-envelope.probes.d.ts +25 -0
- package/dist/doctor/context-envelope.types.d.ts +42 -0
- package/dist/doctor/index.d.ts +3 -0
- package/dist/doctor/node-runtime-cli.d.ts +6 -0
- package/dist/doctor/node-runtime.d.ts +19 -0
- package/dist/executor-ref-routing.d.ts +14 -0
- package/dist/factory-steer-delivery.d.ts +7 -0
- package/dist/index.d.ts +11 -1
- package/dist/index.js +85 -75
- package/dist/landing/land-pr-check-classify.d.ts +11 -0
- package/dist/model-routing.d.ts +1 -1
- package/dist/node-runtime-policy.d.ts +25 -0
- package/dist/node-runtime-policy.js +1 -0
- package/dist/paths.d.ts +1 -1
- package/dist/prompt.d.ts +36 -2
- package/dist/providers/claude.d.ts +2 -0
- package/dist/providers/cursor.d.ts +2 -0
- package/dist/providers/types.d.ts +4 -0
- package/dist/review-head-reconcile.d.ts +17 -0
- package/dist/run-store.d.ts +6 -0
- package/dist/runner-boundary/index.d.ts +6 -0
- package/dist/runner-boundary/runner-boundary.dispatch-guard.d.ts +4 -0
- package/dist/runner-boundary/runner-boundary.forge-legacy-migration.d.ts +23 -0
- package/dist/runner-boundary/runner-boundary.harness-root.d.ts +17 -0
- package/dist/runner-boundary/runner-boundary.resolve.d.ts +4 -0
- package/dist/runner-boundary/runner-boundary.run-guard.d.ts +12 -0
- package/dist/runner-boundary/runner-boundary.types.d.ts +31 -0
- package/dist/runtime-identity.d.ts +9 -0
- package/dist/runtime-memory-envelope.d.ts +16 -0
- package/dist/security-review-environment.d.ts +27 -0
- package/dist/server/cleanup.js +14 -14
- package/dist/server/default-repo.js +1 -1
- package/dist/server/monitor.js +7 -7
- package/dist/server/worker-policy.d.ts +2 -0
- package/dist/server/worker-policy.js +1 -1
- package/dist/status.d.ts +9 -0
- package/dist/supervisor.d.ts +2 -0
- package/dist/worker-execution-mode.d.ts +5 -0
- package/package.json +4 -3
package/dist/server/cleanup.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
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{existsSync as
|
|
2
|
-
`)}function v(e){return String(e||"").toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"worker"}function
|
|
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{existsSync as ps,mkdirSync as ms,readFileSync as Ot,readdirSync as Pu,statSync as Dt,writeFileSync as fs}from"node:fs";import gs from"node:path";function Mr(e){console.error(e),process.exit(1)}function Tr(e){return process.platform!=="win32"?e:{windowsHide:!0,...e}}function Le(e){try{return JSON.parse(e)}catch{return null}}function x(e,r){try{return JSON.parse(Ot(e,"utf8"))}catch(t){if(arguments.length>1)return r;Mr(`failed to read ${e}: ${t.message}`)}}function Wt(e,r){ms(gs.dirname(e),{recursive:!0}),fs(e,`${JSON.stringify(r,null,2)}
|
|
2
|
+
`)}function v(e){return String(e||"").toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"worker"}function je(e){try{return Dt(e).size}catch{return 0}}function $e(e){try{return Dt(e).mtime.toISOString()}catch{return null}}function Nt(e,r){return ps(e)?Ot(e,"utf8").split(`
|
|
3
3
|
`).slice(-r).join(`
|
|
4
|
-
`):""}function
|
|
5
|
-
`).map(r=>r.trim()).filter(Boolean)}function C(e,r){try{let t=ft("git",r,Sr({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 mt(e,r,t){let n=C(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 Fe(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 _r(n,"missing worktree path");let s=C(e,["rev-parse","HEAD"]);if(s.status!==0)return _r(n,s.error||s.stderr||s.stdout||"failed to resolve HEAD");let i;if(o)i=o;else{let m=C(e,["rev-parse",n]);if(m.status!==0)return _r(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=mt(e,i,a),l=mt(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 _r(e,r,t=null){return{checked:!1,base:e,head:t,baseHead:null,baseIsAncestorOfHead:null,headIsAncestorOfBase:null,relation:"unknown",error:r}}var L=g(()=>{"use strict";S();pt()});import{homedir as gt}from"node:os";import ht from"node:path";function Ho(e){return e==="~"?gt():e.startsWith("~/")||e.startsWith("~\\")?ht.join(gt(),e.slice(2)):e}function He(e){return ht.resolve(Ho(e))}var ce=g(()=>{"use strict"});var xr=g(()=>{"use strict";L();ce()});var Cr=g(()=>{"use strict"});var wr=g(()=>{"use strict"});var kt=g(()=>{"use strict"});import{existsSync as Ko,readFileSync as Lo,statfsSync as jo}from"node:fs";function Er(){if(process.platform!=="linux")return!1;for(let e of["/proc/sys/kernel/osrelease","/proc/version"])try{if(!Ko(e))continue;let r=Lo(e,"utf8");if(/microsoft|wsl/i.test(r))return!0}catch{}return!1}function yt(e={}){if(!(e.forceWsl===void 0?Er():e.forceWsl))return null;let t=e.wslHostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||de,n=e.wslHostFreeWarnBytes??$o,o=e.wslHostFreeCriticalBytes??Go,s=e.statfs??jo,i;try{i=s(t)}catch(R){return{ok:!1,path:t,freeBytes:0,totalBytes:0,usedPercent:100,warnBelowBytes:n,criticalBelowBytes:o,reason:`Windows host disk probe failed at ${t}: ${R.message}`,probeError:R.message}}let a=Number(i.bavail)*Number(i.bsize),u=Number(i.blocks)*Number(i.bsize),l=u>0?(u-a)/u*100:100,c=a<n,d=a<o,m=!c&&!d,f=(a/(1024*1024*1024)).toFixed(1),p=null;return m||(p=`Windows host disk ${t} at ${d?"critical":"warning"}: ${f} GiB free (<${(d?o:n)/1024/1024/1024} GiB); WSL VHDX cannot grow safely. ${Yo()}`),{ok:m,path:t,freeBytes:a,totalBytes:u,usedPercent:l,warnBelowBytes:n,criticalBelowBytes:o,reason:p,probeError:null}}function Yo(){return"Recovery: 1) free Windows C: (empty Recycle Bin / Storage Sense / clear %TEMP% and %LOCALAPPDATA%\\Temp\\wsl-crashes); 2) shut down WSL (`wsl --shutdown`) then compact the VHDX (`Optimize-VHD` or `diskpart compact vdisk`); 3) clear local node_modules / .next / harness worktrees before restarting workers; 4) disable recurring dumps via `%USERPROFILE%/.wslconfig` (`maxCrashDumpCount=-1`) or `kynver wsl-crashes --execute`. Full runbook: docs/runbooks/wsl-disk-pressure.md."}var $o,Go,de,Ar=g(()=>{"use strict";$o=25*1024*1024*1024,Go=12*1024*1024*1024,de="/mnt/c"});import{execFileSync as Rt}from"node:child_process";import{existsSync as Le,readFileSync as bt,readdirSync as Vo,statSync as zo}from"node:fs";import Pr from"node:path";function Ke(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function St(){let e=process.env.KYNVER_WSL_WIN_USER?.trim();if(e)return e;try{let n=Rt("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()||de;return r&&Le(Pr.join(t,"Users",r))?r:null}function Zo(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()||de,n=e.windowsUser??St();return n?`${t.replace(/\\/g,"/").replace(/\/$/,"")}/Users/${n}/AppData/Local/Temp/wsl-crashes`:null}function es(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 rs(){try{if(Le("/proc/sys/kernel/core_pattern"))return bt("/proc/sys/kernel/core_pattern","utf8").trim()}catch{}try{return Rt("sysctl",["-n","kernel.core_pattern"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function ts(e){return!!(e&&/wsl-capture-crash/i.test(e))}function ns(e,r=de){let t=Pr.join(r,"Users",e,".wslconfig");if(!Le(t))return{maxCrashDumpCount:null,crashDumpFolder:null};let n;try{n=bt(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 os(e){if(!Le(e))return[];let r=Vo(e,{withFileTypes:!0}),t=[];for(let n of r){if(!n.isFile()||!n.name.toLowerCase().endsWith(".dmp"))continue;let o=Pr.join(e,n.name);try{let s=zo(o),i=es(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 pe(e={}){if(!(e.forceWsl===void 0?Er():e.forceWsl))return null;let t=e.hostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||de,n=e.windowsUser??St(),o=e.warnBelowBytes??Ke("KYNVER_WSL_CRASH_DUMP_WARN_BYTES",Jo),s=e.criticalBelowBytes??Ke("KYNVER_WSL_CRASH_DUMP_CRITICAL_BYTES",Xo),i=e.warnCount??Ke("KYNVER_WSL_CRASH_DUMP_WARN_COUNT",qo),a=e.criticalCount??Ke("KYNVER_WSL_CRASH_DUMP_CRITICAL_COUNT",Qo),u=(e.readCorePattern??rs)(),l=ts(u),c=null;n&&(c=(e.readWslConfig??ns)(n,t));let d=c?.maxCrashDumpCount??null,m=d===-1,f=Zo({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:m,reason:null,probeError:"windows_user_unresolved"};let p;try{p=(e.listDumps??os)(f)}catch(E){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:m,reason:`WSL crash dump probe failed at ${f}: ${E.message}`,probeError:E.message}}let R=p.reduce((E,h)=>E+h.bytes,0),b=p.length,y=[...new Set(p.map(E=>E.executableHint).filter(E=>!!E))],w=R>=s,H=R>=o,U=b>=a,Ie=b>=i,Q=!(w||U||H||Ie),Z=null;if(!Q){let E=w||U?"critical":"warning",h=(R/1024**3).toFixed(1),V=y.length>0?y.join(", "):"unknown";Z=`WSL crash dumps ${E}: ${b} file(s), ${h} GiB at ${f} (executables: ${V}). `+ss({wslCaptureEnabled:l,dumpsDisabledInWslConfig:m})}return{ok:Q,path:f,windowsUser:n,dumpCount:b,totalBytes:R,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:p,executables:y,corePattern:u,wslCaptureEnabled:l,maxCrashDumpCount:d,dumpsDisabledInWslConfig:m,reason:Z,probeError:null}}function ss(e={}){let r=["Recovery:","1) run `kynver wsl-crashes --execute` or scripts/cleanup-wsl-crashes.ps1 to prune old .dmp files;"];return e.dumpsDisabledInWslConfig||r.push("2) add `[wsl2]\\nmaxCrashDumpCount=-1` to %USERPROFILE%/.wslconfig then `wsl --shutdown` to disable future dumps;"),e.wslCaptureEnabled&&r.push("3) investigate crashing executables (node OOM/SIGBUS often follows Windows C: pressure \u2014 see docs/runbooks/wsl-disk-pressure.md);"),r.push("full runbook: docs/runbooks/wsl-disk-pressure.md."),r.join(" ")}var Jo,Xo,qo,Qo,je=g(()=>{"use strict";Ar();Jo=5*1024*1024*1024,Xo=10*1024*1024*1024,qo=2,Qo=4});import{statfsSync as is}from"node:fs";function $e(e={}){let r=e.diskPath?.trim()||"/",t=e.diskFreeWarnBytes??as,n=e.diskFreeCriticalBytes??us,o=e.diskMaxUsedPercent??ls,s=e.diskHardMaxUsedPercent??cs,i=is(r),a=Number(i.bavail)*Number(i.bsize),u=Number(i.blocks)*Number(i.bsize),l=u>0?(u-a)/u*100:100,c=a<t,d=a<n,m=a<t*2,f=m&&l>o,p=m&&l>s,R=!c&&!d&&!f&&!p,b=e.skipWslHostCheck?null:yt(e.wslHost),y=e.skipWslCrashDumpCheck?null:pe(e.wslCrashDumps),w=R&&(b?b.ok:!0)&&(y?y.ok:!0),H=null;return w||(H=[d?`free space below critical ${n} bytes`:null,c?`free space below warning ${t} bytes`:null,p?`used percent above hard cap ${s}%`:null,f?`used percent above cap ${o}%`:null,b&&!b.ok?b.reason:null,y&&!y.ok?y.reason:null].filter(Boolean).join("; ")),ds({ok:w,path:r,freeBytes:a,totalBytes:u,usedPercent:l,warnBelowBytes:t,criticalBelowBytes:n,maxUsedPercent:o,hardMaxUsedPercent:s,reason:H,wslHost:b,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 ds(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 as,us,ls,cs,Ge=g(()=>{"use strict";je();Ar();as=30*1024*1024*1024,us=15*1024*1024*1024,ls=80,cs=90});import{existsSync as ps,readdirSync as ms,statSync as fs}from"node:fs";import Wr from"node:path";function Ye(){return _t()}function Or(){let{runsDir:e}=Ye();return vt(e)}function Ve(e){return vt(j(e))}function gs(e){try{return fs(e).isDirectory()}catch{return!1}}function vt(e){if(!ps(e))return[];let r=[];for(let t of ms(e,{withFileTypes:!0})){if(t.name==="runs")continue;let n=Wr.join(e,t.name);if(!gs(n))continue;let o=x(Wr.join(n,"run.json"),void 0);o?.id&&r.push(o)}return r}function Dr(e){let{runsDir:r}=Ye();lt(Wr.join(Ir(r,e.id),"run.json"),e)}function Se(e){let{harnessRoot:r}=Ye();return ve(r,e)}function ve(e,r){return Ir(j(e),v(r))}var ee=g(()=>{"use strict";$();S()});import{existsSync as hs,readdirSync as ks}from"node:fs";import ys from"node:path";function Nr(e){let r=new Set;for(let n of Object.keys(e.workers||{}))r.add(v(n));let t=ys.join(Se(e.id),"workers");if(!hs(t))return[...r];for(let n of ks(t,{withFileTypes:!0}))n.isDirectory()&&r.add(v(n.name));return[...r]}var Mr=g(()=>{"use strict";ee();S()});function Ur(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 xt(e){let r=e.trim();if(!r)return null;let t=Ur(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let u=Ur(s[1]??"");u&&n.push(u)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let u=Ur(r.slice(i,a+1));u&&n.push(u)}return n.length>0?n[n.length-1]:null}function Ct(e){let r=e.finalResult??e.final_result;if(r!=null)return typeof r=="string"?xt(r)??(r.trim()||null):r;let t=typeof e.summary=="string"?e.summary.trim():"";if(!t)return null;let n=xt(t);return n||t}var wt=g(()=>{"use strict"});import{existsSync as Rs,readFileSync as bs}from"node:fs";function Et(e){return e==="complete"}function At(e){return Et(e.lastHeartbeatPhase)?e.terminalFinalResult!==void 0&&e.terminalFinalResult!==null?e.terminalFinalResult:e.lastHeartbeatSummary?.trim()||"completed":null}function me(e){let r={heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,terminalFinalResult:null,heartbeatBlocker:null,timestampAnomalies:[],lastBoxResourceSnapshot:null,lastPrEvidence:[]};if(!Rs(e))return r;let t=Date.now()+Ss,n=new Date(t).toISOString(),o=bs(e,"utf8").split(`
|
|
6
|
-
`).filter(Boolean);for(let s of o){let i=
|
|
7
|
-
`).find(Boolean)??o,160):"npm audit failed"}function
|
|
8
|
-
${e.stderr}`.trim(),t=
|
|
9
|
-
`).filter(Boolean);for(let n of t){let o=Ue(n);if(!o)continue;let s=Ys(o);if(s&&(r.firstEventAt||=s,r.lastEventAt=s),o.type==="stream_event"&&o.event&&typeof o.event=="object"&&o.event.type==="content_block_start"){let a=o.event.content_block;a?.type==="tool_use"&&(r.currentTool=String(a.name||"tool"))}if(o.type==="assistant"&&o.message&&typeof o.message=="object"){let a=o.message.content;if(Array.isArray(a)){let u=a.find(l=>l?.type==="tool_use");u&&(r.currentTool=String(u.name||r.currentTool))}}if(o.type==="tool_call"&&o.subtype==="started"){let a=o.tool_call&&typeof o.tool_call=="object"&&!Array.isArray(o.tool_call)?o.tool_call:void 0,u=Vs(a);u&&(r.currentTool=u)}let i=Js(o);i&&Xs(r,Dt({command:i.command,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr,interleavedOutput:i.interleaved})),o.type==="result"&&zs(r,o)}return r}var Mt=g(()=>{"use strict";It();S()});function Qs(e,r=240){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function Ut(e){let r=(e??"").trim();if(!r)return null;for(let t of qs)if(t.test.test(r))return{blocked:!0,reason:`${t.label}: ${Qs(r)}`};return null}var qs,Tt=g(()=>{"use strict";qs=[{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 Bt(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function Zs(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 ei(e){return!e?.checked||e.headIsAncestorOfBase!==!1?null:Bt(e.head)}function ri(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 Ft(e){if(e.alive||Zs(e.finalResult))return null;let r=(e.changedFiles??[]).filter(i=>i.trim()).length,t=Bt(e.headCommit)??ei(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:ri(s,r,t)}}var Ht=g(()=>{"use strict"});function Ce(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function ti(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 ni(e){if(Ce(e.headCommit)||Ce(e.prUrl)||Ce(e.artifactBundlePath)||Ce(e.patchPath))return!0;let r=e.gitAncestry;return!!(r?.checked&&r.headIsAncestorOfBase===!1&&Ce(r.head))}function fe(e){return ti(e.finalResult)?e.changedFiles.length===0?{blocked:!1}:ni(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 Kt(e){if(e.blocked)return e.detail??e.reason??"dirty_worktree_no_pr"}var Je=g(()=>{"use strict"});function Kr(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 Lt(e){let r=e.targetPrReconciliation??e.target_pr_reconciliation??e.targetPrs??e.target_prs;return Array.isArray(r)?r.length:0}function Xe(e){let r=e.trim();if(!r)return null;let t=Kr(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let c=Kr(s[1]??"");c&&n.push(c)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let c=Kr(r.slice(i,a+1));c&&n.push(c)}if(n.length===0)return null;let u=n[n.length-1],l=Lt(u);for(let c of n){let d=Lt(c);d>l&&(u=c,l=d)}return u}var Lr=g(()=>{"use strict"});function jt(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 $t(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function oi(e){return new Set(e.map(r=>$t(jt(r)??r)).filter(Boolean))}function Gt(e,r,t){let n=jt(e)??e;if(!n)return"unrelated";let o=$t(n);return oi(r).has(o)?"contract":t?(t.outcome==="skipped"||t.outcome==="blocked")&&t.reason?.trim()?"support":(t.outcome==="merged","unrelated"):"unrelated"}var Yt=g(()=>{"use strict"});function ge(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function si(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"?Object.keys(e).length>0:!0}function re(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`https://github.com/${r[1]}/pull/${r[2]}`:ge(e)}function qe(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function Vt(e){let r=null;if(typeof e=="string"){let o=Xe(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=re(String(s.prUrl??s.pr_url??"")),a=ge(s.outcome);!i||a!=="merged"&&a!=="skipped"&&a!=="blocked"||n.push({prUrl:i,outcome:a,mergeCommit:ge(s.mergeCommit??s.merge_commit),reason:ge(s.reason)})}return n}function zt(e,r){let t=[],n=re(ge(e.prUrl)??"");if(n&&t.push(n),r&&typeof r=="object"&&!Array.isArray(r)){let o=r,s=re(String(o.prUrl??o.pr_url??""));s&&t.push(s)}return[...new Set(t)]}function Jt(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(!si(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?re(ge(r.targetPrUrl)??"")??(r.targetPrUrls.length===1?re(r.targetPrUrls[0]):null):null;if(s){let d=zt(t,n);if(!(n&&typeof n=="object"&&!Array.isArray(n)&&n.supersedesOriginalTargetPr===!0)){for(let R of d)if(R!==s)return{blocked:!0,reason:"duplicate_repair_pr",detail:`Repair worker opened or attached PR ${R} instead of canonical target ${s}`}}let p=Vt(n).find(R=>R.prUrl===s);if(!p||p.outcome!=="merged"&&!(p.reason?.trim()&&(p.outcome==="skipped"||p.outcome==="blocked")))return{blocked:!0,reason:"missing_repair_target_reconciliation",detail:`Repair worker must reconcile target PR ${s}`}}let i=Vt(n),a=new Map(i.map(d=>[qe(d.prUrl),d])),u=new Set(r.targetPrUrls.map(d=>qe(re(d)??d)).filter(Boolean)),l=zt(t,n);if(r.landingOnly)for(let d of l){let m=a.get(qe(d)),f=Gt(d,r.targetPrUrls,m);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 m=qe(re(d)??d),f=a.get(m);if(!f){c.push(m);continue}f.outcome!=="merged"&&!f.reason?.trim()&&c.push(m)}return c.length>0?{blocked:!0,reason:c.every(d=>a.has(d))?"incomplete_target_pr_landing":"missing_target_pr_reconciliation",detail:`Target PR reconciliation incomplete: ${c.join(", ")}`}:{blocked:!1}}function Xt(e){if(e.blocked)return e.detail??e.reason}var qt=g(()=>{"use strict";Lr();Yt()});function ui(e){let r=Date.now();if(e.completionBlocker&&!Qt(e.completionBlocker))return{state:"blocked",reason:e.completionBlocker};if(e.finalResult){if(e.localOnly&&ci(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=fe(o);if(s.blocked){let i=Kt(s);return{state:"needs_attention",reason:s.reason?`landing blocked (${s.reason}): ${i}`:`landing blocked: ${i}`}}if(e.landingContract){let i=Jt({contract:e.landingContract,snapshot:o,finalResult:e.finalResult}),a=Xt(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(li(e))return{state:"done",reason:"empty abandoned worker record"};let o=Ut(e.error);if(o)return{state:"blocked",reason:o.reason};let s=Ft({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>ii)return{state:"needs_attention",reason:`no first stream event ${vr(t)}s after start`};let n=e.lastActivityAt?Date.parse(e.lastActivityAt):NaN;return Number.isFinite(n)&&r-n>ai?{state:"stale",reason:`no log/event/heartbeat activity for ${vr(n)}s`}:{state:"ok",reason:"recent activity"}}function Qt(e){let r=e?.trim();return r?/completion acknowledged but board not advanced/i.test(r)&&/task already terminal/i.test(r):!1}function li(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 ci(e){let r=null;if(typeof e=="string"?r=Xe(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 di(e,r,t){let n=e.completionSnapshot?.finalResult;return e.completionAckSource==="local-pr-merged-reconcile"&&n!==void 0&&n!==null?n:r||(n??At(t))}function we(e,r={}){let t=Nt(e.stdoutPath),n=me(e.heartbeatPath),o=typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim().length>0,s=di(e,t.finalResult,n),i=o?!1:z(e.pid),a=Te(e.stdoutPath),u=Te(e.stderrPath),l=Te(e.heartbeatPath),c=be(e.worktreePath),d=Fe(e.worktreePath,{base:r.base,baseCommit:r.baseCommit}),m=dt([t.lastEventAt,n.lastHeartbeatAt,Be(e.stdoutPath),Be(e.stderrPath),Be(e.heartbeatPath)]),f=t.error||!i&&!s&&ct(e.stderrPath,10).trim()||void 0,p=typeof e.completionBlocker=="string"&&e.completionBlocker.trim()?e.completionBlocker.trim():null,R=Qt(p)?null:p,b=e.repairTargetPrUrl?{landingOnly:!1,targetPrUrls:[e.repairTargetPrUrl],targetPrUrl:e.repairTargetPrUrl,repairEnforceOriginalPr:!0}:null,y=ui({alive:i,finalResult:s,firstEventAt:t.firstEventAt,stdoutBytes:a,stderrBytes:u,heartbeatBytes:l,lastActivityAt:m,heartbeatBlocker:n.heartbeatBlocker,startedAt:e.startedAt,error:f,changedFiles:c,gitAncestry:d,completionBlocker:R,landingContract:b,prUrl:e.repairTargetPrUrl??e.taskPrUrl??null,localOnly:e.localOnly===!0,taskId:e.taskId??null,agentOsId:e.agentOsId??null,reconcileReason:e.reconcileReason??null}),w=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:w,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:f,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,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 te(e){return!!(e.finalResult||e.alive===!1||e.status==="exited"||e.status==="done")}function Zt(e){return e.finalResult?e.attention.state==="needs_attention"||e.attention.state==="blocked":!1}var ii,ai,ne=g(()=>{"use strict";ze();Mt();Tt();Ht();L();Je();qt();Lr();S();ii=18e4,ai=6e5});var en=g(()=>{"use strict";ne()});var mi,fi,rn=g(()=>{"use strict";kt();Ee();Cr();wr();jr();Ge();ee();Mr();en();S();mi=500*1024*1024,fi=4*1024*1024*1024});var jr=g(()=>{"use strict";rn()});import{homedir as gi}from"node:os";import hi from"node:path";var ki,tn=g(()=>{"use strict";ki=hi.join(gi(),".kynver",".env")});var nn=g(()=>{"use strict"});var on=g(()=>{"use strict";nn()});var sn=g(()=>{"use strict"});var an=g(()=>{"use strict";on();sn()});var un=g(()=>{"use strict"});var ln=g(()=>{"use strict";un()});var dn=g(()=>{"use strict";tn();ce();Ee();an();ln()});import{existsSync as vi,mkdirSync as fc,readFileSync as _i,writeFileSync as gc}from"node:fs";import{homedir as xi,totalmem as kc}from"node:os";import $r from"node:path";function Qe(){if(!vi(pn))return{};try{return JSON.parse(_i(pn,"utf8"))}catch{return{}}}var mn,pn,Ec,Ac,Pc,Ee=g(()=>{"use strict";xr();ce();S();Cr();wr();jr();Ge();dn();mn=$r.join(xi(),".kynver"),pn=$r.join(mn,"config.json"),Ec=$r.join(mn,"credentials");Ac=500*1024*1024,Pc=4*1024*1024*1024});import{existsSync as fn}from"node:fs";import{homedir as hn}from"node:os";import J from"node:path";function P(e){let r=J.resolve(He(e.trim()));for(;Ci.has(J.basename(r));)r=J.dirname(r);return r}function X(){let e=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(e)return P(e);let r=Qe().harnessRoot?.trim();if(r)return P(r);let t=J.join(hn(),".kynver","harness");return fn(t)?t:fn(gn)?gn:t}function j(e){return J.join(P(e),"runs")}function he(e){return J.join(P(e),"worktrees")}function _t(){let e=X();return{harnessRoot:e,runsDir:j(e),worktreesDir:he(e)}}function Ir(e,r){return J.join(e,v(r))}var gn,Ci,$=g(()=>{"use strict";Ee();ce();S();gn=J.join(hn(),".openclaw","harness"),Ci=new Set(["runs","worktrees"])});$();import I from"node:path";Je();import tr from"node:path";L();ne();var Gr=[".next",".turbo","dist","build",".cache","node_modules/.cache"];function kn(e){let r=e.replace(/\\/g,"/").replace(/\/+$/,"");if(r==="node_modules"||r.startsWith("node_modules/"))return!0;for(let t of Gr)if(r===t||r.startsWith(`${t}/`))return!0;return!1}function W(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!kn(n)})}function oe(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 Ae(e){let r=e.gitAncestry?.relation;return r==="merged"||r==="synced"?W(e.changedFiles).length>0:!!(oe(e.finalResult)||r==="ahead"||r==="diverged"||e.changedFiles.length>0&&e.finalResult)}S();function Pe(e){return e.status||(e.status=we(e.worker,{base:e.run.base,baseCommit:e.run.baseCommit})),e.status}function Yr(e,r){if(e.status)return W(e.status.changedFiles).length>0;let t=r?r.porcelain(e.worktreePath):be(e.worktreePath);return W(t).length>0}function wi(e){let r=e.worker.completionSnapshot?.finalResult;return r??(e.worker.taskPrUrl?{prUrl:e.worker.taskPrUrl}:null)}function Vr(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=wi(e);if(o&&!z(t.pid)){let i=r?.gitStatusCache?r.gitStatusCache.porcelain(e.worktreePath):be(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"}:Fe(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??oe(s)};return e.status=c,c}return Pe(e)}ne();ee();Mr();ne();S();import Ei from"node:path";var Ai=new Set(["running","dispatching","pending","queued","needs_attention"]),se=new Set(["completed","failed","cancelled","done"]);function ie(e){let r=Nr(e);if(r.length===0)return"failed";let t=!1,n=!1,o=!1,s=!1;for(let i of r){let a=x(Ei.join(Se(e.id),"workers",v(i),"worker.json"),void 0);if(!a)continue;let u=we(a,{base:e.base,baseCommit:e.baseCommit});if(u.alive&&!u.finalResult){t=!0;break}typeof a.completionBlocker=="string"&&a.completionBlocker&&(o=!0),Zt(u)&&(s=!0),u.finalResult&&u.attention.state==="done"&&(n=!0)}return t||o||s?null:n?"completed":"failed"}function yn(){let e=[];for(let r of Or()){if(!Ai.has(r.status))continue;let t=ie(r);if(!t||t===r.status)continue;let n=r.status;r.status=t,Dr(r),e.push({runId:r.id,from:n,to:t})}return e}ne();ze();import{existsSync as Ze,mkdirSync as md,readdirSync as Sn,renameSync as fd,statSync as Pi}from"node:fs";import ae from"node:path";Ee();xr();ce();ze();$();ee();$();S();import q from"node:path";var ud=`${q.sep}runs${q.sep}runs${q.sep}`;function Rn(e){return{workerJsonPath:q.join(e,"worker.json"),stdoutPath:q.join(e,"stdout.jsonl"),stderrPath:q.join(e,"stderr.log"),heartbeatPath:q.join(e,"heartbeat.jsonl"),lastStatusPath:q.join(e,"last-status.json")}}S();var We=900*1e3,vd=3600*1e3;function vn(e,r){let t=ae.resolve(e),n=ae.resolve(j(r)),o=ae.relative(n,t);return o!==".."&&!o.startsWith("..")&&!ae.isAbsolute(o)}function Wi(e){if(!Ze(e))return[];try{return Sn(e,{withFileTypes:!0}).filter(r=>r.isDirectory()&&r.name!=="runs").map(r=>r.name)}catch{return[]}}function Oi(e){let r=ae.join(e,"workers");if(!Ze(r))return[];try{return Sn(r,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}}function bn(e,r,t){if(!Ze(e))return!1;try{let n=r-Pi(e).mtimeMs;return Number.isFinite(n)&&n>=0&&n<t}catch{return!1}}function Di(e,r=Date.now(),t=We){if(!Ze(e))return!1;let n=Rn(e),o=x(n.workerJsonPath,void 0);if(o?.status==="running"&&z(o.pid))return!0;let s=me(n.heartbeatPath);if(s.lastHeartbeatAt){let i=r-Date.parse(s.lastHeartbeatAt);if(Number.isFinite(i)&&i>=0&&i<t)return!0}return!!(bn(n.stdoutPath,r,t)||bn(n.heartbeatPath,r,t))}function Ii(e,r=Date.now(),t=We){for(let n of Oi(e))if(Di(ae.join(e,"workers",n),r,t))return!0;return!1}function _n(e,r=Date.now()){let t=new Set,n=j(e);for(let o of Wi(n)){let s=ae.join(n,o);Ii(s,r)&&t.add(`${e}\0${o}`)}return t}S();function zr(e,r=Date.now(),t=We){let n=me(e.heartbeatPath);if(!n.lastHeartbeatAt)return!1;let o=r-Date.parse(n.lastHeartbeatAt);return Number.isFinite(o)&&o>=0&&o<t}function er(e,r=Date.now(),t=We){return z(e.pid)?!0:zr(e,r,t)}function Ni(e,r){return r?r.runTerminalCache.derive(e.run):ie(e.run)}function G(e,r=Date.now()){return er(e.worker,r)}function Jr(e,r){return se.has(e.run.status)?!1:Ni(e,r)!==null}function xn(e,r,t=Date.now()){if(G(e,t))return!0;if(se.has(e.run.status)||Jr(e,r))return!1;let n=Pe(e);return te(n)?!1:!!G(e,t)}Je();ne();function Cn(e,r){if(!(typeof e.worker.completionBlocker=="string"?e.worker.completionBlocker.trim():""))return!1;if(G(e))return!0;let n=r??Pe(e);return!!(!te(n)||Ae(n)||W(n.changedFiles).length>0||fe({finalResult:n.finalResult,changedFiles:n.changedFiles,gitAncestry:n.gitAncestry,prUrl:oe(n.finalResult)}).blocked)}L();S();import{existsSync as En,mkdirSync as Mi,writeFileSync as wn}from"node:fs";import rr from"node:path";function An(e,r,t){return rr.join(e,"salvage",v(r),v(t))}function Pn(e){return En(rr.join(An(e.harnessRoot,e.runId,e.workerName),"evidence.json"))}function Wn(e){let r=An(e.harnessRoot,e.indexed.runId,e.indexed.workerName);Mi(r,{recursive:!0});let t=rr.join(r,"salvage.patch"),n=!1;if(En(e.indexed.worktreePath)){let s=C(e.indexed.worktreePath,["diff","HEAD"]),i=C(e.indexed.worktreePath,["diff","--cached"]),a=[s.stdout,i.stdout].filter(u=>u.trim()).join(`
|
|
10
|
-
`);a.trim()&&(
|
|
4
|
+
`):""}function Q(e){if(!e)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Mt(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 Ur(e){return Math.max(0,Math.round((Date.now()-e)/1e3))}var b=g(()=>{"use strict"});var hs,Du,Tt=g(()=>{"use strict";hs=["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"],Du=new Set(hs)});import{spawnSync as Bt}from"node:child_process";function Ce(e,r,t={}){let n=Bt("git",r,Tr({cwd:e,encoding:"utf8"}));if(n.status!==0&&!t.allowFailure){let o=`git ${r.join(" ")} failed: ${n.stderr||n.stdout}`;if(t.throwError)throw new Error(o);Mr(o)}return n.stdout||""}function Ee(e){return Ce(e,["status","--short"],{allowFailure:!0}).split(`
|
|
5
|
+
`).map(r=>r.trim()).filter(Boolean)}function w(e,r){try{let t=Bt("git",r,Tr({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 Ut(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 Ge(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 Br(n,"missing worktree path");let s=w(e,["rev-parse","HEAD"]);if(s.status!==0)return Br(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 Br(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=Ut(e,i,a),l=Ut(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 Br(e,r,t=null){return{checked:!1,base:e,head:t,baseHead:null,baseIsAncestorOfHead:null,headIsAncestorOfBase:null,relation:"unknown",error:r}}var $=g(()=>{"use strict";b();Tt()});import{homedir as Ht}from"node:os";import Kt from"node:path";function ks(e){return e==="~"?Ht():e.startsWith("~/")||e.startsWith("~\\")?Kt.join(Ht(),e.slice(2)):e}function Ye(e){return Kt.resolve(ks(e))}var me=g(()=>{"use strict"});var Hr=g(()=>{"use strict";$();me()});function fe(e){let r=(e??"").trim().toLowerCase();return r==="ghost"||r==="forge"?r:r.includes("forge")?"forge":r.includes("ghost")||r.includes("openclaw")?"ghost":"forge"}function Ve(e,r){return e[r]?.trim()||null}function Ft(e){let r=e?.split(":")[0]?.trim();return r?fe(r):null}function Kr(e=process.env,r={}){let t=[],n=Ft(r.boxId),o=Ft(Ve(e,"KYNVER_BOX_ID")),s=r.boxKind?.trim();if(s)return n&&n!==fe(s)&&t.push(`config.boxId=${r.boxId} conflicts with boxKind=${s}; using explicit boxKind=${s}`),{boxKind:fe(s),source:"config",slugInferenceBlocked:!1,warnings:t};let i=Ve(e,"KYNVER_BOX_KIND");if(i)return o&&o!==fe(i)&&t.push(`KYNVER_BOX_ID=${Ve(e,"KYNVER_BOX_ID")} conflicts with KYNVER_BOX_KIND=${i}; using explicit KYNVER_BOX_KIND=${i}`),{boxKind:fe(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=Ve(e,"KYNVER_AGENT_OS_SLUG");return a&&t.push(`KYNVER_AGENT_OS_SLUG=${a} is a workspace slug, not box identity \u2014 set boxKind via \`kynver setup --box-kind forge|ghost\` or KYNVER_BOX_KIND (defaulting box kind to forge)`),{boxKind:"forge",source:"default",slugInferenceBlocked:!!a,warnings:t}}var ze=g(()=>{"use strict"});function Fr(e,r){return e==="forge"?4:Math.max(1,r)}function Je(e,r){return e==="forge"?Math.min(Math.max(1,r),4):Math.max(1,r)}var qe=g(()=>{"use strict"});var Lt=g(()=>{"use strict"});import{existsSync as ys,readFileSync as Rs,statfsSync as bs}from"node:fs";function Lr(){if(process.platform!=="linux")return!1;for(let e of["/proc/sys/kernel/osrelease","/proc/version"])try{if(!ys(e))continue;let r=Rs(e,"utf8");if(/microsoft|wsl/i.test(r))return!0}catch{}return!1}function jt(e={}){if(!(e.forceWsl===void 0?Lr():e.forceWsl))return null;let t=e.wslHostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||ge,n=e.wslHostFreeWarnBytes??Ss,o=e.wslHostFreeCriticalBytes??vs,s=e.statfs??bs,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,m=!c&&!d,f=(a/(1024*1024*1024)).toFixed(1),p=null;return m||(p=`Windows host disk ${t} at ${d?"critical":"warning"}: ${f} GiB free (<${(d?o:n)/1024/1024/1024} GiB); WSL VHDX cannot grow safely. ${xs()}`),{ok:m,path:t,freeBytes:a,totalBytes:u,usedPercent:l,warnBelowBytes:n,criticalBelowBytes:o,reason:p,probeError:null}}function xs(){return"Recovery: 1) free Windows C: (empty Recycle Bin / Storage Sense / clear %TEMP% and %LOCALAPPDATA%\\Temp\\wsl-crashes); 2) shut down WSL (`wsl --shutdown`) then compact the VHDX (`Optimize-VHD` or `diskpart compact vdisk`); 3) clear local node_modules / .next / harness worktrees before restarting workers; 4) disable recurring dumps via `%USERPROFILE%/.wslconfig` (`maxCrashDumpCount=-1`) or `kynver wsl-crashes --execute`. Full runbook: docs/runbooks/wsl-disk-pressure.md."}var Ss,vs,ge,jr=g(()=>{"use strict";Ss=25*1024*1024*1024,vs=12*1024*1024*1024,ge="/mnt/c"});import{execFileSync as $t}from"node:child_process";import{existsSync as Qe,readFileSync as Gt,readdirSync as _s,statSync as Cs}from"node:fs";import $r from"node:path";function Xe(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function Yt(){let e=process.env.KYNVER_WSL_WIN_USER?.trim();if(e)return e;try{let n=$t("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()||ge;return r&&Qe($r.join(t,"Users",r))?r:null}function Is(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()||ge,n=e.windowsUser??Yt();return n?`${t.replace(/\\/g,"/").replace(/\/$/,"")}/Users/${n}/AppData/Local/Temp/wsl-crashes`:null}function Os(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 Ds(){try{if(Qe("/proc/sys/kernel/core_pattern"))return Gt("/proc/sys/kernel/core_pattern","utf8").trim()}catch{}try{return $t("sysctl",["-n","kernel.core_pattern"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function Ws(e){return!!(e&&/wsl-capture-crash/i.test(e))}function Ns(e,r=ge){let t=$r.join(r,"Users",e,".wslconfig");if(!Qe(t))return{maxCrashDumpCount:null,crashDumpFolder:null};let n;try{n=Gt(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 Ms(e){if(!Qe(e))return[];let r=_s(e,{withFileTypes:!0}),t=[];for(let n of r){if(!n.isFile()||!n.name.toLowerCase().endsWith(".dmp"))continue;let o=$r.join(e,n.name);try{let s=Cs(o),i=Os(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 he(e={}){if(!(e.forceWsl===void 0?Lr():e.forceWsl))return null;let t=e.hostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||ge,n=e.windowsUser??Yt(),o=e.warnBelowBytes??Xe("KYNVER_WSL_CRASH_DUMP_WARN_BYTES",Es),s=e.criticalBelowBytes??Xe("KYNVER_WSL_CRASH_DUMP_CRITICAL_BYTES",ws),i=e.warnCount??Xe("KYNVER_WSL_CRASH_DUMP_WARN_COUNT",As),a=e.criticalCount??Xe("KYNVER_WSL_CRASH_DUMP_CRITICAL_COUNT",Ps),u=(e.readCorePattern??Ds)(),l=Ws(u),c=null;n&&(c=(e.readWslConfig??Ns)(n,t));let d=c?.maxCrashDumpCount??null,m=d===-1,f=Is({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:m,reason:null,probeError:"windows_user_unresolved"};let p;try{p=(e.listDumps??Ms)(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:m,reason:`WSL crash dump probe failed at ${f}: ${P.message}`,probeError:P.message}}let y=p.reduce((P,h)=>P+h.bytes,0),S=p.length,R=[...new Set(p.map(P=>P.executableHint).filter(P=>!!P))],A=y>=s,L=y>=o,B=S>=a,He=S>=i,re=!(A||B||L||He),te=null;if(!re){let P=A||B?"critical":"warning",h=(y/1024**3).toFixed(1),X=R.length>0?R.join(", "):"unknown";te=`WSL crash dumps ${P}: ${S} file(s), ${h} GiB at ${f} (executables: ${X}). `+Ts({wslCaptureEnabled:l,dumpsDisabledInWslConfig:m})}return{ok:re,path:f,windowsUser:n,dumpCount:S,totalBytes:y,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:p,executables:R,corePattern:u,wslCaptureEnabled:l,maxCrashDumpCount:d,dumpsDisabledInWslConfig:m,reason:te,probeError:null}}function Ts(e={}){let r=["Recovery:","1) run `kynver wsl-crashes --execute` or scripts/cleanup-wsl-crashes.ps1 to prune old .dmp files;"];return e.dumpsDisabledInWslConfig||r.push("2) add `[wsl2]\\nmaxCrashDumpCount=-1` to %USERPROFILE%/.wslconfig then `wsl --shutdown` to disable future dumps;"),e.wslCaptureEnabled&&r.push("3) investigate crashing executables (node OOM/SIGBUS often follows Windows C: pressure \u2014 see docs/runbooks/wsl-disk-pressure.md);"),r.push("full runbook: docs/runbooks/wsl-disk-pressure.md."),r.join(" ")}var Es,ws,As,Ps,Ze=g(()=>{"use strict";jr();Es=5*1024*1024*1024,ws=10*1024*1024*1024,As=2,Ps=4});import{statfsSync as Us}from"node:fs";function er(e={}){let r=e.diskPath?.trim()||"/",t=e.diskFreeWarnBytes??Bs,n=e.diskFreeCriticalBytes??Hs,o=e.diskMaxUsedPercent??Ks,s=e.diskHardMaxUsedPercent??Fs,i=Us(r),a=Number(i.bavail)*Number(i.bsize),u=Number(i.blocks)*Number(i.bsize),l=u>0?(u-a)/u*100:100,c=a<t,d=a<n,m=a<t*2,f=m&&l>o,p=m&&l>s,y=!c&&!d&&!f&&!p,S=e.skipWslHostCheck?null:jt(e.wslHost),R=e.skipWslCrashDumpCheck?null:he(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,p?`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("; ")),Ls({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 Ls(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 Bs,Hs,Ks,Fs,rr=g(()=>{"use strict";Ze();jr();Bs=30*1024*1024*1024,Hs=15*1024*1024*1024,Ks=80,Fs=90});import{existsSync as js,readdirSync as $s,statSync as Gs}from"node:fs";import Gr from"node:path";function tr(){return zt()}function Yr(){let{runsDir:e}=tr();return Vt(e)}function nr(e){return Vt(G(e))}function Ys(e){try{return Gs(e).isDirectory()}catch{return!1}}function Vt(e){if(!js(e))return[];let r=[];for(let t of $s(e,{withFileTypes:!0})){if(t.name==="runs")continue;let n=Gr.join(e,t.name);if(!Ys(n))continue;let o=x(Gr.join(n,"run.json"),void 0);o?.id&&r.push(o)}return r}function Vr(e){let{runsDir:r}=tr();Wt(Gr.join(zr(r,e.id),"run.json"),e)}function we(e){let{harnessRoot:r}=tr();return Ae(r,e)}function Ae(e,r){return zr(G(e),v(r))}var ne=g(()=>{"use strict";Y();b()});import{existsSync as Vs,readdirSync as zs}from"node:fs";import Js from"node:path";function Jr(e){let r=new Set;for(let n of Object.keys(e.workers||{}))r.add(v(n));let t=Js.join(we(e.id),"workers");if(!Vs(t))return[...r];for(let n of zs(t,{withFileTypes:!0}))n.isDirectory()&&r.add(v(n.name));return[...r]}var qr=g(()=>{"use strict";ne();b()});function Xr(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 Jt(e){let r=e.trim();if(!r)return null;let t=Xr(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let u=Xr(s[1]??"");u&&n.push(u)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let u=Xr(r.slice(i,a+1));u&&n.push(u)}return n.length>0?n[n.length-1]:null}function qt(e){let r=e.finalResult??e.final_result;if(r!=null)return typeof r=="string"?Jt(r)??(r.trim()||null):r;let t=typeof e.summary=="string"?e.summary.trim():"";if(!t)return null;let n=Jt(t);return n||t}var Xt=g(()=>{"use strict"});import{existsSync as qs,readFileSync as Xs}from"node:fs";function Qt(e){return e==="complete"}function Zt(e){return Qt(e.lastHeartbeatPhase)?e.terminalFinalResult!==void 0&&e.terminalFinalResult!==null?e.terminalFinalResult:e.lastHeartbeatSummary?.trim()||"completed":null}function ke(e){let r={heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,terminalFinalResult:null,heartbeatBlocker:null,timestampAnomalies:[],lastBoxResourceSnapshot:null,lastPrEvidence:[]};if(!qs(e))return r;let t=Date.now()+Qs,n=new Date(t).toISOString(),o=Xs(e,"utf8").split(`
|
|
6
|
+
`).filter(Boolean);for(let s of o){let i=Le(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)),Qt(r.lastHeartbeatPhase)&&(r.terminalFinalResult=qt(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 Qs,or=g(()=>{"use strict";Xt();b();Qs=6e4});function ei(e){return e?(e.split("/").pop()??e).replace(/\.exe$/i,"").toLowerCase():null}function ri(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 ti(e){let r=ei(e[0]);return!!(r&&Zs.has(r))}function Qr(e){return!e||e.includes("/")||e.includes("*")?!1:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(e)}function Zr(e){if(!e)return!1;let r=e.trim();return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")}function ni(e){if(!e.startsWith("--glob="))return e;let r=e.slice(7);return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")?`--glob=${r}/**`:e}function oi(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;en.has(n)&&(t+=1);continue}r.push(n)}}return r}function si(e){let r=!1,t=e.map((o,s)=>{let i=ni(o),a=e[s-1];return a&&en.has(a)&&o.startsWith("!")&&!o.includes("/")&&!o.endsWith("/**")&&(i=`${o}/**`),i!==o&&(r=!0),i}),n=oi(t);if(n.length===2){let[o,s]=n;if(Zr(s))return{argv:[t[0]??"rg",o,"-g",`${s}/**`,"."],changed:!0};if(Qr(s))return{argv:[t[0]??"rg","-g",s,o,"."],changed:!0}}return r&&n.length===1?{argv:[...t,"."],changed:!0}:{argv:t,changed:r}}function et(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=ri(i.trim());if(!a.length||!ti(a))return i;let u=si(a);return u.changed?(o=!0,u.argv.join(" ")):i});return o?{command:s.join(t),changed:!0}:{command:r,changed:!1}}function rn(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 ii(e){let{pattern:r,target:t}=rn(e);return r?Zr(t)?{kind:"rg_exclude_syntax",pattern:r,target:t}:Qr(t)?{kind:"bad_scope",pattern:r,target:t}:{kind:"not_repo_search",pattern:r,target:t}:{kind:"not_repo_search"}}function ai(e){let{pattern:r,target:t}=rn(e);if(!r)return null;if(Zr(t)){let n=`${t.trim()}/**`;return{command:`rg "${r}" -g '${n}' .`,changed:!0}}return t&&Qr(t)?{command:`rg -g ${t} "${r}" .`,changed:!0}:null}function ui(e){if(e.kind==="bad_scope"&&e.pattern?.includes("agent-os-land-pr")&&e.target==="package.json")return"Search package.json with a glob from the repo root: `rg -g package.json agent-os-land-pr .` \u2014 or run `node scripts/agent-os-land-pr.mjs <pr-url>` directly.";if(e.kind==="bad_scope"&&e.pattern&&e.target)return`Use \`rg -g '${e.target}' ${e.pattern} .\` from the repo root instead of treating ${e.target} as a folder.`;if(e.kind==="rg_exclude_syntax"&&e.pattern){let r=e.target?`${e.target.trim()}/**`:"!node_modules/**";return`Repo search scope \`${e.target??"!node_modules"}\` is not a valid ripgrep path. Use \`rg "${e.pattern}" -g '${r}' .\` from the repo root (exclude globs need a \`/**\` suffix).`}return e.kind==="no_matches"&&e.pattern?`No matches for "${e.pattern}". Try a broader pattern, drop overly short tokens, or search from the repo root with \`rg "${e.pattern}" .\`.`:null}function li(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 rt(e){let r=e.meta?.trim()||(e.command?li(e.command):null)||null;if(r){let t=ii(r),n=ui(t);if(n)return n;let o=ai(r);if(o?.changed)return`Repo search used an invalid scope. Retry with: \`${o.command}\`.`}if(e.command&&/\b(rg|ripgrep)\b/i.test(e.command)){let t=et(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 Zs,en,tn=g(()=>{"use strict";Zs=new Set(["rg","ripgrep","grep"]),en=new Set(["-e","--regexp","-f","--file","-m","--max-count","-A","--after-context","-B","--before-context","-C","--context","-g","--glob","--iglob"])});function Pe(e,r=200){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function mi(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 Ie(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function fi(e){let r=e.metadata;if(!Ie(r))return null;let t=r.vulnerabilities;if(!Ie(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 gi(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 hi(e,r){let t=e.error;if(Ie(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?Pe(o.split(`
|
|
7
|
+
`).find(Boolean)??o,160):"npm audit failed"}function ki(e){let r=`${e.stdout}
|
|
8
|
+
${e.stderr}`.trim(),t=mi(r);if(!t||!Ie(t)){let o=Pe(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(Ie(t.error))return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit command failed: ${hi(t,e.stderr)}`};let n=fi(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:gi(n),audit:n}:{kind:"command_failure",exitCode:e.exitCode,summary:"npm audit failed: JSON response missing vulnerability metadata",parseError:"missing_metadata"}}function yi(e){return ci.test(e)}function Ri(e){return di.test(e)}function bi(e){let r=rt({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&&pi.test(n)){let i=Pe(n,160);return{kind:"command_failure",exitCode:1,summary:r??`ripgrep failed (exit 1): ${i}`}}let o=et(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=Pe(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 nn(e){let r=e.stdout??"",t=e.stderr??"",n=e.interleavedOutput??"";if(yi(e.command)){let i=r.trim()||n.trim()||t.trim();return ki({exitCode:e.exitCode,stdout:i,stderr:t})}if(Ri(e.command))return bi({command:e.command,exitCode:e.exitCode,stdout:r,stderr:t,interleaved:n});let o=rt({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=Pe(n||r||t||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:`command failed (exit ${e.exitCode}): ${s}`}}var ci,di,pi,on=g(()=>{"use strict";tn();ci=/\bnpm\s+audit\b/i,di=/\b(rg|ripgrep)\b/i,pi=/\b(error|invalid|unknown|panic|not found)\b/i});import{existsSync as Si,readFileSync as vi}from"node:fs";function xi(e){let r=e.timestamp_ms;return e.timestamp||e.ts||(r?new Date(r).toISOString():void 0)}function _i(e){if(!e)return null;for(let r of Object.keys(e))if(r.endsWith("ToolCall")){let t=r.slice(0,-8);return t.length?t:r}return null}function Ci(e,r){e.finalResult=r.result||r.subtype||r.terminal_reason||"completed",r.is_error&&(e.error=String(r.result||r.api_error_status||"stream result error"))}function Ei(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 wi(e,r){r.kind==="success"||r.kind==="search_no_matches"||(e.lastShellOutcome=r)}function sn(e){let r={firstEventAt:null,lastEventAt:null,currentTool:null,finalResult:null,error:null,lastShellOutcome:null};if(!Si(e))return r;let t=vi(e,"utf8").split(`
|
|
9
|
+
`).filter(Boolean);for(let n of t){let o=Le(n);if(!o)continue;let s=xi(o);if(s&&(r.firstEventAt||=s,r.lastEventAt=s),o.type==="stream_event"&&o.event&&typeof o.event=="object"&&o.event.type==="content_block_start"){let a=o.event.content_block;a?.type==="tool_use"&&(r.currentTool=String(a.name||"tool"))}if(o.type==="assistant"&&o.message&&typeof o.message=="object"){let a=o.message.content;if(Array.isArray(a)){let u=a.find(l=>l?.type==="tool_use");u&&(r.currentTool=String(u.name||r.currentTool))}}if(o.type==="tool_call"&&o.subtype==="started"){let a=o.tool_call&&typeof o.tool_call=="object"&&!Array.isArray(o.tool_call)?o.tool_call:void 0,u=_i(a);u&&(r.currentTool=u)}let i=Ei(o);i&&wi(r,nn({command:i.command,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr,interleavedOutput:i.interleaved})),o.type==="result"&&Ci(r,o)}return r}var an=g(()=>{"use strict";on();b()});function Pi(e,r=240){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function un(e){let r=(e??"").trim();if(!r)return null;for(let t of Ai)if(t.test.test(r))return{blocked:!0,reason:`${t.label}: ${Pi(r)}`};return null}var Ai,ln=g(()=>{"use strict";Ai=[{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 cn(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function Ii(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 Oi(e){return!e?.checked||e.headIsAncestorOfBase!==!1?null:cn(e.head)}function Di(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 dn(e){if(e.alive||Ii(e.finalResult))return null;let r=(e.changedFiles??[]).filter(i=>i.trim()).length,t=cn(e.headCommit)??Oi(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:Di(s,r,t)}}var pn=g(()=>{"use strict"});function Oe(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function Wi(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 Ni(e){if(Oe(e.headCommit)||Oe(e.prUrl)||Oe(e.artifactBundlePath)||Oe(e.patchPath))return!0;let r=e.gitAncestry;return!!(r?.checked&&r.headIsAncestorOfBase===!1&&Oe(r.head))}function ye(e){return Wi(e.finalResult)?e.changedFiles.length===0?{blocked:!1}:Ni(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 mn(e){if(e.blocked)return e.detail??e.reason??"dirty_worktree_no_pr"}var sr=g(()=>{"use strict"});function tt(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 fn(e){let r=e.targetPrReconciliation??e.target_pr_reconciliation??e.targetPrs??e.target_prs;return Array.isArray(r)?r.length:0}function ir(e){let r=e.trim();if(!r)return null;let t=tt(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let c=tt(s[1]??"");c&&n.push(c)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let c=tt(r.slice(i,a+1));c&&n.push(c)}if(n.length===0)return null;let u=n[n.length-1],l=fn(u);for(let c of n){let d=fn(c);d>l&&(u=c,l=d)}return u}var nt=g(()=>{"use strict"});function gn(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 hn(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function Mi(e){return new Set(e.map(r=>hn(gn(r)??r)).filter(Boolean))}function kn(e,r,t){let n=gn(e)??e;if(!n)return"unrelated";let o=hn(n);return Mi(r).has(o)?"contract":t?(t.outcome==="skipped"||t.outcome==="blocked")&&t.reason?.trim()?"support":(t.outcome==="merged","unrelated"):"unrelated"}var yn=g(()=>{"use strict"});function Re(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function Ti(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"?Object.keys(e).length>0:!0}function oe(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`https://github.com/${r[1]}/pull/${r[2]}`:Re(e)}function ar(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function Rn(e){let r=null;if(typeof e=="string"){let o=ir(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=oe(String(s.prUrl??s.pr_url??"")),a=Re(s.outcome);!i||a!=="merged"&&a!=="skipped"&&a!=="blocked"||n.push({prUrl:i,outcome:a,mergeCommit:Re(s.mergeCommit??s.merge_commit),reason:Re(s.reason)})}return n}function bn(e,r){let t=[],n=oe(Re(e.prUrl)??"");if(n&&t.push(n),r&&typeof r=="object"&&!Array.isArray(r)){let o=r,s=oe(String(o.prUrl??o.pr_url??""));s&&t.push(s)}return[...new Set(t)]}function Sn(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(!Ti(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?oe(Re(r.targetPrUrl)??"")??(r.targetPrUrls.length===1?oe(r.targetPrUrls[0]):null):null;if(s){let d=bn(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 p=Rn(n).find(y=>y.prUrl===s);if(!p||p.outcome!=="merged"&&!(p.reason?.trim()&&(p.outcome==="skipped"||p.outcome==="blocked")))return{blocked:!0,reason:"missing_repair_target_reconciliation",detail:`Repair worker must reconcile target PR ${s}`}}let i=Rn(n),a=new Map(i.map(d=>[ar(d.prUrl),d])),u=new Set(r.targetPrUrls.map(d=>ar(oe(d)??d)).filter(Boolean)),l=bn(t,n);if(r.landingOnly)for(let d of l){let m=a.get(ar(d)),f=kn(d,r.targetPrUrls,m);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 m=ar(oe(d)??d),f=a.get(m);if(!f){c.push(m);continue}f.outcome!=="merged"&&!f.reason?.trim()&&c.push(m)}return c.length>0?{blocked:!0,reason:c.every(d=>a.has(d))?"incomplete_target_pr_landing":"missing_target_pr_reconciliation",detail:`Target PR reconciliation incomplete: ${c.join(", ")}`}:{blocked:!1}}function vn(e){if(e.blocked)return e.detail??e.reason}var xn=g(()=>{"use strict";nt();yn()});function Hi(e){let r=Date.now();if(e.completionBlocker&&!_n(e.completionBlocker))return{state:"blocked",reason:e.completionBlocker};if(e.finalResult){if(e.localOnly&&Fi(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=ye(o);if(s.blocked){let i=mn(s);return{state:"needs_attention",reason:s.reason?`landing blocked (${s.reason}): ${i}`:`landing blocked: ${i}`}}if(e.landingContract){let i=Sn({contract:e.landingContract,snapshot:o,finalResult:e.finalResult}),a=vn(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(Ki(e))return{state:"done",reason:"empty abandoned worker record"};let o=un(e.error);if(o)return{state:"blocked",reason:o.reason};let s=dn({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>Ui)return{state:"needs_attention",reason:`no first stream event ${Ur(t)}s after start`};let n=e.lastActivityAt?Date.parse(e.lastActivityAt):NaN;return Number.isFinite(n)&&r-n>Bi?{state:"stale",reason:`no log/event/heartbeat activity for ${Ur(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 Ki(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 Fi(e){let r=null;if(typeof e=="string"?r=ir(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 Li(e,r,t){let n=e.completionSnapshot?.finalResult;return e.completionAckSource==="local-pr-merged-reconcile"&&n!==void 0&&n!==null?n:r||(n??Zt(t))}function De(e,r={}){let t=sn(e.stdoutPath),n=ke(e.heartbeatPath),o=typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim().length>0,s=Li(e,t.finalResult,n),i=o?!1:Q(e.pid),a=je(e.stdoutPath),u=je(e.stderrPath),l=je(e.heartbeatPath),c=Ee(e.worktreePath),d=Ge(e.worktreePath,{base:r.base,baseCommit:r.baseCommit}),m=Mt([t.lastEventAt,n.lastHeartbeatAt,$e(e.stdoutPath),$e(e.stderrPath),$e(e.heartbeatPath)]),f=t.error||!i&&!s&&Nt(e.stderrPath,10).trim()||void 0,p=typeof e.completionBlocker=="string"&&e.completionBlocker.trim()?e.completionBlocker.trim():null,y=_n(p)?null:p,S=e.repairTargetPrUrl?{landingOnly:!1,targetPrUrls:[e.repairTargetPrUrl],targetPrUrl:e.repairTargetPrUrl,repairEnforceOriginalPr:!0}:null,R=Hi({alive:i,finalResult:s,firstEventAt:t.firstEventAt,stdoutBytes:a,stderrBytes:u,heartbeatBytes:l,lastActivityAt:m,heartbeatBlocker:n.heartbeatBlocker,startedAt:e.startedAt,error:f,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: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:f,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,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 se(e){return!!(e.finalResult||e.alive===!1||e.status==="exited"||e.status==="done")}function Cn(e){return e.finalResult?e.attention.state==="needs_attention"||e.attention.state==="blocked":!1}var Ui,Bi,ie=g(()=>{"use strict";or();an();ln();pn();$();sr();xn();nt();b();Ui=18e4,Bi=6e5});var En=g(()=>{"use strict";ie()});function wn(e,r={}){let t=r.perWorkerMemBytes??ot,n=r.memReserveBytes??st,o=r.memUtilization??it,s=Math.max(0,Math.floor(e*o)-n),i=Math.max(1,Math.floor(s/t));return Math.min(i,ur)}var ot,st,it,ur,An=g(()=>{"use strict";Lt();Se();ze();qe();lr();rr();ne();qr();En();b();ot=500*1024*1024,st=4*1024*1024*1024,it=.85,ur=64});function We(e,r){let t=Number(e);return!Number.isFinite(t)||t<=0?r:Math.floor(t)}function at(e){let r=e.config??{},t=e.env??process.env,n=We(r.perWorkerMemBytes,ot),o=We(r.memReserveBytes,st),s=Math.min(1,Math.max(.1,Number(r.memUtilization)>0?Number(r.memUtilization):it)),i=wn(e.totalMemBytes,{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s});if(e.configuredMaxWorkersOverride!==void 0&&e.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:We(e.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(r.maxConcurrentWorkers!==void 0&&r.maxConcurrentWorkers!==null){let l=We(r.maxConcurrentWorkers,0)||null;if(l)return{configuredMaxWorkers:Math.min(l,ur),autoCap:i,workerCapSource:"config"}}let u=(t.KYNVER_MAX_WORKERS_INTENTIONAL==="1"||t.KYNVER_MAX_WORKERS_INTENTIONAL==="true")&&t.KYNVER_MAX_WORKERS&&We(t.KYNVER_MAX_WORKERS,0)||null;return u?{configuredMaxWorkers:Math.min(u,ur),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var lr=g(()=>{"use strict";An()});import{homedir as ji}from"node:os";import $i from"node:path";var Gi,Pn=g(()=>{"use strict";Gi=$i.join(ji(),".kynver",".env")});var In=g(()=>{"use strict"});var On=g(()=>{"use strict";In()});var Dn=g(()=>{"use strict"});var Wn=g(()=>{"use strict";On();Dn()});var Nn=g(()=>{"use strict"});var Mn=g(()=>{"use strict";Nn()});var Un=g(()=>{"use strict";Pn();me();Se();Wn();Mn()});import{existsSync as V,mkdirSync as Vi,readdirSync as cr,renameSync as Bn,statSync as zi}from"node:fs";import z from"node:path";function Kn(e){try{return zi(e).isDirectory()}catch{return!1}}function Ji(e){if(!V(e))return!0;for(let r of Hn){let t=z.join(e,r);if(V(t)&&(!Kn(t)||cr(t).length>0))return!1}return!0}function qi(e){let r=z.join(e,"runs");if(!V(r)||!Kn(r))return!1;for(let t of cr(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 Xi(e){let r=z.join(e,"runs");if(!V(r))return!1;for(let t of cr(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 Qi(e){let r=z.join(e,"ghost");return V(r)?!V(z.join(r,"runs")):Xi(e)}function Fn(e){return qi(e.sharedRoot)?Ji(e.forgeRoot)?Qi(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 Ln(e,r){Vi(r,{recursive:!0});for(let t of Hn){let n=z.join(e,t),o=z.join(r,t);if(V(n)){if(V(o)&&cr(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(V(o)){Bn(n,o);continue}Bn(n,o)}}}var Hn,jn=g(()=>{"use strict";b();Hn=["runs","worktrees"]});import{existsSync as E}from"node:fs";import{homedir as Zi}from"node:os";import C from"node:path";function ut(e=process.env){return e.HOME?.trim()||Zi()}function lt(e=process.env){return C.join(ut(e),".kynver","harness")}function dr(e){let r=C.resolve(Ye(e.trim()));for(;ea.has(C.basename(r));)r=C.dirname(r);return r}function ra(e,r=process.env){return C.join(lt(r),e)}function ta(e=process.env){let r=lt(e);if(E(C.join(r,"runs")))return!0;if(E(r)&&!E(C.join(r,"ghost"))&&!E(C.join(r,"forge")))return E(r);let t=C.join(ut(e),$n);return E(t)}function pr(e){let r=e.env??process.env,t=r.KYNVER_HARNESS_ROOT?.trim()||r.OPUS_HARNESS_ROOT?.trim();if(t)return{harnessRoot:dr(t),source:"env"};let n=e.configuredHarnessRoot?.trim();if(n)return{harnessRoot:dr(n),source:"config"};let o=ra(e.boxKind,r);if(E(C.join(o,"runs"))||E(o)&&!na(o))return{harnessRoot:o,source:"box_scoped"};let i=lt(r);if(e.boxKind==="forge"){let a=Fn({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&&Ln(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(e.boxKind==="ghost"&&ta(r)){if(E(C.join(i,"runs")))return{harnessRoot:i,source:"legacy_shared"};if(E(i)&&!E(C.join(i,"ghost"))&&!E(C.join(i,"forge")))return{harnessRoot:i,source:"legacy_shared"};let u=C.join(ut(r),$n);if(E(u))return{harnessRoot:u,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function na(e){if(!E(e))return!0;for(let r of["runs","worktrees"]){let t=C.join(e,r);if(E(t))return!1}return!0}var $n,ea,ct=g(()=>{"use strict";me();jn();$n=C.join(".openclaw","harness");ea=new Set(["runs","worktrees"])});import Gn from"node:os";function mr(e){return e?.trim()?e.trim():null}function oa(e,r){let t=r.trim().toLowerCase()||"host";return`${e}-${t}`.replace(/[^a-z0-9._-]+/g,"-")}function sa(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 dt(e=be(),r=process.env,t={}){let n=Kr(r,e),o=[...n.warnings],s=[],i=!!(e.boxKind?.trim()||mr(r.KYNVER_BOX_KIND)),a=t.strict===!0||sa(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 --box-kind forge|ghost` 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 forge`)}let u=mr(e.runnerId),l=mr(r.KYNVER_RUNTIME_ID)??mr(r.OPENCLAW_RUNTIME_ID),c=u??l??oa(n.boxKind,Gn.hostname()),d=u?"config":l?"env":"derived";d==="derived"&&o.push(`runnerId not persisted \u2014 using derived id "${c}"; run \`kynver setup --box-kind ${n.boxKind}\` to persist runner identity`);let m=at({config:e,env:r,totalMemBytes:Gn.totalmem()}),f=Je(n.boxKind,m.configuredMaxWorkers??Fr(n.boxKind,m.autoCap)),p=pr({boxKind:n.boxKind,configuredHarnessRoot:e.harnessRoot,env:r});return p.migrationBlocker&&s.push(p.migrationBlocker),s.length>0?{ok:!1,identity:null,errors:s,warnings:o}:{ok:!0,identity:{boxKind:n.boxKind,boxKindSource:n.source,runnerId:c,runnerIdSource:d,maxConcurrentWorkers:f,workerCapSource:m.workerCapSource,harnessRoot:p.harnessRoot,harnessRootSource:p.source},errors:s,warnings:o}}var pt=g(()=>{"use strict";Se();ze();qe();lr();ct()});import{existsSync as la,mkdirSync as cd,readFileSync as ca,writeFileSync as dd}from"node:fs";import{homedir as da,totalmem as md}from"node:os";import mt from"node:path";function be(){if(!la(Yn))return{};try{return JSON.parse(ca(Yn,"utf8"))}catch{return{}}}var Vn,Yn,_d,Cd,Ed,Se=g(()=>{"use strict";Hr();me();b();ze();qe();lr();rr();Un();pt();Vn=mt.join(da(),".kynver"),Yn=mt.join(Vn,"config.json"),_d=mt.join(Vn,"credentials");Cd=500*1024*1024,Ed=4*1024*1024*1024});import ft from"node:path";function O(e){return dr(e)}function Z(){let e=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(e)return O(e);let r=be(),t=r.harnessRoot?.trim();if(t)return O(t);let n=dt(r,process.env);return n.identity?n.identity.harnessRoot:pr({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function G(e){return ft.join(O(e),"runs")}function ve(e){return ft.join(O(e),"worktrees")}function zt(){let e=Z();return{harnessRoot:e,runsDir:G(e),worktreesDir:ve(e)}}function zr(e,r){return ft.join(e,v(r))}var Y=g(()=>{"use strict";Se();ct();pt();b()});Y();import M from"node:path";sr();import kr from"node:path";$();ie();var gt=[".next",".turbo","dist","build",".cache","node_modules/.cache"];function zn(e){let r=e.replace(/\\/g,"/").replace(/\/+$/,"");if(r==="node_modules"||r.startsWith("node_modules/"))return!0;for(let t of gt)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!zn(n)})}function ae(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 Ne(e){let r=e.gitAncestry?.relation;return r==="merged"||r==="synced"?D(e.changedFiles).length>0:!!(ae(e.finalResult)||r==="ahead"||r==="diverged"||e.changedFiles.length>0&&e.finalResult)}b();function Me(e){return e.status||(e.status=De(e.worker,{base:e.run.base,baseCommit:e.run.baseCommit})),e.status}function ht(e,r){if(e.status)return D(e.status.changedFiles).length>0;let t=r?r.porcelain(e.worktreePath):Ee(e.worktreePath);return D(t).length>0}function pa(e){let r=e.worker.completionSnapshot?.finalResult;return r??(e.worker.taskPrUrl?{prUrl:e.worker.taskPrUrl}:null)}function kt(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=pa(e);if(o&&!Q(t.pid)){let i=r?.gitStatusCache?r.gitStatusCache.porcelain(e.worktreePath):Ee(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"}:Ge(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??ae(s)};return e.status=c,c}return Me(e)}ie();ne();qr();ie();b();import ma from"node:path";var fa=new Set(["running","dispatching","pending","queued","needs_attention"]),ue=new Set(["completed","failed","cancelled","done"]);function le(e){let r=Jr(e);if(r.length===0)return"failed";let t=!1,n=!1,o=!1,s=!1;for(let i of r){let a=x(ma.join(we(e.id),"workers",v(i),"worker.json"),void 0);if(!a)continue;let u=De(a,{base:e.base,baseCommit:e.baseCommit});if(u.alive&&!u.finalResult){t=!0;break}typeof a.completionBlocker=="string"&&a.completionBlocker&&(o=!0),Cn(u)&&(s=!0),u.finalResult&&u.attention.state==="done"&&(n=!0)}return t||o||s?null:n?"completed":"failed"}function Jn(){let e=[];for(let r of Yr()){if(!fa.has(r.status))continue;let t=le(r);if(!t||t===r.status)continue;let n=r.status;r.status=t,Vr(r),e.push({runId:r.id,from:n,to:t})}return e}ie();or();import{existsSync as fr,mkdirSync as lp,readdirSync as Qn,renameSync as cp,statSync as ga}from"node:fs";import ce from"node:path";Se();Hr();me();or();Y();ne();Y();b();import ee from"node:path";var op=`${ee.sep}runs${ee.sep}runs${ee.sep}`;function qn(e){return{workerJsonPath:ee.join(e,"worker.json"),stdoutPath:ee.join(e,"stdout.jsonl"),stderrPath:ee.join(e,"stderr.log"),heartbeatPath:ee.join(e,"heartbeat.jsonl"),lastStatusPath:ee.join(e,"last-status.json")}}b();var Te=900*1e3,yp=3600*1e3;function Zn(e,r){let t=ce.resolve(e),n=ce.resolve(G(r)),o=ce.relative(n,t);return o!==".."&&!o.startsWith("..")&&!ce.isAbsolute(o)}function ha(e){if(!fr(e))return[];try{return Qn(e,{withFileTypes:!0}).filter(r=>r.isDirectory()&&r.name!=="runs").map(r=>r.name)}catch{return[]}}function ka(e){let r=ce.join(e,"workers");if(!fr(r))return[];try{return Qn(r,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}}function Xn(e,r,t){if(!fr(e))return!1;try{let n=r-ga(e).mtimeMs;return Number.isFinite(n)&&n>=0&&n<t}catch{return!1}}function ya(e,r=Date.now(),t=Te){if(!fr(e))return!1;let n=qn(e),o=x(n.workerJsonPath,void 0);if(o?.status==="running"&&Q(o.pid))return!0;let s=ke(n.heartbeatPath);if(s.lastHeartbeatAt){let i=r-Date.parse(s.lastHeartbeatAt);if(Number.isFinite(i)&&i>=0&&i<t)return!0}return!!(Xn(n.stdoutPath,r,t)||Xn(n.heartbeatPath,r,t))}function Ra(e,r=Date.now(),t=Te){for(let n of ka(e))if(ya(ce.join(e,"workers",n),r,t))return!0;return!1}function eo(e,r=Date.now()){let t=new Set,n=G(e);for(let o of ha(n)){let s=ce.join(n,o);Ra(s,r)&&t.add(`${e}\0${o}`)}return t}b();function yt(e,r=Date.now(),t=Te){let n=ke(e.heartbeatPath);if(!n.lastHeartbeatAt)return!1;let o=r-Date.parse(n.lastHeartbeatAt);return Number.isFinite(o)&&o>=0&&o<t}function gr(e,r=Date.now(),t=Te){return Q(e.pid)?!0:yt(e,r,t)}function ba(e,r){return r?r.runTerminalCache.derive(e.run):le(e.run)}function J(e,r=Date.now()){return gr(e.worker,r)}function Rt(e,r){return ue.has(e.run.status)?!1:ba(e,r)!==null}function ro(e,r,t=Date.now()){if(J(e,t))return!0;if(ue.has(e.run.status)||Rt(e,r))return!1;let n=Me(e);return se(n)?!1:!!J(e,t)}sr();ie();function to(e,r){if(!(typeof e.worker.completionBlocker=="string"?e.worker.completionBlocker.trim():""))return!1;if(J(e))return!0;let n=r??Me(e);return!!(!se(n)||Ne(n)||D(n.changedFiles).length>0||ye({finalResult:n.finalResult,changedFiles:n.changedFiles,gitAncestry:n.gitAncestry,prUrl:ae(n.finalResult)}).blocked)}$();b();import{existsSync as oo,mkdirSync as Sa,writeFileSync as no}from"node:fs";import hr from"node:path";function so(e,r,t){return hr.join(e,"salvage",v(r),v(t))}function io(e){return oo(hr.join(so(e.harnessRoot,e.runId,e.workerName),"evidence.json"))}function ao(e){let r=so(e.harnessRoot,e.indexed.runId,e.indexed.workerName);Sa(r,{recursive:!0});let t=hr.join(r,"salvage.patch"),n=!1;if(oo(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()&&(no(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 Ui=new Set(["completion_blocked","dirty_worktree","pr_or_unmerged_commits","landing_blocked"]);function Ti(e){return!Ui.has(e.skipReason)||G(e.indexed,e.now)?!1:Pn({harnessRoot:e.harnessRoot,runId:e.indexed.runId,workerName:e.indexed.workerName})?!0:e.writeSalvageEvidence?(Wn({harnessRoot:e.harnessRoot,indexed:e.indexed,skipReason:e.skipReason,status:e.status,now:e.now}),!0):!1}function Bi(e){let{indexed:r,worktreesAgeMs:t,terminalWorktreesAgeMs:n}=e;return r&&(se.has(r.run.status)||e.liveness&&Jr(r,e.liveness)||e.liveness&&te(Vr(r,e.liveness))&&!G(r))?n:t}function Fi(e){return!e.indexed||e.includeOrphans&&e.worktreesAgeMs<=0?0:Bi(e)}function Hi(e,r){if(e.harnessRoot?.trim())return tr.resolve(e.harnessRoot);let t=r.worker.workerDir;if(!t)return null;let n=`${tr.sep}runs${tr.sep}`,o=t.indexOf(n);return o<0?null:t.slice(0,o+n.length-1)}function On(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=Fi(e);if(n<=0&&!t&&u<=0)return"worktrees_disabled";if(u>0&&o<u)return"below_age_threshold";if(G(r,a))return"active_worker";let l=Vr(r,e.liveness),c=Hi(e,r),d=p=>c&&Ti({indexed:r,harnessRoot:c,skipReason:p,status:l,now:a,writeSalvageEvidence:e.writeSalvageEvidence===!0})?null:p;if(Cn(r,l)){let p=d("completion_blocked");if(p)return p}if(Yr(r,e.liveness?.gitStatusCache)){let p=d("dirty_worktree");if(p)return p}let m=e.liveness?.gitRevCache?.countAheadOfMain(e.worktreePath);if(m!=null&&m>0){let p=d("pr_or_unmerged_commits");if(p)return p}if(xn(r,e.liveness,a)||!te(l))return"run_still_active";if(Ae(l)){let p=d("pr_or_unmerged_commits");if(p)return p}if(W(l.changedFiles).length>0){let p=d("dirty_worktree");if(p)return p}if(fe({finalResult:l.finalResult,changedFiles:l.changedFiles,gitAncestry:l.gitAncestry,prUrl:oe(l.finalResult)}).blocked){let p=d("landing_blocked");if(p)return p}if(i&&e.worktreePath){let p=i({worktreePath:e.worktreePath,indexed:!!r,runId:r?.runId,worker:r?.workerName});if(p)return p.detail?{reason:p.reason,detail:p.detail}:p.reason}return null}function Xr(e){let{indexed:r,nodeModulesAgeMs:t,ageMs:n,worktreePath:o,activeWorktreePaths:s,diskPressure:i}=e;return!i&&n<t?"below_age_threshold":s.has(tr.resolve(o))||r&&G(r)?"active_worker":r&&Yr(r,e.gitStatusCache)?"dirty_worktree":null}function Dn(e){return Xr(e)}var qr=216e5,nr=6048e5;var Qr=36e5,or=120;var In=new Set(["active_worker","run_still_active","completion_blocked","landing_blocked"]);function Nn(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)In.has(s.reason)&&o(s.path,s.reason,s.detail);for(let s of e)!s.skipped||!s.skipReason||In.has(s.skipReason)&&o(s.path,s.skipReason);return t}import{existsSync as Bn,readdirSync as Fn,statSync as ji}from"node:fs";import Hn from"node:path";ee();$();import Mn from"node:path";S();function Li(e,r){return er(e,r)}function Un(e,r=Date.now()){let t=new Set,n=new Set;for(let o of e){for(let s of Ve(o)){let i=!1;for(let a of Object.keys(s.workers||{})){let u=x(Mn.join(ve(o,s.id),"workers",v(a),"worker.json"),void 0);if(!u?.worktreePath)continue;let l=Mn.resolve(u.worktreePath);Li(u,r)&&(i=!0,t.add(l))}i&&n.add(`${o}\0${s.id}`)}for(let s of _n(o))n.add(s)}return{activeWorktreePaths:t,liveRunKeys:n}}function Tn(e,r,t,n){return t?n.has(`${r}\0${t}`):!1}S();function $i(e,r){try{let t=ji(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function Gi(e,r){let t=Hn.join(e,"runs",r,"run.json");return Bn(t)?x(t,null):null}function Kn(e){try{return Fn(e).length===0}catch{return!1}}function Ln(e){let{harnessRoot:r,runId:t,runPath:n,ageMs:o,runDirectoriesAgeMs:s,activeGuards:i}=e;if(Tn(n,r,t,i.liveRunKeys)||!Kn(n))return"run_still_active";let a=Gi(r,t);return a&&!se.has(a.status)&&!ie(a)?"run_still_active":s>0&&o<s?"below_age_threshold":null}function jn(e){if(!Bn(e.worktreesDir))return[];let r=[],t;try{t=Fn(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=Hn.join(e.worktreesDir,o);Kn(s)&&r.push({kind:"remove_run_directory",path:s,bytes:null,harnessRoot:e.harnessRoot,runId:o,ageMs:$i(s,e.now)})}return r}L();import{existsSync as et,rmSync as eo}from"node:fs";import{execFileSync as Yi}from"node:child_process";import{existsSync as $n,readdirSync as Vi,statSync as zi}from"node:fs";import Ji from"node:path";var Xi=2500;function qi(e,r=Xi){if(!$n(e))return 0;try{let n=Yi("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 Y(e,r=5e4){if(!$n(e))return 0;let t=qi(e);if(t!==null)return t;let n=0,o=0,s=[e];for(;s.length>0;){let i=s.pop(),a;try{a=Vi(i)}catch{continue}for(let u of a){if(o++>r)return null;let l=Ji.join(i,u),c;try{c=zi(l)}catch{continue}c.isDirectory()?s.push(l):n+=c.size}}return n}import{existsSync as ra,rmSync as ta}from"node:fs";$();import{lstatSync as Qi,readdirSync as Zi}from"node:fs";function Gn(e){try{let r=Qi(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 Yn(e,r=32){let t=Gn(e);if(!t)return!1;if(t.foreign)return!0;try{let n=Zi(e),o=0;for(let s of n){if(o>=r)break;let i=`${e.replace(/\/$/,"")}/${s}`,a=Gn(i);if(o+=1,a?.foreign)return!0}}catch{}return!1}import{spawnSync as ea}from"node:child_process";import Jn from"node:path";import O from"node:path";function Vn(e,r,t,n){let o=O.resolve(e),s=`${O.sep}${n}`,i=o.endsWith(s)?o:null;if(!i)return"path_outside_harness";let a=O.relative(t,i);if(a.startsWith("..")||O.isAbsolute(a))return"path_outside_harness";let u=a.split(O.sep);return u.length<3||u[u.length-1]!==n||!o.startsWith(O.resolve(r))?"path_outside_harness":null}function sr(e,r,t){return Vn(e,r,t,"node_modules")}function ir(e,r,t){return Vn(e,r,t,".next")}function ar(e,r,t){let n=O.resolve(e),o=O.relative(t,n);return o.startsWith("..")||O.isAbsolute(o)||o.split(O.sep).length<3||!n.startsWith(O.resolve(r))?"path_outside_harness":null}function zn(e,r,t){let n=O.resolve(e);return sr(n,r,t)===null||ir(n,r,t)===null||ar(n,r,t)===null}function qn(){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 Xn(e){let r=ea("sudo",["-n",...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{ok:r.status===0,stderr:`${r.stderr??""}${r.stdout??""}`.trim()}}function Qn(e,r,t){if(!zn(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=Xn(["chown","-R",`${n}:${o}`,Jn.resolve(e)]);if(s.ok)return{ok:!0,method:"chown_then_rm"};let i=Xn(["rm","-rf",Jn.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 Zr="Root-owned harness caches require operator reclaim: configure passwordless sudo for chown/rm under ~/.kynver/harness/worktrees, or run `node scripts/reclaim-harness-root-owned-cache.mjs --execute` as the harness owner with sudo available. See docs/runbooks/harness-root-owned-cache-reclaim.md.";function na(e){let r=e?.code;return r==="EACCES"||r==="EPERM"}function Zn(e,r,t={}){if(!ra(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?he(n):null,i=e.bytes??Y(e.path)??void 0,a=t.removePath??ta,u=t.hasForeignOwnedEntry??Yn;try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i}}catch(l){if(!na(l)||!n||!o)return{executed:!1,skipped:!0,skipReason:"remove_failed",error:l.message};let c=u(e.path),d=qn();if(!(d==="force"||d==="auto"&&c))return c?{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${l.message}; ${Zr}`}:{executed:!1,skipped:!0,skipReason:"remove_failed",error:l.message};let f=Qn(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(p){return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${p.message}; privileged chown succeeded but rm still failed`}}return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${l.message}; privileged reclaim failed: ${f.error}; ${Zr}`}}}function rt(e){let r=e.harnessRoot;return!r||!vn(e.path,r)?null:{...e,executed:!1,skipped:!0,skipReason:"run_metadata_protected"}}function tt(e,r){let t=rt(e);if(t)return t;let n=Zn(e,r);return{...e,bytes:n.bytes??e.bytes,executed:n.executed,skipped:n.skipped,skipReason:n.skipReason,error:n.error}}function ro(e,r){return tt(e,r)}function to(e,r){return tt(e,r)}function no(e,r){return tt(e,r)}function oo(e,r){let t=rt(e);if(t)return t;if(!et(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??Y(e.path);return eo(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 so(e,r){let t=rt(e);if(t)return t;if(!et(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??Y(e.path);return n&&Re(n,["worktree","remove","--force",e.path],{allowFailure:!0}),et(e.path)&&eo(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 lr,statSync as oa}from"node:fs";import B from"node:path";function nt(e,r){try{let t=oa(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function ao(e,r){let t=B.relative(r,e);return t===""||!t.startsWith("..")&&!B.isAbsolute(t)}function io(e,r,t,n){let o=[];for(let s of Gr){if(s===".next")continue;let i=B.join(e,s);if(!ur(i))continue;let a=B.resolve(i);t.has(a)||ao(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:nt(a,r.now)}))}return o}function uo(e){let r=[],t=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||r.push(...io(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 lr(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=B.join(e.worktreesDir,n.name);for(let s of lr(o,{withFileTypes:!0})){if(!s.isDirectory())continue;let i=B.join(o,s.name);r.push(...io(i,e,t,{runId:n.name,worker:s.name}))}}return r}function lo(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:nt(a,e.now)})))}if(!t||!ur(e.worktreesDir))return n;let s=new Set;for(let i of e.index.values())s.add(B.resolve(i.worktreePath));for(let i of lr(e.worktreesDir,{withFileTypes:!0})){if(!i.isDirectory()||e.runIdFilter&&i.name!==e.runIdFilter)continue;let a=B.join(e.worktreesDir,i.name),u;try{u=lr(a,{withFileTypes:!0})}catch{continue}for(let l of u){if(!l.isDirectory())continue;let c=B.resolve(B.join(a,l.name));o.has(c)||s.has(c)||ao(c,e.harnessRoot)&&(o.add(c),n.push({kind:"remove_worktree",path:c,bytes:null,runId:i.name,worker:l.name,ageMs:nt(c,e.now)}))}}return n}import{existsSync as mo,readdirSync as co,statSync as sa}from"node:fs";import ke from"node:path";var ia=[{dirName:"node_modules",kind:"remove_node_modules"},{dirName:".next",kind:"remove_next_cache"}];function aa(e,r){try{let t=sa(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function ua(e,r){let t=ke.relative(r,e);return t===""||!t.startsWith("..")&&!ke.isAbsolute(t)}function la(e,r,t,n,o,s){if(!mo(n))return;let i=ke.resolve(n);r.has(i)||ua(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:aa(i,t.now)}))}function po(e,r,t,n,o){for(let s of ia)la(e,r,t,ke.join(n,s.dirName),s.kind,o)}function fo(e){let r=[],t=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||po(r,t,e,n.worktreePath,{runId:n.runId,worker:n.workerName,repo:n.run.repo});if(!e.includeOrphans||!mo(e.worktreesDir))return r;for(let n of co(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory()||e.runIdFilter&&n.name!==e.runIdFilter)continue;let o=ke.join(e.worktreesDir,n.name),s;try{s=co(o,{withFileTypes:!0})}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=ke.join(o,i.name);po(r,t,e,a,{runId:n.name,worker:i.name})}}return r}L();import{existsSync as go,statSync as ca}from"node:fs";import F from"node:path";function da(e,r){try{let t=ca(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function pa(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(
|
|
16
|
-
`).map(t=>t.trim()).filter(Boolean)}var
|
|
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 no(hr.join(r,"evidence.json"),`${JSON.stringify(o,null,2)}
|
|
13
|
+
`),o}var va=new Set(["completion_blocked","dirty_worktree","pr_or_unmerged_commits","landing_blocked"]);function xa(e){return!va.has(e.skipReason)||J(e.indexed,e.now)?!1:io({harnessRoot:e.harnessRoot,runId:e.indexed.runId,workerName:e.indexed.workerName})?!0:e.writeSalvageEvidence?(ao({harnessRoot:e.harnessRoot,indexed:e.indexed,skipReason:e.skipReason,status:e.status,now:e.now}),!0):!1}function _a(e){let{indexed:r,worktreesAgeMs:t,terminalWorktreesAgeMs:n}=e;return r&&(ue.has(r.run.status)||e.liveness&&Rt(r,e.liveness)||e.liveness&&se(kt(r,e.liveness))&&!J(r))?n:t}function Ca(e){return!e.indexed||e.includeOrphans&&e.worktreesAgeMs<=0?0:_a(e)}function Ea(e,r){if(e.harnessRoot?.trim())return kr.resolve(e.harnessRoot);let t=r.worker.workerDir;if(!t)return null;let n=`${kr.sep}runs${kr.sep}`,o=t.indexOf(n);return o<0?null:t.slice(0,o+n.length-1)}function uo(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=Ca(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=kt(r,e.liveness),c=Ea(e,r),d=p=>c&&xa({indexed:r,harnessRoot:c,skipReason:p,status:l,now:a,writeSalvageEvidence:e.writeSalvageEvidence===!0})?null:p;if(to(r,l)){let p=d("completion_blocked");if(p)return p}if(ht(r,e.liveness?.gitStatusCache)){let p=d("dirty_worktree");if(p)return p}let m=e.liveness?.gitRevCache?.countAheadOfMain(e.worktreePath);if(m!=null&&m>0){let p=d("pr_or_unmerged_commits");if(p)return p}if(ro(r,e.liveness,a)||!se(l))return"run_still_active";if(Ne(l)){let p=d("pr_or_unmerged_commits");if(p)return p}if(D(l.changedFiles).length>0){let p=d("dirty_worktree");if(p)return p}if(ye({finalResult:l.finalResult,changedFiles:l.changedFiles,gitAncestry:l.gitAncestry,prUrl:ae(l.finalResult)}).blocked){let p=d("landing_blocked");if(p)return p}if(i&&e.worktreePath){let p=i({worktreePath:e.worktreePath,indexed:!!r,runId:r?.runId,worker:r?.workerName});if(p)return p.detail?{reason:p.reason,detail:p.detail}:p.reason}return null}function bt(e){let{indexed:r,nodeModulesAgeMs:t,ageMs:n,worktreePath:o,activeWorktreePaths:s,diskPressure:i}=e;return!i&&n<t?"below_age_threshold":s.has(kr.resolve(o))||r&&J(r)?"active_worker":r&&ht(r,e.gitStatusCache)?"dirty_worktree":null}function lo(e){return bt(e)}var St=216e5,yr=6048e5;var vt=36e5,Rr=120;var co=new Set(["active_worker","run_still_active","completion_blocked","landing_blocked"]);function po(e,r){let t=[],n=new Set,o=(s,i,a)=>{let u=`${s}\0${i}`;n.has(u)||t.length>=24||(n.add(u),t.push({path:s,reason:i,...a?{detail:a}:{}}))};for(let s of r)co.has(s.reason)&&o(s.path,s.reason,s.detail);for(let s of e)!s.skipped||!s.skipReason||co.has(s.skipReason)&&o(s.path,s.skipReason);return t}import{existsSync as ho,readdirSync as ko,statSync as Pa}from"node:fs";import yo from"node:path";ne();Y();import mo from"node:path";b();function Aa(e,r){return gr(e,r)}function fo(e,r=Date.now()){let t=new Set,n=new Set;for(let o of e){for(let s of nr(o)){let i=!1;for(let a of Object.keys(s.workers||{})){let u=x(mo.join(Ae(o,s.id),"workers",v(a),"worker.json"),void 0);if(!u?.worktreePath)continue;let l=mo.resolve(u.worktreePath);Aa(u,r)&&(i=!0,t.add(l))}i&&n.add(`${o}\0${s.id}`)}for(let s of eo(o))n.add(s)}return{activeWorktreePaths:t,liveRunKeys:n}}function go(e,r,t,n){return t?n.has(`${r}\0${t}`):!1}b();function Ia(e,r){try{let t=Pa(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function Oa(e,r){let t=yo.join(e,"runs",r,"run.json");return ho(t)?x(t,null):null}function Ro(e){try{return ko(e).length===0}catch{return!1}}function bo(e){let{harnessRoot:r,runId:t,runPath:n,ageMs:o,runDirectoriesAgeMs:s,activeGuards:i}=e;if(go(n,r,t,i.liveRunKeys)||!Ro(n))return"run_still_active";let a=Oa(r,t);return a&&!ue.has(a.status)&&!le(a)?"run_still_active":s>0&&o<s?"below_age_threshold":null}function So(e){if(!ho(e.worktreesDir))return[];let r=[],t;try{t=ko(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=yo.join(e.worktreesDir,o);Ro(s)&&r.push({kind:"remove_run_directory",path:s,bytes:null,harnessRoot:e.harnessRoot,runId:o,ageMs:Ia(s,e.now)})}return r}$();import{existsSync as _t,rmSync as Do}from"node:fs";import{execFileSync as Da}from"node:child_process";import{existsSync as vo,readdirSync as Wa,statSync as Na}from"node:fs";import Ma from"node:path";var Ta=2500;function Ua(e,r=Ta){if(!vo(e))return 0;try{let n=Da("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=Ua(e);if(t!==null)return t;let n=0,o=0,s=[e];for(;s.length>0;){let i=s.pop(),a;try{a=Wa(i)}catch{continue}for(let u of a){if(o++>r)return null;let l=Ma.join(i,u),c;try{c=Na(l)}catch{continue}c.isDirectory()?s.push(l):n+=c.size}}return n}import{existsSync as Fa,rmSync as La}from"node:fs";Y();import{lstatSync as Ba,readdirSync as Ha}from"node:fs";function xo(e){try{let r=Ba(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 _o(e,r=32){let t=xo(e);if(!t)return!1;if(t.foreign)return!0;try{let n=Ha(e),o=0;for(let s of n){if(o>=r)break;let i=`${e.replace(/\/$/,"")}/${s}`,a=xo(i);if(o+=1,a?.foreign)return!0}}catch{}return!1}import{spawnSync as Ka}from"node:child_process";import wo from"node:path";import W from"node:path";function Co(e,r,t,n){let o=W.resolve(e),s=`${W.sep}${n}`,i=o.endsWith(s)?o:null;if(!i)return"path_outside_harness";let a=W.relative(t,i);if(a.startsWith("..")||W.isAbsolute(a))return"path_outside_harness";let u=a.split(W.sep);return u.length<3||u[u.length-1]!==n||!o.startsWith(W.resolve(r))?"path_outside_harness":null}function br(e,r,t){return Co(e,r,t,"node_modules")}function Sr(e,r,t){return Co(e,r,t,".next")}function vr(e,r,t){let n=W.resolve(e),o=W.relative(t,n);return o.startsWith("..")||W.isAbsolute(o)||o.split(W.sep).length<3||!n.startsWith(W.resolve(r))?"path_outside_harness":null}function Eo(e,r,t){let n=W.resolve(e);return br(n,r,t)===null||Sr(n,r,t)===null||vr(n,r,t)===null}function Po(){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 Ao(e){let r=Ka("sudo",["-n",...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{ok:r.status===0,stderr:`${r.stderr??""}${r.stdout??""}`.trim()}}function Io(e,r,t){if(!Eo(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=Ao(["chown","-R",`${n}:${o}`,wo.resolve(e)]);if(s.ok)return{ok:!0,method:"chown_then_rm"};let i=Ao(["rm","-rf",wo.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 xt="Root-owned harness caches require operator reclaim: configure passwordless sudo for chown/rm under ~/.kynver/harness/worktrees, or run `node scripts/reclaim-harness-root-owned-cache.mjs --execute` as the harness owner with sudo available. See docs/runbooks/harness-root-owned-cache-reclaim.md.";function ja(e){let r=e?.code;return r==="EACCES"||r==="EPERM"}function Oo(e,r,t={}){if(!Fa(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?ve(n):null,i=e.bytes??q(e.path)??void 0,a=t.removePath??La,u=t.hasForeignOwnedEntry??_o;try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i}}catch(l){if(!ja(l)||!n||!o)return{executed:!1,skipped:!0,skipReason:"remove_failed",error:l.message};let c=u(e.path),d=Po();if(!(d==="force"||d==="auto"&&c))return c?{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${l.message}; ${xt}`}:{executed:!1,skipped:!0,skipReason:"remove_failed",error:l.message};let f=Io(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(p){return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${p.message}; privileged chown succeeded but rm still failed`}}return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${l.message}; privileged reclaim failed: ${f.error}; ${xt}`}}}function Ct(e){let r=e.harnessRoot;return!r||!Zn(e.path,r)?null:{...e,executed:!1,skipped:!0,skipReason:"run_metadata_protected"}}function Et(e,r){let t=Ct(e);if(t)return t;let n=Oo(e,r);return{...e,bytes:n.bytes??e.bytes,executed:n.executed,skipped:n.skipped,skipReason:n.skipReason,error:n.error}}function Wo(e,r){return Et(e,r)}function No(e,r){return Et(e,r)}function Mo(e,r){return Et(e,r)}function To(e,r){let t=Ct(e);if(t)return t;if(!_t(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 Do(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 Uo(e,r){let t=Ct(e);if(t)return t;if(!_t(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&&Ce(n,["worktree","remove","--force",e.path],{allowFailure:!0}),_t(e.path)&&Do(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 xr,readdirSync as _r,statSync as $a}from"node:fs";import K from"node:path";function wt(e,r){try{let t=$a(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function Ho(e,r){let t=K.relative(r,e);return t===""||!t.startsWith("..")&&!K.isAbsolute(t)}function Bo(e,r,t,n){let o=[];for(let s of gt){if(s===".next")continue;let i=K.join(e,s);if(!xr(i))continue;let a=K.resolve(i);t.has(a)||Ho(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:wt(a,r.now)}))}return o}function Ko(e){let r=[],t=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||r.push(...Bo(n.worktreePath,e,t,{runId:n.runId,worker:n.workerName,repo:n.run.repo}));if(!e.includeOrphans||!xr(e.worktreesDir))return r;for(let n of _r(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=K.join(e.worktreesDir,n.name);for(let s of _r(o,{withFileTypes:!0})){if(!s.isDirectory())continue;let i=K.join(o,s.name);r.push(...Bo(i,e,t,{runId:n.name,worker:s.name}))}}return r}function Fo(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;xr(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:wt(a,e.now)})))}if(!t||!xr(e.worktreesDir))return n;let s=new Set;for(let i of e.index.values())s.add(K.resolve(i.worktreePath));for(let i of _r(e.worktreesDir,{withFileTypes:!0})){if(!i.isDirectory()||e.runIdFilter&&i.name!==e.runIdFilter)continue;let a=K.join(e.worktreesDir,i.name),u;try{u=_r(a,{withFileTypes:!0})}catch{continue}for(let l of u){if(!l.isDirectory())continue;let c=K.resolve(K.join(a,l.name));o.has(c)||s.has(c)||Ho(c,e.harnessRoot)&&(o.add(c),n.push({kind:"remove_worktree",path:c,bytes:null,runId:i.name,worker:l.name,ageMs:wt(c,e.now)}))}}return n}import{existsSync as $o,readdirSync as Lo,statSync as Ga}from"node:fs";import xe from"node:path";var Ya=[{dirName:"node_modules",kind:"remove_node_modules"},{dirName:".next",kind:"remove_next_cache"}];function Va(e,r){try{let t=Ga(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function za(e,r){let t=xe.relative(r,e);return t===""||!t.startsWith("..")&&!xe.isAbsolute(t)}function Ja(e,r,t,n,o,s){if(!$o(n))return;let i=xe.resolve(n);r.has(i)||za(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:Va(i,t.now)}))}function jo(e,r,t,n,o){for(let s of Ya)Ja(e,r,t,xe.join(n,s.dirName),s.kind,o)}function Go(e){let r=[],t=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||jo(r,t,e,n.worktreePath,{runId:n.runId,worker:n.workerName,repo:n.run.repo});if(!e.includeOrphans||!$o(e.worktreesDir))return r;for(let n of Lo(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory()||e.runIdFilter&&n.name!==e.runIdFilter)continue;let o=xe.join(e.worktreesDir,n.name),s;try{s=Lo(o,{withFileTypes:!0})}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=xe.join(o,i.name);jo(r,t,e,a,{runId:n.name,worker:i.name})}}return r}$();import{existsSync as Yo,statSync as qa}from"node:fs";import F from"node:path";function Xa(e,r){try{let t=qa(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function Qa(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 Za(e,r){let t=F.relative(F.resolve(r),F.resolve(e));return t!==""&&!t.startsWith("..")&&!F.isAbsolute(t)}var eu=200;function Vo(e){if(!e.includeOrphans||!Yo(e.worktreesDir))return[];let r=new Set;for(let s of e.index.values())s.run.repo&&r.add(F.resolve(s.run.repo));let t=new Set;for(let s of e.index.values())t.add(F.resolve(s.worktreePath));let n=[],o=new Set;for(let s of r){let i=0,a;try{a=Ce(s,["worktree","list","--porcelain"],{allowFailure:!0})}catch{continue}let u=Qa(a);for(let l of u){if(i>=eu)break;let c=F.resolve(l.path);if(c===F.resolve(s)||!Za(c,e.worktreesDir)||t.has(c)||o.has(c)||!Yo(c))continue;let m=F.relative(e.worktreesDir,c).split(F.sep),f=m[0],p=m[1]??"unknown";o.add(c),i+=1,n.push({kind:"remove_worktree",path:c,bytes:null,runId:f,worker:p,repo:s,ageMs:Xa(c,e.now)})}}return n}ne();b();import Ue from"node:path";function zo(e,r){let t=Ue.resolve(r),n=new Map;for(let[o,s]of e){let i=s.harnessRoot?Ue.resolve(s.harnessRoot):null;i&&i!==t||n.set(o,s)}return n}function Jo(e){let r=new Map;for(let t of nr(e))for(let n of Object.keys(t.workers||{})){let o=Ue.join(Ae(e,t.id),"workers",v(n),"worker.json"),s=x(o,void 0);s?.worktreePath&&r.set(Ue.resolve(s.worktreePath),{harnessRoot:e,worktreePath:Ue.resolve(s.worktreePath),runId:t.id,workerName:n,run:t,worker:s})}return r}function Be(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function de(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)&&n>=0?n:r}function qo(e={}){let r=e.execute===!0||e.execute!==!1&&Be("KYNVER_CLEANUP_EXECUTE"),t=e.finalizeStaleRuns!==!1&&!Be("KYNVER_CLEANUP_SKIP_FINALIZE"),n=e.nodeModulesAgeMs??de("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??de("KYNVER_CLEANUP_WORKTREES_AGE_MS",0),i=e.terminalWorktreesAgeMs??de("KYNVER_CLEANUP_TERMINAL_WORKTREES_AGE_MS",216e5),a=e.runDirectoriesAgeMs??de("KYNVER_CLEANUP_RUN_DIRECTORIES_AGE_MS",36e5),u=e.maxActionsPerSweep??de("KYNVER_CLEANUP_MAX_ACTIONS_PER_SWEEP",120),l=e.includeOrphans===!0||Be("KYNVER_CLEANUP_INCLUDE_ORPHANS"),d=Be("KYNVER_CLEANUP_SCOPE_ALL")||process.env.KYNVER_CLEANUP_SCOPE==="all"?e.runIdFilter:e.runIdFilter??(process.env.KYNVER_CLEANUP_RUN_ID||void 0),m=e.accountBytes!==!1&&!Be("KYNVER_CLEANUP_SKIP_BYTE_ACCOUNTING"),f=de("KYNVER_CLEANUP_STORAGE_ENTRY_CAP",2e3),p=e.storagePerRunEntryCap!==void 0?e.storagePerRunEntryCap:m&&f>0?f:null,y=de("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:m,storagePerRunEntryCap:p,byteAccountingEntryCap:S}}$();import{existsSync as At,statSync as tu}from"node:fs";import Cr from"node:path";b();var nu=1800*1e3;function Xo(e){let r=e.now??Date.now(),t=e.heartbeatFreshMs??nu;if(!At(e.worktreePath))return null;if(e.runId&&e.workerName){let l=Cr.join(e.harnessRoot,"runs",e.runId,"workers",e.workerName),c=x(Cr.join(l,"worker.json"),void 0);if(c&&yt(c,r,t))return"active_worker";if(!c){let d=Cr.join(l,"heartbeat.jsonl");if(At(d))try{let m=r-tu(d).mtimeMs;if(Number.isFinite(m)&&m>=0&&m<t)return"active_worker"}catch{}}}let n=Cr.join(e.worktreePath,".git");if(!At(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 ou,readdirSync as Qo,statSync as su}from"node:fs";import iu from"node:path";function Zo(e={}){let r=O(e.harnessRoot??Z()),t=ve(r),n=e.now??Date.now(),o=new Date(n).toISOString();if(!ou(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=Qo(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=iu.join(t,c.name);try{let m=su(d);u=u===null?m.mtimeMs:Math.min(u,m.mtimeMs)}catch{}try{for(let m of Qo(d,{withFileTypes:!0}))m.isDirectory()&&(a+=1)}catch{}if(s!==null&&e.perRunEntryCap!==null){let m=e.perRunEntryCap??5e4;if(m<=0)s=null;else{let f=q(d,m);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 au}from"node:fs";import{homedir as uu}from"node:os";import es from"node:path";var lu=["/var/tmp/kynver-harness",es.join(uu(),".openclaw","harness")];function Pt(e,r,t){if(!t?.trim())return;let n=O(t.trim());e.has(n)||(e.add(n),r.push(n))}function cu(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 rs(e={}){let r=new Set,t=[];Pt(r,t,e.harnessRoot??Z());let n=process.env.KYNVER_CLEANUP_EXTRA_ROOTS?.split(",").map(o=>o.trim()).filter(Boolean);for(let o of n??[])Pt(r,t,o);if(cu(e))for(let o of lu){let s=es.resolve(o);!r.has(s)&&au(s)&&Pt(r,t,s)}return t}rr();function du(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function pu(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=pu("KYNVER_DISK_GUARD_MAX_USED_PERCENT",75),n=er({...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 ns(e,r){if(!r.pressured)return e;let t=e.execute||!du("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}}Ze();import{unlinkSync as mu}from"node:fs";function Er(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function os(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function fu(e,r,t){return e.length===0?[]:t?[...e]:e.length<=r?[]:e.slice(r)}function ss(e={}){let r=e.execute===!0||Er("KYNVER_WSL_CRASH_DUMP_EXECUTE")||Er("KYNVER_CLEANUP_EXECUTE"),t=e.purgeAll===!0||Er("KYNVER_WSL_CRASH_DUMP_PURGE_ALL"),n=Math.max(0,e.keepNewest??os("KYNVER_WSL_CRASH_DUMP_KEEP_NEWEST",t?0:1)),o=he({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=fu(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{mu(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 is(e){return e?Er("KYNVER_WSL_CRASH_DUMP_CLEANUP")||!e.ok?!0:e.dumpCount>os("KYNVER_WSL_CRASH_DUMP_KEEP_NEWEST",1):!1}Ze();function N(e,r){if(process.env.KYNVER_CLEANUP_QUIET==="1")return;let t=r?`: ${r}`:"";console.error(`[kynver cleanup] ${e}${t}`)}$();var wr=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 gu}from"node:child_process";import{existsSync as hu}from"node:fs";import ku from"node:path";var yu=5e3;function Ru(e,r){if(!hu(ku.join(e,".git")))return{status:null,stdout:"",stderr:"",error:"not_a_git_repo"};try{let t=gu("git",r,{cwd:e,encoding:"utf8",timeout:yu}),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 as(e){let r=Ru(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 Ar=class{cache=new Map;porcelain(r){let t=r,n=this.cache.get(t);if(n!==void 0)return n;let o=as(t)??[];return this.cache.set(t,o),o}};var Pr=class{cache=new Map;derive(r){let t=this.cache.get(r.id);if(t!==void 0)return t;let n=le(r);return this.cache.set(r.id,n),n}};function bu(e){let r={};for(let t of e)r[t.kind]=(r[t.kind]??0)+1;return r}function us(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:bu(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 Su(e={}){let r=e.harnessRoot?O(e.harnessRoot):Z(),t=rs({harnessRoot:r}),n=e.now??Date.now();return{harnessRoot:r,scanRoots:t,now:n}}function vu(e){return typeof e=="string"?{reason:e}:e}function _e(e,r,t,n){e.push({path:r,reason:t,...n?{detail:n}:{}})}function Ir(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 xu(e,r){return e.kind==="remove_next_cache"?No(e,r):Wo(e,r)}function _u(e,r,t){return e.kind==="remove_next_cache"?Sr(e.path,r,t):br(e.path,r,t)}function Cu(e){let r=new Map;for(let t of e)for(let[n,o]of Jo(t))r.set(n,o);return r}function cs(e,r){return e.runId&&e.worker?M.join(r,e.runId,e.worker):M.resolve(e.path,"..")}function Eu(e={}){let r=qo(e),t=ts();r=ns(r,t);let n=Su(e);N("scan",`${n.scanRoots.length} harness root(s)`);let o=fo(n.scanRoots,n.now),s=r.finalizeStaleRuns?Jn().map(h=>({runId:h.runId,from:h.from,to:h.to})):[];s.length>0&&N("finalize",`${s.length} stale run(s) marked terminal`),N("index","building worktree index");let i=Cu(n.scanRoots);N("index",`${i.size} indexed worktree(s)`);let a={runTerminalCache:new Pr,gitStatusCache:new Ar,gitRevCache:new wr},u=[],l=[],c=new Set,d=r.maxActionsPerSweep,m=()=>l.length>=d;for(let h of n.scanRoots){if(m())break;N("root",h);let X=M.join(h,"worktrees"),Ke=zo(i,h),Fe={harnessRoot:h,worktreesDir:X,nodeModulesAgeMs:r.nodeModulesAgeMs,worktreesAgeMs:r.worktreesAgeMs,includeOrphans:r.includeOrphans,runIdFilter:r.runIdFilter,index:Ke,now:n.now},Or=r.scanDependencyCaches?Go(Fe):[];N("dependency",r.scanDependencyCaches?`${Or.length} cache candidate(s) at ${h}`:"skipped (worktree-only sweep)");let Dr=0;for(let T of Or){if(m())break;Dr+=1,Dr%50===0&&N("dependency",`${Dr}/${Or.length} evaluated`);let _=M.resolve(T.path);if(c.has(_))continue;c.add(_);let k={...T,path:_},I=_u(k,h,X);if(I){_e(u,k.path,I),l.push({...k,executed:!1,skipped:!0,skipReason:I});continue}let U=cs(k,X),pe=Ke.get(M.resolve(U))??null,H=bt({indexed:pe,includeOrphans:!0,nodeModulesAgeMs:r.nodeModulesAgeMs,ageMs:k.ageMs,worktreePath:U,activeWorktreePaths:o.activeWorktreePaths,diskPressure:r.diskPressure,gitStatusCache:a.gitStatusCache});if(H){_e(u,k.path,H),l.push({...k,executed:!1,skipped:!0,skipReason:H});continue}l.push(xu(Ir(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}if(r.scanDependencyCaches)for(let T of Ko(Fe)){if(m())break;let _=M.resolve(T.path);if(c.has(_))continue;c.add(_);let k={...T,path:_},I=vr(k.path,h,X);if(I){_e(u,k.path,I),l.push({...k,executed:!1,skipped:!0,skipReason:I});continue}let U=cs(k,X),pe=Ke.get(M.resolve(U))??null,H=lo({indexed:pe,includeOrphans:!0,nodeModulesAgeMs:r.nodeModulesAgeMs,ageMs:k.ageMs,worktreePath:U,activeWorktreePaths:o.activeWorktreePaths,diskPressure:r.diskPressure,gitStatusCache:a.gitStatusCache});if(H){_e(u,k.path,H),l.push({...k,executed:!1,skipped:!0,skipReason:H});continue}l.push(Mo(Ir(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}let Wr=[...Fo(Fe),...Vo(Fe)];N("worktrees",`${Wr.length} candidate(s) at ${h}`);let It=new Set,Nr=0;for(let T of Wr){if(m())break;Nr+=1,Nr%50===0&&N("worktrees",`${Nr}/${Wr.length} evaluated`);let _=M.resolve(T.path);if(It.has(_))continue;It.add(_);let k={...T,path:_},I=Ke.get(M.resolve(k.path))??null,U=I?null:Xo({worktreePath:k.path,harnessRoot:h,runId:k.runId,workerName:k.worker,now:n.now}),pe=uo({indexed:I,worktreePath:M.resolve(k.path),includeOrphans:r.includeOrphans,worktreesAgeMs:r.worktreesAgeMs,terminalWorktreesAgeMs:r.terminalWorktreesAgeMs,ageMs:k.ageMs,orphanSafety:U,worktreeRemovalGuard:e.worktreeRemovalGuard,liveness:a,now:n.now,harnessRoot:h,writeSalvageEvidence:r.execute});if(pe){let{reason:H,detail:ds}=vu(pe);_e(u,k.path,H,ds),l.push({...k,executed:!1,skipped:!0,skipReason:H});continue}l.push(Uo(Ir(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}if(!m()&&r.runDirectoriesAgeMs>=0)for(let T of So({harnessRoot:h,worktreesDir:X,runDirectoriesAgeMs:r.runDirectoriesAgeMs,runIdFilter:r.runIdFilter,activeGuards:o,now:n.now})){if(m())break;let _=M.resolve(T.path);if(c.has(_))continue;c.add(_);let k={...T,path:_},I=k.runId??M.basename(_),U=bo({harnessRoot:h,runId:I,runPath:_,ageMs:k.ageMs,runDirectoriesAgeMs:r.runDirectoriesAgeMs,activeGuards:o});if(U){_e(u,k.path,U),l.push({...k,executed:!1,skipped:!0,skipReason:U});continue}l.push(To(Ir(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}}let f=0,p=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"&&(p+=1)):h.skipped&&(A+=1,h.skipReason==="dry_run"&&h.bytes&&(y+=h.bytes));let L=r.accountBytes?Zo({harnessRoot:n.harnessRoot,now:n.now,perRunEntryCap:r.storagePerRunEntryCap}):void 0,B=he(),He=r.execute&&is(B),j=He?ss({execute:!0}):null,re=B?{observed:!0,execute:He,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,N("wsl-crashes",`removed ${j.removed.length} dump(s), ${j.removedBytes} bytes`)),N("complete",`${l.length} action(s), ${A} skipped, ${R} removed`);let te=po(l,u),P=us({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}:{},...te.length>0?{preservedLivePaths:te}:{},...p>0?{removedRunDirectories:p}:{},...re?{wslCrashDumps:re}:{}});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}:{},...te.length>0?{preservedLivePaths:te}:{},...p>0?{removedRunDirectories:p}:{},...re?{wslCrashDumps:re}:{},compactSummary:P}}export{Rr as DEFAULT_MAX_ACTIONS_PER_SWEEP,St as DEFAULT_NODE_MODULES_AGE_MS,vt as DEFAULT_RUN_DIRECTORIES_AGE_MS,yr as DEFAULT_WORKTREES_AGE_MS,Eu as runHarnessCleanup};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var r=(e,n,t)=>()=>{if(t)throw t[0];try{return e&&(n=e(e=0)),n}catch(o){throw t=[o],o}};function
|
|
1
|
+
var r=(e,n,t)=>()=>{if(t)throw t[0];try{return e&&(n=e(e=0)),n}catch(o){throw t=[o],o}};function P(e){return process.platform!=="win32"?e:{windowsHide:!0,...e}}var i=r(()=>{"use strict"});var ge,Qe,I=r(()=>{"use strict";ge=["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"],Qe=new Set(ge)});import{spawnSync as ye}from"node:child_process";function D(e,n){try{let t=ye("git",n,P({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}}}var y=r(()=>{"use strict";i();I()});import{homedir as N}from"node:os";import W from"node:path";function he(e){return e==="~"?N():e.startsWith("~/")||e.startsWith("~\\")?W.join(N(),e.slice(2)):e}function d(e){return W.resolve(he(e))}var l=r(()=>{"use strict"});import{existsSync as b,readFileSync as B}from"node:fs";import{homedir as be}from"node:os";import a from"node:path";import{fileURLToPath as Re}from"node:url";function xe(e){let n=a.join(e,"package.json");if(!b(n))return null;try{let t=JSON.parse(B(n,"utf8"));return typeof t.name=="string"?t.name.trim():null}catch{return null}}function Se(e){return xe(e)==="kynver"}function U(e){let n=a.resolve(e);if(!b(n))return null;let t=D(n,["rev-parse","--show-toplevel"]);if(t.status!==0)return null;let o=t.stdout.trim();return o.length?a.resolve(o):null}function ve(e=import.meta.url){let n=a.dirname(Re(e));for(let t=0;t<8;t+=1){let o=a.join(n,"package.json");if(b(o))try{if(JSON.parse(B(o,"utf8")).name==="@kynver-app/runtime")return n}catch{}let s=a.dirname(n);if(s===n)break;n=s}return null}function h(e,n,t,o){if(!t)return;let s=a.resolve(t);e.has(s)||Se(s)&&(e.add(s),n.push({repo:s,source:o}))}function _e(e){let n=e?.cwd??process.cwd(),t=new Set,o=[];h(t,o,U(n),"cwd_git");let s=ve(e?.runtimeModuleUrl??import.meta.url);s&&h(t,o,U(s),"runtime_checkout");let c=be();for(let pe of ke)h(t,o,d(a.join(c,pe)),"well_known_path");return o}function R(e){return _e(e)[0]??null}var ke,k=r(()=>{"use strict";y();l();ke=["Kynver","repos/Kynver","repos/kynver-source-main","code/Kynver","projects/Kynver"]});var f=r(()=>{"use strict"});var p=r(()=>{"use strict"});var T=r(()=>{"use strict"});var kr,xr,x=r(()=>{"use strict";kr=25*1024*1024*1024,xr=12*1024*1024*1024});var Cr,Ar,K=r(()=>{"use strict";x();Cr=5*1024*1024*1024,Ar=10*1024*1024*1024});var Nr,Wr,S=r(()=>{"use strict";K();x();Nr=30*1024*1024*1024,Wr=15*1024*1024*1024});var F=r(()=>{"use strict";i()});import Ee from"node:path";var Lr,v=r(()=>{"use strict";l();F();Lr=Ee.join(".openclaw","harness")});var _=r(()=>{"use strict";u();f();p();g();v()});var $=r(()=>{"use strict";u();v();_();i()});var C=r(()=>{"use strict";$();i()});var L=r(()=>{"use strict";C();i()});var j=r(()=>{"use strict"});var Y=r(()=>{"use strict";j();i()});var V=r(()=>{"use strict"});var G=r(()=>{"use strict";V()});var z=r(()=>{"use strict";G();i()});var J=r(()=>{"use strict"});var q=r(()=>{"use strict"});var X=r(()=>{"use strict"});var A=r(()=>{"use strict"});var Q=r(()=>{"use strict"});var Z=r(()=>{"use strict";A();Q()});var ee=r(()=>{"use strict";Y();z();J();q();y();X();Z();A();i()});var re=r(()=>{"use strict";ee()});var Ue,Be,te=r(()=>{"use strict";T();u();f();p();g();S();C();L();re();i();Ue=500*1024*1024,Be=4*1024*1024*1024});var g=r(()=>{"use strict";te()});import{homedir as Te}from"node:os";import Ke from"node:path";var Me,ne=r(()=>{"use strict";Me=Ke.join(Te(),".kynver",".env")});var oe=r(()=>{"use strict"});var se=r(()=>{"use strict";oe()});var ie=r(()=>{"use strict"});var ae=r(()=>{"use strict";se();ie()});var le=r(()=>{"use strict"});var ue=r(()=>{"use strict";le()});var de=r(()=>{"use strict";ne();l();u();ae();ue()});import{existsSync as Le,mkdirSync as Ro,readFileSync as je,writeFileSync as ko}from"node:fs";import{homedir as Ye,totalmem as So}from"node:os";import w from"node:path";function m(){if(!Le(me))return{};try{return JSON.parse(je(me,"utf8"))}catch{return{}}}var fe,me,No,Wo,Uo,u=r(()=>{"use strict";k();l();i();f();p();g();S();de();_();fe=w.join(Ye(),".kynver"),me=w.join(fe,"config.json"),No=w.join(fe,"credentials");Wo=500*1024*1024,Uo=4*1024*1024*1024});u();k();l();import Ve from"node:path";function Ge(e){return Ve.resolve(d(e.trim()))}function O(e,n,t){let o=e?.trim();return o?{repo:Ge(o),source:n,persistedInConfig:t}:null}function ze(e){return e?{repo:e.repo,source:e.source,persistedInConfig:!1}:null}function Je(e={}){let n=e.env??process.env,t=e.config??m(),o=O(t.defaultRepo,"config",!0);if(o)return o;let s=O(n.KYNVER_DEFAULT_REPO,"env_default_repo",!1);if(s)return s;let c=O(n.KYNVER_HARNESS_REPO,"env_harness_repo",!1);return c||ze(R({cwd:e.cwd,runtimeModuleUrl:e.runtimeModuleUrl}))}export{Je as resolveDefaultRepo};
|