@kynver-app/runtime 0.2.19 → 0.2.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +52 -18
  2. package/dist/bootstrap.d.ts +48 -0
  3. package/dist/cli.d.ts +11 -0
  4. package/dist/cli.js +73 -66
  5. package/dist/config.d.ts +1 -1
  6. package/dist/cron/cron-install-plan.d.ts +3 -1
  7. package/dist/daemon-keeper.d.ts +32 -0
  8. package/dist/doctor/runner-install.d.ts +86 -2
  9. package/dist/doctor/runtime-takeover-deploy-evidence.d.ts +7 -3
  10. package/dist/doctor/runtime-takeover.probes.d.ts +1 -1
  11. package/dist/index.d.ts +5 -2
  12. package/dist/index.js +95 -88
  13. package/dist/landing/land-pr-check-classify.d.ts +6 -0
  14. package/dist/orchestration-providers/inventory.d.ts +27 -4
  15. package/dist/provider-evidence/index.d.ts +0 -1
  16. package/dist/providers/model-preflight.d.ts +8 -0
  17. package/dist/providers/openai-compatible-response.d.ts +23 -0
  18. package/dist/providers/openai-compatible-runner.d.ts +1 -0
  19. package/dist/providers/openai-compatible.d.ts +46 -0
  20. package/dist/scheduler-cutover.d.ts +1 -1
  21. package/dist/server/adapter-contract.d.ts +1 -0
  22. package/dist/server/adapter-contract.js +1 -0
  23. package/dist/server/cleanup.js +14 -14
  24. package/dist/server/context-budget-receipt.d.ts +2 -0
  25. package/dist/server/context-budget-receipt.js +6 -0
  26. package/dist/server/db-credentials.d.ts +1 -0
  27. package/dist/server/db-credentials.js +2 -0
  28. package/dist/server/default-repo.js +1 -1
  29. package/dist/server/heavy-verification.js +1 -1
  30. package/dist/server/memory-cost-enforce.js +2 -2
  31. package/dist/server/memory-cost.js +2 -2
  32. package/dist/server/model-routing.d.ts +3 -0
  33. package/dist/server/model-routing.js +5 -0
  34. package/dist/server/monitor.js +7 -7
  35. package/dist/server/node-runtime-policy.d.ts +1 -0
  36. package/dist/server/node-runtime-policy.js +1 -0
  37. package/dist/server/orchestration.d.ts +1 -1
  38. package/dist/server/orchestration.js +1 -1
  39. package/dist/server/prompt.d.ts +1 -0
  40. package/dist/server/prompt.js +19 -0
  41. package/dist/server/worker-policy.d.ts +1 -1
  42. package/dist/server/worker-policy.js +2 -2
  43. package/dist/status.d.ts +3 -1
  44. package/dist/stream.d.ts +13 -0
  45. package/dist/worker-provider-policy.d.ts +21 -4
  46. package/dist/worker-usage.d.ts +20 -0
  47. package/dist/worktree.d.ts +33 -0
  48. package/package.json +34 -3
@@ -1,16 +1,16 @@
1
- var f=(e,r,t)=>()=>{if(t)throw t[0];try{return e&&(r=e(e=0)),r}catch(n){throw t=[n],n}};import{existsSync as Cs,mkdirSync as Es,readFileSync as Mt,readdirSync as Vu,renameSync as ws,rmSync as As,statSync as Tt,writeFileSync as Ps}from"node:fs";import{randomBytes as Is}from"node:crypto";import Os from"node:path";function Lr(e){console.error(e),process.exit(1)}function jr(e){return process.platform!=="win32"?e:{windowsHide:!0,...e}}function $e(e){try{return JSON.parse(e)}catch{return null}}function _(e,r){try{return JSON.parse(Mt(e,"utf8"))}catch(t){if(arguments.length>1)return r;Lr(`failed to read ${e}: ${t.message}`)}}function Ut(e,r){Es(Os.dirname(e),{recursive:!0});let t=`${e}.${process.pid}.${Is(4).toString("hex")}.tmp`;try{Ps(t,`${JSON.stringify(r,null,2)}
2
- `),ws(t,e)}catch(n){try{As(t,{force:!0})}catch{}throw n}}function v(e){return String(e||"").toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"worker"}function Ge(e){try{return Tt(e).size}catch{return 0}}function Ye(e){try{return Tt(e).mtime.toISOString()}catch{return null}}function Bt(e,r){return Cs(e)?Mt(e,"utf8").split(`
1
+ var f=(e,r,n)=>()=>{if(n)throw n[0];try{return e&&(r=e(e=0)),r}catch(t){throw n=[t],t}};import{existsSync as Es,mkdirSync as ws,readFileSync as Un,readdirSync as qu,renameSync as As,rmSync as Ps,statSync as Bn,writeFileSync as Is}from"node:fs";import{randomBytes as Os}from"node:crypto";import Ds from"node:path";function jr(e){console.error(e),process.exit(1)}function $r(e){return process.platform!=="win32"?e:{windowsHide:!0,...e}}function Ge(e){try{return JSON.parse(e)}catch{return null}}function _(e,r){try{return JSON.parse(Un(e,"utf8"))}catch(n){if(arguments.length>1)return r;jr(`failed to read ${e}: ${n.message}`)}}function Kn(e,r){ws(Ds.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Os(4).toString("hex")}.tmp`;try{Is(n,`${JSON.stringify(r,null,2)}
2
+ `),As(n,e)}catch(t){try{Ps(n,{force:!0})}catch{}throw t}}function v(e){return String(e||"").toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"worker"}function Ye(e){try{return Bn(e).size}catch{return 0}}function Ve(e){try{return Bn(e).mtime.toISOString()}catch{return null}}function Fn(e,r){return Es(e)?Un(e,"utf8").split(`
3
3
  `).slice(-r).join(`
4
- `):""}function Z(e){if(!e)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Kt(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 $r(e){return Math.max(0,Math.round((Date.now()-e)/1e3))}var b=f(()=>{"use strict"});var Ds,qu,Ws,Zu,Ft=f(()=>{"use strict";Ds=["ANTHROPIC_API_KEY","ANALYST_API_KEY","RECRUITER_API_KEY","AUTH_SECRET","NEXTAUTH_SECRET","DATABASE_URL","PRODUCTION_DATABASE_URL","KYNVER_PRODUCTION_DATABASE_URL","REDIS_URL","GOOGLE_CLIENT_SECRET","GITHUB_CLIENT_SECRET","KYNVER_API_KEY","KYNVER_SERVICE_SECRET","KYNVER_RUNTIME_SECRET","KYNVER_CRON_SECRET","OPENCLAW_CRON_SECRET","QSTASH_TOKEN","QSTASH_CURRENT_SIGNING_KEY","QSTASH_NEXT_SIGNING_KEY","TOOL_SECRETS_KEK","TOOL_EXECUTOR_DISPATCH_SECRET","CLOUDFLARE_API_TOKEN","STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_IDENTITY_WEBHOOK_SECRET","VOYAGE_API_KEY","PERPLEXITY_API_KEY","FRED_API_KEY","FMP_API_KEY","CURSOR_API_KEY","MEMORY_CONTENT_KEK","LLM_BYOK_KEK","KYNVER_COMMAND_AUTH_KEY","KYNVER_INSTRUCTION_BUNDLE_KEY","KYNVER_MEMORY_LEDGER_KEY","KYNVER_JWKS_PRIVATE_KEY_JWK"],qu=new Set(Ds),Ws=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN"],Zu=new Set(Ws)});import{spawnSync as Lt}from"node:child_process";function ke(e,r,t={}){let n=Lt("git",r,jr({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);Lr(o)}return n.stdout||""}function Ae(e){return ke(e,["status","--short"],{allowFailure:!0}).split(`
5
- `).map(r=>r.trim()).filter(Boolean)}function w(e,r){try{let t=Lt("git",r,jr({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 Ht(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 Ve(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 Gr(n,"missing worktree path");let s=w(e,["rev-parse","HEAD"]);if(s.status!==0)return Gr(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 Gr(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=Ht(e,i,a),l=Ht(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 Gr(e,r,t=null){return{checked:!1,base:e,head:t,baseHead:null,baseIsAncestorOfHead:null,headIsAncestorOfBase:null,relation:"unknown",error:r}}var F=f(()=>{"use strict";b();Ft()});import{homedir as jt}from"node:os";import $t from"node:path";function Ns(e){return e==="~"?jt():e.startsWith("~/")||e.startsWith("~\\")?$t.join(jt(),e.slice(2)):e}function ze(e){return $t.resolve(Ns(e))}var Re=f(()=>{"use strict"});var Je=f(()=>{"use strict";F();Re()});function ne(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 Xe(e,r){return e[r]?.trim()||null}function Gt(e){let r=e?.split(":")[0]?.trim();return r?ne(r):null}function ye(e=process.env,r={}){let t=[],n=Gt(r.boxId),o=Gt(Xe(e,"KYNVER_BOX_ID")),s=r.boxKind?.trim();if(s)return n&&n!==ne(s)&&t.push(`config.boxId=${r.boxId} conflicts with boxKind=${s}; using explicit boxKind=${s}`),{boxKind:ne(s),source:"config",slugInferenceBlocked:!1,warnings:t};let i=Xe(e,"KYNVER_BOX_KIND");if(i)return o&&o!==ne(i)&&t.push(`KYNVER_BOX_ID=${Xe(e,"KYNVER_BOX_ID")} conflicts with KYNVER_BOX_KIND=${i}; using explicit KYNVER_BOX_KIND=${i}`),{boxKind:ne(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=Xe(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 oe=f(()=>{"use strict"});function Yr(e,r){return e==="forge"?4:Math.max(1,r)}function qe(e,r){return e==="forge"?Math.min(Math.max(1,r),4):Math.max(1,r)}var Ze=f(()=>{"use strict"});var Yt=f(()=>{"use strict"});import{existsSync as Ms,readFileSync as Ts,statfsSync as Us}from"node:fs";function Vr(){if(process.platform!=="linux")return!1;for(let e of["/proc/sys/kernel/osrelease","/proc/version"])try{if(!Ms(e))continue;let r=Ts(e,"utf8");if(/microsoft|wsl/i.test(r))return!0}catch{}return!1}function Vt(e={}){if(!(e.forceWsl===void 0?Vr():e.forceWsl))return null;let t=e.wslHostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||be,n=e.wslHostFreeWarnBytes??Bs,o=e.wslHostFreeCriticalBytes??Ks,s=e.statfs??Us,i;try{i=s(t)}catch(R){return{ok:!1,path:t,freeBytes:0,totalBytes:0,usedPercent:100,warnBelowBytes:n,criticalBelowBytes:o,reason:`Windows host disk probe failed at ${t}: ${R.message}`,probeError:R.message}}let a=Number(i.bavail)*Number(i.bsize),u=Number(i.blocks)*Number(i.bsize),l=u>0?(u-a)/u*100:100,c=a<n,d=a<o,m=!c&&!d,g=(a/(1024*1024*1024)).toFixed(1),p=null;return m||(p=`Windows host disk ${t} at ${d?"critical":"warning"}: ${g} GiB free (<${(d?o:n)/1024/1024/1024} GiB); WSL VHDX cannot grow safely. ${Fs()}`),{ok:m,path:t,freeBytes:a,totalBytes:u,usedPercent:l,warnBelowBytes:n,criticalBelowBytes:o,reason:p,probeError:null}}function Fs(){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 Bs,Ks,be,zr=f(()=>{"use strict";Bs=25*1024*1024*1024,Ks=12*1024*1024*1024,be="/mnt/c"});import{execFileSync as zt}from"node:child_process";import{existsSync as er,readFileSync as Jt,readdirSync as Hs,statSync as Ls}from"node:fs";import Jr from"node:path";function Qe(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function Xt(){let e=process.env.KYNVER_WSL_WIN_USER?.trim();if(e)return e;try{let n=zt("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()||be;return r&&er(Jr.join(t,"Users",r))?r:null}function Vs(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()||be,n=e.windowsUser??Xt();return n?`${t.replace(/\\/g,"/").replace(/\/$/,"")}/Users/${n}/AppData/Local/Temp/wsl-crashes`:null}function zs(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 Js(){try{if(er("/proc/sys/kernel/core_pattern"))return Jt("/proc/sys/kernel/core_pattern","utf8").trim()}catch{}try{return zt("sysctl",["-n","kernel.core_pattern"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function Xs(e){return!!(e&&/wsl-capture-crash/i.test(e))}function qs(e,r=be){let t=Jr.join(r,"Users",e,".wslconfig");if(!er(t))return{maxCrashDumpCount:null,crashDumpFolder:null};let n;try{n=Jt(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 Zs(e){if(!er(e))return[];let r=Hs(e,{withFileTypes:!0}),t=[];for(let n of r){if(!n.isFile()||!n.name.toLowerCase().endsWith(".dmp"))continue;let o=Jr.join(e,n.name);try{let s=Ls(o),i=zs(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 Se(e={}){if(!(e.forceWsl===void 0?Vr():e.forceWsl))return null;let t=e.hostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||be,n=e.windowsUser??Xt(),o=e.warnBelowBytes??Qe("KYNVER_WSL_CRASH_DUMP_WARN_BYTES",js),s=e.criticalBelowBytes??Qe("KYNVER_WSL_CRASH_DUMP_CRITICAL_BYTES",$s),i=e.warnCount??Qe("KYNVER_WSL_CRASH_DUMP_WARN_COUNT",Gs),a=e.criticalCount??Qe("KYNVER_WSL_CRASH_DUMP_CRITICAL_COUNT",Ys),u=(e.readCorePattern??Js)(),l=Xs(u),c=null;n&&(c=(e.readWslConfig??qs)(n,t));let d=c?.maxCrashDumpCount??null,m=d===-1,g=Vs({hostMount:t,windowsUser:n,crashDumpDir:e.crashDumpDir});if(!g)return{ok:!0,path:null,windowsUser:n,dumpCount:0,totalBytes:0,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:[],executables:[],corePattern:u,wslCaptureEnabled:l,maxCrashDumpCount:d,dumpsDisabledInWslConfig:m,reason:null,probeError:"windows_user_unresolved"};let p;try{p=(e.listDumps??Zs)(g)}catch(P){return{ok:!1,path:g,windowsUser:n,dumpCount:0,totalBytes:0,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:[],executables:[],corePattern:u,wslCaptureEnabled:l,maxCrashDumpCount:d,dumpsDisabledInWslConfig:m,reason:`WSL crash dump probe failed at ${g}: ${P.message}`,probeError:P.message}}let R=p.reduce((P,h)=>P+h.bytes,0),S=p.length,y=[...new Set(p.map(P=>P.executableHint).filter(P=>!!P))],A=R>=s,j=R>=o,B=S>=a,He=S>=i,re=!(A||B||j||He),te=null;if(!re){let P=A||B?"critical":"warning",h=(R/1024**3).toFixed(1),q=y.length>0?y.join(", "):"unknown";te=`WSL crash dumps ${P}: ${S} file(s), ${h} GiB at ${g} (executables: ${q}). `+Qs({wslCaptureEnabled:l,dumpsDisabledInWslConfig:m})}return{ok:re,path:g,windowsUser:n,dumpCount:S,totalBytes:R,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:p,executables:y,corePattern:u,wslCaptureEnabled:l,maxCrashDumpCount:d,dumpsDisabledInWslConfig:m,reason:te,probeError:null}}function Qs(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 js,$s,Gs,Ys,rr=f(()=>{"use strict";zr();js=5*1024*1024*1024,$s=10*1024*1024*1024,Gs=2,Ys=4});import{statfsSync as ei}from"node:fs";function tr(e={}){let r=e.diskPath?.trim()||"/",t=e.diskFreeWarnBytes??ri,n=e.diskFreeCriticalBytes??ti,o=e.diskMaxUsedPercent??ni,s=e.diskHardMaxUsedPercent??oi,i=ei(r),a=Number(i.bavail)*Number(i.bsize),u=Number(i.blocks)*Number(i.bsize),l=u>0?(u-a)/u*100:100,c=a<t,d=a<n,m=a<t*2,g=m&&l>o,p=m&&l>s,R=!c&&!d&&!g&&!p,S=e.skipWslHostCheck?null:Vt(e.wslHost),y=e.skipWslCrashDumpCheck?null:Se(e.wslCrashDumps),A=R&&(S?S.ok:!0)&&(y?y.ok:!0),j=null;return A||(j=[d?`free space below critical ${n} bytes`:null,c?`free space below warning ${t} bytes`:null,p?`used percent above hard cap ${s}%`:null,g?`used percent above cap ${o}%`:null,S&&!S.ok?S.reason:null,y&&!y.ok?y.reason:null].filter(Boolean).join("; ")),si({ok:A,path:r,freeBytes:a,totalBytes:u,usedPercent:l,warnBelowBytes:t,criticalBelowBytes:n,maxUsedPercent:o,hardMaxUsedPercent:s,reason:j,wslHost:S,wslCrashDumps:y?{ok:y.ok,path:y.path,dumpCount:y.dumpCount,totalBytes:y.totalBytes,executables:y.executables,wslCaptureEnabled:y.wslCaptureEnabled,dumpsDisabledInWslConfig:y.dumpsDisabledInWslConfig,reason:y.reason,probeError:y.probeError}:null})}function si(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 ri,ti,ni,oi,nr=f(()=>{"use strict";rr();zr();ri=30*1024*1024*1024,ti=15*1024*1024*1024,ni=80,oi=90});import{existsSync as ii,readdirSync as ai,statSync as ui}from"node:fs";import Xr from"node:path";function or(){return Zt()}function qr(){let{runsDir:e}=or();return qt(e)}function sr(e){return qt(G(e))}function li(e){try{return ui(e).isDirectory()}catch{return!1}}function qt(e){if(!ii(e))return[];let r=[];for(let t of ai(e,{withFileTypes:!0})){if(t.name==="runs")continue;let n=Xr.join(e,t.name);if(!li(n))continue;let o=_(Xr.join(n,"run.json"),void 0);o?.id&&r.push(o)}return r}function Zr(e){let{runsDir:r}=or();Ut(Xr.join(Qr(r,e.id),"run.json"),e)}function Pe(e){let{harnessRoot:r}=or();return Ie(r,e)}function Ie(e,r){return Qr(G(e),v(r))}var se=f(()=>{"use strict";Y();b()});import{existsSync as ci,readdirSync as di}from"node:fs";import pi from"node:path";function et(e){let r=new Set;for(let n of Object.keys(e.workers||{}))r.add(v(n));let t=pi.join(Pe(e.id),"workers");if(!ci(t))return[...r];for(let n of di(t,{withFileTypes:!0}))n.isDirectory()&&r.add(v(n.name));return[...r]}var rt=f(()=>{"use strict";se();b()});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 Qt(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 u=tt(s[1]??"");u&&n.push(u)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let u=tt(r.slice(i,a+1));u&&n.push(u)}return n.length>0?n[n.length-1]:null}function en(e){let r=e.finalResult??e.final_result;if(r!=null)return typeof r=="string"?Qt(r)??(r.trim()||null):r;let t=typeof e.summary=="string"?e.summary.trim():"";if(!t)return null;let n=Qt(t);return n||t}var rn=f(()=>{"use strict"});import{existsSync as mi,readFileSync as fi}from"node:fs";function tn(e){return e==="complete"}function nn(e){return tn(e.lastHeartbeatPhase)?e.terminalFinalResult!==void 0&&e.terminalFinalResult!==null?e.terminalFinalResult:e.lastHeartbeatSummary?.trim()||"completed":null}function ve(e){let r={heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,terminalFinalResult:null,heartbeatBlocker:null,timestampAnomalies:[],lastBoxResourceSnapshot:null,lastPrEvidence:[]};if(!mi(e))return r;let t=Date.now()+gi,n=new Date(t).toISOString(),o=fi(e,"utf8").split(`
6
- `).filter(Boolean);for(let s of o){let i=$e(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)),tn(r.lastHeartbeatPhase)&&(r.terminalFinalResult=en(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 gi,ir=f(()=>{"use strict";rn();b();gi=6e4});function sn(e){return e?(e.split("/").pop()??e).replace(/\.exe$/i,"").toLowerCase():null}function ar(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 an(e){let r=sn(e[0]);return!!(r&&hi.has(r))}function Ri(e){let r=e.trim();return r.includes("/")?r.split("/").pop()??r:r}function yi(e){if(!e||e.includes("*"))return null;let r=Ri(e);return!r||r.includes("/")?null:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(r)?r:null}function un(e){return!e||e.includes("/")||e.includes("*")?!1:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(e)}function nt(e){if(!e)return!1;let r=e.trim();return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")}function bi(e){if(!e.startsWith("--glob="))return e;let r=e.slice(7);return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")?`--glob=${r}/**`:e}function Si(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;on.has(n)&&(t+=1);continue}r.push(n)}}return r}function vi(e){let r=!1,t=e.map((o,s)=>{let i=bi(o),a=e[s-1];return a&&on.has(a)&&o.startsWith("!")&&!o.includes("/")&&!o.endsWith("/**")&&(i=`${o}/**`),i!==o&&(r=!0),i}),n=Si(t);if(n.length===2){let[o,s]=n;if(nt(s))return{argv:[t[0]??"rg",o,"-g",`${s}/**`,"."],changed:!0};let i=yi(s);if(i)return{argv:[t[0]??"rg","-g",i,o,"."],changed:!0}}return r&&n.length===1?{argv:[...t,"."],changed:!0}:{argv:t,changed:r}}function ln(e){for(let r=1;r<e.length;r+=1){let t=e[r];if(t&&(t==="-c"||t==="-lc"||t==="-cl"||/^-[a-zA-Z]*c[a-zA-Z]*$/u.test(t)))return r+1}return-1}function ur(e){let r=e.trim();if(!r)return{command:r,wrapped:!1};let t=ar(r);if(!t.length)return{command:r,wrapped:!1};let n=sn(t[0]);if(!n||!ki.has(n))return{command:r,wrapped:!1};let o=ln(t);if(o<0||o>=t.length)return{command:r,wrapped:!1};let s=t.slice(o).join(" ").trim();return s?{command:s,wrapped:!0}:{command:r,wrapped:!1}}function _i(e,r){let t=e.trim(),n=ar(t),o=ln(n);if(o<0)return r;let s=n.slice(0,o).join(" "),i=r.includes("'")?`"${r.replace(/"/g,'\\"')}"`:`'${r}'`;return`${s} ${i}`}function xi(e){let r=e.trim(),t=ur(r),n=ar(t.command);if(!n.length||!an(n))return{segment:r,changed:!1};let o=vi(n);if(!o.changed)return{segment:r,changed:!1};let s=o.argv.join(" ");return t.wrapped?{segment:_i(r,s),changed:!0}:{segment:s,changed:!0}}function ot(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=xi(i);return a.changed&&(o=!0),a.segment});return o?{command:s.join(t),changed:!0}:{command:r,changed:!1}}function cn(e){let r=ur(e).command,t=ar(r.trim());return t.length&&an(t)?!0:/\b(rg|ripgrep)\b/i.test(r)}function dn(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 Ci(e){let{pattern:r,target:t}=dn(e);return r?nt(t)?{kind:"rg_exclude_syntax",pattern:r,target:t}:un(t)?{kind:"bad_scope",pattern:r,target:t}:{kind:"not_repo_search",pattern:r,target:t}:{kind:"not_repo_search"}}function Ei(e){let{pattern:r,target:t}=dn(e);if(!r)return null;if(nt(t)){let n=`${t.trim()}/**`;return{command:`rg "${r}" -g '${n}' .`,changed:!0}}return t&&un(t)?{command:`rg -g ${t} "${r}" .`,changed:!0}:null}function wi(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 Ai(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 st(e){let r=e.meta?.trim()||(e.command?Ai(e.command):null)||null;if(r){let t=Ci(r),n=wi(t);if(n)return n;let o=Ei(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=ot(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 hi,ki,on,pn=f(()=>{"use strict";hi=new Set(["rg","ripgrep","grep"]),ki=new Set(["bash","sh","dash","zsh"]),on=new Set(["-e","--regexp","-f","--file","-m","--max-count","-A","--after-context","-B","--before-context","-C","--context","-g","--glob","--iglob"])});function Oe(e,r=200){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function Oi(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 De(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Di(e){let r=e.metadata;if(!De(r))return null;let t=r.vulnerabilities;if(!De(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 Wi(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 Ni(e,r){let t=e.error;if(De(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?Oe(o.split(`
7
- `).find(Boolean)??o,160):"npm audit failed"}function Mi(e){let r=`${e.stdout}
8
- ${e.stderr}`.trim(),t=Oi(r);if(!t||!De(t)){let o=Oe(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(De(t.error))return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit command failed: ${Ni(t,e.stderr)}`};let n=Di(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:Wi(n),audit:n}:{kind:"command_failure",exitCode:e.exitCode,summary:"npm audit failed: JSON response missing vulnerability metadata",parseError:"missing_metadata"}}function Ti(e){return Pi.test(e)}function Ui(e){let r=ur(e).command;return mn.test(e)||mn.test(r)||cn(e)}function Bi(e){let r=st({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&&Ii.test(n)){let i=Oe(n,160);return{kind:"command_failure",exitCode:1,summary:r??`ripgrep failed (exit 1): ${i}`}}let o=ot(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=Oe(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 fn(e){let r=e.stdout??"",t=e.stderr??"",n=e.interleavedOutput??"";if(Ti(e.command)){let i=r.trim()||n.trim()||t.trim();return Mi({exitCode:e.exitCode,stdout:i,stderr:t})}if(Ui(e.command))return Bi({command:e.command,exitCode:e.exitCode,stdout:r,stderr:t,interleaved:n});let o=st({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=Oe(n||r||t||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:`command failed (exit ${e.exitCode}): ${s}`}}var Pi,mn,Ii,gn=f(()=>{"use strict";pn();Pi=/\bnpm\s+audit\b/i,mn=/\b(rg|ripgrep)\b/i,Ii=/\b(error|invalid|unknown|panic|not found)\b/i});import{existsSync as Ki,readFileSync as Fi}from"node:fs";function Hi(e){let r=e.timestamp_ms;return e.timestamp||e.ts||(r?new Date(r).toISOString():void 0)}function Li(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 ji(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 $i(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 Gi(e,r){r.kind==="success"||r.kind==="search_no_matches"||(e.lastShellOutcome=r)}function hn(e){let r={firstEventAt:null,lastEventAt:null,currentTool:null,finalResult:null,error:null,lastShellOutcome:null};if(!Ki(e))return r;let t=Fi(e,"utf8").split(`
9
- `).filter(Boolean);for(let n of t){let o=$e(n);if(!o)continue;let s=Hi(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=Li(a);u&&(r.currentTool=u)}let i=$i(o);i&&Gi(r,fn({command:i.command,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr,interleavedOutput:i.interleaved})),o.type==="result"&&ji(r,o)}return r}var kn=f(()=>{"use strict";gn();b()});function Vi(e,r=240){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function Rn(e){let r=(e??"").trim();if(!r)return null;for(let t of Yi)if(t.test.test(r))return{blocked:!0,reason:`${t.label}: ${Vi(r)}`};return null}var Yi,yn=f(()=>{"use strict";Yi=[{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 bn(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function zi(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 Ji(e){return!e?.checked||e.headIsAncestorOfBase!==!1?null:bn(e.head)}function Xi(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 Sn(e){if(e.alive||zi(e.finalResult))return null;let r=(e.changedFiles??[]).filter(i=>i.trim()).length,t=bn(e.headCommit)??Ji(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:Xi(s,r,t)}}var vn=f(()=>{"use strict"});function We(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function qi(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="boolean"?e:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function Zi(e){if(We(e.headCommit)||We(e.prUrl)||We(e.artifactBundlePath)||We(e.patchPath))return!0;let r=e.gitAncestry;return!!(r?.checked&&r.headIsAncestorOfBase===!1&&We(r.head))}function _e(e){return qi(e.finalResult)?e.changedFiles.length===0?{blocked:!1}:Zi(e)?{blocked:!0,detail:`Worktree has ${e.changedFiles.length} uncommitted change(s); commit or discard before landing`}:{blocked:!0,reason:"dirty_worktree_no_pr",detail:`Worktree has ${e.changedFiles.length} uncommitted change(s) with no commit or PR; commit, open a PR, or discard before landing`}:{blocked:!1}}function _n(e){if(e.blocked)return e.detail??e.reason??"dirty_worktree_no_pr"}var lr=f(()=>{"use strict"});function it(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 xn(e){let r=e.targetPrReconciliation??e.target_pr_reconciliation??e.targetPrs??e.target_prs;return Array.isArray(r)?r.length:0}function cr(e){let r=e.trim();if(!r)return null;let t=it(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let c=it(s[1]??"");c&&n.push(c)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let c=it(r.slice(i,a+1));c&&n.push(c)}if(n.length===0)return null;let u=n[n.length-1],l=xn(u);for(let c of n){let d=xn(c);d>l&&(u=c,l=d)}return u}var at=f(()=>{"use strict"});function Cn(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 En(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function Qi(e){return new Set(e.map(r=>En(Cn(r)??r)).filter(Boolean))}function wn(e,r,t){let n=Cn(e)??e;if(!n)return"unrelated";let o=En(n);return Qi(r).has(o)?"contract":t?(t.outcome==="skipped"||t.outcome==="blocked")&&t.reason?.trim()?"support":(t.outcome==="merged","unrelated"):"unrelated"}var An=f(()=>{"use strict"});function xe(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function ea(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"?Object.keys(e).length>0:!0}function ie(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`https://github.com/${r[1]}/pull/${r[2]}`:xe(e)}function dr(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function Pn(e){let r=null;if(typeof e=="string"){let o=cr(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=ie(String(s.prUrl??s.pr_url??"")),a=xe(s.outcome);!i||a!=="merged"&&a!=="skipped"&&a!=="blocked"||n.push({prUrl:i,outcome:a,mergeCommit:xe(s.mergeCommit??s.merge_commit),reason:xe(s.reason)})}return n}function In(e,r){let t=[],n=ie(xe(e.prUrl)??"");if(n&&t.push(n),r&&typeof r=="object"&&!Array.isArray(r)){let o=r,s=ie(String(o.prUrl??o.pr_url??""));s&&t.push(s)}return[...new Set(t)]}function On(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(!ea(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?ie(xe(r.targetPrUrl)??"")??(r.targetPrUrls.length===1?ie(r.targetPrUrls[0]):null):null;if(s){let d=In(t,n);if(!(n&&typeof n=="object"&&!Array.isArray(n)&&n.supersedesOriginalTargetPr===!0)){for(let R of d)if(R!==s)return{blocked:!0,reason:"duplicate_repair_pr",detail:`Repair worker opened or attached PR ${R} instead of canonical target ${s}`}}let p=Pn(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=Pn(n),a=new Map(i.map(d=>[dr(d.prUrl),d])),u=new Set(r.targetPrUrls.map(d=>dr(ie(d)??d)).filter(Boolean)),l=In(t,n);if(r.landingOnly)for(let d of l){let m=a.get(dr(d)),g=wn(d,r.targetPrUrls,m);if(!(g==="contract"||g==="support"))return u.size>0?{blocked:!0,reason:"unrelated_implementation_pr",detail:`Landing-only worker attached unrelated PR ${d}`}:{blocked:!0,reason:"unrelated_implementation_pr",detail:"Landing-only worker must not open new implementation PRs"}}if(r.targetPrUrls.length===0)return{blocked:!1};let c=[];for(let d of r.targetPrUrls){let m=dr(ie(d)??d),g=a.get(m);if(!g){c.push(m);continue}g.outcome!=="merged"&&!g.reason?.trim()&&c.push(m)}return c.length>0?{blocked:!0,reason:c.every(d=>a.has(d))?"incomplete_target_pr_landing":"missing_target_pr_reconciliation",detail:`Target PR reconciliation incomplete: ${c.join(", ")}`}:{blocked:!1}}function Dn(e){if(e.blocked)return e.detail??e.reason}var Wn=f(()=>{"use strict";at();An()});function na(e){let r=Date.now();if(e.completionBlocker&&!Nn(e.completionBlocker))return{state:"blocked",reason:e.completionBlocker};if(e.finalResult){if(e.localOnly&&sa(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=_e(o);if(s.blocked){let i=_n(s);return{state:"needs_attention",reason:s.reason?`landing blocked (${s.reason}): ${i}`:`landing blocked: ${i}`}}if(e.landingContract){let i=On({contract:e.landingContract,snapshot:o,finalResult:e.finalResult}),a=Dn(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(oa(e))return{state:"done",reason:"empty abandoned worker record"};let o=Rn(e.error);if(o)return{state:"blocked",reason:o.reason};let s=Sn({alive:!1,finalResult:null,changedFiles:e.changedFiles,gitAncestry:e.gitAncestry});if(s?.salvageable){let a=e.error?.trim();return{state:"needs_attention",reason:a?`${s.attentionReason} (${a})`:s.attentionReason}}let i=e.error?.trim();return{state:"needs_attention",reason:i?`process exited without a final result: ${i}`:s?.attentionReason??"process exited without a final result"}}if(e.heartbeatBlocker)return{state:"blocked",reason:`worker heartbeat reported blocker: ${e.heartbeatBlocker}`};let t=e.startedAt?Date.parse(e.startedAt):NaN;if(!e.firstEventAt&&e.stdoutBytes===0&&e.heartbeatBytes===0&&Number.isFinite(t)&&r-t>ra)return{state:"needs_attention",reason:`no first stream event ${$r(t)}s after start`};let n=e.lastActivityAt?Date.parse(e.lastActivityAt):NaN;return Number.isFinite(n)&&r-n>ta?{state:"stale",reason:`no log/event/heartbeat activity for ${$r(n)}s`}:{state:"ok",reason:"recent activity"}}function Nn(e){let r=e?.trim();return r?/completion acknowledged but board not advanced/i.test(r)&&/task already terminal/i.test(r):!1}function oa(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 sa(e){let r=null;if(typeof e=="string"?r=cr(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 ia(e,r,t){let n=e.completionSnapshot?.finalResult;return e.completionAckSource==="local-pr-merged-reconcile"&&n!==void 0&&n!==null?n:r||(n??nn(t))}function Ne(e,r={}){let t=hn(e.stdoutPath),n=ve(e.heartbeatPath),o=typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim().length>0,s=ia(e,t.finalResult,n),i=o?!1:Z(e.pid),a=Ge(e.stdoutPath),u=Ge(e.stderrPath),l=Ge(e.heartbeatPath),c=Ae(e.worktreePath),d=Ve(e.worktreePath,{base:r.base,baseCommit:r.baseCommit}),m=Kt([t.lastEventAt,n.lastHeartbeatAt,Ye(e.stdoutPath),Ye(e.stderrPath),Ye(e.heartbeatPath)]),g=t.error||!i&&!s&&Bt(e.stderrPath,10).trim()||void 0,p=typeof e.completionBlocker=="string"&&e.completionBlocker.trim()?e.completionBlocker.trim():null,R=Nn(p)?null:p,S=e.repairTargetPrUrl?{landingOnly:!1,targetPrUrls:[e.repairTargetPrUrl],targetPrUrl:e.repairTargetPrUrl,repairEnforceOriginalPr:!0}:null,y=na({alive:i,finalResult:s,firstEventAt:t.firstEventAt,stdoutBytes:a,stderrBytes:u,heartbeatBytes:l,lastActivityAt:m,heartbeatBlocker:n.heartbeatBlocker,startedAt:e.startedAt,error:g,changedFiles:c,gitAncestry:d,completionBlocker:R,landingContract:S,prUrl:e.repairTargetPrUrl??e.taskPrUrl??null,localOnly:e.localOnly===!0,taskId:e.taskId??null,agentOsId:e.agentOsId??null,reconcileReason:e.reconcileReason??null}),A=R||y.state==="blocked"?"blocked":o||y.state==="done"?"done":s?"exited":i?"running":"exited";return{runId:e.runId,worker:e.name,pid:e.pid,alive:i,status:A,attention:y,branch:e.branch,worktreePath:e.worktreePath,ownedPaths:e.ownedPaths,stdoutBytes:a,stderrBytes:u,heartbeatBytes:l,firstEventAt:t.firstEventAt,lastEventAt:t.lastEventAt,lastActivityAt:m,currentTool:o?null:t.currentTool,heartbeatCount:n.heartbeatCount,lastHeartbeatAt:n.lastHeartbeatAt,lastHeartbeatPhase:n.lastHeartbeatPhase,lastHeartbeatSummary:n.lastHeartbeatSummary,heartbeatBlocker:n.heartbeatBlocker,timestampAnomalies:n.timestampAnomalies,finalResult:s,error:g,changedFiles:c,gitAncestry:d,instructionPolicyFingerprint:e.instructionPolicyFingerprint??null,instructionPolicyEvidence:e.instructionPolicyEvidence??null,model:e.model??e.orchestrationAudit?.model??null,provider:e.provider??e.orchestrationAudit?.provider??null,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 ae(e){return!!(e.finalResult||e.alive===!1||e.status==="exited"||e.status==="done")}function Mn(e){return e.finalResult?e.attention.state==="needs_attention"||e.attention.state==="blocked":!1}var ra,ta,ue=f(()=>{"use strict";ir();kn();yn();vn();F();lr();Wn();at();b();ra=18e4,ta=6e5});var Tn=f(()=>{"use strict";ue()});function Un(e,r={}){let t=r.perWorkerMemBytes??ut,n=r.memReserveBytes??lt,o=r.memUtilization??ct,s=Math.max(0,Math.floor(e*o)-n),i=Math.max(1,Math.floor(s/t));return Math.min(i,pr)}var ut,lt,ct,pr,Bn=f(()=>{"use strict";Yt();ce();oe();Ze();mr();nr();se();rt();Tn();b();ut=500*1024*1024,lt=4*1024*1024*1024,ct=.85,pr=64});function Me(e,r){let t=Number(e);return!Number.isFinite(t)||t<=0?r:Math.floor(t)}function dt(e){let r=e.config??{},t=e.env??process.env,n=Me(r.perWorkerMemBytes,ut),o=Me(r.memReserveBytes,lt),s=Math.min(1,Math.max(.1,Number(r.memUtilization)>0?Number(r.memUtilization):ct)),i=Un(e.totalMemBytes,{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s});if(e.configuredMaxWorkersOverride!==void 0&&e.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:Me(e.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(r.maxConcurrentWorkers!==void 0&&r.maxConcurrentWorkers!==null){let l=Me(r.maxConcurrentWorkers,0)||null;if(l)return{configuredMaxWorkers:Math.min(l,pr),autoCap:i,workerCapSource:"config"}}let u=(t.KYNVER_MAX_WORKERS_INTENTIONAL==="1"||t.KYNVER_MAX_WORKERS_INTENTIONAL==="true")&&t.KYNVER_MAX_WORKERS&&Me(t.KYNVER_MAX_WORKERS,0)||null;return u?{configuredMaxWorkers:Math.min(u,pr),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var mr=f(()=>{"use strict";Bn()});import{homedir as aa}from"node:os";import ua from"node:path";var Kn,pt=f(()=>{"use strict";Kn=ua.join(aa(),".kynver",".env")});var Fn=f(()=>{"use strict"});var Hn=f(()=>{"use strict";Fn()});var Ln=f(()=>{"use strict"});var mt=f(()=>{"use strict";Hn();Ln()});var jn=f(()=>{"use strict"});var $n=f(()=>{"use strict";jn()});var fr=f(()=>{"use strict";pt();Re();ce();mt();$n()});var Vn=f(()=>{"use strict";oe();oe()});var zn=f(()=>{"use strict";pt();mt();fr()});import{existsSync as V,mkdirSync as ca,readdirSync as gr,renameSync as Jn,statSync as da}from"node:fs";import z from"node:path";function qn(e){try{return da(e).isDirectory()}catch{return!1}}function pa(e){if(!V(e))return!0;for(let r of Xn){let t=z.join(e,r);if(V(t)&&(!qn(t)||gr(t).length>0))return!1}return!0}function ma(e){let r=z.join(e,"runs");if(!V(r)||!qn(r))return!1;for(let t of gr(r,{withFileTypes:!0})){if(!t.isDirectory()||t.name==="runs")continue;let n=z.join(r,t.name,"run.json");if(_(n,void 0)?.id)return!0}return!1}function fa(e){let r=z.join(e,"runs");if(!V(r))return!1;for(let t of gr(r,{withFileTypes:!0})){if(!t.isDirectory())continue;if(_(z.join(r,t.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function ga(e){let r=z.join(e,"ghost");return V(r)?!V(z.join(r,"runs")):fa(e)}function Zn(e){return ma(e.sharedRoot)?pa(e.forgeRoot)?ga(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 Qn(e,r){ca(r,{recursive:!0});for(let t of Xn){let n=z.join(e,t),o=z.join(r,t);if(V(n)){if(V(o)&&gr(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(V(o)){Jn(n,o);continue}Jn(n,o)}}}var Xn,eo=f(()=>{"use strict";b();Xn=["runs","worktrees"]});import{existsSync as E}from"node:fs";import{homedir as ha}from"node:os";import C from"node:path";function ft(e=process.env){return e.HOME?.trim()||ha()}function gt(e=process.env){return C.join(ft(e),".kynver","harness")}function hr(e){let r=C.resolve(ze(e.trim()));for(;ka.has(C.basename(r));)r=C.dirname(r);return r}function Ra(e,r=process.env){return C.join(gt(r),e)}function ya(e=process.env){let r=gt(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(ft(e),ro);return E(t)}function kr(e){let r=e.env??process.env,t=r.KYNVER_HARNESS_ROOT?.trim()||r.OPUS_HARNESS_ROOT?.trim();if(t)return{harnessRoot:hr(t),source:"env"};let n=e.configuredHarnessRoot?.trim();if(n)return{harnessRoot:hr(n),source:"config"};let o=Ra(e.boxKind,r);if(E(C.join(o,"runs"))||E(o)&&!ba(o))return{harnessRoot:o,source:"box_scoped"};let i=gt(r);if(e.boxKind==="forge"){let a=Zn({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&&Qn(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(e.boxKind==="ghost"&&ya(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(ft(r),ro);if(E(u))return{harnessRoot:u,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function ba(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 ro,ka,ht=f(()=>{"use strict";Re();eo();ro=C.join(".openclaw","harness");ka=new Set(["runs","worktrees"])});import to from"node:os";function Rr(e){return e?.trim()?e.trim():null}function Sa(e,r){let t=r.trim().toLowerCase()||"host";return`${e}-${t}`.replace(/[^a-z0-9._-]+/g,"-")}function va(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 yr(e=le(),r=process.env,t={}){let n=ye(r,e),o=[...n.warnings],s=[],i=!!(e.boxKind?.trim()||Rr(r.KYNVER_BOX_KIND)),a=t.strict===!0||va(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 R="ambiguous box identity: KYNVER_AGENT_OS_SLUG is set without KYNVER_BOX_KIND or config.boxKind";a||t.requireExplicitBoxKind?s.push(R):o.push(`${R} \u2014 defaulting box kind to forge`)}let u=Rr(e.runnerId),l=Rr(r.KYNVER_RUNTIME_ID)??Rr(r.OPENCLAW_RUNTIME_ID),c=u??l??Sa(n.boxKind,to.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=dt({config:e,env:r,totalMemBytes:to.totalmem()}),g=qe(n.boxKind,m.configuredMaxWorkers??Yr(n.boxKind,m.autoCap)),p=kr({boxKind:n.boxKind,configuredHarnessRoot:e.harnessRoot,env:r});return p.migrationBlocker&&s.push(p.migrationBlocker),s.length>0?{ok:!1,identity:null,errors:s,warnings:o}:{ok:!0,identity:{boxKind:n.boxKind,boxKindSource:n.source,runnerId:c,runnerIdSource:d,maxConcurrentWorkers:g,workerCapSource:m.workerCapSource,harnessRoot:p.harnessRoot,harnessRootSource:p.source},errors:s,warnings:o}}var br=f(()=>{"use strict";ce();oe();Ze();mr();ht()});var oo=f(()=>{"use strict";Je();oe();Vn();ce();fr();zn();b();br()});import{existsSync as wa,mkdirSync as Jd,readFileSync as Aa,writeFileSync as Xd}from"node:fs";import{homedir as Pa,totalmem as Zd}from"node:os";import kt from"node:path";function le(){if(!wa(so))return{};try{return JSON.parse(Aa(so,"utf8"))}catch{return{}}}var io,so,cp,dp,pp,ce=f(()=>{"use strict";Je();Re();b();oe();Ze();mr();nr();fr();oo();br();io=kt.join(Pa(),".kynver"),so=kt.join(io,"config.json"),cp=kt.join(io,"credentials");dp=500*1024*1024,pp=4*1024*1024*1024});import Rt from"node:path";function O(e){return hr(e)}function Q(){let e=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(e)return O(e);let r=le(),t=r.harnessRoot?.trim();if(t)return O(t);let n=yr(r,process.env);return n.identity?n.identity.harnessRoot:kr({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function G(e){return Rt.join(O(e),"runs")}function Ce(e){return Rt.join(O(e),"worktrees")}function Zt(){let e=Q();return{harnessRoot:e,runsDir:G(e),worktreesDir:Ce(e)}}function Qr(e,r){return Rt.join(e,v(r))}var Y=f(()=>{"use strict";ce();ht();br();b()});Y();import M from"node:path";lr();import xr from"node:path";F();ue();var yt=[".next",".turbo","dist","build",".cache","node_modules/.cache"];function ao(e){let r=e.replace(/\\/g,"/").replace(/\/+$/,"");if(r==="node_modules"||r.startsWith("node_modules/"))return!0;for(let t of yt)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!ao(n)})}function de(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 Te(e){let r=e.gitAncestry?.relation;return r==="merged"||r==="synced"?D(e.changedFiles).length>0:!!(de(e.finalResult)||r==="ahead"||r==="diverged"||e.changedFiles.length>0&&e.finalResult)}b();function Ue(e){return e.status||(e.status=Ne(e.worker,{base:e.run.base,baseCommit:e.run.baseCommit})),e.status}function bt(e,r){if(e.status)return D(e.status.changedFiles).length>0;let t=r?r.porcelain(e.worktreePath):Ae(e.worktreePath);return D(t).length>0}function Ia(e){let r=e.worker.completionSnapshot?.finalResult;return r??(e.worker.taskPrUrl?{prUrl:e.worker.taskPrUrl}:null)}function St(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=Ia(e);if(o&&!Z(t.pid)){let i=r?.gitStatusCache?r.gitStatusCache.porcelain(e.worktreePath):Ae(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"}:Ve(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??de(s)};return e.status=c,c}return Ue(e)}ue();se();rt();ue();b();import Oa from"node:path";var Da=new Set(["running","dispatching","pending","queued","needs_attention"]),pe=new Set(["completed","failed","cancelled","done"]);function me(e){let r=et(e);if(r.length===0)return"failed";let t=!1,n=!1,o=!1,s=!1;for(let i of r){let a=_(Oa.join(Pe(e.id),"workers",v(i),"worker.json"),void 0);if(!a)continue;let u=Ne(a,{base:e.base,baseCommit:e.baseCommit});if(u.alive&&!u.finalResult){t=!0;break}typeof a.completionBlocker=="string"&&a.completionBlocker&&(o=!0),Mn(u)&&(s=!0),u.finalResult&&u.attention.state==="done"&&(n=!0)}return t||o||s?null:n?"completed":"failed"}function uo(){let e=[];for(let r of qr()){if(!Da.has(r.status))continue;let t=me(r);if(!t||t===r.status)continue;let n=r.status;r.status=t,Zr(r),e.push({runId:r.id,from:n,to:t})}return e}ue();ir();import{existsSync as Sr,mkdirSync as Jp,readdirSync as po,renameSync as Xp,statSync as Wa}from"node:fs";import fe from"node:path";ce();Je();Re();F();ir();Y();se();Y();b();import ee from"node:path";var $p=`${ee.sep}runs${ee.sep}runs${ee.sep}`;function lo(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 Be=900*1e3,sm=3600*1e3;function mo(e,r){let t=fe.resolve(e),n=fe.resolve(G(r)),o=fe.relative(n,t);return o!==".."&&!o.startsWith("..")&&!fe.isAbsolute(o)}function Na(e){if(!Sr(e))return[];try{return po(e,{withFileTypes:!0}).filter(r=>r.isDirectory()&&r.name!=="runs").map(r=>r.name)}catch{return[]}}function Ma(e){let r=fe.join(e,"workers");if(!Sr(r))return[];try{return po(r,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}}function co(e,r,t){if(!Sr(e))return!1;try{let n=r-Wa(e).mtimeMs;return Number.isFinite(n)&&n>=0&&n<t}catch{return!1}}function Ta(e,r=Date.now(),t=Be){if(!Sr(e))return!1;let n=lo(e),o=_(n.workerJsonPath,void 0);if(o?.status==="running"&&Z(o.pid))return!0;let s=ve(n.heartbeatPath);if(s.lastHeartbeatAt){let i=r-Date.parse(s.lastHeartbeatAt);if(Number.isFinite(i)&&i>=0&&i<t)return!0}return!!(co(n.stdoutPath,r,t)||co(n.heartbeatPath,r,t))}function Ua(e,r=Date.now(),t=Be){for(let n of Ma(e))if(Ta(fe.join(e,"workers",n),r,t))return!0;return!1}function fo(e,r=Date.now()){let t=new Set,n=G(e);for(let o of Na(n)){let s=fe.join(n,o);Ua(s,r)&&t.add(`${e}\0${o}`)}return t}b();function vt(e,r=Date.now(),t=Be){let n=ve(e.heartbeatPath);if(!n.lastHeartbeatAt)return!1;let o=r-Date.parse(n.lastHeartbeatAt);return Number.isFinite(o)&&o>=0&&o<t}function vr(e,r=Date.now(),t=Be){return Z(e.pid)?!0:vt(e,r,t)}function Ba(e,r){return r?r.runTerminalCache.derive(e.run):me(e.run)}function J(e,r=Date.now()){return vr(e.worker,r)}function _t(e,r){return pe.has(e.run.status)?!1:Ba(e,r)!==null}function go(e,r,t=Date.now()){if(J(e,t))return!0;if(pe.has(e.run.status)||_t(e,r))return!1;let n=Ue(e);return ae(n)?!1:!!J(e,t)}lr();ue();function ho(e,r){if(!(typeof e.worker.completionBlocker=="string"?e.worker.completionBlocker.trim():""))return!1;if(J(e))return!0;let n=r??Ue(e);return!!(!ae(n)||Te(n)||D(n.changedFiles).length>0||_e({finalResult:n.finalResult,changedFiles:n.changedFiles,gitAncestry:n.gitAncestry,prUrl:de(n.finalResult)}).blocked)}F();b();import{existsSync as Ro,mkdirSync as Ka,writeFileSync as ko}from"node:fs";import _r from"node:path";function yo(e,r,t){return _r.join(e,"salvage",v(r),v(t))}function bo(e){return Ro(_r.join(yo(e.harnessRoot,e.runId,e.workerName),"evidence.json"))}function So(e){let r=yo(e.harnessRoot,e.indexed.runId,e.indexed.workerName);Ka(r,{recursive:!0});let t=_r.join(r,"salvage.patch"),n=!1;if(Ro(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()&&(ko(t,a.endsWith(`
4
+ `):""}function Z(e){if(!e)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Hn(e){let r=null,n=-1/0;for(let t of e){if(!t)continue;let o=Date.parse(t);Number.isFinite(o)&&o>n&&(n=o,r=t)}return r}function Gr(e){return Math.max(0,Math.round((Date.now()-e)/1e3))}var b=f(()=>{"use strict"});var Ns,rl,Ws,nl,Ln=f(()=>{"use strict";Ns=["ANTHROPIC_API_KEY","ANALYST_API_KEY","RECRUITER_API_KEY","AUTH_SECRET","NEXTAUTH_SECRET","DATABASE_URL","PRODUCTION_DATABASE_URL","KYNVER_PRODUCTION_DATABASE_URL","REDIS_URL","GOOGLE_CLIENT_SECRET","GITHUB_CLIENT_SECRET","KYNVER_API_KEY","KYNVER_SERVICE_SECRET","KYNVER_RUNTIME_SECRET","KYNVER_CRON_SECRET","OPENCLAW_CRON_SECRET","QSTASH_TOKEN","QSTASH_CURRENT_SIGNING_KEY","QSTASH_NEXT_SIGNING_KEY","TOOL_SECRETS_KEK","TOOL_EXECUTOR_DISPATCH_SECRET","CLOUDFLARE_API_TOKEN","STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_IDENTITY_WEBHOOK_SECRET","VOYAGE_API_KEY","PERPLEXITY_API_KEY","FRED_API_KEY","FMP_API_KEY","CURSOR_API_KEY","MEMORY_CONTENT_KEK","LLM_BYOK_KEK","KYNVER_COMMAND_AUTH_KEY","KYNVER_INSTRUCTION_BUNDLE_KEY","KYNVER_MEMORY_LEDGER_KEY","KYNVER_JWKS_PRIVATE_KEY_JWK"],rl=new Set(Ns),Ws=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN"],nl=new Set(Ws)});import{spawnSync as $n}from"node:child_process";function ke(e,r,n={}){let t=$n("git",r,$r({cwd:e,encoding:"utf8"}));if(t.status!==0&&!n.allowFailure){let o=`git ${r.join(" ")} failed: ${t.stderr||t.stdout}`;if(n.throwError)throw new Error(o);jr(o)}return t.stdout||""}function Pe(e){return ke(e,["status","--short"],{allowFailure:!0}).split(`
5
+ `).map(r=>r.trim()).filter(Boolean)}function w(e,r){try{let n=$n("git",r,$r({cwd:e,encoding:"utf8"}));return{status:n.status,stdout:n.stdout||"",stderr:n.stderr||"",error:n.error?n.error.message:null}}catch(n){return{status:null,stdout:"",stderr:"",error:n.message}}}function jn(e,r,n){let t=w(e,["merge-base","--is-ancestor",r,n]);return t.status===0?{isAncestor:!0,error:null}:t.status===1?{isAncestor:!1,error:null}:{isAncestor:null,error:t.error||t.stderr||t.stdout||`git exited ${t.status}`}}function ze(e,r="origin/main"){let n=typeof r=="string"?{base:r}:r,t=n.baseCommit?.trim()||n.base?.trim()||"origin/main",o=n.baseCommit?.trim()||null;if(!e)return Yr(t,"missing worktree path");let s=w(e,["rev-parse","HEAD"]);if(s.status!==0)return Yr(t,s.error||s.stderr||s.stdout||"failed to resolve HEAD");let i;if(o)i=o;else{let m=w(e,["rev-parse",t]);if(m.status!==0)return Yr(t,m.error||m.stderr||m.stdout||`failed to resolve ${t}`,s.stdout.trim());i=m.stdout.trim()}let a=s.stdout.trim();if(a===i)return{checked:!0,base:t,head:a,baseHead:i,baseIsAncestorOfHead:!0,headIsAncestorOfBase:!0,relation:"synced"};let u=jn(e,i,a),l=jn(e,a,i),c=u.error||l.error||void 0;if(u.isAncestor==null||l.isAncestor==null)return{checked:!1,base:t,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:t,head:a,baseHead:i,baseIsAncestorOfHead:u.isAncestor,headIsAncestorOfBase:l.isAncestor,relation:d,...c?{error:c}:{}}}function Yr(e,r,n=null){return{checked:!1,base:e,head:n,baseHead:null,baseIsAncestorOfHead:null,headIsAncestorOfBase:null,relation:"unknown",error:r}}var F=f(()=>{"use strict";b();Ln()});import{homedir as Gn}from"node:os";import Yn from"node:path";function Ms(e){return e==="~"?Gn():e.startsWith("~/")||e.startsWith("~\\")?Yn.join(Gn(),e.slice(2)):e}function Je(e){return Yn.resolve(Ms(e))}var Re=f(()=>{"use strict"});var Xe=f(()=>{"use strict";F();Re()});function te(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 qe(e,r){return e[r]?.trim()||null}function Vn(e){let r=e?.split(":")[0]?.trim();return r?te(r):null}function ye(e=process.env,r={}){let n=[],t=Vn(r.boxId),o=Vn(qe(e,"KYNVER_BOX_ID")),s=r.boxKind?.trim();if(s)return t&&t!==te(s)&&n.push(`config.boxId=${r.boxId} conflicts with boxKind=${s}; using explicit boxKind=${s}`),{boxKind:te(s),source:"config",slugInferenceBlocked:!1,warnings:n};let i=qe(e,"KYNVER_BOX_KIND");if(i)return o&&o!==te(i)&&n.push(`KYNVER_BOX_ID=${qe(e,"KYNVER_BOX_ID")} conflicts with KYNVER_BOX_KIND=${i}; using explicit KYNVER_BOX_KIND=${i}`),{boxKind:te(i),source:"env",slugInferenceBlocked:!1,warnings:n};if(t)return{boxKind:t,source:"config",slugInferenceBlocked:!1,warnings:n};if(o)return{boxKind:o,source:"env",slugInferenceBlocked:!1,warnings:n};let a=qe(e,"KYNVER_AGENT_OS_SLUG");return a&&n.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:n}}var oe=f(()=>{"use strict"});function Vr(e,r){return e==="forge"?4:Math.max(1,r)}function Ze(e,r){return e==="forge"?Math.min(Math.max(1,r),4):Math.max(1,r)}var Qe=f(()=>{"use strict"});var zn=f(()=>{"use strict"});import{existsSync as Ts,readFileSync as Us,statfsSync as Bs}from"node:fs";function zr(){if(process.platform!=="linux")return!1;for(let e of["/proc/sys/kernel/osrelease","/proc/version"])try{if(!Ts(e))continue;let r=Us(e,"utf8");if(/microsoft|wsl/i.test(r))return!0}catch{}return!1}function Jn(e={}){if(!(e.forceWsl===void 0?zr():e.forceWsl))return null;let n=e.wslHostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||be,t=e.wslHostFreeWarnBytes??Ks,o=e.wslHostFreeCriticalBytes??Fs,s=e.statfs??Bs,i;try{i=s(n)}catch(R){return{ok:!1,path:n,freeBytes:0,totalBytes:0,usedPercent:100,warnBelowBytes:t,criticalBelowBytes:o,reason:`Windows host disk probe failed at ${n}: ${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<t,d=a<o,m=!c&&!d,g=(a/(1024*1024*1024)).toFixed(1),p=null;return m||(p=`Windows host disk ${n} at ${d?"critical":"warning"}: ${g} GiB free (<${(d?o:t)/1024/1024/1024} GiB); WSL VHDX cannot grow safely. ${Hs()}`),{ok:m,path:n,freeBytes:a,totalBytes:u,usedPercent:l,warnBelowBytes:t,criticalBelowBytes:o,reason:p,probeError:null}}function Hs(){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 Ks,Fs,be,Jr=f(()=>{"use strict";Ks=25*1024*1024*1024,Fs=12*1024*1024*1024,be="/mnt/c"});import{execFileSync as Xn}from"node:child_process";import{existsSync as rr,readFileSync as qn,readdirSync as Ls,statSync as js}from"node:fs";import Xr from"node:path";function er(e,r){let n=process.env[e];if(!n)return r;let t=Number(n);return Number.isFinite(t)?t:r}function Zn(){let e=process.env.KYNVER_WSL_WIN_USER?.trim();if(e)return e;try{let t=Xn("cmd.exe",["/c","echo","%USERNAME%"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(t&&t!=="%USERNAME%"&&!t.includes("%"))return t}catch{}let r=process.env.USER?.trim()||process.env.LOGNAME?.trim(),n=process.env.KYNVER_WSL_HOST_MOUNT?.trim()||be;return r&&rr(Xr.join(n,"Users",r))?r:null}function zs(e={}){let r=e.crashDumpDir?.trim()||process.env.KYNVER_WSL_CRASH_DUMP_DIR?.trim();if(r)return r;let n=e.hostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||be,t=e.windowsUser??Zn();return t?`${n.replace(/\\/g,"/").replace(/\/$/,"")}/Users/${t}/AppData/Local/Temp/wsl-crashes`:null}function Js(e){let r=/^wsl-crash-\d+-(\d+)-(.+)-(\d+)\.dmp$/i.exec(e);if(!r)return{executableHint:null,signal:null,pid:null};let n=Number(r[1]),t=r[2]??"",o=Number(r[3]),s=t.split("_").filter(Boolean);return{executableHint:s.length>0?s[s.length-1]:null,signal:Number.isFinite(o)?o:null,pid:Number.isFinite(n)?n:null}}function Xs(){try{if(rr("/proc/sys/kernel/core_pattern"))return qn("/proc/sys/kernel/core_pattern","utf8").trim()}catch{}try{return Xn("sysctl",["-n","kernel.core_pattern"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function qs(e){return!!(e&&/wsl-capture-crash/i.test(e))}function Zs(e,r=be){let n=Xr.join(r,"Users",e,".wslconfig");if(!rr(n))return{maxCrashDumpCount:null,crashDumpFolder:null};let t;try{t=qn(n,"utf8")}catch{return null}let o=null,s=null;for(let i of t.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 Qs(e){if(!rr(e))return[];let r=Ls(e,{withFileTypes:!0}),n=[];for(let t of r){if(!t.isFile()||!t.name.toLowerCase().endsWith(".dmp"))continue;let o=Xr.join(e,t.name);try{let s=js(o),i=Js(t.name);n.push({name:t.name,path:o,bytes:s.size,mtimeMs:s.mtimeMs,executableHint:i.executableHint,signal:i.signal,pid:i.pid})}catch{}}return n.sort((t,o)=>o.mtimeMs-t.mtimeMs),n}function Se(e={}){if(!(e.forceWsl===void 0?zr():e.forceWsl))return null;let n=e.hostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||be,t=e.windowsUser??Zn(),o=e.warnBelowBytes??er("KYNVER_WSL_CRASH_DUMP_WARN_BYTES",$s),s=e.criticalBelowBytes??er("KYNVER_WSL_CRASH_DUMP_CRITICAL_BYTES",Gs),i=e.warnCount??er("KYNVER_WSL_CRASH_DUMP_WARN_COUNT",Ys),a=e.criticalCount??er("KYNVER_WSL_CRASH_DUMP_CRITICAL_COUNT",Vs),u=(e.readCorePattern??Xs)(),l=qs(u),c=null;t&&(c=(e.readWslConfig??Zs)(t,n));let d=c?.maxCrashDumpCount??null,m=d===-1,g=zs({hostMount:n,windowsUser:t,crashDumpDir:e.crashDumpDir});if(!g)return{ok:!0,path:null,windowsUser:t,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??Qs)(g)}catch(P){return{ok:!1,path:g,windowsUser:t,dumpCount:0,totalBytes:0,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:[],executables:[],corePattern:u,wslCaptureEnabled:l,maxCrashDumpCount:d,dumpsDisabledInWslConfig:m,reason:`WSL crash dump probe failed at ${g}: ${P.message}`,probeError:P.message}}let R=p.reduce((P,h)=>P+h.bytes,0),S=p.length,y=[...new Set(p.map(P=>P.executableHint).filter(P=>!!P))],A=R>=s,j=R>=o,B=S>=a,Le=S>=i,re=!(A||B||j||Le),ne=null;if(!re){let P=A||B?"critical":"warning",h=(R/1024**3).toFixed(1),q=y.length>0?y.join(", "):"unknown";ne=`WSL crash dumps ${P}: ${S} file(s), ${h} GiB at ${g} (executables: ${q}). `+ei({wslCaptureEnabled:l,dumpsDisabledInWslConfig:m})}return{ok:re,path:g,windowsUser:t,dumpCount:S,totalBytes:R,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:p,executables:y,corePattern:u,wslCaptureEnabled:l,maxCrashDumpCount:d,dumpsDisabledInWslConfig:m,reason:ne,probeError:null}}function ei(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 $s,Gs,Ys,Vs,nr=f(()=>{"use strict";Jr();$s=5*1024*1024*1024,Gs=10*1024*1024*1024,Ys=2,Vs=4});import{statfsSync as ri}from"node:fs";function tr(e={}){let r=e.diskPath?.trim()||"/",n=e.diskFreeWarnBytes??ni,t=e.diskFreeCriticalBytes??ti,o=e.diskMaxUsedPercent??oi,s=e.diskHardMaxUsedPercent??si,i=ri(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<n,d=a<t,m=a<n*2,g=m&&l>o,p=m&&l>s,R=!c&&!d&&!g&&!p,S=e.skipWslHostCheck?null:Jn(e.wslHost),y=e.skipWslCrashDumpCheck?null:Se(e.wslCrashDumps),A=R&&(S?S.ok:!0)&&(y?y.ok:!0),j=null;return A||(j=[d?`free space below critical ${t} bytes`:null,c?`free space below warning ${n} bytes`:null,p?`used percent above hard cap ${s}%`:null,g?`used percent above cap ${o}%`:null,S&&!S.ok?S.reason:null,y&&!y.ok?y.reason:null].filter(Boolean).join("; ")),ii({ok:A,path:r,freeBytes:a,totalBytes:u,usedPercent:l,warnBelowBytes:n,criticalBelowBytes:t,maxUsedPercent:o,hardMaxUsedPercent:s,reason:j,wslHost:S,wslCrashDumps:y?{ok:y.ok,path:y.path,dumpCount:y.dumpCount,totalBytes:y.totalBytes,executables:y.executables,wslCaptureEnabled:y.wslCaptureEnabled,dumpsDisabledInWslConfig:y.dumpsDisabledInWslConfig,reason:y.reason,probeError:y.probeError}:null})}function ii(e){let r=process.env.KYNVER_DISPATCH_DISK_GATE_FORCE?.trim().toLowerCase();return r?r==="ok"||r==="open"||r==="none"?e.ok?e:{...e,ok:!0,reason:`disk gate forced open by KYNVER_DISPATCH_DISK_GATE_FORCE (suppressed: ${e.reason??"no reason"})`}:r==="block"||r==="pressured"?{...e,ok:!1,reason:`disk gate forced closed by KYNVER_DISPATCH_DISK_GATE_FORCE${e.reason?` (underlying: ${e.reason})`:""}`}:e:e}var ni,ti,oi,si,or=f(()=>{"use strict";nr();Jr();ni=30*1024*1024*1024,ti=15*1024*1024*1024,oi=80,si=90});import{existsSync as ai,readdirSync as ui,statSync as li}from"node:fs";import qr from"node:path";function sr(){return et()}function Zr(){let{runsDir:e}=sr();return Qn(e)}function ir(e){return Qn(G(e))}function ci(e){try{return li(e).isDirectory()}catch{return!1}}function Qn(e){if(!ai(e))return[];let r=[];for(let n of ui(e,{withFileTypes:!0})){if(n.name==="runs")continue;let t=qr.join(e,n.name);if(!ci(t))continue;let o=_(qr.join(t,"run.json"),void 0);o?.id&&r.push(o)}return r}function Qr(e){let{runsDir:r}=sr();Kn(qr.join(en(r,e.id),"run.json"),e)}function Ie(e){let{harnessRoot:r}=sr();return Oe(r,e)}function Oe(e,r){return en(G(e),v(r))}var se=f(()=>{"use strict";Y();b()});import{existsSync as di,readdirSync as pi}from"node:fs";import mi from"node:path";function rn(e){let r=new Set;for(let t of Object.keys(e.workers||{}))r.add(v(t));let n=mi.join(Ie(e.id),"workers");if(!di(n))return[...r];for(let t of pi(n,{withFileTypes:!0}))t.isDirectory()&&r.add(v(t.name));return[...r]}var nn=f(()=>{"use strict";se();b()});function tn(e){let r=e.trim();if(!r.startsWith("{"))return null;try{let n=JSON.parse(r);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{return null}return null}function rt(e){let r=e.trim();if(!r)return null;let n=tn(r);if(n)return n;let t=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let u=tn(s[1]??"");u&&t.push(u)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let u=tn(r.slice(i,a+1));u&&t.push(u)}return t.length>0?t[t.length-1]:null}function nt(e){let r=e.finalResult??e.final_result;if(r!=null)return typeof r=="string"?rt(r)??(r.trim()||null):r;let n=typeof e.summary=="string"?e.summary.trim():"";if(!n)return null;let t=rt(n);return t||n}var tt=f(()=>{"use strict"});import{existsSync as fi,readFileSync as gi}from"node:fs";function ot(e){return e==="complete"}function st(e){return ot(e.lastHeartbeatPhase)?e.terminalFinalResult!==void 0&&e.terminalFinalResult!==null?e.terminalFinalResult:e.lastHeartbeatSummary?.trim()||"completed":null}function ve(e){let r={heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,terminalFinalResult:null,heartbeatBlocker:null,timestampAnomalies:[],lastBoxResourceSnapshot:null,lastPrEvidence:[]};if(!fi(e))return r;let n=Date.now()+hi,t=new Date(n).toISOString(),o=gi(e,"utf8").split(`
6
+ `).filter(Boolean);for(let s of o){let i=Ge(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>n?r.timestampAnomalies.push({kind:"future_heartbeat_timestamp",observedAt:u,clampedTo:t}):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)),ot(r.lastHeartbeatPhase)&&(r.terminalFinalResult=nt(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 hi,ar=f(()=>{"use strict";tt();b();hi=6e4});function at(e){return e?(e.split("/").pop()??e).replace(/\.exe$/i,"").toLowerCase():null}function ur(e){if(!e)return[];let r=[],n="",t,o=!1;for(let s of e){if(o){n+=s,o=!1;continue}if(s==="\\"){o=!0;continue}if(t){s===t?t=void 0:n+=s;continue}if(s==='"'||s==="'"){t=s;continue}if(/\s/.test(s)){n&&(r.push(n),n="");continue}n+=s}return n&&r.push(n),r}function ut(e){let r=at(e[0]);return!!(r&&ki.has(r))}function yi(e){let r=e.trim();return r.includes("/")?r.split("/").pop()??r:r}function bi(e){if(!e||e.includes("*"))return null;let r=yi(e);return!r||r.includes("/")?null:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(r)?r:null}function lt(e){return!e||e.includes("/")||e.includes("*")?!1:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(e)}function on(e){if(!e)return!1;let r=e.trim();return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")}function Si(e){if(!e.startsWith("--glob="))return e;let r=e.slice(7);return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")?`--glob=${r}/**`:e}function vi(e){let r=[];for(let n=1;n<e.length;n+=1){let t=e[n];if(t){if(t==="--"){r.push(...e.slice(n+1));break}if(t.startsWith("-")){if(t.includes("="))continue;it.has(t)&&(n+=1);continue}r.push(t)}}return r}function _i(e){let r=!1,n=e.map((o,s)=>{let i=Si(o),a=e[s-1];return a&&it.has(a)&&o.startsWith("!")&&!o.includes("/")&&!o.endsWith("/**")&&(i=`${o}/**`),i!==o&&(r=!0),i}),t=vi(n);if(t.length===2){let[o,s]=t;if(on(s))return{argv:[n[0]??"rg",o,"-g",`${s}/**`,"."],changed:!0};let i=bi(s);if(i)return{argv:[n[0]??"rg","-g",i,o,"."],changed:!0}}return r&&t.length===1?{argv:[...n,"."],changed:!0}:{argv:n,changed:r}}function ct(e){for(let r=1;r<e.length;r+=1){let n=e[r];if(n&&(n==="-c"||n==="-lc"||n==="-cl"||/^-[a-zA-Z]*c[a-zA-Z]*$/u.test(n)))return r+1}return-1}function lr(e){let r=e.trim();if(!r)return{command:r,wrapped:!1};let n=ur(r);if(!n.length)return{command:r,wrapped:!1};let t=at(n[0]);if(!t||!Ri.has(t))return{command:r,wrapped:!1};let o=ct(n);if(o<0||o>=n.length)return{command:r,wrapped:!1};let s=n.slice(o).join(" ").trim();return s?{command:s,wrapped:!0}:{command:r,wrapped:!1}}function xi(e,r){let n=e.trim(),t=ur(n),o=ct(t);if(o<0)return r;let s=t.slice(0,o).join(" "),i=r.includes("'")?`"${r.replace(/"/g,'\\"')}"`:`'${r}'`;return`${s} ${i}`}function Ci(e){let r=e.trim(),n=lr(r),t=ur(n.command);if(!t.length||!ut(t))return{segment:r,changed:!1};let o=_i(t);if(!o.changed)return{segment:r,changed:!1};let s=o.argv.join(" ");return n.wrapped?{segment:xi(r,s),changed:!0}:{segment:s,changed:!0}}function sn(e){let r=e.trim();if(!r)return{command:r,changed:!1};let n=r.includes("&&")?" && ":r.includes("||")?" || ":"; ",t=r.split(/\s*(?:&&|\|\||;)\s*/u),o=!1,s=t.map(i=>{let a=Ci(i);return a.changed&&(o=!0),a.segment});return o?{command:s.join(n),changed:!0}:{command:r,changed:!1}}function dt(e){let r=lr(e).command,n=ur(r.trim());return n.length&&ut(n)?!0:/\b(rg|ripgrep)\b/i.test(r)}function pt(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 n=e.match(/^search\s+"(.+)"\s+in\s+(.+)$/iu);return n?{pattern:n[1],target:n[2]?.trim()}:{}}function Ei(e){let{pattern:r,target:n}=pt(e);return r?on(n)?{kind:"rg_exclude_syntax",pattern:r,target:n}:lt(n)?{kind:"bad_scope",pattern:r,target:n}:{kind:"not_repo_search",pattern:r,target:n}:{kind:"not_repo_search"}}function wi(e){let{pattern:r,target:n}=pt(e);if(!r)return null;if(on(n)){let t=`${n.trim()}/**`;return{command:`rg "${r}" -g '${t}' .`,changed:!0}}return n&&lt(n)?{command:`rg -g ${n} "${r}" .`,changed:!0}:null}function Ai(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 Pi(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 an(e){let r=e.meta?.trim()||(e.command?Pi(e.command):null)||null;if(r){let n=Ei(r),t=Ai(n);if(t)return t;let o=wi(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 n=sn(e.command);if(n.changed)return`Ripgrep scope may be invalid. Retry with: \`${n.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 ki,Ri,it,mt=f(()=>{"use strict";ki=new Set(["rg","ripgrep","grep"]),Ri=new Set(["bash","sh","dash","zsh"]),it=new Set(["-e","--regexp","-f","--file","-m","--max-count","-A","--after-context","-B","--before-context","-C","--context","-g","--glob","--iglob"])});function De(e,r=200){let n=e.replace(/\s+/g," ").trim();return n.length>r?`${n.slice(0,r-1)}\u2026`:n}function Di(e){let r=e.trim();if(!r)return null;if(r.startsWith("{"))try{return JSON.parse(r)}catch{}let n=r.indexOf("{"),t=r.lastIndexOf("}");if(n>=0&&t>n)try{return JSON.parse(r.slice(n,t+1))}catch{return null}return null}function Ne(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ni(e){let r=e.metadata;if(!Ne(r))return null;let n=r.vulnerabilities;if(!Ne(n))return null;let t=s=>typeof n[s]=="number"?n[s]:0,o={info:t("info"),low:t("low"),moderate:t("moderate"),high:t("high"),critical:t("critical"),total:t("total")};return typeof n.total!="number"&&!o.critical&&!o.high&&!o.moderate&&!o.low&&!o.info?null:o}function Wi(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 n=r.length?r.join(", "):"see report";return`npm audit: ${e.total} vulnerabilit${e.total===1?"y":"ies"} (${n}) \u2014 remediation required`}function Mi(e,r){let n=e.error;if(Ne(n)){let s=typeof n.summary=="string"?n.summary.trim():"",i=typeof n.code=="string"?n.code.trim():"";if(s)return i?`${i}: ${s}`:s;if(i)return i}let t=typeof e.message=="string"?e.message.trim():"";if(t)return t;let o=r.trim();return o?De(o.split(`
7
+ `).find(Boolean)??o,160):"npm audit failed"}function Ti(e){let r=`${e.stdout}
8
+ ${e.stderr}`.trim(),n=Di(r);if(!n||!Ne(n)){let o=De(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(Ne(n.error))return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit command failed: ${Mi(n,e.stderr)}`};let t=Ni(n);return t?e.exitCode===0&&t.total===0?{kind:"success",exitCode:0,summary:"npm audit: no vulnerabilities reported",audit:t}:{kind:"audit_findings",exitCode:e.exitCode,summary:Wi(t),audit:t}:{kind:"command_failure",exitCode:e.exitCode,summary:"npm audit failed: JSON response missing vulnerability metadata",parseError:"missing_metadata"}}function Ui(e){return Ii.test(e)}function Bi(e){let r=lr(e).command;return ft.test(e)||ft.test(r)||dt(e)}function Ki(e){let r=an({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 t=(e.stderr||e.interleaved).trim();if(t&&Oi.test(t)){let i=De(t,160);return{kind:"command_failure",exitCode:1,summary:r??`ripgrep failed (exit 1): ${i}`}}let o=sn(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 n=De(e.interleaved||e.stdout||e.stderr||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:r??`ripgrep failed (exit ${e.exitCode}): ${n}`}}function gt(e){let r=e.stdout??"",n=e.stderr??"",t=e.interleavedOutput??"";if(Ui(e.command)){let i=r.trim()||t.trim()||n.trim();return Ti({exitCode:e.exitCode,stdout:i,stderr:n})}if(Bi(e.command))return Ki({command:e.command,exitCode:e.exitCode,stdout:r,stderr:n,interleaved:t});let o=an({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=De(t||r||n||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:`command failed (exit ${e.exitCode}): ${s}`}}var Ii,ft,Oi,ht=f(()=>{"use strict";mt();Ii=/\bnpm\s+audit\b/i,ft=/\b(rg|ripgrep)\b/i,Oi=/\b(error|invalid|unknown|panic|not found)\b/i});import{existsSync as Fi,readFileSync as Hi}from"node:fs";function Li(e){let r=e.timestamp_ms;return e.timestamp||e.ts||(r?new Date(r).toISOString():void 0)}function ji(e){if(!e)return null;for(let r of Object.keys(e))if(r.endsWith("ToolCall")){let n=r.slice(0,-8);return n.length?n:r}return null}function $i(e,r){e.finalResult=r.result||r.subtype||r.terminal_reason||"completed",r.is_error&&(e.error=String(r.result||r.api_error_status||"stream result error"))}function _e(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function Gi(e){let r=e.usage;return r&&typeof r=="object"&&!Array.isArray(r)?r:null}function Yi(e){if(typeof e.model=="string"&&e.model.trim())return e.model.trim();let r=e.modelUsage;if(r&&typeof r=="object"&&!Array.isArray(r)){let n=Object.keys(r)[0];if(n?.trim())return n.trim()}}function Vi(e,r){let n=Gi(r);if(!n)return;let t=_e(n.input_tokens)??_e(n.inputTokens)??_e(n.prompt_tokens),o=_e(n.output_tokens)??_e(n.outputTokens)??_e(n.completion_tokens);if(t===void 0&&o===void 0)return;let s=Yi(r)??e.usage?.model;e.usage={...t!==void 0?{inputTokens:t}:{},...o!==void 0?{outputTokens:o}:{},...s?{model:s}:{}}}function zi(e){if(e.type!=="tool_call"||e.subtype!=="completed")return null;let n=(e.tool_call&&typeof e.tool_call=="object"&&!Array.isArray(e.tool_call)?e.tool_call:null)?.shellToolCall;if(!n||typeof n!="object"||Array.isArray(n))return null;let t=n,o=t.args,s=o&&typeof o=="object"&&!Array.isArray(o)&&typeof o.command=="string"?String(o.command):"",i=t.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 Ji(e,r){r.kind==="success"||r.kind==="search_no_matches"||(e.lastShellOutcome=r)}function kt(e){let r={firstEventAt:null,lastEventAt:null,currentTool:null,finalResult:null,error:null,lastShellOutcome:null,usage:null};if(!Fi(e))return r;let n=Hi(e,"utf8").split(`
9
+ `).filter(Boolean);for(let t of n){let o=Ge(t);if(!o)continue;let s=Li(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=ji(a);u&&(r.currentTool=u)}let i=zi(o);i&&Ji(r,gt({command:i.command,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr,interleavedOutput:i.interleaved})),o.type==="result"&&$i(r,o),Vi(r,o)}return r}var Rt=f(()=>{"use strict";ht();b()});function qi(e,r=240){let n=e.replace(/\s+/g," ").trim();return n.length>r?`${n.slice(0,r-1)}\u2026`:n}function yt(e){let r=(e??"").trim();if(!r)return null;for(let n of Xi)if(n.test.test(r))return{blocked:!0,reason:`${n.label}: ${qi(r)}`};return null}var Xi,bt=f(()=>{"use strict";Xi=[{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 St(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function Zi(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 Qi(e){return!e?.checked||e.headIsAncestorOfBase!==!1?null:St(e.head)}function ea(e,r,n){let t=["exited_with_changes_salvage"];if((e==="uncommitted"||e==="both")&&t.push(`${r} uncommitted change${r===1?"":"s"} with no final result`),(e==="committed_ahead"||e==="both")&&n){let o=n.length>12?n.slice(0,12):n;t.push(`commit ${o} ahead of base with no final result`)}return t.push("review worktree \u2014 commit, open a PR, or run a salvage worker before discarding"),t.join(": ")}function vt(e){if(e.alive||Zi(e.finalResult))return null;let r=(e.changedFiles??[]).filter(i=>i.trim()).length,n=St(e.headCommit)??Qi(e.gitAncestry),t=r>0,o=!!n;if(!t&&!o)return{kind:"none",salvageable:!1,uncommittedCount:0,headCommit:null,attentionReason:"process exited without a final result"};let s=t&&o?"both":t?"uncommitted":"committed_ahead";return{kind:s,salvageable:!0,uncommittedCount:r,headCommit:n,attentionReason:ea(s,r,n)}}var _t=f(()=>{"use strict"});function We(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function ra(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="boolean"?e:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function na(e){if(We(e.headCommit)||We(e.prUrl)||We(e.artifactBundlePath)||We(e.patchPath))return!0;let r=e.gitAncestry;return!!(r?.checked&&r.headIsAncestorOfBase===!1&&We(r.head))}function xe(e){return ra(e.finalResult)?e.changedFiles.length===0?{blocked:!1}:na(e)?{blocked:!0,detail:`Worktree has ${e.changedFiles.length} uncommitted change(s); commit or discard before landing`}:{blocked:!0,reason:"dirty_worktree_no_pr",detail:`Worktree has ${e.changedFiles.length} uncommitted change(s) with no commit or PR; commit, open a PR, or discard before landing`}:{blocked:!1}}function xt(e){if(e.blocked)return e.detail??e.reason??"dirty_worktree_no_pr"}var cr=f(()=>{"use strict"});function un(e){let r=e.trim();if(!r.startsWith("{"))return null;try{let n=JSON.parse(r);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{return null}return null}function Ct(e){let r=e.targetPrReconciliation??e.target_pr_reconciliation??e.targetPrs??e.target_prs;return Array.isArray(r)?r.length:0}function dr(e){let r=e.trim();if(!r)return null;let n=un(r);if(n)return n;let t=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let c=un(s[1]??"");c&&t.push(c)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let c=un(r.slice(i,a+1));c&&t.push(c)}if(t.length===0)return null;let u=t[t.length-1],l=Ct(u);for(let c of t){let d=Ct(c);d>l&&(u=c,l=d)}return u}var ln=f(()=>{"use strict"});function Et(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 wt(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function ta(e){return new Set(e.map(r=>wt(Et(r)??r)).filter(Boolean))}function At(e,r,n){let t=Et(e)??e;if(!t)return"unrelated";let o=wt(t);return ta(r).has(o)?"contract":n?(n.outcome==="skipped"||n.outcome==="blocked")&&n.reason?.trim()?"support":(n.outcome==="merged","unrelated"):"unrelated"}var Pt=f(()=>{"use strict"});function Ce(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function oa(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"?Object.keys(e).length>0:!0}function ie(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`https://github.com/${r[1]}/pull/${r[2]}`:Ce(e)}function pr(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function It(e){let r=null;if(typeof e=="string"){let o=dr(e);o&&(r=o)}else e&&typeof e=="object"&&!Array.isArray(e)&&(r=e);if(!r)return[];let n=r.targetPrReconciliation??r.target_pr_reconciliation;if(!Array.isArray(n))return[];let t=[];for(let o of n){if(!o||typeof o!="object"||Array.isArray(o))continue;let s=o,i=ie(String(s.prUrl??s.pr_url??"")),a=Ce(s.outcome);!i||a!=="merged"&&a!=="skipped"&&a!=="blocked"||t.push({prUrl:i,outcome:a,mergeCommit:Ce(s.mergeCommit??s.merge_commit),reason:Ce(s.reason)})}return t}function Ot(e,r){let n=[],t=ie(Ce(e.prUrl)??"");if(t&&n.push(t),r&&typeof r=="object"&&!Array.isArray(r)){let o=r,s=ie(String(o.prUrl??o.pr_url??""));s&&n.push(s)}return[...new Set(n)]}function Dt(e){let{contract:r,snapshot:n}=e,t=e.finalResult??n.finalResult;if(!r.landingOnly&&r.targetPrUrls.length===0&&!r.repairEnforceOriginalPr)return{blocked:!1};if(!oa(t))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?ie(Ce(r.targetPrUrl)??"")??(r.targetPrUrls.length===1?ie(r.targetPrUrls[0]):null):null;if(s){let d=Ot(n,t);if(!(t&&typeof t=="object"&&!Array.isArray(t)&&t.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=It(t).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=It(t),a=new Map(i.map(d=>[pr(d.prUrl),d])),u=new Set(r.targetPrUrls.map(d=>pr(ie(d)??d)).filter(Boolean)),l=Ot(n,t);if(r.landingOnly)for(let d of l){let m=a.get(pr(d)),g=At(d,r.targetPrUrls,m);if(!(g==="contract"||g==="support"))return u.size>0?{blocked:!0,reason:"unrelated_implementation_pr",detail:`Landing-only worker attached unrelated PR ${d}`}:{blocked:!0,reason:"unrelated_implementation_pr",detail:"Landing-only worker must not open new implementation PRs"}}if(r.targetPrUrls.length===0)return{blocked:!1};let c=[];for(let d of r.targetPrUrls){let m=pr(ie(d)??d),g=a.get(m);if(!g){c.push(m);continue}g.outcome!=="merged"&&!g.reason?.trim()&&c.push(m)}return c.length>0?{blocked:!0,reason:c.every(d=>a.has(d))?"incomplete_target_pr_landing":"missing_target_pr_reconciliation",detail:`Target PR reconciliation incomplete: ${c.join(", ")}`}:{blocked:!1}}function Nt(e){if(e.blocked)return e.detail??e.reason}var Wt=f(()=>{"use strict";ln();Pt()});function aa(e){let r=Date.now();if(e.completionBlocker&&!Mt(e.completionBlocker))return{state:"blocked",reason:e.completionBlocker};if(e.finalResult){if(e.localOnly&&la(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=xe(o);if(s.blocked){let i=xt(s);return{state:"needs_attention",reason:s.reason?`landing blocked (${s.reason}): ${i}`:`landing blocked: ${i}`}}if(e.landingContract){let i=Dt({contract:e.landingContract,snapshot:o,finalResult:e.finalResult}),a=Nt(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(ua(e))return{state:"done",reason:"empty abandoned worker record"};let o=yt(e.error);if(o)return{state:"blocked",reason:o.reason};let s=vt({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 n=e.startedAt?Date.parse(e.startedAt):NaN;if(!e.firstEventAt&&e.stdoutBytes===0&&e.heartbeatBytes===0&&Number.isFinite(n)&&r-n>sa)return{state:"needs_attention",reason:`no first stream event ${Gr(n)}s after start`};let t=e.lastActivityAt?Date.parse(e.lastActivityAt):NaN;return Number.isFinite(t)&&r-t>ia?{state:"stale",reason:`no log/event/heartbeat activity for ${Gr(t)}s`}:{state:"ok",reason:"recent activity"}}function Mt(e){let r=e?.trim();return r?/completion acknowledged but board not advanced/i.test(r)&&/task already terminal/i.test(r):!1}function ua(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 la(e){let r=null;if(typeof e=="string"?r=dr(e):e&&typeof e=="object"&&!Array.isArray(e)&&(r=e),!r)return!1;let n=r.targetPrReconciliation??r.target_pr_reconciliation;return Array.isArray(n)?n.some(t=>!t||typeof t!="object"||Array.isArray(t)?!1:String(t.outcome??"").trim()==="merged"):!1}function ca(e,r,n){let t=e.completionSnapshot?.finalResult;return e.completionAckSource==="local-pr-merged-reconcile"&&t!==void 0&&t!==null?t:r||(t??st(n))}function Me(e,r={}){let n=kt(e.stdoutPath),t=ve(e.heartbeatPath),o=typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim().length>0,s=ca(e,n.finalResult,t),i=o?!1:Z(e.pid),a=Ye(e.stdoutPath),u=Ye(e.stderrPath),l=Ye(e.heartbeatPath),c=Pe(e.worktreePath),d=ze(e.worktreePath,{base:r.base,baseCommit:r.baseCommit}),m=Hn([n.lastEventAt,t.lastHeartbeatAt,Ve(e.stdoutPath),Ve(e.stderrPath),Ve(e.heartbeatPath)]),g=n.error||!i&&!s&&Fn(e.stderrPath,10).trim()||void 0,p=typeof e.completionBlocker=="string"&&e.completionBlocker.trim()?e.completionBlocker.trim():null,R=Mt(p)?null:p,S=e.repairTargetPrUrl?{landingOnly:!1,targetPrUrls:[e.repairTargetPrUrl],targetPrUrl:e.repairTargetPrUrl,repairEnforceOriginalPr:!0}:null,y=aa({alive:i,finalResult:s,firstEventAt:n.firstEventAt,stdoutBytes:a,stderrBytes:u,heartbeatBytes:l,lastActivityAt:m,heartbeatBlocker:t.heartbeatBlocker,startedAt:e.startedAt,error:g,changedFiles:c,gitAncestry:d,completionBlocker:R,landingContract:S,prUrl:e.repairTargetPrUrl??e.taskPrUrl??null,localOnly:e.localOnly===!0,taskId:e.taskId??null,agentOsId:e.agentOsId??null,reconcileReason:e.reconcileReason??null}),A=R||y.state==="blocked"?"blocked":o||y.state==="done"?"done":s?"exited":i?"running":"exited";return{runId:e.runId,worker:e.name,pid:e.pid,alive:i,status:A,attention:y,branch:e.branch,worktreePath:e.worktreePath,ownedPaths:e.ownedPaths,stdoutBytes:a,stderrBytes:u,heartbeatBytes:l,firstEventAt:n.firstEventAt,lastEventAt:n.lastEventAt,lastActivityAt:m,currentTool:o?null:n.currentTool,heartbeatCount:t.heartbeatCount,lastHeartbeatAt:t.lastHeartbeatAt,lastHeartbeatPhase:t.lastHeartbeatPhase,lastHeartbeatSummary:t.lastHeartbeatSummary,heartbeatBlocker:t.heartbeatBlocker,timestampAnomalies:t.timestampAnomalies,finalResult:s,error:g,changedFiles:c,gitAncestry:d,instructionPolicyFingerprint:e.instructionPolicyFingerprint??null,instructionPolicyEvidence:e.instructionPolicyEvidence??null,model:e.model??e.orchestrationAudit?.model??null,provider:e.provider??e.orchestrationAudit?.provider??null,usage:n.usage??null,boxKind:e.boxKind??null,boxId:e.boxId??null,runtimeId:e.runtimeId??null,personaSlug:e.personaSlug??null,dispatched:e.dispatched??null,localOnly:e.localOnly??null}}function ae(e){return!!(e.finalResult||e.alive===!1||e.status==="exited"||e.status==="done")}function Tt(e){return e.finalResult?e.attention.state==="needs_attention"||e.attention.state==="blocked":!1}var sa,ia,ue=f(()=>{"use strict";ar();Rt();bt();_t();F();cr();Wt();ln();b();sa=18e4,ia=6e5});var Ut=f(()=>{"use strict";ue()});function Bt(e,r={}){let n=r.perWorkerMemBytes??cn,t=r.memReserveBytes??dn,o=r.memUtilization??pn,s=Math.max(0,Math.floor(e*o)-t),i=Math.max(1,Math.floor(s/n));return Math.min(i,mr)}var cn,dn,pn,mr,Kt=f(()=>{"use strict";zn();ce();oe();Qe();fr();or();se();nn();Ut();b();cn=500*1024*1024,dn=4*1024*1024*1024,pn=.85,mr=64});function Te(e,r){let n=Number(e);return!Number.isFinite(n)||n<=0?r:Math.floor(n)}function mn(e){let r=e.config??{},n=e.env??process.env,t=Te(r.perWorkerMemBytes,cn),o=Te(r.memReserveBytes,dn),s=Math.min(1,Math.max(.1,Number(r.memUtilization)>0?Number(r.memUtilization):pn)),i=Bt(e.totalMemBytes,{perWorkerMemBytes:t,memReserveBytes:o,memUtilization:s});if(e.configuredMaxWorkersOverride!==void 0&&e.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:Te(e.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(r.maxConcurrentWorkers!==void 0&&r.maxConcurrentWorkers!==null){let l=Te(r.maxConcurrentWorkers,0)||null;if(l)return{configuredMaxWorkers:Math.min(l,mr),autoCap:i,workerCapSource:"config"}}let u=(n.KYNVER_MAX_WORKERS_INTENTIONAL==="1"||n.KYNVER_MAX_WORKERS_INTENTIONAL==="true")&&n.KYNVER_MAX_WORKERS&&Te(n.KYNVER_MAX_WORKERS,0)||null;return u?{configuredMaxWorkers:Math.min(u,mr),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var fr=f(()=>{"use strict";Kt()});import{homedir as da}from"node:os";import pa from"node:path";var Ft,fn=f(()=>{"use strict";Ft=pa.join(da(),".kynver",".env")});var Ht=f(()=>{"use strict"});var Lt=f(()=>{"use strict";Ht()});var jt=f(()=>{"use strict"});var gn=f(()=>{"use strict";Lt();jt()});var $t=f(()=>{"use strict"});var Gt=f(()=>{"use strict";$t()});var gr=f(()=>{"use strict";fn();Re();ce();gn();Gt()});var zt=f(()=>{"use strict";oe();oe()});var Jt=f(()=>{"use strict";fn();gn();gr()});import{existsSync as V,mkdirSync as fa,readdirSync as hr,renameSync as Xt,statSync as ga}from"node:fs";import z from"node:path";function Zt(e){try{return ga(e).isDirectory()}catch{return!1}}function ha(e){if(!V(e))return!0;for(let r of qt){let n=z.join(e,r);if(V(n)&&(!Zt(n)||hr(n).length>0))return!1}return!0}function ka(e){let r=z.join(e,"runs");if(!V(r)||!Zt(r))return!1;for(let n of hr(r,{withFileTypes:!0})){if(!n.isDirectory()||n.name==="runs")continue;let t=z.join(r,n.name,"run.json");if(_(t,void 0)?.id)return!0}return!1}function Ra(e){let r=z.join(e,"runs");if(!V(r))return!1;for(let n of hr(r,{withFileTypes:!0})){if(!n.isDirectory())continue;if(_(z.join(r,n.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function ya(e){let r=z.join(e,"ghost");return V(r)?!V(z.join(r,"runs")):Ra(e)}function Qt(e){return ka(e.sharedRoot)?ha(e.forgeRoot)?ya(e.sharedRoot)?{action:"blocked",blocker:"Forge legacy harness migration blocked: Ghost pool is co-hosted on this host (ghost namespace or ghost-attributed runs under ~/.kynver/harness). Drain in-flight Ghost runs from the shared root, or get operator sign-off for a fresh Forge cutover before enabling box-scoped isolation."}:{action:"migrate"}:{action:"none"}:{action:"none"}}function eo(e,r){fa(r,{recursive:!0});for(let n of qt){let t=z.join(e,n),o=z.join(r,n);if(V(t)){if(V(o)&&hr(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(V(o)){Xt(t,o);continue}Xt(t,o)}}}var qt,ro=f(()=>{"use strict";b();qt=["runs","worktrees"]});import{existsSync as E}from"node:fs";import{homedir as ba}from"node:os";import C from"node:path";function hn(e=process.env){return e.HOME?.trim()||ba()}function kn(e=process.env){return C.join(hn(e),".kynver","harness")}function kr(e){let r=C.resolve(Je(e.trim()));for(;Sa.has(C.basename(r));)r=C.dirname(r);return r}function va(e,r=process.env){return C.join(kn(r),e)}function _a(e=process.env){let r=kn(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 n=C.join(hn(e),no);return E(n)}function Rr(e){let r=e.env??process.env,n=r.KYNVER_HARNESS_ROOT?.trim()||r.OPUS_HARNESS_ROOT?.trim();if(n)return{harnessRoot:kr(n),source:"env"};let t=e.configuredHarnessRoot?.trim();if(t)return{harnessRoot:kr(t),source:"config"};let o=va(e.boxKind,r);if(E(C.join(o,"runs"))||E(o)&&!xa(o))return{harnessRoot:o,source:"box_scoped"};let i=kn(r);if(e.boxKind==="forge"){let a=Qt({sharedRoot:i,forgeRoot:o});if(a.action==="blocked")return{harnessRoot:o,source:"box_scoped",migrationBlocker:a.blocker};if(a.action==="migrate")return e.allowForgeLegacyMigration!==!1&&eo(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(e.boxKind==="ghost"&&_a(r)){if(E(C.join(i,"runs")))return{harnessRoot:i,source:"legacy_shared"};if(E(i)&&!E(C.join(i,"ghost"))&&!E(C.join(i,"forge")))return{harnessRoot:i,source:"legacy_shared"};let u=C.join(hn(r),no);if(E(u))return{harnessRoot:u,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function xa(e){if(!E(e))return!0;for(let r of["runs","worktrees"]){let n=C.join(e,r);if(E(n))return!1}return!0}var no,Sa,Rn=f(()=>{"use strict";Re();ro();no=C.join(".openclaw","harness");Sa=new Set(["runs","worktrees"])});import to from"node:os";function yr(e){return e?.trim()?e.trim():null}function Ca(e,r){let n=r.trim().toLowerCase()||"host";return`${e}-${n}`.replace(/[^a-z0-9._-]+/g,"-")}function Ea(e){return e.KYNVER_DISPATCH_STRICT_IDENTITY==="1"||e.KYNVER_DISPATCH_STRICT_IDENTITY==="true"||e.KYNVER_DAEMON_STRICT_IDENTITY==="1"||e.KYNVER_DAEMON_STRICT_IDENTITY==="true"}function br(e=le(),r=process.env,n={}){let t=ye(r,e),o=[...t.warnings],s=[],i=!!(e.boxKind?.trim()||yr(r.KYNVER_BOX_KIND)),a=n.strict===!0||Ea(r);if((n.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"),t.slugInferenceBlocked&&!i){let R="ambiguous box identity: KYNVER_AGENT_OS_SLUG is set without KYNVER_BOX_KIND or config.boxKind";a||n.requireExplicitBoxKind?s.push(R):o.push(`${R} \u2014 defaulting box kind to forge`)}let u=yr(e.runnerId),l=yr(r.KYNVER_RUNTIME_ID)??yr(r.OPENCLAW_RUNTIME_ID),c=u??l??Ca(t.boxKind,to.hostname()),d=u?"config":l?"env":"derived";d==="derived"&&o.push(`runnerId not persisted \u2014 using derived id "${c}"; run \`kynver setup --box-kind ${t.boxKind}\` to persist runner identity`);let m=mn({config:e,env:r,totalMemBytes:to.totalmem()}),g=Ze(t.boxKind,m.configuredMaxWorkers??Vr(t.boxKind,m.autoCap)),p=Rr({boxKind:t.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:t.boxKind,boxKindSource:t.source,runnerId:c,runnerIdSource:d,maxConcurrentWorkers:g,workerCapSource:m.workerCapSource,harnessRoot:p.harnessRoot,harnessRootSource:p.source},errors:s,warnings:o}}var Sr=f(()=>{"use strict";ce();oe();Qe();fr();Rn()});var so=f(()=>{"use strict";Xe();oe();zt();ce();gr();Jt();b();Sr()});import{existsSync as Oa,mkdirSync as Qd,readFileSync as Da,writeFileSync as ep}from"node:fs";import{homedir as Na,totalmem as np}from"node:os";import yn from"node:path";function le(){if(!Oa(io))return{};try{return JSON.parse(Da(io,"utf8"))}catch{return{}}}var ao,io,fp,gp,hp,ce=f(()=>{"use strict";Xe();Re();b();oe();Qe();fr();or();gr();so();Sr();ao=yn.join(Na(),".kynver"),io=yn.join(ao,"config.json"),fp=yn.join(ao,"credentials");gp=500*1024*1024,hp=4*1024*1024*1024});import bn from"node:path";function O(e){return kr(e)}function Q(){let e=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(e)return O(e);let r=le(),n=r.harnessRoot?.trim();if(n)return O(n);let t=br(r,process.env);return t.identity?t.identity.harnessRoot:Rr({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function G(e){return bn.join(O(e),"runs")}function Ee(e){return bn.join(O(e),"worktrees")}function et(){let e=Q();return{harnessRoot:e,runsDir:G(e),worktreesDir:Ee(e)}}function en(e,r){return bn.join(e,v(r))}var Y=f(()=>{"use strict";ce();Rn();Sr();b()});Y();import M from"node:path";cr();import Cr from"node:path";F();ue();var Sn=[".next",".turbo","dist","build",".cache","node_modules/.cache"];function uo(e){let r=e.replace(/\\/g,"/").replace(/\/+$/,"");if(r==="node_modules"||r.startsWith("node_modules/"))return!0;for(let n of Sn)if(r===n||r.startsWith(`${n}/`))return!0;return!1}function D(e){return e.filter(r=>{let n=r.trim(),t=n.startsWith("??")?n.slice(2).trim():n.length>3?n.slice(3).trim():n;return!uo(t)})}function de(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 n of["prUrl","pr_url","pullRequestUrl"]){let t=r[n];if(typeof t=="string"&&t.trim())return t.trim()}}return null}function Ue(e){let r=e.gitAncestry?.relation;return r==="merged"||r==="synced"?D(e.changedFiles).length>0:!!(de(e.finalResult)||r==="ahead"||r==="diverged"||e.changedFiles.length>0&&e.finalResult)}b();function Be(e){return e.status||(e.status=Me(e.worker,{base:e.run.base,baseCommit:e.run.baseCommit})),e.status}function vn(e,r){if(e.status)return D(e.status.changedFiles).length>0;let n=r?r.porcelain(e.worktreePath):Pe(e.worktreePath);return D(n).length>0}function Wa(e){let r=e.worker.completionSnapshot?.finalResult;return r??(e.worker.taskPrUrl?{prUrl:e.worker.taskPrUrl}:null)}function _n(e,r){if(e.status)return e.status;let n=e.worker,t=typeof n.completionReportedAt=="string"&&n.completionReportedAt.trim().length>0,o=!!(n.status&&["done","exited","blocked","failed","abandoned"].includes(n.status))||t,s=Wa(e);if(o&&!Z(n.pid)){let i=r?.gitStatusCache?r.gitStatusCache.porcelain(e.worktreePath):Pe(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"}:ze(e.worktreePath,{base:e.run.base,baseCommit:e.run.baseCommit}),c={runId:e.runId,worker:e.workerName,pid:n.pid,alive:!1,status:n.status??(t?"done":"exited"),attention:{state:t?"done":"stale"},branch:n.branch,worktreePath:e.worktreePath,ownedPaths:n.ownedPaths,stdoutBytes:0,stderrBytes:0,heartbeatBytes:0,firstEventAt:null,lastEventAt:null,lastActivityAt:n.completionReportedAt??null,currentTool:null,heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,heartbeatBlocker:null,changedFiles:i,gitAncestry:l,finalResult:s,completionBlocker:typeof n.completionBlocker=="string"&&n.completionBlocker.trim()||null,prUrl:n.repairTargetPrUrl??n.taskPrUrl??de(s)};return e.status=c,c}return Be(e)}ue();se();nn();ue();b();import Ma from"node:path";var Ta=new Set(["running","dispatching","pending","queued","needs_attention"]),pe=new Set(["completed","failed","cancelled","done"]);function me(e){let r=rn(e);if(r.length===0)return"failed";let n=!1,t=!1,o=!1,s=!1;for(let i of r){let a=_(Ma.join(Ie(e.id),"workers",v(i),"worker.json"),void 0);if(!a)continue;let u=Me(a,{base:e.base,baseCommit:e.baseCommit});if(u.alive&&!u.finalResult){n=!0;break}typeof a.completionBlocker=="string"&&a.completionBlocker&&(o=!0),Tt(u)&&(s=!0),u.finalResult&&u.attention.state==="done"&&(t=!0)}return n||o||s?null:t?"completed":"failed"}function lo(){let e=[];for(let r of Zr()){if(!Ta.has(r.status))continue;let n=me(r);if(!n||n===r.status)continue;let t=r.status;r.status=n,Qr(r),e.push({runId:r.id,from:t,to:n})}return e}ue();ar();import{existsSync as vr,mkdirSync as Qp,readdirSync as mo,renameSync as em,statSync as Ua}from"node:fs";import fe from"node:path";ce();Xe();Re();F();ar();Y();se();Y();b();import ee from"node:path";var zp=`${ee.sep}runs${ee.sep}runs${ee.sep}`;function co(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 Ke=900*1e3,lm=3600*1e3;function fo(e,r){let n=fe.resolve(e),t=fe.resolve(G(r)),o=fe.relative(t,n);return o!==".."&&!o.startsWith("..")&&!fe.isAbsolute(o)}function Ba(e){if(!vr(e))return[];try{return mo(e,{withFileTypes:!0}).filter(r=>r.isDirectory()&&r.name!=="runs").map(r=>r.name)}catch{return[]}}function Ka(e){let r=fe.join(e,"workers");if(!vr(r))return[];try{return mo(r,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>n.name)}catch{return[]}}function po(e,r,n){if(!vr(e))return!1;try{let t=r-Ua(e).mtimeMs;return Number.isFinite(t)&&t>=0&&t<n}catch{return!1}}function Fa(e,r=Date.now(),n=Ke){if(!vr(e))return!1;let t=co(e),o=_(t.workerJsonPath,void 0);if(o?.status==="running"&&Z(o.pid))return!0;let s=ve(t.heartbeatPath);if(s.lastHeartbeatAt){let i=r-Date.parse(s.lastHeartbeatAt);if(Number.isFinite(i)&&i>=0&&i<n)return!0}return!!(po(t.stdoutPath,r,n)||po(t.heartbeatPath,r,n))}function Ha(e,r=Date.now(),n=Ke){for(let t of Ka(e))if(Fa(fe.join(e,"workers",t),r,n))return!0;return!1}function go(e,r=Date.now()){let n=new Set,t=G(e);for(let o of Ba(t)){let s=fe.join(t,o);Ha(s,r)&&n.add(`${e}\0${o}`)}return n}b();function xn(e,r=Date.now(),n=Ke){let t=ve(e.heartbeatPath);if(!t.lastHeartbeatAt)return!1;let o=r-Date.parse(t.lastHeartbeatAt);return Number.isFinite(o)&&o>=0&&o<n}function _r(e,r=Date.now(),n=Ke){return Z(e.pid)?!0:xn(e,r,n)}function La(e,r){return r?r.runTerminalCache.derive(e.run):me(e.run)}function J(e,r=Date.now()){return _r(e.worker,r)}function Cn(e,r){return pe.has(e.run.status)?!1:La(e,r)!==null}function ho(e,r,n=Date.now()){if(J(e,n))return!0;if(pe.has(e.run.status)||Cn(e,r))return!1;let t=Be(e);return ae(t)?!1:!!J(e,n)}cr();ue();function ko(e,r){if(!(typeof e.worker.completionBlocker=="string"?e.worker.completionBlocker.trim():""))return!1;if(J(e))return!0;let t=r??Be(e);return!!(!ae(t)||Ue(t)||D(t.changedFiles).length>0||xe({finalResult:t.finalResult,changedFiles:t.changedFiles,gitAncestry:t.gitAncestry,prUrl:de(t.finalResult)}).blocked)}F();b();import{existsSync as yo,mkdirSync as ja,writeFileSync as Ro}from"node:fs";import xr from"node:path";function bo(e,r,n){return xr.join(e,"salvage",v(r),v(n))}function So(e){return yo(xr.join(bo(e.harnessRoot,e.runId,e.workerName),"evidence.json"))}function vo(e){let r=bo(e.harnessRoot,e.indexed.runId,e.indexed.workerName);ja(r,{recursive:!0});let n=xr.join(r,"salvage.patch"),t=!1;if(yo(e.indexed.worktreePath)){let s=w(e.indexed.worktreePath,["diff","HEAD"]),i=w(e.indexed.worktreePath,["diff","--cached"]),a=[s.stdout,i.stdout].filter(u=>u.trim()).join(`
10
+ `);a.trim()&&(Ro(n,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 ko(_r.join(r,"evidence.json"),`${JSON.stringify(o,null,2)}
13
- `),o}var Fa=new Set(["completion_blocked","dirty_worktree","pr_or_unmerged_commits","landing_blocked"]);function Ha(e){return!Fa.has(e.skipReason)||J(e.indexed,e.now)?!1:bo({harnessRoot:e.harnessRoot,runId:e.indexed.runId,workerName:e.indexed.workerName})?!0:e.writeSalvageEvidence?(So({harnessRoot:e.harnessRoot,indexed:e.indexed,skipReason:e.skipReason,status:e.status,now:e.now}),!0):!1}function La(e){let{indexed:r,worktreesAgeMs:t,terminalWorktreesAgeMs:n}=e;return r&&(pe.has(r.run.status)||e.liveness&&_t(r,e.liveness)||e.liveness&&ae(St(r,e.liveness))&&!J(r))?n:t}function ja(e){return!e.indexed||e.includeOrphans&&e.worktreesAgeMs<=0?0:La(e)}function $a(e,r){if(e.harnessRoot?.trim())return xr.resolve(e.harnessRoot);let t=r.worker.workerDir;if(!t)return null;let n=`${xr.sep}runs${xr.sep}`,o=t.indexOf(n);return o<0?null:t.slice(0,o+n.length-1)}function vo(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=ja(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=St(r,e.liveness),c=$a(e,r),d=p=>c&&Ha({indexed:r,harnessRoot:c,skipReason:p,status:l,now:a,writeSalvageEvidence:e.writeSalvageEvidence===!0})?null:p;if(ho(r,l)){let p=d("completion_blocked");if(p)return p}if(bt(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(go(r,e.liveness,a)||!ae(l))return"run_still_active";if(Te(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(_e({finalResult:l.finalResult,changedFiles:l.changedFiles,gitAncestry:l.gitAncestry,prUrl:de(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 xt(e){let{indexed:r,nodeModulesAgeMs:t,ageMs:n,worktreePath:o,activeWorktreePaths:s,diskPressure:i}=e;return!i&&n<t?"below_age_threshold":s.has(xr.resolve(o))||r&&J(r)?"active_worker":r&&bt(r,e.gitStatusCache)?"dirty_worktree":null}function _o(e){return xt(e)}var Ct=216e5,Cr=6048e5;var Et=36e5,Er=120;var xo=new Set(["active_worker","run_still_active","completion_blocked","landing_blocked"]);function Co(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)xo.has(s.reason)&&o(s.path,s.reason,s.detail);for(let s of e)!s.skipped||!s.skipReason||xo.has(s.skipReason)&&o(s.path,s.skipReason);return t}import{existsSync as Po,readdirSync as Io,statSync as Va}from"node:fs";import Oo from"node:path";se();Y();import Eo from"node:path";b();function Ya(e,r){return vr(e,r)}function wo(e,r=Date.now()){let t=new Set,n=new Set;for(let o of e){for(let s of sr(o)){let i=!1;for(let a of Object.keys(s.workers||{})){let u=_(Eo.join(Ie(o,s.id),"workers",v(a),"worker.json"),void 0);if(!u?.worktreePath)continue;let l=Eo.resolve(u.worktreePath);Ya(u,r)&&(i=!0,t.add(l))}i&&n.add(`${o}\0${s.id}`)}for(let s of fo(o))n.add(s)}return{activeWorktreePaths:t,liveRunKeys:n}}function Ao(e,r,t,n){return t?n.has(`${r}\0${t}`):!1}b();function za(e,r){try{let t=Va(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function Ja(e,r){let t=Oo.join(e,"runs",r,"run.json");return Po(t)?_(t,null):null}function Do(e){try{return Io(e).length===0}catch{return!1}}function Wo(e){let{harnessRoot:r,runId:t,runPath:n,ageMs:o,runDirectoriesAgeMs:s,activeGuards:i}=e;if(Ao(n,r,t,i.liveRunKeys)||!Do(n))return"run_still_active";let a=Ja(r,t);return a&&!pe.has(a.status)&&!me(a)?"run_still_active":s>0&&o<s?"below_age_threshold":null}function No(e){if(!Po(e.worktreesDir))return[];let r=[],t;try{t=Io(e.worktreesDir,{withFileTypes:!0})}catch{return[]}for(let n of t){if(!n.isDirectory())continue;let o=n.name;if(e.runIdFilter&&o!==e.runIdFilter)continue;let s=Oo.join(e.worktreesDir,o);Do(s)&&r.push({kind:"remove_run_directory",path:s,bytes:null,harnessRoot:e.harnessRoot,runId:o,ageMs:za(s,e.now)})}return r}F();import{existsSync as At,rmSync as Go}from"node:fs";import{execFileSync as Xa}from"node:child_process";import{existsSync as Mo,readdirSync as qa,statSync as Za}from"node:fs";import Qa from"node:path";var eu=2500;function ru(e,r=eu){if(!Mo(e))return 0;try{let n=Xa("du",["-sb",e],{encoding:"utf8",timeout:r,stdio:["ignore","pipe","ignore"]}).trim().split(/\s+/)[0],o=Number(n);return Number.isFinite(o)&&o>=0?o:null}catch{return null}}function X(e,r=5e4){if(!Mo(e))return 0;let t=ru(e);if(t!==null)return t;let n=0,o=0,s=[e];for(;s.length>0;){let i=s.pop(),a;try{a=qa(i)}catch{continue}for(let u of a){if(o++>r)return null;let l=Qa.join(i,u),c;try{c=Za(l)}catch{continue}c.isDirectory()?s.push(l):n+=c.size}}return n}import{existsSync as su,rmSync as iu}from"node:fs";Y();import{lstatSync as tu,readdirSync as nu}from"node:fs";function To(e){try{let r=tu(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 Uo(e,r=32){let t=To(e);if(!t)return!1;if(t.foreign)return!0;try{let n=nu(e),o=0;for(let s of n){if(o>=r)break;let i=`${e.replace(/\/$/,"")}/${s}`,a=To(i);if(o+=1,a?.foreign)return!0}}catch{}return!1}import{spawnSync as ou}from"node:child_process";import Fo from"node:path";import W from"node:path";function Bo(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 wr(e,r,t){return Bo(e,r,t,"node_modules")}function Ar(e,r,t){return Bo(e,r,t,".next")}function Pr(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 Ko(e,r,t){let n=W.resolve(e);return wr(n,r,t)===null||Ar(n,r,t)===null||Pr(n,r,t)===null}function Lo(){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 Ho(e){let r=ou("sudo",["-n",...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{ok:r.status===0,stderr:`${r.stderr??""}${r.stdout??""}`.trim()}}function jo(e,r,t){if(!Ko(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=Ho(["chown","-R",`${n}:${o}`,Fo.resolve(e)]);if(s.ok)return{ok:!0,method:"chown_then_rm"};let i=Ho(["rm","-rf",Fo.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 wt="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 au(e){let r=e?.code;return r==="EACCES"||r==="EPERM"}function $o(e,r,t={}){if(!su(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?Ce(n):null,i=e.bytes??X(e.path)??void 0,a=t.removePath??iu,u=t.hasForeignOwnedEntry??Uo;try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i}}catch(l){if(!au(l)||!n||!o)return{executed:!1,skipped:!0,skipReason:"remove_failed",error:l.message};let c=u(e.path),d=Lo();if(!(d==="force"||d==="auto"&&c))return c?{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${l.message}; ${wt}`}:{executed:!1,skipped:!0,skipReason:"remove_failed",error:l.message};let g=jo(e.path,n,o);if(g.ok&&g.method==="sudo_rm")return{executed:!0,skipped:!1,bytes:i,privilegedReclaim:!0};if(g.ok)try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i,privilegedReclaim:!0}}catch(p){return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${p.message}; privileged chown succeeded but rm still failed`}}return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${l.message}; privileged reclaim failed: ${g.error}; ${wt}`}}}function Pt(e){let r=e.harnessRoot;return!r||!mo(e.path,r)?null:{...e,executed:!1,skipped:!0,skipReason:"run_metadata_protected"}}function It(e,r){let t=Pt(e);if(t)return t;let n=$o(e,r);return{...e,bytes:n.bytes??e.bytes,executed:n.executed,skipped:n.skipped,skipReason:n.skipReason,error:n.error}}function Yo(e,r){return It(e,r)}function Vo(e,r){return It(e,r)}function zo(e,r){return It(e,r)}function Jo(e,r){let t=Pt(e);if(t)return t;if(!At(e.path))return{...e,executed:!1,skipped:!0,skipReason:"missing_worktree"};if(!r)return{...e,executed:!1,skipped:!0,skipReason:"dry_run"};try{let n=e.bytes??X(e.path);return Go(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 Xo(e,r){let t=Pt(e);if(t)return t;if(!At(e.path))return{...e,executed:!1,skipped:!0,skipReason:"missing_worktree"};if(!r)return{...e,executed:!1,skipped:!0,skipReason:"dry_run"};let n=e.repo;try{let o=e.bytes??X(e.path);return n&&ke(n,["worktree","remove","--force",e.path],{allowFailure:!0}),At(e.path)&&Go(e.path,{recursive:!0,force:!0}),{...e,bytes:o,executed:!0,skipped:!1}}catch(o){return{...e,executed:!1,skipped:!0,skipReason:"remove_failed",error:o.message}}}import{existsSync as Ir,readdirSync as Or,statSync as uu}from"node:fs";import H from"node:path";function Ot(e,r){try{let t=uu(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function Zo(e,r){let t=H.relative(r,e);return t===""||!t.startsWith("..")&&!H.isAbsolute(t)}function qo(e,r,t,n){let o=[];for(let s of yt){if(s===".next")continue;let i=H.join(e,s);if(!Ir(i))continue;let a=H.resolve(i);t.has(a)||Zo(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:Ot(a,r.now)}))}return o}function Qo(e){let r=[],t=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||r.push(...qo(n.worktreePath,e,t,{runId:n.runId,worker:n.workerName,repo:n.run.repo}));if(!e.includeOrphans||!Ir(e.worktreesDir))return r;for(let n of Or(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=H.join(e.worktreesDir,n.name);for(let s of Or(o,{withFileTypes:!0})){if(!s.isDirectory())continue;let i=H.join(o,s.name);r.push(...qo(i,e,t,{runId:n.name,worker:s.name}))}}return r}function es(e){let r=e.worktreesAgeMs>0||e.includeOrphans,t=e.includeOrphans;if(!r&&!t)return[];let n=[],o=new Set;if(r)for(let i of e.index.values()){if(e.runIdFilter&&i.runId!==e.runIdFilter)continue;let a=i.worktreePath;Ir(a)&&(o.has(a)||(o.add(a),n.push({kind:"remove_worktree",path:a,bytes:null,runId:i.runId,worker:i.workerName,repo:i.run.repo,ageMs:Ot(a,e.now)})))}if(!t||!Ir(e.worktreesDir))return n;let s=new Set;for(let i of e.index.values())s.add(H.resolve(i.worktreePath));for(let i of Or(e.worktreesDir,{withFileTypes:!0})){if(!i.isDirectory()||e.runIdFilter&&i.name!==e.runIdFilter)continue;let a=H.join(e.worktreesDir,i.name),u;try{u=Or(a,{withFileTypes:!0})}catch{continue}for(let l of u){if(!l.isDirectory())continue;let c=H.resolve(H.join(a,l.name));o.has(c)||s.has(c)||Zo(c,e.harnessRoot)&&(o.add(c),n.push({kind:"remove_worktree",path:c,bytes:null,runId:i.name,worker:l.name,ageMs:Ot(c,e.now)}))}}return n}import{existsSync as ns,readdirSync as rs,statSync as lu}from"node:fs";import Ee from"node:path";var cu=[{dirName:"node_modules",kind:"remove_node_modules"},{dirName:".next",kind:"remove_next_cache"}];function du(e,r){try{let t=lu(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function pu(e,r){let t=Ee.relative(r,e);return t===""||!t.startsWith("..")&&!Ee.isAbsolute(t)}function mu(e,r,t,n,o,s){if(!ns(n))return;let i=Ee.resolve(n);r.has(i)||pu(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:du(i,t.now)}))}function ts(e,r,t,n,o){for(let s of cu)mu(e,r,t,Ee.join(n,s.dirName),s.kind,o)}function os(e){let r=[],t=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||ts(r,t,e,n.worktreePath,{runId:n.runId,worker:n.workerName,repo:n.run.repo});if(!e.includeOrphans||!ns(e.worktreesDir))return r;for(let n of rs(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory()||e.runIdFilter&&n.name!==e.runIdFilter)continue;let o=Ee.join(e.worktreesDir,n.name),s;try{s=rs(o,{withFileTypes:!0})}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=Ee.join(o,i.name);ts(r,t,e,a,{runId:n.name,worker:i.name})}}return r}F();import{existsSync as ss,statSync as fu}from"node:fs";import L from"node:path";function gu(e,r){try{let t=fu(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function hu(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 ku(e,r){let t=L.relative(L.resolve(r),L.resolve(e));return t!==""&&!t.startsWith("..")&&!L.isAbsolute(t)}var Ru=200;function is(e){if(!e.includeOrphans||!ss(e.worktreesDir))return[];let r=new Set;for(let s of e.index.values())s.run.repo&&r.add(L.resolve(s.run.repo));let t=new Set;for(let s of e.index.values())t.add(L.resolve(s.worktreePath));let n=[],o=new Set;for(let s of r){let i=0,a;try{a=ke(s,["worktree","list","--porcelain"],{allowFailure:!0})}catch{continue}let u=hu(a);for(let l of u){if(i>=Ru)break;let c=L.resolve(l.path);if(c===L.resolve(s)||!ku(c,e.worktreesDir)||t.has(c)||o.has(c)||!ss(c))continue;let m=L.relative(e.worktreesDir,c).split(L.sep),g=m[0],p=m[1]??"unknown";o.add(c),i+=1,n.push({kind:"remove_worktree",path:c,bytes:null,runId:g,worker:p,repo:s,ageMs:gu(c,e.now)})}}return n}se();b();import Ke from"node:path";function as(e,r){let t=Ke.resolve(r),n=new Map;for(let[o,s]of e){let i=s.harnessRoot?Ke.resolve(s.harnessRoot):null;i&&i!==t||n.set(o,s)}return n}function us(e){let r=new Map;for(let t of sr(e))for(let n of Object.keys(t.workers||{})){let o=Ke.join(Ie(e,t.id),"workers",v(n),"worker.json"),s=_(o,void 0);s?.worktreePath&&r.set(Ke.resolve(s.worktreePath),{harnessRoot:e,worktreePath:Ke.resolve(s.worktreePath),runId:t.id,workerName:n,run:t,worker:s})}return r}function Fe(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function ge(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)&&n>=0?n:r}function ls(e={}){let r=e.execute===!0||e.execute!==!1&&Fe("KYNVER_CLEANUP_EXECUTE"),t=e.finalizeStaleRuns!==!1&&!Fe("KYNVER_CLEANUP_SKIP_FINALIZE"),n=e.nodeModulesAgeMs??ge("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??ge("KYNVER_CLEANUP_WORKTREES_AGE_MS",0),i=e.terminalWorktreesAgeMs??ge("KYNVER_CLEANUP_TERMINAL_WORKTREES_AGE_MS",216e5),a=e.runDirectoriesAgeMs??ge("KYNVER_CLEANUP_RUN_DIRECTORIES_AGE_MS",36e5),u=e.maxActionsPerSweep??ge("KYNVER_CLEANUP_MAX_ACTIONS_PER_SWEEP",120),l=e.includeOrphans===!0||Fe("KYNVER_CLEANUP_INCLUDE_ORPHANS"),d=Fe("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&&!Fe("KYNVER_CLEANUP_SKIP_BYTE_ACCOUNTING"),g=ge("KYNVER_CLEANUP_STORAGE_ENTRY_CAP",2e3),p=e.storagePerRunEntryCap!==void 0?e.storagePerRunEntryCap:m&&g>0?g:null,R=ge("KYNVER_CLEANUP_BYTE_ENTRY_CAP",2e3),S=e.byteAccountingEntryCap??(Number.isFinite(R)&&R>0?Math.floor(R):2e3);return{execute:r,finalizeStaleRuns:t,scanDependencyCaches:o,nodeModulesAgeMs:n,worktreesAgeMs:s>0?s:0,terminalWorktreesAgeMs:i>=0?i:0,runDirectoriesAgeMs:a>=0?a:0,maxActionsPerSweep:Number.isFinite(u)&&u>0?Math.floor(u):120,includeOrphans:l,runIdFilter:d?String(d):void 0,accountBytes:m,storagePerRunEntryCap:p,byteAccountingEntryCap:S}}F();import{existsSync as Dt,statSync as bu}from"node:fs";import Dr from"node:path";b();var Su=1800*1e3;function cs(e){let r=e.now??Date.now(),t=e.heartbeatFreshMs??Su;if(!Dt(e.worktreePath))return null;if(e.runId&&e.workerName){let l=Dr.join(e.harnessRoot,"runs",e.runId,"workers",e.workerName),c=_(Dr.join(l,"worker.json"),void 0);if(c&&vt(c,r,t))return"active_worker";if(!c){let d=Dr.join(l,"heartbeat.jsonl");if(Dt(d))try{let m=r-bu(d).mtimeMs;if(Number.isFinite(m)&&m>=0&&m<t)return"active_worker"}catch{}}}let n=Dr.join(e.worktreePath,".git");if(!Dt(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 vu,readdirSync as ds,statSync as _u}from"node:fs";import xu from"node:path";function ps(e={}){let r=O(e.harnessRoot??Q()),t=Ce(r),n=e.now??Date.now(),o=new Date(n).toISOString();if(!vu(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=ds(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=xu.join(t,c.name);try{let m=_u(d);u=u===null?m.mtimeMs:Math.min(u,m.mtimeMs)}catch{}try{for(let m of ds(d,{withFileTypes:!0}))m.isDirectory()&&(a+=1)}catch{}if(s!==null&&e.perRunEntryCap!==null){let m=e.perRunEntryCap??5e4;if(m<=0)s=null;else{let g=X(d,m);g===null?s=null:s+=g}}}return{harnessRoot:r,worktreesDir:t,worktreesBytes:s,runCount:i,workerCount:a,oldestRunAt:u===null?null:new Date(u).toISOString(),scannedAt:o}}Y();import{existsSync as Cu}from"node:fs";import{homedir as Eu}from"node:os";import ms from"node:path";var wu=["/var/tmp/kynver-harness",ms.join(Eu(),".openclaw","harness")];function Wt(e,r,t){if(!t?.trim())return;let n=O(t.trim());e.has(n)||(e.add(n),r.push(n))}function Au(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 fs(e={}){let r=new Set,t=[];Wt(r,t,e.harnessRoot??Q());let n=process.env.KYNVER_CLEANUP_EXTRA_ROOTS?.split(",").map(o=>o.trim()).filter(Boolean);for(let o of n??[])Wt(r,t,o);if(Au(e))for(let o of wu){let s=ms.resolve(o);!r.has(s)&&Cu(s)&&Wt(r,t,s)}return t}nr();function Pu(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function Iu(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function gs(e={}){let r=e.diskPath?.trim()||process.env.KYNVER_DISK_GUARD_PATH?.trim()||"/",t=Iu("KYNVER_DISK_GUARD_MAX_USED_PERCENT",75),n=tr({...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 hs(e,r){if(!r.pressured)return e;let t=e.execute||!Pu("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}}rr();import{unlinkSync as Ou}from"node:fs";function Wr(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function ks(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function Du(e,r,t){return e.length===0?[]:t?[...e]:e.length<=r?[]:e.slice(r)}function Rs(e={}){let r=e.execute===!0||Wr("KYNVER_WSL_CRASH_DUMP_EXECUTE")||Wr("KYNVER_CLEANUP_EXECUTE"),t=e.purgeAll===!0||Wr("KYNVER_WSL_CRASH_DUMP_PURGE_ALL"),n=Math.max(0,e.keepNewest??ks("KYNVER_WSL_CRASH_DUMP_KEEP_NEWEST",t?0:1)),o=Se({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=Du(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{Ou(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 ys(e){return e?Wr("KYNVER_WSL_CRASH_DUMP_CLEANUP")||!e.ok?!0:e.dumpCount>ks("KYNVER_WSL_CRASH_DUMP_KEEP_NEWEST",1):!1}rr();function N(e,r){if(process.env.KYNVER_CLEANUP_QUIET==="1")return;let t=r?`: ${r}`:"";console.error(`[kynver cleanup] ${e}${t}`)}F();var Nr=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 Wu}from"node:child_process";import{existsSync as Nu}from"node:fs";import Mu from"node:path";var Tu=5e3;function Uu(e,r){if(!Nu(Mu.join(e,".git")))return{status:null,stdout:"",stderr:"",error:"not_a_git_repo"};try{let t=Wu("git",r,{cwd:e,encoding:"utf8",timeout:Tu}),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 bs(e){let r=Uu(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 Mr=class{cache=new Map;porcelain(r){let t=r,n=this.cache.get(t);if(n!==void 0)return n;let o=bs(t)??[];return this.cache.set(t,o),o}};var Tr=class{cache=new Map;derive(r){let t=this.cache.get(r.id);if(t!==void 0)return t;let n=me(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 Ss(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 Ku(e={}){let r=e.harnessRoot?O(e.harnessRoot):Q(),t=fs({harnessRoot:r}),n=e.now??Date.now();return{harnessRoot:r,scanRoots:t,now:n}}function Fu(e){return typeof e=="string"?{reason:e}:e}function we(e,r,t,n){e.push({path:r,reason:t,...n?{detail:n}:{}})}function Ur(e,r,t){return!r||e.bytes!=null?e:{...e,bytes:X(e.path,t)}}function vs(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 Hu(e,r){return e.kind==="remove_next_cache"?Vo(e,r):Yo(e,r)}function Lu(e,r,t){return e.kind==="remove_next_cache"?Ar(e.path,r,t):wr(e.path,r,t)}function ju(e){let r=new Map;for(let t of e)for(let[n,o]of us(t))r.set(n,o);return r}function _s(e,r){return e.runId&&e.worker?M.join(r,e.runId,e.worker):M.resolve(e.path,"..")}function $u(e={}){let r=ls(e),t=gs();r=hs(r,t);let n=Ku(e);N("scan",`${n.scanRoots.length} harness root(s)`);let o=wo(n.scanRoots,n.now),s=r.finalizeStaleRuns?uo().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=ju(n.scanRoots);N("index",`${i.size} indexed worktree(s)`);let a={runTerminalCache:new Tr,gitStatusCache:new Mr,gitRevCache:new Nr},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 q=M.join(h,"worktrees"),Le=as(i,h),je={harnessRoot:h,worktreesDir:q,nodeModulesAgeMs:r.nodeModulesAgeMs,worktreesAgeMs:r.worktreesAgeMs,includeOrphans:r.includeOrphans,runIdFilter:r.runIdFilter,index:Le,now:n.now},Br=r.scanDependencyCaches?os(je):[];N("dependency",r.scanDependencyCaches?`${Br.length} cache candidate(s) at ${h}`:"skipped (worktree-only sweep)");let Kr=0;for(let T of Br){if(m())break;Kr+=1,Kr%50===0&&N("dependency",`${Kr}/${Br.length} evaluated`);let x=M.resolve(T.path);if(c.has(x))continue;c.add(x);let k={...T,path:x},I=Lu(k,h,q);if(I){we(u,k.path,I),l.push({...k,executed:!1,skipped:!0,skipReason:I});continue}let U=_s(k,q),he=Le.get(M.resolve(U))??null,K=xt({indexed:he,includeOrphans:!0,nodeModulesAgeMs:r.nodeModulesAgeMs,ageMs:k.ageMs,worktreePath:U,activeWorktreePaths:o.activeWorktreePaths,diskPressure:r.diskPressure,gitStatusCache:a.gitStatusCache});if(K){we(u,k.path,K),l.push({...k,executed:!1,skipped:!0,skipReason:K});continue}l.push(Hu(Ur(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}if(r.scanDependencyCaches)for(let T of Qo(je)){if(m())break;let x=M.resolve(T.path);if(c.has(x))continue;c.add(x);let k={...T,path:x},I=Pr(k.path,h,q);if(I){we(u,k.path,I),l.push({...k,executed:!1,skipped:!0,skipReason:I});continue}let U=_s(k,q),he=Le.get(M.resolve(U))??null,K=_o({indexed:he,includeOrphans:!0,nodeModulesAgeMs:r.nodeModulesAgeMs,ageMs:k.ageMs,worktreePath:U,activeWorktreePaths:o.activeWorktreePaths,diskPressure:r.diskPressure,gitStatusCache:a.gitStatusCache});if(K){we(u,k.path,K),l.push({...k,executed:!1,skipped:!0,skipReason:K});continue}l.push(zo(Ur(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}let Fr=[...es(je),...is(je)];N("worktrees",`${Fr.length} candidate(s) at ${h}`);let Nt=new Set,Hr=0;for(let T of Fr){if(m())break;Hr+=1,Hr%50===0&&N("worktrees",`${Hr}/${Fr.length} evaluated`);let x=M.resolve(T.path);if(Nt.has(x))continue;Nt.add(x);let k={...T,path:x},I=Le.get(M.resolve(k.path))??null,U=I?null:cs({worktreePath:k.path,harnessRoot:h,runId:k.runId,workerName:k.worker,now:n.now}),he=vo({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(he){let{reason:K,detail:xs}=Fu(he);we(u,k.path,K,xs),l.push({...k,executed:!1,skipped:!0,skipReason:K});continue}l.push(Xo(Ur(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}if(!m()&&r.runDirectoriesAgeMs>=0)for(let T of No({harnessRoot:h,worktreesDir:q,runDirectoriesAgeMs:r.runDirectoriesAgeMs,runIdFilter:r.runIdFilter,activeGuards:o,now:n.now})){if(m())break;let x=M.resolve(T.path);if(c.has(x))continue;c.add(x);let k={...T,path:x},I=k.runId??M.basename(x),U=Wo({harnessRoot:h,runId:I,runPath:x,ageMs:k.ageMs,runDirectoriesAgeMs:r.runDirectoriesAgeMs,activeGuards:o});if(U){we(u,k.path,U),l.push({...k,executed:!1,skipped:!0,skipReason:U});continue}l.push(Jo(Ur(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}}let g=0,p=0,R=0,S=0,y=0,A=0;for(let h of l)h.bytes&&(g+=h.bytes),!h.skipped&&!h.executed&&h.bytes&&(R+=h.bytes),h.executed?(y+=1,S+=h.bytes??0,h.kind==="remove_run_directory"&&(p+=1)):h.skipped&&(A+=1,h.skipReason==="dry_run"&&h.bytes&&(R+=h.bytes));let j=r.accountBytes?ps({harnessRoot:n.harnessRoot,now:n.now,perRunEntryCap:r.storagePerRunEntryCap}):void 0,B=Se(),He=r.execute&&ys(B),$=He?Rs({execute:!0}):null,re=B?{observed:!0,execute:He,dumpCount:B.dumpCount,totalBytes:B.totalBytes,removedCount:$?.removed.length??0,removedBytes:$?.removedBytes??0,executables:B.executables,path:B.path,reason:B.reason}:void 0;$&&$.removed.length>0&&(S+=$.removedBytes,y+=$.removed.length,N("wsl-crashes",`removed ${$.removed.length} dump(s), ${$.removedBytes} bytes`)),N("complete",`${l.length} action(s), ${A} skipped, ${y} removed`);let te=Co(l,u),P=Ss({harnessRoot:n.harnessRoot,scanRoots:n.scanRoots,dryRun:!r.execute,execute:r.execute,nodeModulesAgeMs:r.nodeModulesAgeMs,worktreesAgeMs:r.worktreesAgeMs,includeOrphans:r.includeOrphans,diskPressure:r.diskPressure,diskGate:r.diskGate?{ok:r.diskGate.ok,path:r.diskGate.path,freeBytes:r.diskGate.freeBytes,usedPercent:r.diskGate.usedPercent,reason:r.diskGate.reason}:void 0,scannedAt:new Date(n.now).toISOString(),finalizedRuns:s,actions:l,skips:u,totals:{candidateBytes:g,reclaimableBytes:R,removedBytes:S,removedPaths:y,skippedPaths:A,skipReasons:vs(l,u)},...j?{storage:j}:{},...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:g,reclaimableBytes:R,removedBytes:S,removedPaths:y,skippedPaths:A,skipReasons:vs(l,u)},...j?{storage:j}:{},...te.length>0?{preservedLivePaths:te}:{},...p>0?{removedRunDirectories:p}:{},...re?{wslCrashDumps:re}:{},compactSummary:P}}export{Er as DEFAULT_MAX_ACTIONS_PER_SWEEP,Ct as DEFAULT_NODE_MODULES_AGE_MS,Et as DEFAULT_RUN_DIRECTORIES_AGE_MS,Cr as DEFAULT_WORKTREES_AGE_MS,$u as runHarnessCleanup};
12
+ `),t=!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,...t?{patchPath:n}:{}};return Ro(xr.join(r,"evidence.json"),`${JSON.stringify(o,null,2)}
13
+ `),o}var $a=new Set(["completion_blocked","dirty_worktree","pr_or_unmerged_commits","landing_blocked"]);function Ga(e){return!$a.has(e.skipReason)||J(e.indexed,e.now)?!1:So({harnessRoot:e.harnessRoot,runId:e.indexed.runId,workerName:e.indexed.workerName})?!0:e.writeSalvageEvidence?(vo({harnessRoot:e.harnessRoot,indexed:e.indexed,skipReason:e.skipReason,status:e.status,now:e.now}),!0):!1}function Ya(e){let{indexed:r,worktreesAgeMs:n,terminalWorktreesAgeMs:t}=e;return r&&(pe.has(r.run.status)||e.liveness&&Cn(r,e.liveness)||e.liveness&&ae(_n(r,e.liveness))&&!J(r))?t:n}function Va(e){return!e.indexed||e.includeOrphans&&e.worktreesAgeMs<=0?0:Ya(e)}function za(e,r){if(e.harnessRoot?.trim())return Cr.resolve(e.harnessRoot);let n=r.worker.workerDir;if(!n)return null;let t=`${Cr.sep}runs${Cr.sep}`,o=n.indexOf(t);return o<0?null:n.slice(0,o+t.length-1)}function _o(e){let{indexed:r,includeOrphans:n,worktreesAgeMs:t,ageMs:o,orphanSafety:s,worktreeRemovalGuard:i}=e,a=e.now??Date.now();if(!r)return n?s??null:"orphan_without_flag";let u=Va(e);if(t<=0&&!n&&u<=0)return"worktrees_disabled";if(u>0&&o<u)return"below_age_threshold";if(J(r,a))return"active_worker";let l=_n(r,e.liveness),c=za(e,r),d=p=>c&&Ga({indexed:r,harnessRoot:c,skipReason:p,status:l,now:a,writeSalvageEvidence:e.writeSalvageEvidence===!0})?null:p;if(ko(r,l)){let p=d("completion_blocked");if(p)return p}if(vn(r,e.liveness?.gitStatusCache)){let p=d("dirty_worktree");if(p)return p}let m=e.liveness?.gitRevCache?.countAheadOfMain(e.worktreePath);if(m!=null&&m>0){let p=d("pr_or_unmerged_commits");if(p)return p}if(ho(r,e.liveness,a)||!ae(l))return"run_still_active";if(Ue(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(xe({finalResult:l.finalResult,changedFiles:l.changedFiles,gitAncestry:l.gitAncestry,prUrl:de(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 En(e){let{indexed:r,nodeModulesAgeMs:n,ageMs:t,worktreePath:o,activeWorktreePaths:s,diskPressure:i}=e;return!i&&t<n?"below_age_threshold":s.has(Cr.resolve(o))||r&&J(r)?"active_worker":r&&vn(r,e.gitStatusCache)?"dirty_worktree":null}function xo(e){return En(e)}var wn=216e5,Er=6048e5;var An=36e5,wr=120;var Co=new Set(["active_worker","run_still_active","completion_blocked","landing_blocked"]);function Eo(e,r){let n=[],t=new Set,o=(s,i,a)=>{let u=`${s}\0${i}`;t.has(u)||n.length>=24||(t.add(u),n.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 n}import{existsSync as Io,readdirSync as Oo,statSync as qa}from"node:fs";import Do from"node:path";se();Y();import wo from"node:path";b();function Xa(e,r){return _r(e,r)}function Ao(e,r=Date.now()){let n=new Set,t=new Set;for(let o of e){for(let s of ir(o)){let i=!1;for(let a of Object.keys(s.workers||{})){let u=_(wo.join(Oe(o,s.id),"workers",v(a),"worker.json"),void 0);if(!u?.worktreePath)continue;let l=wo.resolve(u.worktreePath);Xa(u,r)&&(i=!0,n.add(l))}i&&t.add(`${o}\0${s.id}`)}for(let s of go(o))t.add(s)}return{activeWorktreePaths:n,liveRunKeys:t}}function Po(e,r,n,t){return n?t.has(`${r}\0${n}`):!1}b();function Za(e,r){try{let n=qa(e).mtimeMs;return Math.max(0,r-n)}catch{return 0}}function Qa(e,r){let n=Do.join(e,"runs",r,"run.json");return Io(n)?_(n,null):null}function No(e){try{return Oo(e).length===0}catch{return!1}}function Wo(e){let{harnessRoot:r,runId:n,runPath:t,ageMs:o,runDirectoriesAgeMs:s,activeGuards:i}=e;if(Po(t,r,n,i.liveRunKeys)||!No(t))return"run_still_active";let a=Qa(r,n);return a&&!pe.has(a.status)&&!me(a)?"run_still_active":s>0&&o<s?"below_age_threshold":null}function Mo(e){if(!Io(e.worktreesDir))return[];let r=[],n;try{n=Oo(e.worktreesDir,{withFileTypes:!0})}catch{return[]}for(let t of n){if(!t.isDirectory())continue;let o=t.name;if(e.runIdFilter&&o!==e.runIdFilter)continue;let s=Do.join(e.worktreesDir,o);No(s)&&r.push({kind:"remove_run_directory",path:s,bytes:null,harnessRoot:e.harnessRoot,runId:o,ageMs:Za(s,e.now)})}return r}F();import{existsSync as In,rmSync as Yo}from"node:fs";import{execFileSync as eu}from"node:child_process";import{existsSync as To,readdirSync as ru,statSync as nu}from"node:fs";import tu from"node:path";var ou=2500;function su(e,r=ou){if(!To(e))return 0;try{let t=eu("du",["-sb",e],{encoding:"utf8",timeout:r,stdio:["ignore","pipe","ignore"]}).trim().split(/\s+/)[0],o=Number(t);return Number.isFinite(o)&&o>=0?o:null}catch{return null}}function X(e,r=5e4){if(!To(e))return 0;let n=su(e);if(n!==null)return n;let t=0,o=0,s=[e];for(;s.length>0;){let i=s.pop(),a;try{a=ru(i)}catch{continue}for(let u of a){if(o++>r)return null;let l=tu.join(i,u),c;try{c=nu(l)}catch{continue}c.isDirectory()?s.push(l):t+=c.size}}return t}import{existsSync as lu,rmSync as cu}from"node:fs";Y();import{lstatSync as iu,readdirSync as au}from"node:fs";function Uo(e){try{let r=iu(e),n=typeof process.getuid=="function"?process.getuid():null,t=typeof process.getgid=="function"?process.getgid():null,o=n!==null&&(r.uid!==n||t!==null&&r.gid!==t);return{uid:r.uid,gid:r.gid,foreign:o}}catch{return null}}function Bo(e,r=32){let n=Uo(e);if(!n)return!1;if(n.foreign)return!0;try{let t=au(e),o=0;for(let s of t){if(o>=r)break;let i=`${e.replace(/\/$/,"")}/${s}`,a=Uo(i);if(o+=1,a?.foreign)return!0}}catch{}return!1}import{spawnSync as uu}from"node:child_process";import Ho from"node:path";import N from"node:path";function Ko(e,r,n,t){let o=N.resolve(e),s=`${N.sep}${t}`,i=o.endsWith(s)?o:null;if(!i)return"path_outside_harness";let a=N.relative(n,i);if(a.startsWith("..")||N.isAbsolute(a))return"path_outside_harness";let u=a.split(N.sep);return u.length<3||u[u.length-1]!==t||!o.startsWith(N.resolve(r))?"path_outside_harness":null}function Ar(e,r,n){return Ko(e,r,n,"node_modules")}function Pr(e,r,n){return Ko(e,r,n,".next")}function Ir(e,r,n){let t=N.resolve(e),o=N.relative(n,t);return o.startsWith("..")||N.isAbsolute(o)||o.split(N.sep).length<3||!t.startsWith(N.resolve(r))?"path_outside_harness":null}function Fo(e,r,n){let t=N.resolve(e);return Ar(t,r,n)===null||Pr(t,r,n)===null||Ir(t,r,n)===null}function jo(){let e=(process.env.KYNVER_CLEANUP_PRIVILEGED??"auto").trim().toLowerCase();return e==="0"||e==="false"||e==="off"||e==="no"?"off":e==="1"||e==="true"||e==="force"||e==="yes"?"force":"auto"}function Lo(e){let r=uu("sudo",["-n",...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{ok:r.status===0,stderr:`${r.stderr??""}${r.stdout??""}`.trim()}}function $o(e,r,n){if(!Fo(e,r,n))return{ok:!1,error:"path is not an allowed harness generated cache"};let t=typeof process.getuid=="function"?process.getuid():null,o=typeof process.getgid=="function"?process.getgid():null;if(t===null||o===null)return{ok:!1,error:"privileged reclaim requires POSIX uid/gid"};let s=Lo(["chown","-R",`${t}:${o}`,Ho.resolve(e)]);if(s.ok)return{ok:!0,method:"chown_then_rm"};let i=Lo(["rm","-rf",Ho.resolve(e)]);return i.ok?{ok:!0,method:"sudo_rm"}:{ok:!1,error:s.stderr||i.stderr||"sudo -n failed (password required or not permitted)"}}var Pn="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 du(e){let r=e?.code;return r==="EACCES"||r==="EPERM"}function Go(e,r,n={}){if(!lu(e.path))return{executed:!1,skipped:!0,skipReason:"missing_worktree"};if(!r)return{executed:!1,skipped:!0,skipReason:"dry_run"};let t=e.harnessRoot,o=t?Ee(t):null,i=e.bytes??X(e.path)??void 0,a=n.removePath??cu,u=n.hasForeignOwnedEntry??Bo;try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i}}catch(l){if(!du(l)||!t||!o)return{executed:!1,skipped:!0,skipReason:"remove_failed",error:l.message};let c=u(e.path),d=jo();if(!(d==="force"||d==="auto"&&c))return c?{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${l.message}; ${Pn}`}:{executed:!1,skipped:!0,skipReason:"remove_failed",error:l.message};let g=$o(e.path,t,o);if(g.ok&&g.method==="sudo_rm")return{executed:!0,skipped:!1,bytes:i,privilegedReclaim:!0};if(g.ok)try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i,privilegedReclaim:!0}}catch(p){return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${p.message}; privileged chown succeeded but rm still failed`}}return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${l.message}; privileged reclaim failed: ${g.error}; ${Pn}`}}}function On(e){let r=e.harnessRoot;return!r||!fo(e.path,r)?null:{...e,executed:!1,skipped:!0,skipReason:"run_metadata_protected"}}function Dn(e,r){let n=On(e);if(n)return n;let t=Go(e,r);return{...e,bytes:t.bytes??e.bytes,executed:t.executed,skipped:t.skipped,skipReason:t.skipReason,error:t.error}}function Vo(e,r){return Dn(e,r)}function zo(e,r){return Dn(e,r)}function Jo(e,r){return Dn(e,r)}function Xo(e,r){let n=On(e);if(n)return n;if(!In(e.path))return{...e,executed:!1,skipped:!0,skipReason:"missing_worktree"};if(!r)return{...e,executed:!1,skipped:!0,skipReason:"dry_run"};try{let t=e.bytes??X(e.path);return Yo(e.path,{recursive:!0,force:!0}),{...e,bytes:t,executed:!0,skipped:!1}}catch(t){return{...e,executed:!1,skipped:!0,skipReason:"remove_failed",error:t.message}}}function qo(e,r){let n=On(e);if(n)return n;if(!In(e.path))return{...e,executed:!1,skipped:!0,skipReason:"missing_worktree"};if(!r)return{...e,executed:!1,skipped:!0,skipReason:"dry_run"};let t=e.repo;try{let o=e.bytes??X(e.path);return t&&ke(t,["worktree","remove","--force",e.path],{allowFailure:!0}),In(e.path)&&Yo(e.path,{recursive:!0,force:!0}),{...e,bytes:o,executed:!0,skipped:!1}}catch(o){return{...e,executed:!1,skipped:!0,skipReason:"remove_failed",error:o.message}}}import{existsSync as Or,readdirSync as Dr,statSync as pu}from"node:fs";import H from"node:path";function Nn(e,r){try{let n=pu(e).mtimeMs;return Math.max(0,r-n)}catch{return 0}}function Qo(e,r){let n=H.relative(r,e);return n===""||!n.startsWith("..")&&!H.isAbsolute(n)}function Zo(e,r,n,t){let o=[];for(let s of Sn){if(s===".next")continue;let i=H.join(e,s);if(!Or(i))continue;let a=H.resolve(i);n.has(a)||Qo(a,r.harnessRoot)&&(n.add(a),o.push({kind:"remove_build_cache",path:a,bytes:null,runId:t.runId,worker:t.worker,repo:t.repo,ageMs:Nn(a,r.now)}))}return o}function es(e){let r=[],n=new Set;for(let t of e.index.values())e.runIdFilter&&t.runId!==e.runIdFilter||r.push(...Zo(t.worktreePath,e,n,{runId:t.runId,worker:t.workerName,repo:t.run.repo}));if(!e.includeOrphans||!Or(e.worktreesDir))return r;for(let t of Dr(e.worktreesDir,{withFileTypes:!0})){if(!t.isDirectory())continue;let o=H.join(e.worktreesDir,t.name);for(let s of Dr(o,{withFileTypes:!0})){if(!s.isDirectory())continue;let i=H.join(o,s.name);r.push(...Zo(i,e,n,{runId:t.name,worker:s.name}))}}return r}function rs(e){let r=e.worktreesAgeMs>0||e.includeOrphans,n=e.includeOrphans;if(!r&&!n)return[];let t=[],o=new Set;if(r)for(let i of e.index.values()){if(e.runIdFilter&&i.runId!==e.runIdFilter)continue;let a=i.worktreePath;Or(a)&&(o.has(a)||(o.add(a),t.push({kind:"remove_worktree",path:a,bytes:null,runId:i.runId,worker:i.workerName,repo:i.run.repo,ageMs:Nn(a,e.now)})))}if(!n||!Or(e.worktreesDir))return t;let s=new Set;for(let i of e.index.values())s.add(H.resolve(i.worktreePath));for(let i of Dr(e.worktreesDir,{withFileTypes:!0})){if(!i.isDirectory()||e.runIdFilter&&i.name!==e.runIdFilter)continue;let a=H.join(e.worktreesDir,i.name),u;try{u=Dr(a,{withFileTypes:!0})}catch{continue}for(let l of u){if(!l.isDirectory())continue;let c=H.resolve(H.join(a,l.name));o.has(c)||s.has(c)||Qo(c,e.harnessRoot)&&(o.add(c),t.push({kind:"remove_worktree",path:c,bytes:null,runId:i.name,worker:l.name,ageMs:Nn(c,e.now)}))}}return t}import{existsSync as os,readdirSync as ns,statSync as mu}from"node:fs";import we from"node:path";var fu=[{dirName:"node_modules",kind:"remove_node_modules"},{dirName:".next",kind:"remove_next_cache"}];function gu(e,r){try{let n=mu(e).mtimeMs;return Math.max(0,r-n)}catch{return 0}}function hu(e,r){let n=we.relative(r,e);return n===""||!n.startsWith("..")&&!we.isAbsolute(n)}function ku(e,r,n,t,o,s){if(!os(t))return;let i=we.resolve(t);r.has(i)||hu(i,n.harnessRoot)&&(r.add(i),e.push({kind:o,path:i,bytes:null,harnessRoot:n.harnessRoot,runId:s.runId,worker:s.worker,repo:s.repo,ageMs:gu(i,n.now)}))}function ts(e,r,n,t,o){for(let s of fu)ku(e,r,n,we.join(t,s.dirName),s.kind,o)}function ss(e){let r=[],n=new Set;for(let t of e.index.values())e.runIdFilter&&t.runId!==e.runIdFilter||ts(r,n,e,t.worktreePath,{runId:t.runId,worker:t.workerName,repo:t.run.repo});if(!e.includeOrphans||!os(e.worktreesDir))return r;for(let t of ns(e.worktreesDir,{withFileTypes:!0})){if(!t.isDirectory()||e.runIdFilter&&t.name!==e.runIdFilter)continue;let o=we.join(e.worktreesDir,t.name),s;try{s=ns(o,{withFileTypes:!0})}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=we.join(o,i.name);ts(r,n,e,a,{runId:t.name,worker:i.name})}}return r}F();import{existsSync as is,statSync as Ru}from"node:fs";import L from"node:path";function yu(e,r){try{let n=Ru(e).mtimeMs;return Math.max(0,r-n)}catch{return 0}}function bu(e){let r=[],n=null;for(let t of e.split(`
14
+ `)){if(!t.trim())continue;let[o,...s]=t.split(" "),i=s.join(" ");if(o==="worktree"){n&&r.push(n),n={path:i};continue}n&&(o==="branch"&&(n.branch=i),o==="HEAD"&&(n.head=i),o==="bare"&&(n.bare=!0))}return n&&r.push(n),r}function Su(e,r){let n=L.relative(L.resolve(r),L.resolve(e));return n!==""&&!n.startsWith("..")&&!L.isAbsolute(n)}var vu=200;function as(e){if(!e.includeOrphans||!is(e.worktreesDir))return[];let r=new Set;for(let s of e.index.values())s.run.repo&&r.add(L.resolve(s.run.repo));let n=new Set;for(let s of e.index.values())n.add(L.resolve(s.worktreePath));let t=[],o=new Set;for(let s of r){let i=0,a;try{a=ke(s,["worktree","list","--porcelain"],{allowFailure:!0})}catch{continue}let u=bu(a);for(let l of u){if(i>=vu)break;let c=L.resolve(l.path);if(c===L.resolve(s)||!Su(c,e.worktreesDir)||n.has(c)||o.has(c)||!is(c))continue;let m=L.relative(e.worktreesDir,c).split(L.sep),g=m[0],p=m[1]??"unknown";o.add(c),i+=1,t.push({kind:"remove_worktree",path:c,bytes:null,runId:g,worker:p,repo:s,ageMs:yu(c,e.now)})}}return t}se();b();import Fe from"node:path";function us(e,r){let n=Fe.resolve(r),t=new Map;for(let[o,s]of e){let i=s.harnessRoot?Fe.resolve(s.harnessRoot):null;i&&i!==n||t.set(o,s)}return t}function ls(e){let r=new Map;for(let n of ir(e))for(let t of Object.keys(n.workers||{})){let o=Fe.join(Oe(e,n.id),"workers",v(t),"worker.json"),s=_(o,void 0);s?.worktreePath&&r.set(Fe.resolve(s.worktreePath),{harnessRoot:e,worktreePath:Fe.resolve(s.worktreePath),runId:n.id,workerName:t,run:n,worker:s})}return r}function He(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function ge(e,r){let n=process.env[e];if(!n)return r;let t=Number(n);return Number.isFinite(t)&&t>=0?t:r}function cs(e={}){let r=e.execute===!0||e.execute!==!1&&He("KYNVER_CLEANUP_EXECUTE"),n=e.finalizeStaleRuns!==!1&&!He("KYNVER_CLEANUP_SKIP_FINALIZE"),t=e.nodeModulesAgeMs??ge("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??ge("KYNVER_CLEANUP_WORKTREES_AGE_MS",0),i=e.terminalWorktreesAgeMs??ge("KYNVER_CLEANUP_TERMINAL_WORKTREES_AGE_MS",216e5),a=e.runDirectoriesAgeMs??ge("KYNVER_CLEANUP_RUN_DIRECTORIES_AGE_MS",36e5),u=e.maxActionsPerSweep??ge("KYNVER_CLEANUP_MAX_ACTIONS_PER_SWEEP",120),l=e.includeOrphans===!0||He("KYNVER_CLEANUP_INCLUDE_ORPHANS"),d=He("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&&!He("KYNVER_CLEANUP_SKIP_BYTE_ACCOUNTING"),g=ge("KYNVER_CLEANUP_STORAGE_ENTRY_CAP",2e3),p=e.storagePerRunEntryCap!==void 0?e.storagePerRunEntryCap:m&&g>0?g:null,R=ge("KYNVER_CLEANUP_BYTE_ENTRY_CAP",2e3),S=e.byteAccountingEntryCap??(Number.isFinite(R)&&R>0?Math.floor(R):2e3);return{execute:r,finalizeStaleRuns:n,scanDependencyCaches:o,nodeModulesAgeMs:t,worktreesAgeMs:s>0?s:0,terminalWorktreesAgeMs:i>=0?i:0,runDirectoriesAgeMs:a>=0?a:0,maxActionsPerSweep:Number.isFinite(u)&&u>0?Math.floor(u):120,includeOrphans:l,runIdFilter:d?String(d):void 0,accountBytes:m,storagePerRunEntryCap:p,byteAccountingEntryCap:S}}F();import{existsSync as Wn,statSync as xu}from"node:fs";import Nr from"node:path";b();var Cu=1800*1e3;function ds(e){let r=e.now??Date.now(),n=e.heartbeatFreshMs??Cu;if(!Wn(e.worktreePath))return null;if(e.runId&&e.workerName){let l=Nr.join(e.harnessRoot,"runs",e.runId,"workers",e.workerName),c=_(Nr.join(l,"worker.json"),void 0);if(c&&xn(c,r,n))return"active_worker";if(!c){let d=Nr.join(l,"heartbeat.jsonl");if(Wn(d))try{let m=r-xu(d).mtimeMs;if(Number.isFinite(m)&&m>=0&&m<n)return"active_worker"}catch{}}}let t=Nr.join(e.worktreePath,".git");if(!Wn(t))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 Eu,readdirSync as ps,statSync as wu}from"node:fs";import Au from"node:path";function ms(e={}){let r=O(e.harnessRoot??Q()),n=Ee(r),t=e.now??Date.now(),o=new Date(t).toISOString();if(!Eu(n))return{harnessRoot:r,worktreesDir:n,worktreesBytes:0,runCount:0,workerCount:0,oldestRunAt:null,scannedAt:o};let s=0,i=0,a=0,u=null,l;try{l=ps(n,{withFileTypes:!0})}catch{return{harnessRoot:r,worktreesDir:n,worktreesBytes:null,runCount:0,workerCount:0,oldestRunAt:null,scannedAt:o}}for(let c of l){if(!c.isDirectory())continue;i+=1;let d=Au.join(n,c.name);try{let m=wu(d);u=u===null?m.mtimeMs:Math.min(u,m.mtimeMs)}catch{}try{for(let m of ps(d,{withFileTypes:!0}))m.isDirectory()&&(a+=1)}catch{}if(s!==null&&e.perRunEntryCap!==null){let m=e.perRunEntryCap??5e4;if(m<=0)s=null;else{let g=X(d,m);g===null?s=null:s+=g}}}return{harnessRoot:r,worktreesDir:n,worktreesBytes:s,runCount:i,workerCount:a,oldestRunAt:u===null?null:new Date(u).toISOString(),scannedAt:o}}Y();import{existsSync as Pu}from"node:fs";import{homedir as Iu}from"node:os";import fs from"node:path";var Ou=["/var/tmp/kynver-harness",fs.join(Iu(),".openclaw","harness")];function Mn(e,r,n){if(!n?.trim())return;let t=O(n.trim());e.has(t)||(e.add(t),r.push(t))}function Du(e){return e.scanWellKnown!=null?e.scanWellKnown:process.env.VITEST==="true"?!1:process.env.KYNVER_CLEANUP_SCAN_WELL_KNOWN!=="0"&&!["0","false","no"].includes((process.env.KYNVER_CLEANUP_SCAN_WELL_KNOWN??"").toLowerCase())}function gs(e={}){let r=new Set,n=[];Mn(r,n,e.harnessRoot??Q());let t=process.env.KYNVER_CLEANUP_EXTRA_ROOTS?.split(",").map(o=>o.trim()).filter(Boolean);for(let o of t??[])Mn(r,n,o);if(Du(e))for(let o of Ou){let s=fs.resolve(o);!r.has(s)&&Pu(s)&&Mn(r,n,s)}return n}or();function Nu(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function Wu(e,r){let n=process.env[e];if(!n)return r;let t=Number(n);return Number.isFinite(t)?t:r}function hs(e={}){let r=e.diskPath?.trim()||process.env.KYNVER_DISK_GUARD_PATH?.trim()||"/",n=Wu("KYNVER_DISK_GUARD_MAX_USED_PERCENT",75),t=tr({...e,diskPath:r,diskMaxUsedPercent:e.diskMaxUsedPercent??n}),o=!t.ok||t.usedPercent>=n,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:t,pressured:o,maxUsedPercent:n}}function ks(e,r){if(!r.pressured)return e;let n=e.execute||!Nu("KYNVER_CLEANUP_DRY_RUN_ON_PRESSURE");return{...e,execute:n,nodeModulesAgeMs:0,runIdFilter:void 0,includeOrphans:!0,terminalWorktreesAgeMs:0,runDirectoriesAgeMs:0,worktreesAgeMs:e.worktreesAgeMs>0?e.worktreesAgeMs:6048e5,diskPressure:!0,diskGate:r.diskGate}}nr();import{unlinkSync as Mu}from"node:fs";function Wr(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function Rs(e,r){let n=process.env[e];if(!n)return r;let t=Number(n);return Number.isFinite(t)?t:r}function Tu(e,r,n){return e.length===0?[]:n?[...e]:e.length<=r?[]:e.slice(r)}function ys(e={}){let r=e.execute===!0||Wr("KYNVER_WSL_CRASH_DUMP_EXECUTE")||Wr("KYNVER_CLEANUP_EXECUTE"),n=e.purgeAll===!0||Wr("KYNVER_WSL_CRASH_DUMP_PURGE_ALL"),t=Math.max(0,e.keepNewest??Rs("KYNVER_WSL_CRASH_DUMP_KEEP_NEWEST",n?0:1)),o=Se({forceWsl:e.forceWsl});if(!o?.path)return{observation:o,execute:r,keepNewest:t,removed:[],removedBytes:0,skipped:o?.probeError?[{path:o.path??"(unresolved)",reason:o.probeError}]:[]};let s=Tu(o.dumps,t,n),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:t,removed:i,removedBytes:u,skipped:a}}function bs(e){return e?Wr("KYNVER_WSL_CRASH_DUMP_CLEANUP")||!e.ok?!0:e.dumpCount>Rs("KYNVER_WSL_CRASH_DUMP_KEEP_NEWEST",1):!1}nr();function W(e,r){if(process.env.KYNVER_CLEANUP_QUIET==="1")return;let n=r?`: ${r}`:"";console.error(`[kynver cleanup] ${e}${n}`)}F();var Mr=class{aheadOfMain=new Map;countAheadOfMain(r,n="origin/main"){let t=`${r}\0${n}`;if(this.aheadOfMain.has(t))return this.aheadOfMain.get(t)??null;let o=w(r,["rev-list","--count",`${n}..HEAD`]);if(o.status!==0)return this.aheadOfMain.set(t,null),null;let s=Number(o.stdout.trim()),i=Number.isFinite(s)?s:null;return this.aheadOfMain.set(t,i),i}};import{spawnSync as Uu}from"node:child_process";import{existsSync as Bu}from"node:fs";import Ku from"node:path";var Fu=5e3;function Hu(e,r){if(!Bu(Ku.join(e,".git")))return{status:null,stdout:"",stderr:"",error:"not_a_git_repo"};try{let n=Uu("git",r,{cwd:e,encoding:"utf8",timeout:Fu}),t=n.error?.message?.includes("ETIMEDOUT")===!0;return{status:t?null:n.status,stdout:n.stdout||"",stderr:n.stderr||"",error:t?"git_timeout":n.error?n.error.message:null}}catch(n){return{status:null,stdout:"",stderr:"",error:n.message}}}function Ss(e){let r=Hu(e,["status","--short"]);return r.error==="not_a_git_repo"?[]:r.error==="git_timeout"||r.status!==0?null:r.stdout.split(`
16
+ `).map(n=>n.trim()).filter(Boolean)}var Tr=class{cache=new Map;porcelain(r){let n=r,t=this.cache.get(n);if(t!==void 0)return t;let o=Ss(n)??[];return this.cache.set(n,o),o}};var Ur=class{cache=new Map;derive(r){let n=this.cache.get(r.id);if(n!==void 0)return n;let t=me(r);return this.cache.set(r.id,t),t}};function Lu(e){let r={};for(let n of e)r[n.kind]=(r[n.kind]??0)+1;return r}function vs(e,r={}){let n=r.maxSampleActions??12,t=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:Lu(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,n).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,t)}}function ju(e={}){let r=e.harnessRoot?O(e.harnessRoot):Q(),n=gs({harnessRoot:r}),t=e.now??Date.now();return{harnessRoot:r,scanRoots:n,now:t}}function $u(e){return typeof e=="string"?{reason:e}:e}function Ae(e,r,n,t){e.push({path:r,reason:n,...t?{detail:t}:{}})}function Br(e,r,n){return!r||e.bytes!=null?e:{...e,bytes:X(e.path,n)}}function _s(e,r){let n={};for(let t of r)n[t.reason]=(n[t.reason]??0)+1;for(let t of e)t.skipReason&&(n[t.skipReason]=(n[t.skipReason]??0)+1);return n}function Gu(e,r){return e.kind==="remove_next_cache"?zo(e,r):Vo(e,r)}function Yu(e,r,n){return e.kind==="remove_next_cache"?Pr(e.path,r,n):Ar(e.path,r,n)}function Vu(e){let r=new Map;for(let n of e)for(let[t,o]of ls(n))r.set(t,o);return r}function xs(e,r){return e.runId&&e.worker?M.join(r,e.runId,e.worker):M.resolve(e.path,"..")}function zu(e={}){let r=cs(e),n=hs();r=ks(r,n);let t=ju(e);W("scan",`${t.scanRoots.length} harness root(s)`);let o=Ao(t.scanRoots,t.now),s=r.finalizeStaleRuns?lo().map(h=>({runId:h.runId,from:h.from,to:h.to})):[];s.length>0&&W("finalize",`${s.length} stale run(s) marked terminal`),W("index","building worktree index");let i=Vu(t.scanRoots);W("index",`${i.size} indexed worktree(s)`);let a={runTerminalCache:new Ur,gitStatusCache:new Tr,gitRevCache:new Mr},u=[],l=[],c=new Set,d=r.maxActionsPerSweep,m=()=>l.length>=d;for(let h of t.scanRoots){if(m())break;W("root",h);let q=M.join(h,"worktrees"),je=us(i,h),$e={harnessRoot:h,worktreesDir:q,nodeModulesAgeMs:r.nodeModulesAgeMs,worktreesAgeMs:r.worktreesAgeMs,includeOrphans:r.includeOrphans,runIdFilter:r.runIdFilter,index:je,now:t.now},Kr=r.scanDependencyCaches?ss($e):[];W("dependency",r.scanDependencyCaches?`${Kr.length} cache candidate(s) at ${h}`:"skipped (worktree-only sweep)");let Fr=0;for(let T of Kr){if(m())break;Fr+=1,Fr%50===0&&W("dependency",`${Fr}/${Kr.length} evaluated`);let x=M.resolve(T.path);if(c.has(x))continue;c.add(x);let k={...T,path:x},I=Yu(k,h,q);if(I){Ae(u,k.path,I),l.push({...k,executed:!1,skipped:!0,skipReason:I});continue}let U=xs(k,q),he=je.get(M.resolve(U))??null,K=En({indexed:he,includeOrphans:!0,nodeModulesAgeMs:r.nodeModulesAgeMs,ageMs:k.ageMs,worktreePath:U,activeWorktreePaths:o.activeWorktreePaths,diskPressure:r.diskPressure,gitStatusCache:a.gitStatusCache});if(K){Ae(u,k.path,K),l.push({...k,executed:!1,skipped:!0,skipReason:K});continue}l.push(Gu(Br(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}if(r.scanDependencyCaches)for(let T of es($e)){if(m())break;let x=M.resolve(T.path);if(c.has(x))continue;c.add(x);let k={...T,path:x},I=Ir(k.path,h,q);if(I){Ae(u,k.path,I),l.push({...k,executed:!1,skipped:!0,skipReason:I});continue}let U=xs(k,q),he=je.get(M.resolve(U))??null,K=xo({indexed:he,includeOrphans:!0,nodeModulesAgeMs:r.nodeModulesAgeMs,ageMs:k.ageMs,worktreePath:U,activeWorktreePaths:o.activeWorktreePaths,diskPressure:r.diskPressure,gitStatusCache:a.gitStatusCache});if(K){Ae(u,k.path,K),l.push({...k,executed:!1,skipped:!0,skipReason:K});continue}l.push(Jo(Br(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}let Hr=[...rs($e),...as($e)];W("worktrees",`${Hr.length} candidate(s) at ${h}`);let Tn=new Set,Lr=0;for(let T of Hr){if(m())break;Lr+=1,Lr%50===0&&W("worktrees",`${Lr}/${Hr.length} evaluated`);let x=M.resolve(T.path);if(Tn.has(x))continue;Tn.add(x);let k={...T,path:x},I=je.get(M.resolve(k.path))??null,U=I?null:ds({worktreePath:k.path,harnessRoot:h,runId:k.runId,workerName:k.worker,now:t.now}),he=_o({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:t.now,harnessRoot:h,writeSalvageEvidence:r.execute});if(he){let{reason:K,detail:Cs}=$u(he);Ae(u,k.path,K,Cs),l.push({...k,executed:!1,skipped:!0,skipReason:K});continue}l.push(qo(Br(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}if(!m()&&r.runDirectoriesAgeMs>=0)for(let T of Mo({harnessRoot:h,worktreesDir:q,runDirectoriesAgeMs:r.runDirectoriesAgeMs,runIdFilter:r.runIdFilter,activeGuards:o,now:t.now})){if(m())break;let x=M.resolve(T.path);if(c.has(x))continue;c.add(x);let k={...T,path:x},I=k.runId??M.basename(x),U=Wo({harnessRoot:h,runId:I,runPath:x,ageMs:k.ageMs,runDirectoriesAgeMs:r.runDirectoriesAgeMs,activeGuards:o});if(U){Ae(u,k.path,U),l.push({...k,executed:!1,skipped:!0,skipReason:U});continue}l.push(Xo(Br(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}}let g=0,p=0,R=0,S=0,y=0,A=0;for(let h of l)h.bytes&&(g+=h.bytes),!h.skipped&&!h.executed&&h.bytes&&(R+=h.bytes),h.executed?(y+=1,S+=h.bytes??0,h.kind==="remove_run_directory"&&(p+=1)):h.skipped&&(A+=1,h.skipReason==="dry_run"&&h.bytes&&(R+=h.bytes));let j=r.accountBytes?ms({harnessRoot:t.harnessRoot,now:t.now,perRunEntryCap:r.storagePerRunEntryCap}):void 0,B=Se(),Le=r.execute&&bs(B),$=Le?ys({execute:!0}):null,re=B?{observed:!0,execute:Le,dumpCount:B.dumpCount,totalBytes:B.totalBytes,removedCount:$?.removed.length??0,removedBytes:$?.removedBytes??0,executables:B.executables,path:B.path,reason:B.reason}:void 0;$&&$.removed.length>0&&(S+=$.removedBytes,y+=$.removed.length,W("wsl-crashes",`removed ${$.removed.length} dump(s), ${$.removedBytes} bytes`)),W("complete",`${l.length} action(s), ${A} skipped, ${y} removed`);let ne=Eo(l,u),P=vs({harnessRoot:t.harnessRoot,scanRoots:t.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(t.now).toISOString(),finalizedRuns:s,actions:l,skips:u,totals:{candidateBytes:g,reclaimableBytes:R,removedBytes:S,removedPaths:y,skippedPaths:A,skipReasons:_s(l,u)},...j?{storage:j}:{},...ne.length>0?{preservedLivePaths:ne}:{},...p>0?{removedRunDirectories:p}:{},...re?{wslCrashDumps:re}:{}});return{harnessRoot:t.harnessRoot,scanRoots:t.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(t.now).toISOString(),finalizedRuns:s,actions:l,skips:u,totals:{candidateBytes:g,reclaimableBytes:R,removedBytes:S,removedPaths:y,skippedPaths:A,skipReasons:_s(l,u)},...j?{storage:j}:{},...ne.length>0?{preservedLivePaths:ne}:{},...p>0?{removedRunDirectories:p}:{},...re?{wslCrashDumps:re}:{},compactSummary:P}}export{wr as DEFAULT_MAX_ACTIONS_PER_SWEEP,wn as DEFAULT_NODE_MODULES_AGE_MS,An as DEFAULT_RUN_DIRECTORIES_AGE_MS,Er as DEFAULT_WORKTREES_AGE_MS,zu as runHarnessCleanup};
@@ -0,0 +1,2 @@
1
+ export { RUNTIME_CONTEXT_BUDGET_RECEIPT_SCHEMA_VERSION, RUNTIME_CONTEXT_BUDGET_RECEIPT_V2_SCHEMA_VERSION, buildContextBudgetReceiptV2, estimateTokensFromChars, finalizeReceiptTotals, isRuntimeContextBudgetReceiptV2, sectionReceiptFromMarkdown, upgradeReceiptToV2, type BuildContextBudgetReceiptV2Input, type ContextBudgetReceiptSurface, type ContextEnvelopeMode, type RuntimeContextActiveStateLookup, type RuntimeContextActiveStateLookupKind, type RuntimeContextActiveStateLookupStatus, type RuntimeContextBudgetReceipt, type RuntimeContextBudgetReceiptSchemaVersion, type RuntimeContextBudgetReceiptV2, type RuntimeContextRehydrationKind, type RuntimeContextRehydrationRoute, type RuntimeContextSection, type RuntimeContextSectionReceipt, type UsefulContextCoverage, } from "../context-budget-receipt.js";
2
+ export { MEMORY_LANE_PREVIEW_CHARS, buildChatMemoryShadowPreview, buildLegacyChatMemorySection, chatMemoriesToPreviewItems, formatContextPreviewMemoryBlock, type ContextPreviewBlockInput, type ContextPreviewMemoryItem, } from "../context-preview/chat-memory-preview.js";
@@ -0,0 +1,6 @@
1
+ var C="runtime-context-budget-receipt.v1",u="runtime-context-budget-receipt.v2";function l(e){return!Number.isFinite(e)||e<=0?0:Math.ceil(e/4)}function R(e,t,n){let o=t?.length??0;return{section:e,chars:o,estimatedTokens:l(o),...n}}function c(e,t){let n=e.reduce((i,r)=>i+r.chars,0),o=e.reduce((i,r)=>i+r.estimatedTokens,0),s=e.reduce((i,r)=>i+(r.omittedCount??0),0),a=e.reduce((i,r)=>i+(r.duplicatesCollapsed??0),0);return{totalChars:n,estimatedTokens:o,duplicatesCollapsed:t?.duplicatesCollapsed??a,omittedCount:t?.omittedCount??s}}function d(e){let t=c(e.sections,{duplicatesCollapsed:e.duplicatesCollapsed,omittedCount:e.omittedCount});return{schemaVersion:u,surface:e.surface,agentOsId:e.agentOsId?.trim()||null,taskId:e.taskId?.trim()||null,planId:e.planId?.trim()||null,personaSlug:e.personaSlug?.trim().toLowerCase()||null,mode:e.mode,generatedAt:e.generatedAt,...t,finalSerializedChars:e.finalSerializedChars,finalSerializedTokens:l(e.finalSerializedChars),usefulContextCoverage:e.usefulContextCoverage,budgetSatisfied:e.budgetSatisfied??!0,overBudgetReason:e.overBudgetReason??null,activeStateLookups:e.activeStateLookups??[],sections:e.sections}}function g(e,t){return d({surface:t.surface,agentOsId:t.agentOsId??e.agentOsId,taskId:t.taskId??e.taskId,planId:t.planId??e.planId,personaSlug:t.personaSlug??e.personaSlug,mode:t.mode??e.mode,generatedAt:t.generatedAt??e.generatedAt,finalSerializedChars:t.finalSerializedChars,sections:e.sections,usefulContextCoverage:t.usefulContextCoverage,activeStateLookups:t.activeStateLookups??e.activeStateLookups,duplicatesCollapsed:t.duplicatesCollapsed??e.duplicatesCollapsed,omittedCount:t.omittedCount??e.omittedCount,budgetSatisfied:t.budgetSatisfied,overBudgetReason:t.overBudgetReason})}function x(e){return e.schemaVersion===u}var S=160,f="agent_os_search_memory";function _(e,t){let n=e.trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}\u2026`}function p(e){let t=e.previewCharsPerItem??160,n=[`## ${e.sectionTitle} (preview)`,""];if(e.items.length===0)return n.push(e.emptyFallback??"None selected. Use search_memory or authorized expansion routes for deeper context."),n.join(`
2
+ `).trim();for(let o of e.items){let s=o.selectedBecause?` \xB7 ${o.selectedBecause}`:"",a=o.trust?` [${o.trust}]`:"",i=o.lane?` (${o.lane})`:"";n.push(`- **${o.slug}**${a}${i}${s}`),n.push(` ${_(o.contentPreview,t)}`),o.expansionRoute&&n.push(` _(expand: ${o.expansionRoute})_`)}return n.push("","Preview-only injection \u2014 full bodies require explicit expansion."),n.join(`
3
+ `).trim()}function m(e){return e.map((t,n)=>({slug:`recalled-${n+1}`,lane:null,trust:null,contentPreview:t.content,selectedBecause:"relevant_match",expansionRoute:`${f}({ query: "<topic>" })`,expandable:t.content.length>160}))}function E(e){return e.length>0?`## Retrieved Memories
4
+ ${e.map(t=>`- ${t.content}`).join(`
5
+ `)}`:`## Retrieved Memories
6
+ None retrieved. Use search_memory to look up specific topics.`}function I(e){return p({sectionTitle:"Retrieved Memories",items:m(e),emptyFallback:"None retrieved. Use search_memory to look up specific topics."})}export{S as MEMORY_LANE_PREVIEW_CHARS,C as RUNTIME_CONTEXT_BUDGET_RECEIPT_SCHEMA_VERSION,u as RUNTIME_CONTEXT_BUDGET_RECEIPT_V2_SCHEMA_VERSION,I as buildChatMemoryShadowPreview,d as buildContextBudgetReceiptV2,E as buildLegacyChatMemorySection,m as chatMemoriesToPreviewItems,l as estimateTokensFromChars,c as finalizeReceiptTotals,p as formatContextPreviewMemoryBlock,x as isRuntimeContextBudgetReceiptV2,R as sectionReceiptFromMarkdown,g as upgradeReceiptToV2};
@@ -0,0 +1 @@
1
+ export { resolveProductionDatabaseUrl, type DbCredentialFailure, type DbCredentialResolution, type DbCredentialSource, type ResolveProductionDatabaseOptions, type ResolveProductionDatabaseResult, } from "../db-credential-resolver.js";
@@ -0,0 +1,2 @@
1
+ import{execFileSync as m,spawnSync as I}from"node:child_process";import*as R from"node:fs";import*as v from"node:path";import*as u from"node:fs";import{homedir as O}from"node:os";import*as c from"node:path";function P(e){return e.startsWith("~/")?c.join(O(),e.slice(2)):e}function p(e={}){let n=e.env??process.env,o=e.cwd??process.cwd(),r=e.homeDir??(n.HOME?.trim()||n.USERPROFILE?.trim()||O()),t=new Set,s=[],l=E=>{let i=c.resolve(P(E));t.has(i)||(t.add(i),s.push(i))},d=n.KYNVER_ENV_FILE?.trim();d&&l(d);let _=o;for(let E=0;E<12;E+=1){l(c.join(_,".env"));let i=c.dirname(_);if(i===_)break;_=i}l(c.join(r,".kynver",".env"));try{let E=c.join(r,".kynver","config.json");if(u.existsSync(E)){let A=JSON.parse(u.readFileSync(E,"utf8")).defaultRepo?.trim();A&&l(c.join(A,".env"))}}catch{}return s}function N(e){if(!e?.trim())return"(not set)";try{let n=new URL(e),o=(n.pathname||"").replace(/^\//,"").split("?")[0]||"(no database name)";return`${n.hostname} / ${o}`}catch{return"(invalid URL)"}}var b=["ANTHROPIC_API_KEY","ANALYST_API_KEY","RECRUITER_API_KEY","AUTH_SECRET","NEXTAUTH_SECRET","DATABASE_URL","PRODUCTION_DATABASE_URL","KYNVER_PRODUCTION_DATABASE_URL","REDIS_URL","GOOGLE_CLIENT_SECRET","GITHUB_CLIENT_SECRET","KYNVER_API_KEY","KYNVER_SERVICE_SECRET","KYNVER_RUNTIME_SECRET","KYNVER_CRON_SECRET","OPENCLAW_CRON_SECRET","QSTASH_TOKEN","QSTASH_CURRENT_SIGNING_KEY","QSTASH_NEXT_SIGNING_KEY","TOOL_SECRETS_KEK","TOOL_EXECUTOR_DISPATCH_SECRET","CLOUDFLARE_API_TOKEN","STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_IDENTITY_WEBHOOK_SECRET","VOYAGE_API_KEY","PERPLEXITY_API_KEY","FRED_API_KEY","FMP_API_KEY","CURSOR_API_KEY","MEMORY_CONTENT_KEK","LLM_BYOK_KEK","KYNVER_COMMAND_AUTH_KEY","KYNVER_INSTRUCTION_BUNDLE_KEY","KYNVER_MEMORY_LEDGER_KEY","KYNVER_JWKS_PRIVATE_KEY_JWK"],k=new Set(b);var T=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN"],B=new Set(T);var K="KYNVER_NO_PROD_DB_CREDENTIALS";var C=new Set(["1","true","yes","on"]);function D(e){let n=e[K]?.trim().toLowerCase();return n!==void 0&&C.has(n)}var f=["KYNVER_PRODUCTION_DATABASE_URL","PRODUCTION_DATABASE_URL"],S=[...f];function a(e,n){return e[n]?.trim()||void 0}function h(e){if(!R.existsSync(e))return{};let n={},o=new Set(S);for(let r of R.readFileSync(e,"utf8").split(`
2
+ `)){let t=r.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);if(!t||!o.has(t[1]))continue;let s=t[1];n[s]=t[2].replace(/^["']|["']$/g,"").trim()}return n}function g(e){for(let n of f){let o=a(e,n);if(o)return{ok:!0,databaseUrl:o,source:`env:${n}`,hint:N(o)}}return null}function Y(e,n){for(let o of p({cwd:e,env:n})){let r=h(o);for(let t of S){let s=r[t]?.trim();if(s)return{ok:!0,databaseUrl:s,source:`env-file:${t}`,hint:`${N(s)} (${v.basename(o)})`}}}return null}function L(e){let n=process.platform==="win32"?"neon.cmd":"neon",o=["connection-string",e.branch,"--prisma","-o","json","--no-color","--no-analytics"];e.projectId&&o.push("--project-id",e.projectId),e.databaseName&&o.push("--database-name",e.databaseName),e.roleName&&o.push("--role-name",e.roleName),e.pooled&&o.push("--pooled");let r;try{let t=I(n,o,{encoding:"utf8",env:process.env,timeout:3e4});if(t.status!==0)return null;r=(t.stdout||"").trim()}catch{try{r=m("neonctl",o,{encoding:"utf8",env:process.env,timeout:3e4}).trim()}catch{return null}}if(!r)return null;try{let t=JSON.parse(r),s=typeof t.connection_uri=="string"&&t.connection_uri||typeof t.connection_string=="string"&&t.connection_string||typeof t.connectionString=="string"&&t.connectionString;if(s)return s}catch{}return/^postgres(ql)?:\/\//i.test(r)?r:null}function w(e,n){let o=a(e,"KYNVER_NEON_BRANCH")||a(e,"NEON_BRANCH")||"production",r=n({branch:o,projectId:a(e,"KYNVER_NEON_PROJECT_ID")||a(e,"NEON_PROJECT_ID"),databaseName:a(e,"KYNVER_NEON_DATABASE_NAME")||a(e,"NEON_DATABASE_NAME"),roleName:a(e,"KYNVER_NEON_ROLE_NAME")||a(e,"NEON_ROLE_NAME"),pooled:a(e,"KYNVER_NEON_POOLED")==="1"||a(e,"NEON_POOLED")==="1"});return r?{ok:!0,databaseUrl:r,source:"neon-cli",hint:N(r)}:null}function U(e={}){let n=e.env??process.env;if(D(n))return{ok:!1,reason:"Production database credentials are blocked in this harness worker (KYNVER_NO_PROD_DB_CREDENTIALS). Review workers must use scoped AgentOS APIs \u2014 not direct prod DB access.",attempted:[]};let o=e.cwd??process.cwd(),r=e.neonConnectionString??L,t=[],s=p({cwd:o,env:n}),l=w(n,r);if(t.push("neon-cli"),l)return l;for(let i of f)t.push(`env:${i}`);let d=g(n);if(d)return d;for(let i of S)t.push(`env-file:${i}`);let _=Y(o,n);return _||{ok:!1,reason:"No production database credentials found. Authenticate Neon CLI (`neon auth`), set KYNVER_NEON_* / NEON_* project hints, or provide PRODUCTION_DATABASE_URL / KYNVER_PRODUCTION_DATABASE_URL (process env, KYNVER_ENV_FILE, ~/.kynver/.env, or selective .env keys in the repo / defaultRepo checkout)."+(s.length>0?` Searched env files: ${s.slice(0,6).join(", ")}${s.length>6?"\u2026":""}.`:""),attempted:t}}export{U as resolveProductionDatabaseUrl};