@kynver-app/runtime 0.1.134 → 0.1.135

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,16 +1,16 @@
1
- var k=(e,r)=>()=>(e&&(r=e(e=0)),r);import{existsSync as ro,mkdirSync as to,readFileSync as Gr,readdirSync as Gi,statSync as $r,writeFileSync as no}from"node:fs";import oo from"node:path";function ur(e){console.error(e),process.exit(1)}function cr(e){return process.platform!=="win32"?e:{windowsHide:!0,...e}}function Ee(e){try{return JSON.parse(e)}catch{return null}}function _(e,r){try{return JSON.parse(Gr(e,"utf8"))}catch(t){if(arguments.length>1)return r;ur(`failed to read ${e}: ${t.message}`)}}function Yr(e,r){to(oo.dirname(e),{recursive:!0}),no(e,`${JSON.stringify(r,null,2)}
2
- `)}function b(e){return String(e||"").toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"worker"}function Pe(e){try{return $r(e).size}catch{return 0}}function We(e){try{return $r(e).mtime.toISOString()}catch{return null}}function Vr(e,r){return ro(e)?Gr(e,"utf8").split(`
1
+ var k=(e,r)=>()=>(e&&(r=e(e=0)),r);import{existsSync as to,mkdirSync as no,readFileSync as $r,readdirSync as Gi,statSync as Yr,writeFileSync as oo}from"node:fs";import so from"node:path";function ur(e){console.error(e),process.exit(1)}function cr(e){return process.platform!=="win32"?e:{windowsHide:!0,...e}}function Ee(e){try{return JSON.parse(e)}catch{return null}}function _(e,r){try{return JSON.parse($r(e,"utf8"))}catch(t){if(arguments.length>1)return r;ur(`failed to read ${e}: ${t.message}`)}}function Vr(e,r){no(so.dirname(e),{recursive:!0}),oo(e,`${JSON.stringify(r,null,2)}
2
+ `)}function b(e){return String(e||"").toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"worker"}function Pe(e){try{return Yr(e).size}catch{return 0}}function We(e){try{return Yr(e).mtime.toISOString()}catch{return null}}function zr(e,r){return to(e)?$r(e,"utf8").split(`
3
3
  `).slice(-r).join(`
4
- `):""}function L(e){if(!e)return!1;try{return process.kill(e,0),!0}catch{return!1}}function zr(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 lr(e){return Math.max(0,Math.round((Date.now()-e)/1e3))}var y=k(()=>{"use strict"});var so,Vi,Jr=k(()=>{"use strict";so=["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"],Vi=new Set(so)});import{spawnSync as Xr}from"node:child_process";function le(e,r,t={}){let n=Xr("git",r,cr({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);ur(o)}return n.stdout||""}function de(e){return le(e,["status","--short"],{allowFailure:!0}).split(`
5
- `).map(r=>r.trim()).filter(Boolean)}function v(e,r){try{let t=Xr("git",r,cr({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 qr(e,r,t){let n=v(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 Oe(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 dr(n,"missing worktree path");let s=v(e,["rev-parse","HEAD"]);if(s.status!==0)return dr(n,s.error||s.stderr||s.stdout||"failed to resolve HEAD");let i;if(o)i=o;else{let f=v(e,["rev-parse",n]);if(f.status!==0)return dr(n,f.error||f.stderr||f.stdout||`failed to resolve ${n}`,s.stdout.trim());i=f.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=qr(e,i,a),c=qr(e,a,i),l=u.error||c.error||void 0;if(u.isAncestor==null||c.isAncestor==null)return{checked:!1,base:n,head:a,baseHead:i,baseIsAncestorOfHead:u.isAncestor,headIsAncestorOfBase:c.isAncestor,relation:"unknown",...l?{error:l}:{}};let p=u.isAncestor?"ahead":c.isAncestor?"merged":"diverged";return{checked:!0,base:n,head:a,baseHead:i,baseIsAncestorOfHead:u.isAncestor,headIsAncestorOfBase:c.isAncestor,relation:p,...l?{error:l}:{}}}function dr(e,r,t=null){return{checked:!1,base:e,head:t,baseHead:null,baseIsAncestorOfHead:null,headIsAncestorOfBase:null,relation:"unknown",error:r}}var H=k(()=>{"use strict";y();Jr()});import{homedir as Qr}from"node:os";import Zr from"node:path";function io(e){return e==="~"?Qr():e.startsWith("~/")||e.startsWith("~\\")?Zr.join(Qr(),e.slice(2)):e}function Ie(e){return Zr.resolve(io(e))}var pe=k(()=>{"use strict"});var pr=k(()=>{"use strict";H();pe()});var fr=k(()=>{"use strict"});var et=k(()=>{"use strict"});import{existsSync as ao,readFileSync as uo,statfsSync as co}from"node:fs";function mo(){if(process.platform!=="linux")return!1;for(let e of["/proc/sys/kernel/osrelease","/proc/version"])try{if(!ao(e))continue;let r=uo(e,"utf8");if(/microsoft|wsl/i.test(r))return!0}catch{}return!1}function rt(e={}){if(!(e.forceWsl===void 0?mo():e.forceWsl))return null;let t=e.wslHostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||fo,n=e.wslHostFreeWarnBytes??lo,o=e.wslHostFreeCriticalBytes??po,s=e.statfs??co,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),c=u>0?(u-a)/u*100:100,l=a<n,p=a<o,f=!l&&!p,g=(a/(1024*1024*1024)).toFixed(1),d=null;return f||(d=`Windows host disk ${t} at ${p?"critical":"warning"}: ${g} GiB free (<${(p?o:n)/1024/1024/1024} GiB); WSL VHDX cannot grow safely. ${go()}`),{ok:f,path:t,freeBytes:a,totalBytes:u,usedPercent:c,warnBelowBytes:n,criticalBelowBytes:o,reason:d,probeError:null}}function go(){return"Recovery: 1) free Windows C: (empty Recycle Bin / Storage Sense / clear %TEMP%); 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. Full runbook: docs/runbooks/wsl-disk-pressure.md."}var lo,po,fo,tt=k(()=>{"use strict";lo=25*1024*1024*1024,po=12*1024*1024*1024,fo="/mnt/c"});import{statfsSync as ho}from"node:fs";function Ne(e={}){let r=e.diskPath?.trim()||"/",t=e.diskFreeWarnBytes??ko,n=e.diskFreeCriticalBytes??Ro,o=e.diskMaxUsedPercent??yo,s=e.diskHardMaxUsedPercent??bo,i=ho(r),a=Number(i.bavail)*Number(i.bsize),u=Number(i.blocks)*Number(i.bsize),c=u>0?(u-a)/u*100:100,l=a<t,p=a<n,f=a<t*2,g=f&&c>o,d=f&&c>s,R=!l&&!p&&!g&&!d,x=e.skipWslHostCheck?null:rt(e.wslHost),W=R&&(x?x.ok:!0),U=null;return W||(U=[p?`free space below critical ${n} bytes`:null,l?`free space below warning ${t} bytes`:null,d?`used percent above hard cap ${s}%`:null,g?`used percent above cap ${o}%`:null,x&&!x.ok?x.reason:null].filter(Boolean).join("; ")),So({ok:W,path:r,freeBytes:a,totalBytes:u,usedPercent:c,warnBelowBytes:t,criticalBelowBytes:n,maxUsedPercent:o,hardMaxUsedPercent:s,reason:U,wslHost:x})}function So(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 ko,Ro,yo,bo,Me=k(()=>{"use strict";tt();ko=30*1024*1024*1024,Ro=15*1024*1024*1024,yo=80,bo=90});import{existsSync as _o,readdirSync as xo,statSync as vo}from"node:fs";import mr from"node:path";function De(){return ot()}function gr(){let{runsDir:e}=De();return nt(e)}function Te(e){return nt(B(e))}function Co(e){try{return vo(e).isDirectory()}catch{return!1}}function nt(e){if(!_o(e))return[];let r=[];for(let t of xo(e,{withFileTypes:!0})){if(t.name==="runs")continue;let n=mr.join(e,t.name);if(!Co(n))continue;let o=_(mr.join(n,"run.json"),void 0);o?.id&&r.push(o)}return r}function hr(e){let{runsDir:r}=De();Yr(mr.join(kr(r,e.id),"run.json"),e)}function fe(e){let{harnessRoot:r}=De();return me(r,e)}function me(e,r){return kr(B(e),b(r))}var V=k(()=>{"use strict";F();y()});import{existsSync as Ao,readdirSync as wo}from"node:fs";import Eo from"node:path";function Rr(e){let r=new Set;for(let n of Object.keys(e.workers||{}))r.add(b(n));let t=Eo.join(fe(e.id),"workers");if(!Ao(t))return[...r];for(let n of wo(t,{withFileTypes:!0}))n.isDirectory()&&r.add(b(n.name));return[...r]}var yr=k(()=>{"use strict";V();y()});function br(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 st(e){let r=e.trim();if(!r)return null;let t=br(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let u=br(s[1]??"");u&&n.push(u)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let u=br(r.slice(i,a+1));u&&n.push(u)}return n.length>0?n[n.length-1]:null}function it(e){let r=e.finalResult??e.final_result;if(r!=null)return typeof r=="string"?st(r)??(r.trim()||null):r;let t=typeof e.summary=="string"?e.summary.trim():"";if(!t)return null;let n=st(t);return n||t}var at=k(()=>{"use strict"});import{existsSync as Po,readFileSync as Wo}from"node:fs";function ut(e){return e==="complete"}function ct(e){return ut(e.lastHeartbeatPhase)?e.terminalFinalResult!==void 0&&e.terminalFinalResult!==null?e.terminalFinalResult:e.lastHeartbeatSummary?.trim()||"completed":null}function oe(e){let r={heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,terminalFinalResult:null,heartbeatBlocker:null,timestampAnomalies:[],lastBoxResourceSnapshot:null,lastPrEvidence:[]};if(!Po(e))return r;let t=Date.now()+Oo,n=new Date(t).toISOString(),o=Wo(e,"utf8").split(`
6
- `).filter(Boolean);for(let s of o){let i=Ee(s);if(!i||typeof i!="object"||Array.isArray(i))continue;let a=i;if(r.heartbeatCount++,a.ts){let u=String(a.ts),c=Date.parse(u);Number.isFinite(c)&&c>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)),ut(r.lastHeartbeatPhase)&&(r.terminalFinalResult=it(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 Oo,Ue=k(()=>{"use strict";at();y();Oo=6e4});function Mo(e){return e?(e.split("/").pop()??e).replace(/\.exe$/i,"").toLowerCase():null}function Do(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 To(e){let r=Mo(e[0]);return!!(r&&Io.has(r))}function Sr(e){return!e||e.includes("/")||e.includes("*")?!1:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(e)}function lt(e){if(!e)return!1;let r=e.trim();return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")}function Uo(e){if(!e.startsWith("--glob="))return e;let r=e.slice(7);return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")?`--glob=${r}/**`:e}function Ho(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;No.has(n)&&(t+=1);continue}r.push(n)}}return r}function Bo(e){let r=!1,t=e.map(o=>{let s=Uo(o);return s!==o&&(r=!0),s}),n=Ho(t);if(n.length===2){let[o,s]=n;if(Sr(s))return{argv:[t[0]??"rg","-g",s,o,"."],changed:!0}}return{argv:t,changed:r}}function _r(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=Do(i.trim());if(!a.length||!To(a))return i;let u=Bo(a);return u.changed?(o=!0,u.argv.join(" ")):i});return o?{command:s.join(t),changed:!0}:{command:r,changed:!1}}function dt(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 Fo(e){let{pattern:r,target:t}=dt(e);return r?lt(t)?{kind:"rg_exclude_syntax",pattern:r,target:t}:Sr(t)?{kind:"bad_scope",pattern:r,target:t}:{kind:"not_repo_search",pattern:r,target:t}:{kind:"not_repo_search"}}function Ko(e){let{pattern:r,target:t}=dt(e);if(!r)return null;if(lt(t)){let n=`${t.trim()}/**`;return{command:`rg "${r}" -g '${n}' .`,changed:!0}}return t&&Sr(t)?{command:`rg -g ${t} "${r}" .`,changed:!0}:null}function jo(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 Lo(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 xr(e){let r=e.meta?.trim()||(e.command?Lo(e.command):null)||null;if(r){let t=Fo(r),n=jo(t);if(n)return n;let o=Ko(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=_r(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 Io,No,pt=k(()=>{"use strict";Io=new Set(["rg","ripgrep","grep"]),No=new Set(["-e","--regexp","-f","--file","-m","--max-count","-A","--after-context","-B","--before-context","-C","--context","-g","--glob","--iglob"])});function ge(e,r=200){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function Vo(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 he(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function zo(e){let r=e.metadata;if(!he(r))return null;let t=r.vulnerabilities;if(!he(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 Jo(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 qo(e,r){let t=e.error;if(he(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?ge(o.split(`
4
+ `):""}function L(e){if(!e)return!1;try{return process.kill(e,0),!0}catch{return!1}}function Jr(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 lr(e){return Math.max(0,Math.round((Date.now()-e)/1e3))}var y=k(()=>{"use strict"});var io,Vi,qr=k(()=>{"use strict";io=["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"],Vi=new Set(io)});import{spawnSync as Qr}from"node:child_process";function le(e,r,t={}){let n=Qr("git",r,cr({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);ur(o)}return n.stdout||""}function de(e){return le(e,["status","--short"],{allowFailure:!0}).split(`
5
+ `).map(r=>r.trim()).filter(Boolean)}function v(e,r){try{let t=Qr("git",r,cr({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 Xr(e,r,t){let n=v(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 Oe(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 dr(n,"missing worktree path");let s=v(e,["rev-parse","HEAD"]);if(s.status!==0)return dr(n,s.error||s.stderr||s.stdout||"failed to resolve HEAD");let i;if(o)i=o;else{let f=v(e,["rev-parse",n]);if(f.status!==0)return dr(n,f.error||f.stderr||f.stdout||`failed to resolve ${n}`,s.stdout.trim());i=f.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=Xr(e,i,a),c=Xr(e,a,i),l=u.error||c.error||void 0;if(u.isAncestor==null||c.isAncestor==null)return{checked:!1,base:n,head:a,baseHead:i,baseIsAncestorOfHead:u.isAncestor,headIsAncestorOfBase:c.isAncestor,relation:"unknown",...l?{error:l}:{}};let p=u.isAncestor?"ahead":c.isAncestor?"merged":"diverged";return{checked:!0,base:n,head:a,baseHead:i,baseIsAncestorOfHead:u.isAncestor,headIsAncestorOfBase:c.isAncestor,relation:p,...l?{error:l}:{}}}function dr(e,r,t=null){return{checked:!1,base:e,head:t,baseHead:null,baseIsAncestorOfHead:null,headIsAncestorOfBase:null,relation:"unknown",error:r}}var H=k(()=>{"use strict";y();qr()});import{homedir as Zr}from"node:os";import et from"node:path";function ao(e){return e==="~"?Zr():e.startsWith("~/")||e.startsWith("~\\")?et.join(Zr(),e.slice(2)):e}function Ie(e){return et.resolve(ao(e))}var pe=k(()=>{"use strict"});var pr=k(()=>{"use strict";H();pe()});var fr=k(()=>{"use strict"});var rt=k(()=>{"use strict"});import{existsSync as uo,readFileSync as co,statfsSync as lo}from"node:fs";function go(){if(process.platform!=="linux")return!1;for(let e of["/proc/sys/kernel/osrelease","/proc/version"])try{if(!uo(e))continue;let r=co(e,"utf8");if(/microsoft|wsl/i.test(r))return!0}catch{}return!1}function tt(e={}){if(!(e.forceWsl===void 0?go():e.forceWsl))return null;let t=e.wslHostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||mo,n=e.wslHostFreeWarnBytes??po,o=e.wslHostFreeCriticalBytes??fo,s=e.statfs??lo,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),c=u>0?(u-a)/u*100:100,l=a<n,p=a<o,f=!l&&!p,g=(a/(1024*1024*1024)).toFixed(1),d=null;return f||(d=`Windows host disk ${t} at ${p?"critical":"warning"}: ${g} GiB free (<${(p?o:n)/1024/1024/1024} GiB); WSL VHDX cannot grow safely. ${ho()}`),{ok:f,path:t,freeBytes:a,totalBytes:u,usedPercent:c,warnBelowBytes:n,criticalBelowBytes:o,reason:d,probeError:null}}function ho(){return"Recovery: 1) free Windows C: (empty Recycle Bin / Storage Sense / clear %TEMP%); 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. Full runbook: docs/runbooks/wsl-disk-pressure.md."}var po,fo,mo,nt=k(()=>{"use strict";po=25*1024*1024*1024,fo=12*1024*1024*1024,mo="/mnt/c"});import{statfsSync as ko}from"node:fs";function Ne(e={}){let r=e.diskPath?.trim()||"/",t=e.diskFreeWarnBytes??Ro,n=e.diskFreeCriticalBytes??yo,o=e.diskMaxUsedPercent??bo,s=e.diskHardMaxUsedPercent??So,i=ko(r),a=Number(i.bavail)*Number(i.bsize),u=Number(i.blocks)*Number(i.bsize),c=u>0?(u-a)/u*100:100,l=a<t,p=a<n,f=a<t*2,g=f&&c>o,d=f&&c>s,R=!l&&!p&&!g&&!d,x=e.skipWslHostCheck?null:tt(e.wslHost),W=R&&(x?x.ok:!0),U=null;return W||(U=[p?`free space below critical ${n} bytes`:null,l?`free space below warning ${t} bytes`:null,d?`used percent above hard cap ${s}%`:null,g?`used percent above cap ${o}%`:null,x&&!x.ok?x.reason:null].filter(Boolean).join("; ")),_o({ok:W,path:r,freeBytes:a,totalBytes:u,usedPercent:c,warnBelowBytes:t,criticalBelowBytes:n,maxUsedPercent:o,hardMaxUsedPercent:s,reason:U,wslHost:x})}function _o(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 Ro,yo,bo,So,Me=k(()=>{"use strict";nt();Ro=30*1024*1024*1024,yo=15*1024*1024*1024,bo=80,So=90});import{existsSync as xo,readdirSync as vo,statSync as Co}from"node:fs";import mr from"node:path";function De(){return st()}function gr(){let{runsDir:e}=De();return ot(e)}function Te(e){return ot(B(e))}function Ao(e){try{return Co(e).isDirectory()}catch{return!1}}function ot(e){if(!xo(e))return[];let r=[];for(let t of vo(e,{withFileTypes:!0})){if(t.name==="runs")continue;let n=mr.join(e,t.name);if(!Ao(n))continue;let o=_(mr.join(n,"run.json"),void 0);o?.id&&r.push(o)}return r}function hr(e){let{runsDir:r}=De();Vr(mr.join(kr(r,e.id),"run.json"),e)}function fe(e){let{harnessRoot:r}=De();return me(r,e)}function me(e,r){return kr(B(e),b(r))}var V=k(()=>{"use strict";F();y()});import{existsSync as wo,readdirSync as Eo}from"node:fs";import Po from"node:path";function Rr(e){let r=new Set;for(let n of Object.keys(e.workers||{}))r.add(b(n));let t=Po.join(fe(e.id),"workers");if(!wo(t))return[...r];for(let n of Eo(t,{withFileTypes:!0}))n.isDirectory()&&r.add(b(n.name));return[...r]}var yr=k(()=>{"use strict";V();y()});function br(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 it(e){let r=e.trim();if(!r)return null;let t=br(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let u=br(s[1]??"");u&&n.push(u)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let u=br(r.slice(i,a+1));u&&n.push(u)}return n.length>0?n[n.length-1]:null}function at(e){let r=e.finalResult??e.final_result;if(r!=null)return typeof r=="string"?it(r)??(r.trim()||null):r;let t=typeof e.summary=="string"?e.summary.trim():"";if(!t)return null;let n=it(t);return n||t}var ut=k(()=>{"use strict"});import{existsSync as Wo,readFileSync as Oo}from"node:fs";function ct(e){return e==="complete"}function lt(e){return ct(e.lastHeartbeatPhase)?e.terminalFinalResult!==void 0&&e.terminalFinalResult!==null?e.terminalFinalResult:e.lastHeartbeatSummary?.trim()||"completed":null}function oe(e){let r={heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,terminalFinalResult:null,heartbeatBlocker:null,timestampAnomalies:[],lastBoxResourceSnapshot:null,lastPrEvidence:[]};if(!Wo(e))return r;let t=Date.now()+Io,n=new Date(t).toISOString(),o=Oo(e,"utf8").split(`
6
+ `).filter(Boolean);for(let s of o){let i=Ee(s);if(!i||typeof i!="object"||Array.isArray(i))continue;let a=i;if(r.heartbeatCount++,a.ts){let u=String(a.ts),c=Date.parse(u);Number.isFinite(c)&&c>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)),ct(r.lastHeartbeatPhase)&&(r.terminalFinalResult=at(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 Io,Ue=k(()=>{"use strict";ut();y();Io=6e4});function Mo(e){return e?(e.split("/").pop()??e).replace(/\.exe$/i,"").toLowerCase():null}function Do(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 To(e){let r=Mo(e[0]);return!!(r&&No.has(r))}function Sr(e){return!e||e.includes("/")||e.includes("*")?!1:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(e)}function _r(e){if(!e)return!1;let r=e.trim();return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")}function Uo(e){if(!e.startsWith("--glob="))return e;let r=e.slice(7);return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")?`--glob=${r}/**`:e}function Ho(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;dt.has(n)&&(t+=1);continue}r.push(n)}}return r}function Bo(e){let r=!1,t=e.map((o,s)=>{let i=Uo(o),a=e[s-1];return a&&dt.has(a)&&o.startsWith("!")&&!o.includes("/")&&!o.endsWith("/**")&&(i=`${o}/**`),i!==o&&(r=!0),i}),n=Ho(t);if(n.length===2){let[o,s]=n;if(_r(s))return{argv:[t[0]??"rg",o,"-g",`${s}/**`,"."],changed:!0};if(Sr(s))return{argv:[t[0]??"rg","-g",s,o,"."],changed:!0}}return r&&n.length===1?{argv:[...t,"."],changed:!0}:{argv:t,changed:r}}function xr(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=Do(i.trim());if(!a.length||!To(a))return i;let u=Bo(a);return u.changed?(o=!0,u.argv.join(" ")):i});return o?{command:s.join(t),changed:!0}:{command:r,changed:!1}}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 t=e.match(/^search\s+"(.+)"\s+in\s+(.+)$/iu);return t?{pattern:t[1],target:t[2]?.trim()}:{}}function Fo(e){let{pattern:r,target:t}=pt(e);return r?_r(t)?{kind:"rg_exclude_syntax",pattern:r,target:t}:Sr(t)?{kind:"bad_scope",pattern:r,target:t}:{kind:"not_repo_search",pattern:r,target:t}:{kind:"not_repo_search"}}function Ko(e){let{pattern:r,target:t}=pt(e);if(!r)return null;if(_r(t)){let n=`${t.trim()}/**`;return{command:`rg "${r}" -g '${n}' .`,changed:!0}}return t&&Sr(t)?{command:`rg -g ${t} "${r}" .`,changed:!0}:null}function jo(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 Lo(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 vr(e){let r=e.meta?.trim()||(e.command?Lo(e.command):null)||null;if(r){let t=Fo(r),n=jo(t);if(n)return n;let o=Ko(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=xr(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 No,dt,ft=k(()=>{"use strict";No=new Set(["rg","ripgrep","grep"]),dt=new Set(["-e","--regexp","-f","--file","-m","--max-count","-A","--after-context","-B","--before-context","-C","--context","-g","--glob","--iglob"])});function ge(e,r=200){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function Vo(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 he(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function zo(e){let r=e.metadata;if(!he(r))return null;let t=r.vulnerabilities;if(!he(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 Jo(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 qo(e,r){let t=e.error;if(he(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?ge(o.split(`
7
7
  `).find(Boolean)??o,160):"npm audit failed"}function Xo(e){let r=`${e.stdout}
8
- ${e.stderr}`.trim(),t=Vo(r);if(!t||!he(t)){let o=ge(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(he(t.error))return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit command failed: ${qo(t,e.stderr)}`};let n=zo(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:Jo(n),audit:n}:{kind:"command_failure",exitCode:e.exitCode,summary:"npm audit failed: JSON response missing vulnerability metadata",parseError:"missing_metadata"}}function Qo(e){return Go.test(e)}function Zo(e){return $o.test(e)}function es(e){let r=xr({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&&Yo.test(n)){let i=ge(n,160);return{kind:"command_failure",exitCode:1,summary:r??`ripgrep failed (exit 1): ${i}`}}let o=_r(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=ge(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 ft(e){let r=e.stdout??"",t=e.stderr??"",n=e.interleavedOutput??"";if(Qo(e.command)){let i=r.trim()||n.trim()||t.trim();return Xo({exitCode:e.exitCode,stdout:i,stderr:t})}if(Zo(e.command))return es({command:e.command,exitCode:e.exitCode,stdout:r,stderr:t,interleaved:n});let o=xr({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=ge(n||r||t||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:`command failed (exit ${e.exitCode}): ${s}`}}var Go,$o,Yo,mt=k(()=>{"use strict";pt();Go=/\bnpm\s+audit\b/i,$o=/\b(rg|ripgrep)\b/i,Yo=/\b(error|invalid|unknown|panic|not found)\b/i});import{existsSync as rs,readFileSync as ts}from"node:fs";function ns(e){let r=e.timestamp_ms;return e.timestamp||e.ts||(r?new Date(r).toISOString():void 0)}function os(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 ss(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 is(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,c=typeof u.exitCode=="number"?u.exitCode:0;return{command:s,exitCode:c,stdout:typeof u.stdout=="string"?u.stdout:"",stderr:typeof u.stderr=="string"?u.stderr:"",interleaved:typeof u.interleavedOutput=="string"?u.interleavedOutput:""}}function as(e,r){r.kind==="success"||r.kind==="search_no_matches"||(e.lastShellOutcome=r)}function gt(e){let r={firstEventAt:null,lastEventAt:null,currentTool:null,finalResult:null,error:null,lastShellOutcome:null};if(!rs(e))return r;let t=ts(e,"utf8").split(`
9
- `).filter(Boolean);for(let n of t){let o=Ee(n);if(!o)continue;let s=ns(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(c=>c?.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=os(a);u&&(r.currentTool=u)}let i=is(o);i&&as(r,ft({command:i.command,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr,interleavedOutput:i.interleaved})),o.type==="result"&&ss(r,o)}return r}var ht=k(()=>{"use strict";mt();y()});function cs(e,r=240){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function kt(e){let r=(e??"").trim();if(!r)return null;for(let t of us)if(t.test.test(r))return{blocked:!0,reason:`${t.label}: ${cs(r)}`};return null}var us,Rt=k(()=>{"use strict";us=[{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"}]});function yt(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function ls(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 ds(e){return!e?.checked||e.headIsAncestorOfBase!==!1?null:yt(e.head)}function ps(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 bt(e){if(e.alive||ls(e.finalResult))return null;let r=(e.changedFiles??[]).filter(i=>i.trim()).length,t=yt(e.headCommit)??ds(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:ps(s,r,t)}}var St=k(()=>{"use strict"});function ke(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function fs(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 ms(e){if(ke(e.headCommit)||ke(e.prUrl)||ke(e.artifactBundlePath)||ke(e.patchPath))return!0;let r=e.gitAncestry;return!!(r?.checked&&r.headIsAncestorOfBase===!1&&ke(r.head))}function se(e){return fs(e.finalResult)?e.changedFiles.length===0?{blocked:!1}:ms(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 _t(e){if(e.blocked)return e.detail??e.reason??"dirty_worktree_no_pr"}var He=k(()=>{"use strict"});function vr(e){let r=e.trim();if(!r.startsWith("{"))return null;try{let t=JSON.parse(r);if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch{return null}return null}function xt(e){let r=e.targetPrReconciliation??e.target_pr_reconciliation??e.targetPrs??e.target_prs;return Array.isArray(r)?r.length:0}function Be(e){let r=e.trim();if(!r)return null;let t=vr(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let l=vr(s[1]??"");l&&n.push(l)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let l=vr(r.slice(i,a+1));l&&n.push(l)}if(n.length===0)return null;let u=n[n.length-1],c=xt(u);for(let l of n){let p=xt(l);p>c&&(u=l,c=p)}return u}var Cr=k(()=>{"use strict"});function ie(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function gs(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"?Object.keys(e).length>0:!0}function z(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`https://github.com/${r[1]}/pull/${r[2]}`:ie(e)}function Fe(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function vt(e){let r=null;if(typeof e=="string"){let o=Be(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=z(String(s.prUrl??s.pr_url??"")),a=ie(s.outcome);!i||a!=="merged"&&a!=="skipped"&&a!=="blocked"||n.push({prUrl:i,outcome:a,mergeCommit:ie(s.mergeCommit??s.merge_commit),reason:ie(s.reason)})}return n}function Ct(e,r){let t=[],n=z(ie(e.prUrl)??"");if(n&&t.push(n),r&&typeof r=="object"&&!Array.isArray(r)){let o=r,s=z(String(o.prUrl??o.pr_url??""));s&&t.push(s)}return[...new Set(t)]}function At(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(!gs(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?z(ie(r.targetPrUrl)??"")??(r.targetPrUrls.length===1?z(r.targetPrUrls[0]):null):null;if(s){let p=Ct(t,n);if(!(n&&typeof n=="object"&&!Array.isArray(n)&&n.supersedesOriginalTargetPr===!0)){for(let R of p)if(R!==s)return{blocked:!0,reason:"duplicate_repair_pr",detail:`Repair worker opened or attached PR ${R} instead of canonical target ${s}`}}let d=vt(n).find(R=>R.prUrl===s);if(!d||d.outcome!=="merged"&&!(d.reason?.trim()&&(d.outcome==="skipped"||d.outcome==="blocked")))return{blocked:!0,reason:"missing_repair_target_reconciliation",detail:`Repair worker must reconcile target PR ${s}`}}let i=vt(n),a=new Map(i.map(p=>[Fe(p.prUrl),p])),u=new Set(r.targetPrUrls.map(p=>Fe(z(p)??p)).filter(Boolean)),c=Ct(t,n);if(r.landingOnly)for(let p of c){if(u.size>0&&!u.has(Fe(p)))return{blocked:!0,reason:"unrelated_implementation_pr",detail:`Landing-only worker attached unrelated PR ${p}`};if(u.size===0)return{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 l=[];for(let p of r.targetPrUrls){let f=Fe(z(p)??p),g=a.get(f);if(!g){l.push(f);continue}g.outcome!=="merged"&&!g.reason?.trim()&&l.push(f)}return l.length>0?{blocked:!0,reason:l.every(p=>a.has(p))?"incomplete_target_pr_landing":"missing_target_pr_reconciliation",detail:`Target PR reconciliation incomplete: ${l.join(", ")}`}:{blocked:!1}}function wt(e){if(e.blocked)return e.detail??e.reason}var Et=k(()=>{"use strict";Cr()});function Rs(e){let r=Date.now();if(e.completionBlocker&&!Pt(e.completionBlocker))return{state:"blocked",reason:e.completionBlocker};if(e.finalResult){if(e.localOnly&&bs(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=se(o);if(s.blocked){let i=_t(s);return{state:"needs_attention",reason:s.reason?`landing blocked (${s.reason}): ${i}`:`landing blocked: ${i}`}}if(e.landingContract){let i=At({contract:e.landingContract,snapshot:o,finalResult:e.finalResult}),a=wt(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(ys(e))return{state:"done",reason:"empty abandoned worker record"};let o=kt(e.error);if(o)return{state:"blocked",reason:o.reason};let s=bt({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>hs)return{state:"needs_attention",reason:`no first stream event ${lr(t)}s after start`};let n=e.lastActivityAt?Date.parse(e.lastActivityAt):NaN;return Number.isFinite(n)&&r-n>ks?{state:"stale",reason:`no log/event/heartbeat activity for ${lr(n)}s`}:{state:"ok",reason:"recent activity"}}function Pt(e){let r=e?.trim();return r?/completion acknowledged but board not advanced/i.test(r)&&/task already terminal/i.test(r):!1}function ys(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 bs(e){let r=null;if(typeof e=="string"?r=Be(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 Ss(e,r,t){let n=e.completionSnapshot?.finalResult;return e.completionAckSource==="local-pr-merged-reconcile"&&n!==void 0&&n!==null?n:r||(n??ct(t))}function Re(e,r={}){let t=gt(e.stdoutPath),n=oe(e.heartbeatPath),o=typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim().length>0,s=Ss(e,t.finalResult,n),i=o?!1:L(e.pid),a=Pe(e.stdoutPath),u=Pe(e.stderrPath),c=Pe(e.heartbeatPath),l=de(e.worktreePath),p=Oe(e.worktreePath,{base:r.base,baseCommit:r.baseCommit}),f=zr([t.lastEventAt,n.lastHeartbeatAt,We(e.stdoutPath),We(e.stderrPath),We(e.heartbeatPath)]),g=t.error||!i&&!s&&Vr(e.stderrPath,10).trim()||void 0,d=typeof e.completionBlocker=="string"&&e.completionBlocker.trim()?e.completionBlocker.trim():null,R=Pt(d)?null:d,x=e.repairTargetPrUrl?{landingOnly:!1,targetPrUrls:[e.repairTargetPrUrl],targetPrUrl:e.repairTargetPrUrl,repairEnforceOriginalPr:!0}:null,W=Rs({alive:i,finalResult:s,firstEventAt:t.firstEventAt,stdoutBytes:a,stderrBytes:u,heartbeatBytes:c,lastActivityAt:f,heartbeatBlocker:n.heartbeatBlocker,startedAt:e.startedAt,error:g,changedFiles:l,gitAncestry:p,completionBlocker:R,landingContract:x,prUrl:e.repairTargetPrUrl??e.taskPrUrl??null,localOnly:e.localOnly===!0,taskId:e.taskId??null,agentOsId:e.agentOsId??null,reconcileReason:e.reconcileReason??null}),U=R||W.state==="blocked"?"blocked":o||W.state==="done"?"done":s?"exited":i?"running":"exited";return{runId:e.runId,worker:e.name,pid:e.pid,alive:i,status:U,attention:W,branch:e.branch,worktreePath:e.worktreePath,ownedPaths:e.ownedPaths,stdoutBytes:a,stderrBytes:u,heartbeatBytes:c,firstEventAt:t.firstEventAt,lastEventAt:t.lastEventAt,lastActivityAt:f,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:l,gitAncestry:p,instructionPolicyFingerprint:e.instructionPolicyFingerprint??null,instructionPolicyEvidence:e.instructionPolicyEvidence??null,model:e.model??e.orchestrationAudit?.model??null,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 J(e){return!!(e.finalResult||e.alive===!1||e.status==="exited"||e.status==="done")}function Wt(e){return e.finalResult?e.attention.state==="needs_attention"||e.attention.state==="blocked":!1}var hs,ks,q=k(()=>{"use strict";Ue();ht();Rt();St();H();He();Et();Cr();y();hs=18e4,ks=6e5});var Ot=k(()=>{"use strict";q()});var _s,xs,It=k(()=>{"use strict";et();je();fr();Ar();Me();V();yr();Ot();y();_s=500*1024*1024,xs=4*1024*1024*1024});var Ar=k(()=>{"use strict";It()});import{existsSync as ws,mkdirSync as wu,readFileSync as Es,writeFileSync as Eu}from"node:fs";import{homedir as Ps,totalmem as Wu}from"node:os";import wr from"node:path";function Ke(){if(!ws(Nt))return{};try{return JSON.parse(Es(Nt,"utf8"))}catch{return{}}}var Mt,Nt,Hu,Bu,Fu,je=k(()=>{"use strict";pr();pe();y();fr();Ar();Me();Mt=wr.join(Ps(),".kynver"),Nt=wr.join(Mt,"config.json"),Hu=wr.join(Mt,"credentials");Bu=500*1024*1024,Fu=4*1024*1024*1024});import{existsSync as Dt}from"node:fs";import{homedir as Ut}from"node:os";import G from"node:path";function A(e){let r=G.resolve(Ie(e.trim()));for(;Ws.has(G.basename(r));)r=G.dirname(r);return r}function $(){let e=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(e)return A(e);let r=Ke().harnessRoot?.trim();if(r)return A(r);let t=G.join(Ut(),".kynver","harness");return Dt(t)?t:Dt(Tt)?Tt:t}function B(e){return G.join(A(e),"runs")}function ae(e){return G.join(A(e),"worktrees")}function ot(){let e=$();return{harnessRoot:e,runsDir:B(e),worktreesDir:ae(e)}}function kr(e,r){return G.join(e,b(r))}var Tt,Ws,F=k(()=>{"use strict";je();pe();y();Tt=G.join(Ut(),".openclaw","harness"),Ws=new Set(["runs","worktrees"])});F();import P from"node:path";He();import Ye from"node:path";H();q();var Er=[".next",".turbo","dist","build",".cache","node_modules/.cache"];function Ht(e){let r=e.replace(/\\/g,"/").replace(/\/+$/,"");if(r==="node_modules"||r.startsWith("node_modules/"))return!0;for(let t of Er)if(r===t||r.startsWith(`${t}/`))return!0;return!1}function w(e){return e.filter(r=>{let t=r.trim(),n=t.startsWith("??")?t.slice(2).trim():t.length>3?t.slice(3).trim():t;return!Ht(n)})}function X(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 ye(e){let r=e.gitAncestry?.relation;return r==="merged"||r==="synced"?w(e.changedFiles).length>0:!!(X(e.finalResult)||r==="ahead"||r==="diverged"||e.changedFiles.length>0&&e.finalResult)}y();function be(e){return e.status||(e.status=Re(e.worker,{base:e.run.base,baseCommit:e.run.baseCommit})),e.status}function Pr(e,r){if(e.status)return w(e.status.changedFiles).length>0;let t=r?r.porcelain(e.worktreePath):de(e.worktreePath);return w(t).length>0}function Os(e){let r=e.worker.completionSnapshot?.finalResult;return r??(e.worker.taskPrUrl?{prUrl:e.worker.taskPrUrl}:null)}function Wr(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=Os(e);if(o&&!L(t.pid)){let i=r?.gitStatusCache?r.gitStatusCache.porcelain(e.worktreePath):de(e.worktreePath),a=e.run.baseCommit?.trim()||e.run.base?.trim()||"origin/main",c=r?.gitRevCache?.countAheadOfMain(e.worktreePath,a)===0?{checked:!0,base:a,relation:"synced"}:Oe(e.worktreePath,{base:e.run.base,baseCommit:e.run.baseCommit}),l={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:c,finalResult:s,completionBlocker:typeof t.completionBlocker=="string"&&t.completionBlocker.trim()||null,prUrl:t.repairTargetPrUrl??t.taskPrUrl??X(s)};return e.status=l,l}return be(e)}q();V();yr();q();y();import Is from"node:path";var Ns=new Set(["running","dispatching","pending","queued","needs_attention"]),Q=new Set(["completed","failed","cancelled","done"]);function Z(e){let r=Rr(e);if(r.length===0)return"failed";let t=!1,n=!1,o=!1,s=!1;for(let i of r){let a=_(Is.join(fe(e.id),"workers",b(i),"worker.json"),void 0);if(!a)continue;let u=Re(a,{base:e.base,baseCommit:e.baseCommit});if(u.alive&&!u.finalResult){t=!0;break}typeof a.completionBlocker=="string"&&a.completionBlocker&&(o=!0),Wt(u)&&(s=!0),u.finalResult&&u.attention.state==="done"&&(n=!0)}return t||o||s?null:n?"completed":"failed"}function Bt(){let e=[];for(let r of gr()){if(!Ns.has(r.status))continue;let t=Z(r);if(!t||t===r.status)continue;let n=r.status;r.status=t,hr(r),e.push({runId:r.id,from:n,to:t})}return e}q();Ue();import{existsSync as Le,mkdirSync as Cc,readdirSync as jt,renameSync as Ac,statSync as Ms}from"node:fs";import ee from"node:path";je();pr();pe();Ue();F();V();F();y();import Y from"node:path";var bc=`${Y.sep}runs${Y.sep}runs${Y.sep}`;function Ft(e){return{workerJsonPath:Y.join(e,"worker.json"),stdoutPath:Y.join(e,"stdout.jsonl"),stderrPath:Y.join(e,"stderr.log"),heartbeatPath:Y.join(e,"heartbeat.jsonl"),lastStatusPath:Y.join(e,"last-status.json")}}y();var Se=900*1e3,Mc=3600*1e3;function Lt(e,r){let t=ee.resolve(e),n=ee.resolve(B(r)),o=ee.relative(n,t);return o!==".."&&!o.startsWith("..")&&!ee.isAbsolute(o)}function Ds(e){if(!Le(e))return[];try{return jt(e,{withFileTypes:!0}).filter(r=>r.isDirectory()&&r.name!=="runs").map(r=>r.name)}catch{return[]}}function Ts(e){let r=ee.join(e,"workers");if(!Le(r))return[];try{return jt(r,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}}function Kt(e,r,t){if(!Le(e))return!1;try{let n=r-Ms(e).mtimeMs;return Number.isFinite(n)&&n>=0&&n<t}catch{return!1}}function Us(e,r=Date.now(),t=Se){if(!Le(e))return!1;let n=Ft(e),o=_(n.workerJsonPath,void 0);if(o?.status==="running"&&L(o.pid))return!0;let s=oe(n.heartbeatPath);if(s.lastHeartbeatAt){let i=r-Date.parse(s.lastHeartbeatAt);if(Number.isFinite(i)&&i>=0&&i<t)return!0}return!!(Kt(n.stdoutPath,r,t)||Kt(n.heartbeatPath,r,t))}function Hs(e,r=Date.now(),t=Se){for(let n of Ts(e))if(Us(ee.join(e,"workers",n),r,t))return!0;return!1}function Gt(e,r=Date.now()){let t=new Set,n=B(e);for(let o of Ds(n)){let s=ee.join(n,o);Hs(s,r)&&t.add(`${e}\0${o}`)}return t}y();function Or(e,r=Date.now(),t=Se){let n=oe(e.heartbeatPath);if(!n.lastHeartbeatAt)return!1;let o=r-Date.parse(n.lastHeartbeatAt);return Number.isFinite(o)&&o>=0&&o<t}function Ge(e,r=Date.now(),t=Se){return L(e.pid)?!0:Or(e,r,t)}function Bs(e,r){return r?r.runTerminalCache.derive(e.run):Z(e.run)}function K(e,r=Date.now()){return Ge(e.worker,r)}function Ir(e,r){return Q.has(e.run.status)?!1:Bs(e,r)!==null}function $t(e,r,t=Date.now()){if(K(e,t))return!0;if(Q.has(e.run.status)||Ir(e,r))return!1;let n=be(e);return J(n)?!1:!!K(e,t)}He();q();function Yt(e,r){if(!(typeof e.worker.completionBlocker=="string"?e.worker.completionBlocker.trim():""))return!1;if(K(e))return!0;let n=r??be(e);return!!(!J(n)||ye(n)||w(n.changedFiles).length>0||se({finalResult:n.finalResult,changedFiles:n.changedFiles,gitAncestry:n.gitAncestry,prUrl:X(n.finalResult)}).blocked)}H();y();import{existsSync as zt,mkdirSync as Fs,writeFileSync as Vt}from"node:fs";import $e from"node:path";function Jt(e,r,t){return $e.join(e,"salvage",b(r),b(t))}function qt(e){return zt($e.join(Jt(e.harnessRoot,e.runId,e.workerName),"evidence.json"))}function Xt(e){let r=Jt(e.harnessRoot,e.indexed.runId,e.indexed.workerName);Fs(r,{recursive:!0});let t=$e.join(r,"salvage.patch"),n=!1;if(zt(e.indexed.worktreePath)){let s=v(e.indexed.worktreePath,["diff","HEAD"]),i=v(e.indexed.worktreePath,["diff","--cached"]),a=[s.stdout,i.stdout].filter(u=>u.trim()).join(`
10
- `);a.trim()&&(Vt(t,a.endsWith(`
8
+ ${e.stderr}`.trim(),t=Vo(r);if(!t||!he(t)){let o=ge(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(he(t.error))return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit command failed: ${qo(t,e.stderr)}`};let n=zo(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:Jo(n),audit:n}:{kind:"command_failure",exitCode:e.exitCode,summary:"npm audit failed: JSON response missing vulnerability metadata",parseError:"missing_metadata"}}function Qo(e){return Go.test(e)}function Zo(e){return $o.test(e)}function es(e){let r=vr({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&&Yo.test(n)){let i=ge(n,160);return{kind:"command_failure",exitCode:1,summary:r??`ripgrep failed (exit 1): ${i}`}}let o=xr(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=ge(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 mt(e){let r=e.stdout??"",t=e.stderr??"",n=e.interleavedOutput??"";if(Qo(e.command)){let i=r.trim()||n.trim()||t.trim();return Xo({exitCode:e.exitCode,stdout:i,stderr:t})}if(Zo(e.command))return es({command:e.command,exitCode:e.exitCode,stdout:r,stderr:t,interleaved:n});let o=vr({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=ge(n||r||t||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:`command failed (exit ${e.exitCode}): ${s}`}}var Go,$o,Yo,gt=k(()=>{"use strict";ft();Go=/\bnpm\s+audit\b/i,$o=/\b(rg|ripgrep)\b/i,Yo=/\b(error|invalid|unknown|panic|not found)\b/i});import{existsSync as rs,readFileSync as ts}from"node:fs";function ns(e){let r=e.timestamp_ms;return e.timestamp||e.ts||(r?new Date(r).toISOString():void 0)}function os(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 ss(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 is(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,c=typeof u.exitCode=="number"?u.exitCode:0;return{command:s,exitCode:c,stdout:typeof u.stdout=="string"?u.stdout:"",stderr:typeof u.stderr=="string"?u.stderr:"",interleaved:typeof u.interleavedOutput=="string"?u.interleavedOutput:""}}function as(e,r){r.kind==="success"||r.kind==="search_no_matches"||(e.lastShellOutcome=r)}function ht(e){let r={firstEventAt:null,lastEventAt:null,currentTool:null,finalResult:null,error:null,lastShellOutcome:null};if(!rs(e))return r;let t=ts(e,"utf8").split(`
9
+ `).filter(Boolean);for(let n of t){let o=Ee(n);if(!o)continue;let s=ns(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(c=>c?.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=os(a);u&&(r.currentTool=u)}let i=is(o);i&&as(r,mt({command:i.command,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr,interleavedOutput:i.interleaved})),o.type==="result"&&ss(r,o)}return r}var kt=k(()=>{"use strict";gt();y()});function cs(e,r=240){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function Rt(e){let r=(e??"").trim();if(!r)return null;for(let t of us)if(t.test.test(r))return{blocked:!0,reason:`${t.label}: ${cs(r)}`};return null}var us,yt=k(()=>{"use strict";us=[{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"}]});function bt(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function ls(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 ds(e){return!e?.checked||e.headIsAncestorOfBase!==!1?null:bt(e.head)}function ps(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 St(e){if(e.alive||ls(e.finalResult))return null;let r=(e.changedFiles??[]).filter(i=>i.trim()).length,t=bt(e.headCommit)??ds(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:ps(s,r,t)}}var _t=k(()=>{"use strict"});function ke(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function fs(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 ms(e){if(ke(e.headCommit)||ke(e.prUrl)||ke(e.artifactBundlePath)||ke(e.patchPath))return!0;let r=e.gitAncestry;return!!(r?.checked&&r.headIsAncestorOfBase===!1&&ke(r.head))}function se(e){return fs(e.finalResult)?e.changedFiles.length===0?{blocked:!1}:ms(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 He=k(()=>{"use strict"});function Cr(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 vt(e){let r=e.targetPrReconciliation??e.target_pr_reconciliation??e.targetPrs??e.target_prs;return Array.isArray(r)?r.length:0}function Be(e){let r=e.trim();if(!r)return null;let t=Cr(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let l=Cr(s[1]??"");l&&n.push(l)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let l=Cr(r.slice(i,a+1));l&&n.push(l)}if(n.length===0)return null;let u=n[n.length-1],c=vt(u);for(let l of n){let p=vt(l);p>c&&(u=l,c=p)}return u}var Ar=k(()=>{"use strict"});function ie(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function gs(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"?Object.keys(e).length>0:!0}function z(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`https://github.com/${r[1]}/pull/${r[2]}`:ie(e)}function Fe(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function Ct(e){let r=null;if(typeof e=="string"){let o=Be(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=z(String(s.prUrl??s.pr_url??"")),a=ie(s.outcome);!i||a!=="merged"&&a!=="skipped"&&a!=="blocked"||n.push({prUrl:i,outcome:a,mergeCommit:ie(s.mergeCommit??s.merge_commit),reason:ie(s.reason)})}return n}function At(e,r){let t=[],n=z(ie(e.prUrl)??"");if(n&&t.push(n),r&&typeof r=="object"&&!Array.isArray(r)){let o=r,s=z(String(o.prUrl??o.pr_url??""));s&&t.push(s)}return[...new Set(t)]}function wt(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(!gs(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?z(ie(r.targetPrUrl)??"")??(r.targetPrUrls.length===1?z(r.targetPrUrls[0]):null):null;if(s){let p=At(t,n);if(!(n&&typeof n=="object"&&!Array.isArray(n)&&n.supersedesOriginalTargetPr===!0)){for(let R of p)if(R!==s)return{blocked:!0,reason:"duplicate_repair_pr",detail:`Repair worker opened or attached PR ${R} instead of canonical target ${s}`}}let d=Ct(n).find(R=>R.prUrl===s);if(!d||d.outcome!=="merged"&&!(d.reason?.trim()&&(d.outcome==="skipped"||d.outcome==="blocked")))return{blocked:!0,reason:"missing_repair_target_reconciliation",detail:`Repair worker must reconcile target PR ${s}`}}let i=Ct(n),a=new Map(i.map(p=>[Fe(p.prUrl),p])),u=new Set(r.targetPrUrls.map(p=>Fe(z(p)??p)).filter(Boolean)),c=At(t,n);if(r.landingOnly)for(let p of c){if(u.size>0&&!u.has(Fe(p)))return{blocked:!0,reason:"unrelated_implementation_pr",detail:`Landing-only worker attached unrelated PR ${p}`};if(u.size===0)return{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 l=[];for(let p of r.targetPrUrls){let f=Fe(z(p)??p),g=a.get(f);if(!g){l.push(f);continue}g.outcome!=="merged"&&!g.reason?.trim()&&l.push(f)}return l.length>0?{blocked:!0,reason:l.every(p=>a.has(p))?"incomplete_target_pr_landing":"missing_target_pr_reconciliation",detail:`Target PR reconciliation incomplete: ${l.join(", ")}`}:{blocked:!1}}function Et(e){if(e.blocked)return e.detail??e.reason}var Pt=k(()=>{"use strict";Ar()});function Rs(e){let r=Date.now();if(e.completionBlocker&&!Wt(e.completionBlocker))return{state:"blocked",reason:e.completionBlocker};if(e.finalResult){if(e.localOnly&&bs(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=se(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=wt({contract:e.landingContract,snapshot:o,finalResult:e.finalResult}),a=Et(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(ys(e))return{state:"done",reason:"empty abandoned worker record"};let o=Rt(e.error);if(o)return{state:"blocked",reason:o.reason};let s=St({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>hs)return{state:"needs_attention",reason:`no first stream event ${lr(t)}s after start`};let n=e.lastActivityAt?Date.parse(e.lastActivityAt):NaN;return Number.isFinite(n)&&r-n>ks?{state:"stale",reason:`no log/event/heartbeat activity for ${lr(n)}s`}:{state:"ok",reason:"recent activity"}}function Wt(e){let r=e?.trim();return r?/completion acknowledged but board not advanced/i.test(r)&&/task already terminal/i.test(r):!1}function ys(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 bs(e){let r=null;if(typeof e=="string"?r=Be(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 Ss(e,r,t){let n=e.completionSnapshot?.finalResult;return e.completionAckSource==="local-pr-merged-reconcile"&&n!==void 0&&n!==null?n:r||(n??lt(t))}function Re(e,r={}){let t=ht(e.stdoutPath),n=oe(e.heartbeatPath),o=typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim().length>0,s=Ss(e,t.finalResult,n),i=o?!1:L(e.pid),a=Pe(e.stdoutPath),u=Pe(e.stderrPath),c=Pe(e.heartbeatPath),l=de(e.worktreePath),p=Oe(e.worktreePath,{base:r.base,baseCommit:r.baseCommit}),f=Jr([t.lastEventAt,n.lastHeartbeatAt,We(e.stdoutPath),We(e.stderrPath),We(e.heartbeatPath)]),g=t.error||!i&&!s&&zr(e.stderrPath,10).trim()||void 0,d=typeof e.completionBlocker=="string"&&e.completionBlocker.trim()?e.completionBlocker.trim():null,R=Wt(d)?null:d,x=e.repairTargetPrUrl?{landingOnly:!1,targetPrUrls:[e.repairTargetPrUrl],targetPrUrl:e.repairTargetPrUrl,repairEnforceOriginalPr:!0}:null,W=Rs({alive:i,finalResult:s,firstEventAt:t.firstEventAt,stdoutBytes:a,stderrBytes:u,heartbeatBytes:c,lastActivityAt:f,heartbeatBlocker:n.heartbeatBlocker,startedAt:e.startedAt,error:g,changedFiles:l,gitAncestry:p,completionBlocker:R,landingContract:x,prUrl:e.repairTargetPrUrl??e.taskPrUrl??null,localOnly:e.localOnly===!0,taskId:e.taskId??null,agentOsId:e.agentOsId??null,reconcileReason:e.reconcileReason??null}),U=R||W.state==="blocked"?"blocked":o||W.state==="done"?"done":s?"exited":i?"running":"exited";return{runId:e.runId,worker:e.name,pid:e.pid,alive:i,status:U,attention:W,branch:e.branch,worktreePath:e.worktreePath,ownedPaths:e.ownedPaths,stdoutBytes:a,stderrBytes:u,heartbeatBytes:c,firstEventAt:t.firstEventAt,lastEventAt:t.lastEventAt,lastActivityAt:f,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:l,gitAncestry:p,instructionPolicyFingerprint:e.instructionPolicyFingerprint??null,instructionPolicyEvidence:e.instructionPolicyEvidence??null,model:e.model??e.orchestrationAudit?.model??null,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 J(e){return!!(e.finalResult||e.alive===!1||e.status==="exited"||e.status==="done")}function Ot(e){return e.finalResult?e.attention.state==="needs_attention"||e.attention.state==="blocked":!1}var hs,ks,q=k(()=>{"use strict";Ue();kt();yt();_t();H();He();Pt();Ar();y();hs=18e4,ks=6e5});var It=k(()=>{"use strict";q()});var _s,xs,Nt=k(()=>{"use strict";rt();je();fr();wr();Me();V();yr();It();y();_s=500*1024*1024,xs=4*1024*1024*1024});var wr=k(()=>{"use strict";Nt()});import{existsSync as ws,mkdirSync as wu,readFileSync as Es,writeFileSync as Eu}from"node:fs";import{homedir as Ps,totalmem as Wu}from"node:os";import Er from"node:path";function Ke(){if(!ws(Mt))return{};try{return JSON.parse(Es(Mt,"utf8"))}catch{return{}}}var Dt,Mt,Hu,Bu,Fu,je=k(()=>{"use strict";pr();pe();y();fr();wr();Me();Dt=Er.join(Ps(),".kynver"),Mt=Er.join(Dt,"config.json"),Hu=Er.join(Dt,"credentials");Bu=500*1024*1024,Fu=4*1024*1024*1024});import{existsSync as Tt}from"node:fs";import{homedir as Ht}from"node:os";import G from"node:path";function A(e){let r=G.resolve(Ie(e.trim()));for(;Ws.has(G.basename(r));)r=G.dirname(r);return r}function $(){let e=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(e)return A(e);let r=Ke().harnessRoot?.trim();if(r)return A(r);let t=G.join(Ht(),".kynver","harness");return Tt(t)?t:Tt(Ut)?Ut:t}function B(e){return G.join(A(e),"runs")}function ae(e){return G.join(A(e),"worktrees")}function st(){let e=$();return{harnessRoot:e,runsDir:B(e),worktreesDir:ae(e)}}function kr(e,r){return G.join(e,b(r))}var Ut,Ws,F=k(()=>{"use strict";je();pe();y();Ut=G.join(Ht(),".openclaw","harness"),Ws=new Set(["runs","worktrees"])});F();import P from"node:path";He();import Ye from"node:path";H();q();var Pr=[".next",".turbo","dist","build",".cache","node_modules/.cache"];function Bt(e){let r=e.replace(/\\/g,"/").replace(/\/+$/,"");if(r==="node_modules"||r.startsWith("node_modules/"))return!0;for(let t of Pr)if(r===t||r.startsWith(`${t}/`))return!0;return!1}function w(e){return e.filter(r=>{let t=r.trim(),n=t.startsWith("??")?t.slice(2).trim():t.length>3?t.slice(3).trim():t;return!Bt(n)})}function X(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 ye(e){let r=e.gitAncestry?.relation;return r==="merged"||r==="synced"?w(e.changedFiles).length>0:!!(X(e.finalResult)||r==="ahead"||r==="diverged"||e.changedFiles.length>0&&e.finalResult)}y();function be(e){return e.status||(e.status=Re(e.worker,{base:e.run.base,baseCommit:e.run.baseCommit})),e.status}function Wr(e,r){if(e.status)return w(e.status.changedFiles).length>0;let t=r?r.porcelain(e.worktreePath):de(e.worktreePath);return w(t).length>0}function Os(e){let r=e.worker.completionSnapshot?.finalResult;return r??(e.worker.taskPrUrl?{prUrl:e.worker.taskPrUrl}:null)}function Or(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=Os(e);if(o&&!L(t.pid)){let i=r?.gitStatusCache?r.gitStatusCache.porcelain(e.worktreePath):de(e.worktreePath),a=e.run.baseCommit?.trim()||e.run.base?.trim()||"origin/main",c=r?.gitRevCache?.countAheadOfMain(e.worktreePath,a)===0?{checked:!0,base:a,relation:"synced"}:Oe(e.worktreePath,{base:e.run.base,baseCommit:e.run.baseCommit}),l={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:c,finalResult:s,completionBlocker:typeof t.completionBlocker=="string"&&t.completionBlocker.trim()||null,prUrl:t.repairTargetPrUrl??t.taskPrUrl??X(s)};return e.status=l,l}return be(e)}q();V();yr();q();y();import Is from"node:path";var Ns=new Set(["running","dispatching","pending","queued","needs_attention"]),Q=new Set(["completed","failed","cancelled","done"]);function Z(e){let r=Rr(e);if(r.length===0)return"failed";let t=!1,n=!1,o=!1,s=!1;for(let i of r){let a=_(Is.join(fe(e.id),"workers",b(i),"worker.json"),void 0);if(!a)continue;let u=Re(a,{base:e.base,baseCommit:e.baseCommit});if(u.alive&&!u.finalResult){t=!0;break}typeof a.completionBlocker=="string"&&a.completionBlocker&&(o=!0),Ot(u)&&(s=!0),u.finalResult&&u.attention.state==="done"&&(n=!0)}return t||o||s?null:n?"completed":"failed"}function Ft(){let e=[];for(let r of gr()){if(!Ns.has(r.status))continue;let t=Z(r);if(!t||t===r.status)continue;let n=r.status;r.status=t,hr(r),e.push({runId:r.id,from:n,to:t})}return e}q();Ue();import{existsSync as Le,mkdirSync as Cc,readdirSync as Lt,renameSync as Ac,statSync as Ms}from"node:fs";import ee from"node:path";je();pr();pe();Ue();F();V();F();y();import Y from"node:path";var bc=`${Y.sep}runs${Y.sep}runs${Y.sep}`;function Kt(e){return{workerJsonPath:Y.join(e,"worker.json"),stdoutPath:Y.join(e,"stdout.jsonl"),stderrPath:Y.join(e,"stderr.log"),heartbeatPath:Y.join(e,"heartbeat.jsonl"),lastStatusPath:Y.join(e,"last-status.json")}}y();var Se=900*1e3,Mc=3600*1e3;function Gt(e,r){let t=ee.resolve(e),n=ee.resolve(B(r)),o=ee.relative(n,t);return o!==".."&&!o.startsWith("..")&&!ee.isAbsolute(o)}function Ds(e){if(!Le(e))return[];try{return Lt(e,{withFileTypes:!0}).filter(r=>r.isDirectory()&&r.name!=="runs").map(r=>r.name)}catch{return[]}}function Ts(e){let r=ee.join(e,"workers");if(!Le(r))return[];try{return Lt(r,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}}function jt(e,r,t){if(!Le(e))return!1;try{let n=r-Ms(e).mtimeMs;return Number.isFinite(n)&&n>=0&&n<t}catch{return!1}}function Us(e,r=Date.now(),t=Se){if(!Le(e))return!1;let n=Kt(e),o=_(n.workerJsonPath,void 0);if(o?.status==="running"&&L(o.pid))return!0;let s=oe(n.heartbeatPath);if(s.lastHeartbeatAt){let i=r-Date.parse(s.lastHeartbeatAt);if(Number.isFinite(i)&&i>=0&&i<t)return!0}return!!(jt(n.stdoutPath,r,t)||jt(n.heartbeatPath,r,t))}function Hs(e,r=Date.now(),t=Se){for(let n of Ts(e))if(Us(ee.join(e,"workers",n),r,t))return!0;return!1}function $t(e,r=Date.now()){let t=new Set,n=B(e);for(let o of Ds(n)){let s=ee.join(n,o);Hs(s,r)&&t.add(`${e}\0${o}`)}return t}y();function Ir(e,r=Date.now(),t=Se){let n=oe(e.heartbeatPath);if(!n.lastHeartbeatAt)return!1;let o=r-Date.parse(n.lastHeartbeatAt);return Number.isFinite(o)&&o>=0&&o<t}function Ge(e,r=Date.now(),t=Se){return L(e.pid)?!0:Ir(e,r,t)}function Bs(e,r){return r?r.runTerminalCache.derive(e.run):Z(e.run)}function K(e,r=Date.now()){return Ge(e.worker,r)}function Nr(e,r){return Q.has(e.run.status)?!1:Bs(e,r)!==null}function Yt(e,r,t=Date.now()){if(K(e,t))return!0;if(Q.has(e.run.status)||Nr(e,r))return!1;let n=be(e);return J(n)?!1:!!K(e,t)}He();q();function Vt(e,r){if(!(typeof e.worker.completionBlocker=="string"?e.worker.completionBlocker.trim():""))return!1;if(K(e))return!0;let n=r??be(e);return!!(!J(n)||ye(n)||w(n.changedFiles).length>0||se({finalResult:n.finalResult,changedFiles:n.changedFiles,gitAncestry:n.gitAncestry,prUrl:X(n.finalResult)}).blocked)}H();y();import{existsSync as Jt,mkdirSync as Fs,writeFileSync as zt}from"node:fs";import $e from"node:path";function qt(e,r,t){return $e.join(e,"salvage",b(r),b(t))}function Xt(e){return Jt($e.join(qt(e.harnessRoot,e.runId,e.workerName),"evidence.json"))}function Qt(e){let r=qt(e.harnessRoot,e.indexed.runId,e.indexed.workerName);Fs(r,{recursive:!0});let t=$e.join(r,"salvage.patch"),n=!1;if(Jt(e.indexed.worktreePath)){let s=v(e.indexed.worktreePath,["diff","HEAD"]),i=v(e.indexed.worktreePath,["diff","--cached"]),a=[s.stdout,i.stdout].filter(u=>u.trim()).join(`
10
+ `);a.trim()&&(zt(t,a.endsWith(`
11
11
  `)?a:`${a}
12
- `),n=!0)}let o={capturedAt:new Date(e.now??Date.now()).toISOString(),skipReason:e.skipReason,runId:e.indexed.runId,workerName:e.indexed.workerName,worktreePath:e.indexed.worktreePath,taskId:e.indexed.worker.taskId,agentOsId:e.indexed.worker.agentOsId,branch:e.indexed.worker.branch,completionBlocker:e.indexed.worker.completionBlocker,finalResult:e.status.finalResult,changedFiles:e.status.changedFiles,gitAncestry:e.status.gitAncestry,prUrl:e.status.prUrl??null,...n?{patchPath:t}:{}};return Vt($e.join(r,"evidence.json"),`${JSON.stringify(o,null,2)}
13
- `),o}var Ks=new Set(["completion_blocked","dirty_worktree","pr_or_unmerged_commits","landing_blocked"]);function js(e){return!Ks.has(e.skipReason)||K(e.indexed,e.now)?!1:qt({harnessRoot:e.harnessRoot,runId:e.indexed.runId,workerName:e.indexed.workerName})?!0:e.writeSalvageEvidence?(Xt({harnessRoot:e.harnessRoot,indexed:e.indexed,skipReason:e.skipReason,status:e.status,now:e.now}),!0):!1}function Ls(e){let{indexed:r,includeOrphans:t,worktreesAgeMs:n,terminalWorktreesAgeMs:o}=e;return r?Q.has(r.run.status)||e.liveness&&Ir(r,e.liveness)||e.liveness&&J(Wr(r,e.liveness))&&!K(r)?o:n:t?o:n}function Gs(e,r){if(e.harnessRoot?.trim())return Ye.resolve(e.harnessRoot);let t=r.worker.workerDir;if(!t)return null;let n=`${Ye.sep}runs${Ye.sep}`,o=t.indexOf(n);return o<0?null:t.slice(0,o+n.length-1)}function Qt(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=Ls(e);if(n<=0&&!t&&u<=0)return"worktrees_disabled";if(u>0&&o<u)return"below_age_threshold";if(K(r,a))return"active_worker";let c=Wr(r,e.liveness),l=Gs(e,r),p=d=>l&&js({indexed:r,harnessRoot:l,skipReason:d,status:c,now:a,writeSalvageEvidence:e.writeSalvageEvidence===!0})?null:d;if(Yt(r,c)){let d=p("completion_blocked");if(d)return d}if(Pr(r,e.liveness?.gitStatusCache)){let d=p("dirty_worktree");if(d)return d}let f=e.liveness?.gitRevCache?.countAheadOfMain(e.worktreePath);if(f!=null&&f>0){let d=p("pr_or_unmerged_commits");if(d)return d}if($t(r,e.liveness,a)||!J(c))return"run_still_active";if(ye(c)){let d=p("pr_or_unmerged_commits");if(d)return d}if(w(c.changedFiles).length>0){let d=p("dirty_worktree");if(d)return d}if(se({finalResult:c.finalResult,changedFiles:c.changedFiles,gitAncestry:c.gitAncestry,prUrl:X(c.finalResult)}).blocked){let d=p("landing_blocked");if(d)return d}if(i&&e.worktreePath){let d=i({worktreePath:e.worktreePath,indexed:!!r,runId:r?.runId,worker:r?.workerName});if(d)return d.detail?{reason:d.reason,detail:d.detail}:d.reason}return null}function Nr(e){let{indexed:r,nodeModulesAgeMs:t,ageMs:n,worktreePath:o,activeWorktreePaths:s,diskPressure:i}=e;return!i&&n<t?"below_age_threshold":s.has(Ye.resolve(o))||r&&K(r)?"active_worker":r&&Pr(r,e.gitStatusCache)?"dirty_worktree":null}function Zt(e){return Nr(e)}var Mr=216e5,Ve=6048e5;var Dr=36e5,ze=120;var en=new Set(["active_worker","run_still_active","completion_blocked","landing_blocked"]);function rn(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)en.has(s.reason)&&o(s.path,s.reason,s.detail);for(let s of e)!s.skipped||!s.skipReason||en.has(s.skipReason)&&o(s.path,s.skipReason);return t}import{existsSync as sn,readdirSync as an,statSync as Vs}from"node:fs";import un from"node:path";V();F();import tn from"node:path";y();function Ys(e,r){return Ge(e,r)}function nn(e,r=Date.now()){let t=new Set,n=new Set;for(let o of e){for(let s of Te(o)){let i=!1;for(let a of Object.keys(s.workers||{})){let u=_(tn.join(me(o,s.id),"workers",b(a),"worker.json"),void 0);if(!u?.worktreePath)continue;let c=tn.resolve(u.worktreePath);Ys(u,r)&&(i=!0,t.add(c))}i&&n.add(`${o}\0${s.id}`)}for(let s of Gt(o))n.add(s)}return{activeWorktreePaths:t,liveRunKeys:n}}function on(e,r,t,n){return t?n.has(`${r}\0${t}`):!1}y();function zs(e,r){try{let t=Vs(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function Js(e,r){let t=un.join(e,"runs",r,"run.json");return sn(t)?_(t,null):null}function cn(e){try{return an(e).length===0}catch{return!1}}function ln(e){let{harnessRoot:r,runId:t,runPath:n,ageMs:o,runDirectoriesAgeMs:s,activeGuards:i}=e;if(on(n,r,t,i.liveRunKeys)||!cn(n))return"run_still_active";let a=Js(r,t);return a&&!Q.has(a.status)&&!Z(a)?"run_still_active":s>0&&o<s?"below_age_threshold":null}function dn(e){if(!sn(e.worktreesDir))return[];let r=[],t;try{t=an(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=un.join(e.worktreesDir,o);cn(s)&&r.push({kind:"remove_run_directory",path:s,bytes:null,harnessRoot:e.harnessRoot,runId:o,ageMs:zs(s,e.now)})}return r}H();import{existsSync as Ur,rmSync as _n}from"node:fs";import{execFileSync as qs}from"node:child_process";import{existsSync as pn,readdirSync as Xs,statSync as Qs}from"node:fs";import Zs from"node:path";var ei=2500;function ri(e,r=ei){if(!pn(e))return 0;try{let n=qs("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 j(e,r=5e4){if(!pn(e))return 0;let t=ri(e);if(t!==null)return t;let n=0,o=0,s=[e];for(;s.length>0;){let i=s.pop(),a;try{a=Xs(i)}catch{continue}for(let u of a){if(o++>r)return null;let c=Zs.join(i,u),l;try{l=Qs(c)}catch{continue}l.isDirectory()?s.push(c):n+=l.size}}return n}import{existsSync as si,rmSync as ii}from"node:fs";F();import{lstatSync as ti,readdirSync as ni}from"node:fs";function fn(e){try{let r=ti(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 mn(e,r=32){let t=fn(e);if(!t)return!1;if(t.foreign)return!0;try{let n=ni(e),o=0;for(let s of n){if(o>=r)break;let i=`${e.replace(/\/$/,"")}/${s}`,a=fn(i);if(o+=1,a?.foreign)return!0}}catch{}return!1}import{spawnSync as oi}from"node:child_process";import kn from"node:path";import E from"node:path";function gn(e,r,t,n){let o=E.resolve(e),s=`${E.sep}${n}`,i=o.endsWith(s)?o:null;if(!i)return"path_outside_harness";let a=E.relative(t,i);if(a.startsWith("..")||E.isAbsolute(a))return"path_outside_harness";let u=a.split(E.sep);return u.length<3||u[u.length-1]!==n||!o.startsWith(E.resolve(r))?"path_outside_harness":null}function Je(e,r,t){return gn(e,r,t,"node_modules")}function qe(e,r,t){return gn(e,r,t,".next")}function Xe(e,r,t){let n=E.resolve(e),o=E.relative(t,n);return o.startsWith("..")||E.isAbsolute(o)||o.split(E.sep).length<3||!n.startsWith(E.resolve(r))?"path_outside_harness":null}function hn(e,r,t){let n=E.resolve(e);return Je(n,r,t)===null||qe(n,r,t)===null||Xe(n,r,t)===null}function yn(){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 Rn(e){let r=oi("sudo",["-n",...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{ok:r.status===0,stderr:`${r.stderr??""}${r.stdout??""}`.trim()}}function bn(e,r,t){if(!hn(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=Rn(["chown","-R",`${n}:${o}`,kn.resolve(e)]);if(s.ok)return{ok:!0,method:"chown_then_rm"};let i=Rn(["rm","-rf",kn.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 Tr="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 ai(e){let r=e?.code;return r==="EACCES"||r==="EPERM"}function Sn(e,r,t={}){if(!si(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?ae(n):null,i=e.bytes??j(e.path)??void 0,a=t.removePath??ii,u=t.hasForeignOwnedEntry??mn;try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i}}catch(c){if(!ai(c)||!n||!o)return{executed:!1,skipped:!0,skipReason:"remove_failed",error:c.message};let l=u(e.path),p=yn();if(!(p==="force"||p==="auto"&&l))return l?{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${c.message}; ${Tr}`}:{executed:!1,skipped:!0,skipReason:"remove_failed",error:c.message};let g=bn(e.path,n,o);if(g.ok&&g.method==="sudo_rm")return{executed:!0,skipped:!1,bytes:i,privilegedReclaim:!0};if(g.ok)try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i,privilegedReclaim:!0}}catch(d){return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${d.message}; privileged chown succeeded but rm still failed`}}return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${c.message}; privileged reclaim failed: ${g.error}; ${Tr}`}}}function Hr(e){let r=e.harnessRoot;return!r||!Lt(e.path,r)?null:{...e,executed:!1,skipped:!0,skipReason:"run_metadata_protected"}}function Br(e,r){let t=Hr(e);if(t)return t;let n=Sn(e,r);return{...e,bytes:n.bytes??e.bytes,executed:n.executed,skipped:n.skipped,skipReason:n.skipReason,error:n.error}}function xn(e,r){return Br(e,r)}function vn(e,r){return Br(e,r)}function Cn(e,r){return Br(e,r)}function An(e,r){let t=Hr(e);if(t)return t;if(!Ur(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??j(e.path);return _n(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 wn(e,r){let t=Hr(e);if(t)return t;if(!Ur(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??j(e.path);return n&&le(n,["worktree","remove","--force",e.path],{allowFailure:!0}),Ur(e.path)&&_n(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 Qe,readdirSync as Ze,statSync as ui}from"node:fs";import D from"node:path";function Fr(e,r){try{let t=ui(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function Pn(e,r){let t=D.relative(r,e);return t===""||!t.startsWith("..")&&!D.isAbsolute(t)}function En(e,r,t,n){let o=[];for(let s of Er){if(s===".next")continue;let i=D.join(e,s);if(!Qe(i))continue;let a=D.resolve(i);t.has(a)||Pn(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:Fr(a,r.now)}))}return o}function Wn(e){let r=[],t=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||r.push(...En(n.worktreePath,e,t,{runId:n.runId,worker:n.workerName,repo:n.run.repo}));if(!e.includeOrphans||!Qe(e.worktreesDir))return r;for(let n of Ze(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=D.join(e.worktreesDir,n.name);for(let s of Ze(o,{withFileTypes:!0})){if(!s.isDirectory())continue;let i=D.join(o,s.name);r.push(...En(i,e,t,{runId:n.name,worker:s.name}))}}return r}function On(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;Qe(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:Fr(a,e.now)})))}if(!t||!Qe(e.worktreesDir))return n;let s=new Set;for(let i of e.index.values())s.add(D.resolve(i.worktreePath));for(let i of Ze(e.worktreesDir,{withFileTypes:!0})){if(!i.isDirectory()||e.runIdFilter&&i.name!==e.runIdFilter)continue;let a=D.join(e.worktreesDir,i.name),u;try{u=Ze(a,{withFileTypes:!0})}catch{continue}for(let c of u){if(!c.isDirectory())continue;let l=D.resolve(D.join(a,c.name));o.has(l)||s.has(l)||Pn(l,e.harnessRoot)&&(o.add(l),n.push({kind:"remove_worktree",path:l,bytes:null,runId:i.name,worker:c.name,ageMs:Fr(l,e.now)}))}}return n}import{existsSync as Mn,readdirSync as In,statSync as ci}from"node:fs";import ue from"node:path";var li=[{dirName:"node_modules",kind:"remove_node_modules"},{dirName:".next",kind:"remove_next_cache"}];function di(e,r){try{let t=ci(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function pi(e,r){let t=ue.relative(r,e);return t===""||!t.startsWith("..")&&!ue.isAbsolute(t)}function fi(e,r,t,n,o,s){if(!Mn(n))return;let i=ue.resolve(n);r.has(i)||pi(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:di(i,t.now)}))}function Nn(e,r,t,n,o){for(let s of li)fi(e,r,t,ue.join(n,s.dirName),s.kind,o)}function Dn(e){let r=[],t=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||Nn(r,t,e,n.worktreePath,{runId:n.runId,worker:n.workerName,repo:n.run.repo});if(!e.includeOrphans||!Mn(e.worktreesDir))return r;for(let n of In(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory()||e.runIdFilter&&n.name!==e.runIdFilter)continue;let o=ue.join(e.worktreesDir,n.name),s;try{s=In(o,{withFileTypes:!0})}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=ue.join(o,i.name);Nn(r,t,e,a,{runId:n.name,worker:i.name})}}return r}H();import{existsSync as Tn,statSync as mi}from"node:fs";import T from"node:path";function gi(e,r){try{let t=mi(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function hi(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 ki(e,r){let t=T.relative(T.resolve(r),T.resolve(e));return t!==""&&!t.startsWith("..")&&!T.isAbsolute(t)}var Ri=200;function Un(e){if(!e.includeOrphans||!Tn(e.worktreesDir))return[];let r=new Set;for(let s of e.index.values())s.run.repo&&r.add(T.resolve(s.run.repo));let t=new Set;for(let s of e.index.values())t.add(T.resolve(s.worktreePath));let n=[],o=new Set;for(let s of r){let i=0,a;try{a=le(s,["worktree","list","--porcelain"],{allowFailure:!0})}catch{continue}let u=hi(a);for(let c of u){if(i>=Ri)break;let l=T.resolve(c.path);if(l===T.resolve(s)||!ki(l,e.worktreesDir)||t.has(l)||o.has(l)||!Tn(l))continue;let f=T.relative(e.worktreesDir,l).split(T.sep),g=f[0],d=f[1]??"unknown";o.add(l),i+=1,n.push({kind:"remove_worktree",path:l,bytes:null,runId:g,worker:d,repo:s,ageMs:gi(l,e.now)})}}return n}V();y();import _e from"node:path";function Hn(e,r){let t=_e.resolve(r),n=new Map;for(let[o,s]of e){let i=s.harnessRoot?_e.resolve(s.harnessRoot):null;i&&i!==t||n.set(o,s)}return n}function Bn(e){let r=new Map;for(let t of Te(e))for(let n of Object.keys(t.workers||{})){let o=_e.join(me(e,t.id),"workers",b(n),"worker.json"),s=_(o,void 0);s?.worktreePath&&r.set(_e.resolve(s.worktreePath),{harnessRoot:e,worktreePath:_e.resolve(s.worktreePath),runId:t.id,workerName:n,run:t,worker:s})}return r}function xe(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function re(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)&&n>=0?n:r}function Fn(e={}){let r=e.execute===!0||e.execute!==!1&&xe("KYNVER_CLEANUP_EXECUTE"),t=e.finalizeStaleRuns!==!1&&!xe("KYNVER_CLEANUP_SKIP_FINALIZE"),n=e.nodeModulesAgeMs??re("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??re("KYNVER_CLEANUP_WORKTREES_AGE_MS",0),i=e.terminalWorktreesAgeMs??re("KYNVER_CLEANUP_TERMINAL_WORKTREES_AGE_MS",216e5),a=e.runDirectoriesAgeMs??re("KYNVER_CLEANUP_RUN_DIRECTORIES_AGE_MS",36e5),u=e.maxActionsPerSweep??re("KYNVER_CLEANUP_MAX_ACTIONS_PER_SWEEP",120),c=e.includeOrphans===!0||xe("KYNVER_CLEANUP_INCLUDE_ORPHANS"),p=xe("KYNVER_CLEANUP_SCOPE_ALL")||process.env.KYNVER_CLEANUP_SCOPE==="all"?e.runIdFilter:e.runIdFilter??(process.env.KYNVER_CLEANUP_RUN_ID||void 0),f=e.accountBytes!==!1&&!xe("KYNVER_CLEANUP_SKIP_BYTE_ACCOUNTING"),g=re("KYNVER_CLEANUP_STORAGE_ENTRY_CAP",2e3),d=e.storagePerRunEntryCap!==void 0?e.storagePerRunEntryCap:f&&g>0?g:null,R=re("KYNVER_CLEANUP_BYTE_ENTRY_CAP",2e3),x=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:c,runIdFilter:p?String(p):void 0,accountBytes:f,storagePerRunEntryCap:d,byteAccountingEntryCap:x}}H();import{existsSync as Kn}from"node:fs";import Kr from"node:path";y();var bi=1800*1e3;function jn(e){let r=e.now??Date.now(),t=e.heartbeatFreshMs??bi;if(!Kn(e.worktreePath))return null;if(e.runId&&e.workerName){let c=Kr.join(e.harnessRoot,"runs",e.runId,"workers",e.workerName),l=_(Kr.join(c,"worker.json"),void 0);if(l&&Or(l,r,t))return"active_worker"}let n=Kr.join(e.worktreePath,".git");if(!Kn(n))return null;let o=v(e.worktreePath,["status","--porcelain"]);if(o.status!==0)return"pr_or_unmerged_commits";let s=o.stdout.split(`
15
- `).map(c=>c.trim()).filter(c=>c.length>0);if(w(s).length>0)return"dirty_worktree";let i=v(e.worktreePath,["rev-list","--count","@{u}..HEAD"]);if(i.status===0){let c=Number(i.stdout.trim());if(Number.isFinite(c)&&c>0)return"pr_or_unmerged_commits"}let a=v(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}F();import{existsSync as Si,readdirSync as Ln,statSync as _i}from"node:fs";import xi from"node:path";function Gn(e={}){let r=A(e.harnessRoot??$()),t=ae(r),n=e.now??Date.now(),o=new Date(n).toISOString();if(!Si(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,c;try{c=Ln(t,{withFileTypes:!0})}catch{return{harnessRoot:r,worktreesDir:t,worktreesBytes:null,runCount:0,workerCount:0,oldestRunAt:null,scannedAt:o}}for(let l of c){if(!l.isDirectory())continue;i+=1;let p=xi.join(t,l.name);try{let f=_i(p);u=u===null?f.mtimeMs:Math.min(u,f.mtimeMs)}catch{}try{for(let f of Ln(p,{withFileTypes:!0}))f.isDirectory()&&(a+=1)}catch{}if(s!==null&&e.perRunEntryCap!==null){let f=e.perRunEntryCap??5e4;if(f<=0)s=null;else{let g=j(p,f);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}}F();import{existsSync as vi}from"node:fs";import{homedir as Ci}from"node:os";import $n from"node:path";var Ai=["/var/tmp/kynver-harness",$n.join(Ci(),".openclaw","harness")];function jr(e,r,t){if(!t?.trim())return;let n=A(t.trim());e.has(n)||(e.add(n),r.push(n))}function wi(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 Yn(e={}){let r=new Set,t=[];jr(r,t,e.harnessRoot??$());let n=process.env.KYNVER_CLEANUP_EXTRA_ROOTS?.split(",").map(o=>o.trim()).filter(Boolean);for(let o of n??[])jr(r,t,o);if(wi(e))for(let o of Ai){let s=$n.resolve(o);!r.has(s)&&vi(s)&&jr(r,t,s)}return t}Me();function Ei(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function Pi(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function Vn(e={}){let r=e.diskPath?.trim()||process.env.KYNVER_DISK_GUARD_PATH?.trim()||"/",t=Pi("KYNVER_DISK_GUARD_MAX_USED_PERCENT",75),n=Ne({...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 zn(e,r){if(!r.pressured)return e;let t=e.execute||!Ei("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}}function N(e,r){if(process.env.KYNVER_CLEANUP_QUIET==="1")return;let t=r?`: ${r}`:"";console.error(`[kynver cleanup] ${e}${t}`)}H();var er=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=v(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 Wi}from"node:child_process";import{existsSync as Oi}from"node:fs";import Ii from"node:path";var Ni=5e3;function Mi(e,r){if(!Oi(Ii.join(e,".git")))return{status:null,stdout:"",stderr:"",error:"not_a_git_repo"};try{let t=Wi("git",r,{cwd:e,encoding:"utf8",timeout:Ni}),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 Jn(e){let r=Mi(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 rr=class{cache=new Map;porcelain(r){let t=r,n=this.cache.get(t);if(n!==void 0)return n;let o=Jn(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=Z(r);return this.cache.set(r.id,n),n}};function Di(e){let r={};for(let t of e)r[t.kind]=(r[t.kind]??0)+1;return r}function qn(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:Di(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 Ti(e={}){let r=e.harnessRoot?A(e.harnessRoot):$(),t=Yn({harnessRoot:r}),n=e.now??Date.now();return{harnessRoot:r,scanRoots:t,now:n}}function Ui(e){return typeof e=="string"?{reason:e}:e}function ce(e,r,t,n){e.push({path:r,reason:t,...n?{detail:n}:{}})}function nr(e,r,t){return!r||e.bytes!=null?e:{...e,bytes:j(e.path,t)}}function Xn(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 Hi(e,r){return e.kind==="remove_next_cache"?vn(e,r):xn(e,r)}function Bi(e,r,t){return e.kind==="remove_next_cache"?qe(e.path,r,t):Je(e.path,r,t)}function Fi(e){let r=new Map;for(let t of e)for(let[n,o]of Bn(t))r.set(n,o);return r}function Qn(e,r){return e.runId&&e.worker?P.join(r,e.runId,e.worker):P.resolve(e.path,"..")}function Ki(e={}){let r=Fn(e),t=Vn();r=zn(r,t);let n=Ti(e);N("scan",`${n.scanRoots.length} harness root(s)`);let o=nn(n.scanRoots,n.now),s=r.finalizeStaleRuns?Bt().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=Fi(n.scanRoots);N("index",`${i.size} indexed worktree(s)`);let a={runTerminalCache:new tr,gitStatusCache:new rr,gitRevCache:new er},u=[],c=[],l=new Set,p=r.maxActionsPerSweep,f=()=>c.length>=p;for(let h of n.scanRoots){if(f())break;N("root",h);let te=P.join(h,"worktrees"),Ae=Hn(i,h),we={harnessRoot:h,worktreesDir:te,nodeModulesAgeMs:r.nodeModulesAgeMs,worktreesAgeMs:r.worktreesAgeMs,includeOrphans:r.includeOrphans,runIdFilter:r.runIdFilter,index:Ae,now:n.now},or=r.scanDependencyCaches?Dn(we):[];N("dependency",r.scanDependencyCaches?`${or.length} cache candidate(s) at ${h}`:"skipped (worktree-only sweep)");let sr=0;for(let O of or){if(f())break;sr+=1,sr%50===0&&N("dependency",`${sr}/${or.length} evaluated`);let S=P.resolve(O.path);if(l.has(S))continue;l.add(S);let m={...O,path:S},C=Bi(m,h,te);if(C){ce(u,m.path,C),c.push({...m,executed:!1,skipped:!0,skipReason:C});continue}let I=Qn(m,te),ne=Ae.get(P.resolve(I))??null,M=Nr({indexed:ne,includeOrphans:!0,nodeModulesAgeMs:r.nodeModulesAgeMs,ageMs:m.ageMs,worktreePath:I,activeWorktreePaths:o.activeWorktreePaths,diskPressure:r.diskPressure,gitStatusCache:a.gitStatusCache});if(M){ce(u,m.path,M),c.push({...m,executed:!1,skipped:!0,skipReason:M});continue}c.push(Hi(nr(m,r.accountBytes,r.byteAccountingEntryCap),r.execute))}if(r.scanDependencyCaches)for(let O of Wn(we)){if(f())break;let S=P.resolve(O.path);if(l.has(S))continue;l.add(S);let m={...O,path:S},C=Xe(m.path,h,te);if(C){ce(u,m.path,C),c.push({...m,executed:!1,skipped:!0,skipReason:C});continue}let I=Qn(m,te),ne=Ae.get(P.resolve(I))??null,M=Zt({indexed:ne,includeOrphans:!0,nodeModulesAgeMs:r.nodeModulesAgeMs,ageMs:m.ageMs,worktreePath:I,activeWorktreePaths:o.activeWorktreePaths,diskPressure:r.diskPressure,gitStatusCache:a.gitStatusCache});if(M){ce(u,m.path,M),c.push({...m,executed:!1,skipped:!0,skipReason:M});continue}c.push(Cn(nr(m,r.accountBytes,r.byteAccountingEntryCap),r.execute))}let ir=[...On(we),...Un(we)];N("worktrees",`${ir.length} candidate(s) at ${h}`);let Lr=new Set,ar=0;for(let O of ir){if(f())break;ar+=1,ar%50===0&&N("worktrees",`${ar}/${ir.length} evaluated`);let S=P.resolve(O.path);if(Lr.has(S))continue;Lr.add(S);let m={...O,path:S},C=Ae.get(P.resolve(m.path))??null,I=C?null:jn({worktreePath:m.path,harnessRoot:h,runId:m.runId,workerName:m.worker,now:n.now}),ne=Qt({indexed:C,worktreePath:P.resolve(m.path),includeOrphans:r.includeOrphans,worktreesAgeMs:r.worktreesAgeMs,terminalWorktreesAgeMs:r.terminalWorktreesAgeMs,ageMs:m.ageMs,orphanSafety:I,worktreeRemovalGuard:e.worktreeRemovalGuard,liveness:a,now:n.now,harnessRoot:h,writeSalvageEvidence:r.execute});if(ne){let{reason:M,detail:eo}=Ui(ne);ce(u,m.path,M,eo),c.push({...m,executed:!1,skipped:!0,skipReason:M});continue}c.push(wn(nr(m,r.accountBytes,r.byteAccountingEntryCap),r.execute))}if(!f()&&r.runDirectoriesAgeMs>=0)for(let O of dn({harnessRoot:h,worktreesDir:te,runDirectoriesAgeMs:r.runDirectoriesAgeMs,runIdFilter:r.runIdFilter,activeGuards:o,now:n.now})){if(f())break;let S=P.resolve(O.path);if(l.has(S))continue;l.add(S);let m={...O,path:S},C=m.runId??P.basename(S),I=ln({harnessRoot:h,runId:C,runPath:S,ageMs:m.ageMs,runDirectoriesAgeMs:r.runDirectoriesAgeMs,activeGuards:o});if(I){ce(u,m.path,I),c.push({...m,executed:!1,skipped:!0,skipReason:I});continue}c.push(An(nr(m,r.accountBytes,r.byteAccountingEntryCap),r.execute))}}let g=0,d=0,R=0,x=0,W=0,U=0;for(let h of c)h.bytes&&(g+=h.bytes),!h.skipped&&!h.executed&&h.bytes&&(R+=h.bytes),h.executed?(W+=1,x+=h.bytes??0,h.kind==="remove_run_directory"&&(d+=1)):h.skipped&&(U+=1,h.skipReason==="dry_run"&&h.bytes&&(R+=h.bytes));let ve=r.accountBytes?Gn({harnessRoot:n.harnessRoot,now:n.now,perRunEntryCap:r.storagePerRunEntryCap}):void 0;N("complete",`${c.length} action(s), ${U} skipped, ${W} removed`);let Ce=rn(c,u),Zn=qn({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:c,skips:u,totals:{candidateBytes:g,reclaimableBytes:R,removedBytes:x,removedPaths:W,skippedPaths:U,skipReasons:Xn(c,u)},...ve?{storage:ve}:{},...Ce.length>0?{preservedLivePaths:Ce}:{},...d>0?{removedRunDirectories:d}:{}});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:c,skips:u,totals:{candidateBytes:g,reclaimableBytes:R,removedBytes:x,removedPaths:W,skippedPaths:U,skipReasons:Xn(c,u)},...ve?{storage:ve}:{},...Ce.length>0?{preservedLivePaths:Ce}:{},...d>0?{removedRunDirectories:d}:{},compactSummary:Zn}}export{ze as DEFAULT_MAX_ACTIONS_PER_SWEEP,Mr as DEFAULT_NODE_MODULES_AGE_MS,Dr as DEFAULT_RUN_DIRECTORIES_AGE_MS,Ve as DEFAULT_WORKTREES_AGE_MS,Ki as runHarnessCleanup};
12
+ `),n=!0)}let o={capturedAt:new Date(e.now??Date.now()).toISOString(),skipReason:e.skipReason,runId:e.indexed.runId,workerName:e.indexed.workerName,worktreePath:e.indexed.worktreePath,taskId:e.indexed.worker.taskId,agentOsId:e.indexed.worker.agentOsId,branch:e.indexed.worker.branch,completionBlocker:e.indexed.worker.completionBlocker,finalResult:e.status.finalResult,changedFiles:e.status.changedFiles,gitAncestry:e.status.gitAncestry,prUrl:e.status.prUrl??null,...n?{patchPath:t}:{}};return zt($e.join(r,"evidence.json"),`${JSON.stringify(o,null,2)}
13
+ `),o}var Ks=new Set(["completion_blocked","dirty_worktree","pr_or_unmerged_commits","landing_blocked"]);function js(e){return!Ks.has(e.skipReason)||K(e.indexed,e.now)?!1:Xt({harnessRoot:e.harnessRoot,runId:e.indexed.runId,workerName:e.indexed.workerName})?!0:e.writeSalvageEvidence?(Qt({harnessRoot:e.harnessRoot,indexed:e.indexed,skipReason:e.skipReason,status:e.status,now:e.now}),!0):!1}function Ls(e){let{indexed:r,includeOrphans:t,worktreesAgeMs:n,terminalWorktreesAgeMs:o}=e;return r?Q.has(r.run.status)||e.liveness&&Nr(r,e.liveness)||e.liveness&&J(Or(r,e.liveness))&&!K(r)?o:n:t?o:n}function Gs(e,r){if(e.harnessRoot?.trim())return Ye.resolve(e.harnessRoot);let t=r.worker.workerDir;if(!t)return null;let n=`${Ye.sep}runs${Ye.sep}`,o=t.indexOf(n);return o<0?null:t.slice(0,o+n.length-1)}function Zt(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=Ls(e);if(n<=0&&!t&&u<=0)return"worktrees_disabled";if(u>0&&o<u)return"below_age_threshold";if(K(r,a))return"active_worker";let c=Or(r,e.liveness),l=Gs(e,r),p=d=>l&&js({indexed:r,harnessRoot:l,skipReason:d,status:c,now:a,writeSalvageEvidence:e.writeSalvageEvidence===!0})?null:d;if(Vt(r,c)){let d=p("completion_blocked");if(d)return d}if(Wr(r,e.liveness?.gitStatusCache)){let d=p("dirty_worktree");if(d)return d}let f=e.liveness?.gitRevCache?.countAheadOfMain(e.worktreePath);if(f!=null&&f>0){let d=p("pr_or_unmerged_commits");if(d)return d}if(Yt(r,e.liveness,a)||!J(c))return"run_still_active";if(ye(c)){let d=p("pr_or_unmerged_commits");if(d)return d}if(w(c.changedFiles).length>0){let d=p("dirty_worktree");if(d)return d}if(se({finalResult:c.finalResult,changedFiles:c.changedFiles,gitAncestry:c.gitAncestry,prUrl:X(c.finalResult)}).blocked){let d=p("landing_blocked");if(d)return d}if(i&&e.worktreePath){let d=i({worktreePath:e.worktreePath,indexed:!!r,runId:r?.runId,worker:r?.workerName});if(d)return d.detail?{reason:d.reason,detail:d.detail}:d.reason}return null}function Mr(e){let{indexed:r,nodeModulesAgeMs:t,ageMs:n,worktreePath:o,activeWorktreePaths:s,diskPressure:i}=e;return!i&&n<t?"below_age_threshold":s.has(Ye.resolve(o))||r&&K(r)?"active_worker":r&&Wr(r,e.gitStatusCache)?"dirty_worktree":null}function en(e){return Mr(e)}var Dr=216e5,Ve=6048e5;var Tr=36e5,ze=120;var rn=new Set(["active_worker","run_still_active","completion_blocked","landing_blocked"]);function tn(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)rn.has(s.reason)&&o(s.path,s.reason,s.detail);for(let s of e)!s.skipped||!s.skipReason||rn.has(s.skipReason)&&o(s.path,s.skipReason);return t}import{existsSync as an,readdirSync as un,statSync as Vs}from"node:fs";import cn from"node:path";V();F();import nn from"node:path";y();function Ys(e,r){return Ge(e,r)}function on(e,r=Date.now()){let t=new Set,n=new Set;for(let o of e){for(let s of Te(o)){let i=!1;for(let a of Object.keys(s.workers||{})){let u=_(nn.join(me(o,s.id),"workers",b(a),"worker.json"),void 0);if(!u?.worktreePath)continue;let c=nn.resolve(u.worktreePath);Ys(u,r)&&(i=!0,t.add(c))}i&&n.add(`${o}\0${s.id}`)}for(let s of $t(o))n.add(s)}return{activeWorktreePaths:t,liveRunKeys:n}}function sn(e,r,t,n){return t?n.has(`${r}\0${t}`):!1}y();function zs(e,r){try{let t=Vs(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function Js(e,r){let t=cn.join(e,"runs",r,"run.json");return an(t)?_(t,null):null}function ln(e){try{return un(e).length===0}catch{return!1}}function dn(e){let{harnessRoot:r,runId:t,runPath:n,ageMs:o,runDirectoriesAgeMs:s,activeGuards:i}=e;if(sn(n,r,t,i.liveRunKeys)||!ln(n))return"run_still_active";let a=Js(r,t);return a&&!Q.has(a.status)&&!Z(a)?"run_still_active":s>0&&o<s?"below_age_threshold":null}function pn(e){if(!an(e.worktreesDir))return[];let r=[],t;try{t=un(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=cn.join(e.worktreesDir,o);ln(s)&&r.push({kind:"remove_run_directory",path:s,bytes:null,harnessRoot:e.harnessRoot,runId:o,ageMs:zs(s,e.now)})}return r}H();import{existsSync as Hr,rmSync as xn}from"node:fs";import{execFileSync as qs}from"node:child_process";import{existsSync as fn,readdirSync as Xs,statSync as Qs}from"node:fs";import Zs from"node:path";var ei=2500;function ri(e,r=ei){if(!fn(e))return 0;try{let n=qs("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 j(e,r=5e4){if(!fn(e))return 0;let t=ri(e);if(t!==null)return t;let n=0,o=0,s=[e];for(;s.length>0;){let i=s.pop(),a;try{a=Xs(i)}catch{continue}for(let u of a){if(o++>r)return null;let c=Zs.join(i,u),l;try{l=Qs(c)}catch{continue}l.isDirectory()?s.push(c):n+=l.size}}return n}import{existsSync as si,rmSync as ii}from"node:fs";F();import{lstatSync as ti,readdirSync as ni}from"node:fs";function mn(e){try{let r=ti(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 gn(e,r=32){let t=mn(e);if(!t)return!1;if(t.foreign)return!0;try{let n=ni(e),o=0;for(let s of n){if(o>=r)break;let i=`${e.replace(/\/$/,"")}/${s}`,a=mn(i);if(o+=1,a?.foreign)return!0}}catch{}return!1}import{spawnSync as oi}from"node:child_process";import Rn from"node:path";import E from"node:path";function hn(e,r,t,n){let o=E.resolve(e),s=`${E.sep}${n}`,i=o.endsWith(s)?o:null;if(!i)return"path_outside_harness";let a=E.relative(t,i);if(a.startsWith("..")||E.isAbsolute(a))return"path_outside_harness";let u=a.split(E.sep);return u.length<3||u[u.length-1]!==n||!o.startsWith(E.resolve(r))?"path_outside_harness":null}function Je(e,r,t){return hn(e,r,t,"node_modules")}function qe(e,r,t){return hn(e,r,t,".next")}function Xe(e,r,t){let n=E.resolve(e),o=E.relative(t,n);return o.startsWith("..")||E.isAbsolute(o)||o.split(E.sep).length<3||!n.startsWith(E.resolve(r))?"path_outside_harness":null}function kn(e,r,t){let n=E.resolve(e);return Je(n,r,t)===null||qe(n,r,t)===null||Xe(n,r,t)===null}function bn(){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 yn(e){let r=oi("sudo",["-n",...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{ok:r.status===0,stderr:`${r.stderr??""}${r.stdout??""}`.trim()}}function Sn(e,r,t){if(!kn(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=yn(["chown","-R",`${n}:${o}`,Rn.resolve(e)]);if(s.ok)return{ok:!0,method:"chown_then_rm"};let i=yn(["rm","-rf",Rn.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 Ur="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 ai(e){let r=e?.code;return r==="EACCES"||r==="EPERM"}function _n(e,r,t={}){if(!si(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?ae(n):null,i=e.bytes??j(e.path)??void 0,a=t.removePath??ii,u=t.hasForeignOwnedEntry??gn;try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i}}catch(c){if(!ai(c)||!n||!o)return{executed:!1,skipped:!0,skipReason:"remove_failed",error:c.message};let l=u(e.path),p=bn();if(!(p==="force"||p==="auto"&&l))return l?{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${c.message}; ${Ur}`}:{executed:!1,skipped:!0,skipReason:"remove_failed",error:c.message};let g=Sn(e.path,n,o);if(g.ok&&g.method==="sudo_rm")return{executed:!0,skipped:!1,bytes:i,privilegedReclaim:!0};if(g.ok)try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i,privilegedReclaim:!0}}catch(d){return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${d.message}; privileged chown succeeded but rm still failed`}}return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${c.message}; privileged reclaim failed: ${g.error}; ${Ur}`}}}function Br(e){let r=e.harnessRoot;return!r||!Gt(e.path,r)?null:{...e,executed:!1,skipped:!0,skipReason:"run_metadata_protected"}}function Fr(e,r){let t=Br(e);if(t)return t;let n=_n(e,r);return{...e,bytes:n.bytes??e.bytes,executed:n.executed,skipped:n.skipped,skipReason:n.skipReason,error:n.error}}function vn(e,r){return Fr(e,r)}function Cn(e,r){return Fr(e,r)}function An(e,r){return Fr(e,r)}function wn(e,r){let t=Br(e);if(t)return t;if(!Hr(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??j(e.path);return xn(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 En(e,r){let t=Br(e);if(t)return t;if(!Hr(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??j(e.path);return n&&le(n,["worktree","remove","--force",e.path],{allowFailure:!0}),Hr(e.path)&&xn(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 Qe,readdirSync as Ze,statSync as ui}from"node:fs";import D from"node:path";function Kr(e,r){try{let t=ui(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function Wn(e,r){let t=D.relative(r,e);return t===""||!t.startsWith("..")&&!D.isAbsolute(t)}function Pn(e,r,t,n){let o=[];for(let s of Pr){if(s===".next")continue;let i=D.join(e,s);if(!Qe(i))continue;let a=D.resolve(i);t.has(a)||Wn(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:Kr(a,r.now)}))}return o}function On(e){let r=[],t=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||r.push(...Pn(n.worktreePath,e,t,{runId:n.runId,worker:n.workerName,repo:n.run.repo}));if(!e.includeOrphans||!Qe(e.worktreesDir))return r;for(let n of Ze(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=D.join(e.worktreesDir,n.name);for(let s of Ze(o,{withFileTypes:!0})){if(!s.isDirectory())continue;let i=D.join(o,s.name);r.push(...Pn(i,e,t,{runId:n.name,worker:s.name}))}}return r}function In(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;Qe(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:Kr(a,e.now)})))}if(!t||!Qe(e.worktreesDir))return n;let s=new Set;for(let i of e.index.values())s.add(D.resolve(i.worktreePath));for(let i of Ze(e.worktreesDir,{withFileTypes:!0})){if(!i.isDirectory()||e.runIdFilter&&i.name!==e.runIdFilter)continue;let a=D.join(e.worktreesDir,i.name),u;try{u=Ze(a,{withFileTypes:!0})}catch{continue}for(let c of u){if(!c.isDirectory())continue;let l=D.resolve(D.join(a,c.name));o.has(l)||s.has(l)||Wn(l,e.harnessRoot)&&(o.add(l),n.push({kind:"remove_worktree",path:l,bytes:null,runId:i.name,worker:c.name,ageMs:Kr(l,e.now)}))}}return n}import{existsSync as Dn,readdirSync as Nn,statSync as ci}from"node:fs";import ue from"node:path";var li=[{dirName:"node_modules",kind:"remove_node_modules"},{dirName:".next",kind:"remove_next_cache"}];function di(e,r){try{let t=ci(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function pi(e,r){let t=ue.relative(r,e);return t===""||!t.startsWith("..")&&!ue.isAbsolute(t)}function fi(e,r,t,n,o,s){if(!Dn(n))return;let i=ue.resolve(n);r.has(i)||pi(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:di(i,t.now)}))}function Mn(e,r,t,n,o){for(let s of li)fi(e,r,t,ue.join(n,s.dirName),s.kind,o)}function Tn(e){let r=[],t=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||Mn(r,t,e,n.worktreePath,{runId:n.runId,worker:n.workerName,repo:n.run.repo});if(!e.includeOrphans||!Dn(e.worktreesDir))return r;for(let n of Nn(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory()||e.runIdFilter&&n.name!==e.runIdFilter)continue;let o=ue.join(e.worktreesDir,n.name),s;try{s=Nn(o,{withFileTypes:!0})}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=ue.join(o,i.name);Mn(r,t,e,a,{runId:n.name,worker:i.name})}}return r}H();import{existsSync as Un,statSync as mi}from"node:fs";import T from"node:path";function gi(e,r){try{let t=mi(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function hi(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 ki(e,r){let t=T.relative(T.resolve(r),T.resolve(e));return t!==""&&!t.startsWith("..")&&!T.isAbsolute(t)}var Ri=200;function Hn(e){if(!e.includeOrphans||!Un(e.worktreesDir))return[];let r=new Set;for(let s of e.index.values())s.run.repo&&r.add(T.resolve(s.run.repo));let t=new Set;for(let s of e.index.values())t.add(T.resolve(s.worktreePath));let n=[],o=new Set;for(let s of r){let i=0,a;try{a=le(s,["worktree","list","--porcelain"],{allowFailure:!0})}catch{continue}let u=hi(a);for(let c of u){if(i>=Ri)break;let l=T.resolve(c.path);if(l===T.resolve(s)||!ki(l,e.worktreesDir)||t.has(l)||o.has(l)||!Un(l))continue;let f=T.relative(e.worktreesDir,l).split(T.sep),g=f[0],d=f[1]??"unknown";o.add(l),i+=1,n.push({kind:"remove_worktree",path:l,bytes:null,runId:g,worker:d,repo:s,ageMs:gi(l,e.now)})}}return n}V();y();import _e from"node:path";function Bn(e,r){let t=_e.resolve(r),n=new Map;for(let[o,s]of e){let i=s.harnessRoot?_e.resolve(s.harnessRoot):null;i&&i!==t||n.set(o,s)}return n}function Fn(e){let r=new Map;for(let t of Te(e))for(let n of Object.keys(t.workers||{})){let o=_e.join(me(e,t.id),"workers",b(n),"worker.json"),s=_(o,void 0);s?.worktreePath&&r.set(_e.resolve(s.worktreePath),{harnessRoot:e,worktreePath:_e.resolve(s.worktreePath),runId:t.id,workerName:n,run:t,worker:s})}return r}function xe(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function re(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)&&n>=0?n:r}function Kn(e={}){let r=e.execute===!0||e.execute!==!1&&xe("KYNVER_CLEANUP_EXECUTE"),t=e.finalizeStaleRuns!==!1&&!xe("KYNVER_CLEANUP_SKIP_FINALIZE"),n=e.nodeModulesAgeMs??re("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??re("KYNVER_CLEANUP_WORKTREES_AGE_MS",0),i=e.terminalWorktreesAgeMs??re("KYNVER_CLEANUP_TERMINAL_WORKTREES_AGE_MS",216e5),a=e.runDirectoriesAgeMs??re("KYNVER_CLEANUP_RUN_DIRECTORIES_AGE_MS",36e5),u=e.maxActionsPerSweep??re("KYNVER_CLEANUP_MAX_ACTIONS_PER_SWEEP",120),c=e.includeOrphans===!0||xe("KYNVER_CLEANUP_INCLUDE_ORPHANS"),p=xe("KYNVER_CLEANUP_SCOPE_ALL")||process.env.KYNVER_CLEANUP_SCOPE==="all"?e.runIdFilter:e.runIdFilter??(process.env.KYNVER_CLEANUP_RUN_ID||void 0),f=e.accountBytes!==!1&&!xe("KYNVER_CLEANUP_SKIP_BYTE_ACCOUNTING"),g=re("KYNVER_CLEANUP_STORAGE_ENTRY_CAP",2e3),d=e.storagePerRunEntryCap!==void 0?e.storagePerRunEntryCap:f&&g>0?g:null,R=re("KYNVER_CLEANUP_BYTE_ENTRY_CAP",2e3),x=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:c,runIdFilter:p?String(p):void 0,accountBytes:f,storagePerRunEntryCap:d,byteAccountingEntryCap:x}}H();import{existsSync as jn}from"node:fs";import jr from"node:path";y();var bi=1800*1e3;function Ln(e){let r=e.now??Date.now(),t=e.heartbeatFreshMs??bi;if(!jn(e.worktreePath))return null;if(e.runId&&e.workerName){let c=jr.join(e.harnessRoot,"runs",e.runId,"workers",e.workerName),l=_(jr.join(c,"worker.json"),void 0);if(l&&Ir(l,r,t))return"active_worker"}let n=jr.join(e.worktreePath,".git");if(!jn(n))return null;let o=v(e.worktreePath,["status","--porcelain"]);if(o.status!==0)return"pr_or_unmerged_commits";let s=o.stdout.split(`
15
+ `).map(c=>c.trim()).filter(c=>c.length>0);if(w(s).length>0)return"dirty_worktree";let i=v(e.worktreePath,["rev-list","--count","@{u}..HEAD"]);if(i.status===0){let c=Number(i.stdout.trim());if(Number.isFinite(c)&&c>0)return"pr_or_unmerged_commits"}let a=v(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}F();import{existsSync as Si,readdirSync as Gn,statSync as _i}from"node:fs";import xi from"node:path";function $n(e={}){let r=A(e.harnessRoot??$()),t=ae(r),n=e.now??Date.now(),o=new Date(n).toISOString();if(!Si(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,c;try{c=Gn(t,{withFileTypes:!0})}catch{return{harnessRoot:r,worktreesDir:t,worktreesBytes:null,runCount:0,workerCount:0,oldestRunAt:null,scannedAt:o}}for(let l of c){if(!l.isDirectory())continue;i+=1;let p=xi.join(t,l.name);try{let f=_i(p);u=u===null?f.mtimeMs:Math.min(u,f.mtimeMs)}catch{}try{for(let f of Gn(p,{withFileTypes:!0}))f.isDirectory()&&(a+=1)}catch{}if(s!==null&&e.perRunEntryCap!==null){let f=e.perRunEntryCap??5e4;if(f<=0)s=null;else{let g=j(p,f);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}}F();import{existsSync as vi}from"node:fs";import{homedir as Ci}from"node:os";import Yn from"node:path";var Ai=["/var/tmp/kynver-harness",Yn.join(Ci(),".openclaw","harness")];function Lr(e,r,t){if(!t?.trim())return;let n=A(t.trim());e.has(n)||(e.add(n),r.push(n))}function wi(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 Vn(e={}){let r=new Set,t=[];Lr(r,t,e.harnessRoot??$());let n=process.env.KYNVER_CLEANUP_EXTRA_ROOTS?.split(",").map(o=>o.trim()).filter(Boolean);for(let o of n??[])Lr(r,t,o);if(wi(e))for(let o of Ai){let s=Yn.resolve(o);!r.has(s)&&vi(s)&&Lr(r,t,s)}return t}Me();function Ei(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function Pi(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function zn(e={}){let r=e.diskPath?.trim()||process.env.KYNVER_DISK_GUARD_PATH?.trim()||"/",t=Pi("KYNVER_DISK_GUARD_MAX_USED_PERCENT",75),n=Ne({...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 Jn(e,r){if(!r.pressured)return e;let t=e.execute||!Ei("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}}function N(e,r){if(process.env.KYNVER_CLEANUP_QUIET==="1")return;let t=r?`: ${r}`:"";console.error(`[kynver cleanup] ${e}${t}`)}H();var er=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=v(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 Wi}from"node:child_process";import{existsSync as Oi}from"node:fs";import Ii from"node:path";var Ni=5e3;function Mi(e,r){if(!Oi(Ii.join(e,".git")))return{status:null,stdout:"",stderr:"",error:"not_a_git_repo"};try{let t=Wi("git",r,{cwd:e,encoding:"utf8",timeout:Ni}),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 qn(e){let r=Mi(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 rr=class{cache=new Map;porcelain(r){let t=r,n=this.cache.get(t);if(n!==void 0)return n;let o=qn(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=Z(r);return this.cache.set(r.id,n),n}};function Di(e){let r={};for(let t of e)r[t.kind]=(r[t.kind]??0)+1;return r}function Xn(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:Di(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 Ti(e={}){let r=e.harnessRoot?A(e.harnessRoot):$(),t=Vn({harnessRoot:r}),n=e.now??Date.now();return{harnessRoot:r,scanRoots:t,now:n}}function Ui(e){return typeof e=="string"?{reason:e}:e}function ce(e,r,t,n){e.push({path:r,reason:t,...n?{detail:n}:{}})}function nr(e,r,t){return!r||e.bytes!=null?e:{...e,bytes:j(e.path,t)}}function Qn(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 Hi(e,r){return e.kind==="remove_next_cache"?Cn(e,r):vn(e,r)}function Bi(e,r,t){return e.kind==="remove_next_cache"?qe(e.path,r,t):Je(e.path,r,t)}function Fi(e){let r=new Map;for(let t of e)for(let[n,o]of Fn(t))r.set(n,o);return r}function Zn(e,r){return e.runId&&e.worker?P.join(r,e.runId,e.worker):P.resolve(e.path,"..")}function Ki(e={}){let r=Kn(e),t=zn();r=Jn(r,t);let n=Ti(e);N("scan",`${n.scanRoots.length} harness root(s)`);let o=on(n.scanRoots,n.now),s=r.finalizeStaleRuns?Ft().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=Fi(n.scanRoots);N("index",`${i.size} indexed worktree(s)`);let a={runTerminalCache:new tr,gitStatusCache:new rr,gitRevCache:new er},u=[],c=[],l=new Set,p=r.maxActionsPerSweep,f=()=>c.length>=p;for(let h of n.scanRoots){if(f())break;N("root",h);let te=P.join(h,"worktrees"),Ae=Bn(i,h),we={harnessRoot:h,worktreesDir:te,nodeModulesAgeMs:r.nodeModulesAgeMs,worktreesAgeMs:r.worktreesAgeMs,includeOrphans:r.includeOrphans,runIdFilter:r.runIdFilter,index:Ae,now:n.now},or=r.scanDependencyCaches?Tn(we):[];N("dependency",r.scanDependencyCaches?`${or.length} cache candidate(s) at ${h}`:"skipped (worktree-only sweep)");let sr=0;for(let O of or){if(f())break;sr+=1,sr%50===0&&N("dependency",`${sr}/${or.length} evaluated`);let S=P.resolve(O.path);if(l.has(S))continue;l.add(S);let m={...O,path:S},C=Bi(m,h,te);if(C){ce(u,m.path,C),c.push({...m,executed:!1,skipped:!0,skipReason:C});continue}let I=Zn(m,te),ne=Ae.get(P.resolve(I))??null,M=Mr({indexed:ne,includeOrphans:!0,nodeModulesAgeMs:r.nodeModulesAgeMs,ageMs:m.ageMs,worktreePath:I,activeWorktreePaths:o.activeWorktreePaths,diskPressure:r.diskPressure,gitStatusCache:a.gitStatusCache});if(M){ce(u,m.path,M),c.push({...m,executed:!1,skipped:!0,skipReason:M});continue}c.push(Hi(nr(m,r.accountBytes,r.byteAccountingEntryCap),r.execute))}if(r.scanDependencyCaches)for(let O of On(we)){if(f())break;let S=P.resolve(O.path);if(l.has(S))continue;l.add(S);let m={...O,path:S},C=Xe(m.path,h,te);if(C){ce(u,m.path,C),c.push({...m,executed:!1,skipped:!0,skipReason:C});continue}let I=Zn(m,te),ne=Ae.get(P.resolve(I))??null,M=en({indexed:ne,includeOrphans:!0,nodeModulesAgeMs:r.nodeModulesAgeMs,ageMs:m.ageMs,worktreePath:I,activeWorktreePaths:o.activeWorktreePaths,diskPressure:r.diskPressure,gitStatusCache:a.gitStatusCache});if(M){ce(u,m.path,M),c.push({...m,executed:!1,skipped:!0,skipReason:M});continue}c.push(An(nr(m,r.accountBytes,r.byteAccountingEntryCap),r.execute))}let ir=[...In(we),...Hn(we)];N("worktrees",`${ir.length} candidate(s) at ${h}`);let Gr=new Set,ar=0;for(let O of ir){if(f())break;ar+=1,ar%50===0&&N("worktrees",`${ar}/${ir.length} evaluated`);let S=P.resolve(O.path);if(Gr.has(S))continue;Gr.add(S);let m={...O,path:S},C=Ae.get(P.resolve(m.path))??null,I=C?null:Ln({worktreePath:m.path,harnessRoot:h,runId:m.runId,workerName:m.worker,now:n.now}),ne=Zt({indexed:C,worktreePath:P.resolve(m.path),includeOrphans:r.includeOrphans,worktreesAgeMs:r.worktreesAgeMs,terminalWorktreesAgeMs:r.terminalWorktreesAgeMs,ageMs:m.ageMs,orphanSafety:I,worktreeRemovalGuard:e.worktreeRemovalGuard,liveness:a,now:n.now,harnessRoot:h,writeSalvageEvidence:r.execute});if(ne){let{reason:M,detail:ro}=Ui(ne);ce(u,m.path,M,ro),c.push({...m,executed:!1,skipped:!0,skipReason:M});continue}c.push(En(nr(m,r.accountBytes,r.byteAccountingEntryCap),r.execute))}if(!f()&&r.runDirectoriesAgeMs>=0)for(let O of pn({harnessRoot:h,worktreesDir:te,runDirectoriesAgeMs:r.runDirectoriesAgeMs,runIdFilter:r.runIdFilter,activeGuards:o,now:n.now})){if(f())break;let S=P.resolve(O.path);if(l.has(S))continue;l.add(S);let m={...O,path:S},C=m.runId??P.basename(S),I=dn({harnessRoot:h,runId:C,runPath:S,ageMs:m.ageMs,runDirectoriesAgeMs:r.runDirectoriesAgeMs,activeGuards:o});if(I){ce(u,m.path,I),c.push({...m,executed:!1,skipped:!0,skipReason:I});continue}c.push(wn(nr(m,r.accountBytes,r.byteAccountingEntryCap),r.execute))}}let g=0,d=0,R=0,x=0,W=0,U=0;for(let h of c)h.bytes&&(g+=h.bytes),!h.skipped&&!h.executed&&h.bytes&&(R+=h.bytes),h.executed?(W+=1,x+=h.bytes??0,h.kind==="remove_run_directory"&&(d+=1)):h.skipped&&(U+=1,h.skipReason==="dry_run"&&h.bytes&&(R+=h.bytes));let ve=r.accountBytes?$n({harnessRoot:n.harnessRoot,now:n.now,perRunEntryCap:r.storagePerRunEntryCap}):void 0;N("complete",`${c.length} action(s), ${U} skipped, ${W} removed`);let Ce=tn(c,u),eo=Xn({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:c,skips:u,totals:{candidateBytes:g,reclaimableBytes:R,removedBytes:x,removedPaths:W,skippedPaths:U,skipReasons:Qn(c,u)},...ve?{storage:ve}:{},...Ce.length>0?{preservedLivePaths:Ce}:{},...d>0?{removedRunDirectories:d}:{}});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:c,skips:u,totals:{candidateBytes:g,reclaimableBytes:R,removedBytes:x,removedPaths:W,skippedPaths:U,skipReasons:Qn(c,u)},...ve?{storage:ve}:{},...Ce.length>0?{preservedLivePaths:Ce}:{},...d>0?{removedRunDirectories:d}:{},compactSummary:eo}}export{ze as DEFAULT_MAX_ACTIONS_PER_SWEEP,Dr as DEFAULT_NODE_MODULES_AGE_MS,Tr as DEFAULT_RUN_DIRECTORIES_AGE_MS,Ve as DEFAULT_WORKTREES_AGE_MS,Ki as runHarnessCleanup};
@@ -1 +1 @@
1
- var t=(e,n)=>()=>(e&&(n=e(e=0)),n);function C(e){return process.platform!=="win32"?e:{windowsHide:!0,...e}}var i=t(()=>{"use strict"});var Q,Ce,P=t(()=>{"use strict";Q=["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"],Ce=new Set(Q)});import{spawnSync as Z}from"node:child_process";function w(e,n){try{let r=Z("git",n,C({cwd:e,encoding:"utf8"}));return{status:r.status,stdout:r.stdout||"",stderr:r.stderr||"",error:r.error?r.error.message:null}}catch(r){return{status:null,stdout:"",stderr:"",error:r.message}}}var g=t(()=>{"use strict";i();P()});import{homedir as O}from"node:os";import B from"node:path";function ee(e){return e==="~"?O():e.startsWith("~/")||e.startsWith("~\\")?B.join(O(),e.slice(2)):e}function u(e){return B.resolve(ee(e))}var d=t(()=>{"use strict"});import{existsSync as y,readFileSync as W}from"node:fs";import{homedir as re}from"node:os";import a from"node:path";import{fileURLToPath as te}from"node:url";function oe(e){let n=a.join(e,"package.json");if(!y(n))return null;try{let r=JSON.parse(W(n,"utf8"));return typeof r.name=="string"?r.name.trim():null}catch{return null}}function se(e){return oe(e)==="kynver"}function T(e){let n=a.resolve(e);if(!y(n))return null;let r=w(n,["rev-parse","--show-toplevel"]);if(r.status!==0)return null;let o=r.stdout.trim();return o.length?a.resolve(o):null}function ie(e=import.meta.url){let n=a.dirname(te(e));for(let r=0;r<8;r+=1){let o=a.join(n,"package.json");if(y(o))try{if(JSON.parse(W(o,"utf8")).name==="@kynver-app/runtime")return n}catch{}let s=a.dirname(n);if(s===n)break;n=s}return null}function p(e,n,r,o){if(!r)return;let s=a.resolve(r);e.has(s)||se(s)&&(e.add(s),n.push({repo:s,source:o}))}function ae(e){let n=e?.cwd??process.cwd(),r=new Set,o=[];p(r,o,T(n),"cwd_git");let s=ie(e?.runtimeModuleUrl??import.meta.url);s&&p(r,o,T(s),"runtime_checkout");let l=re();for(let c of ne)p(r,o,u(a.join(l,c)),"well_known_path");return o}function h(e){return ae(e)[0]??null}var ne,b=t(()=>{"use strict";g();d();ne=["Kynver","repos/Kynver","repos/kynver-source-main","code/Kynver","projects/Kynver"]});var k=t(()=>{"use strict"});var N=t(()=>{"use strict"});var ze,Je,U=t(()=>{"use strict";ze=25*1024*1024*1024,Je=12*1024*1024*1024});var Ze,er,R=t(()=>{"use strict";U();Ze=30*1024*1024*1024,er=15*1024*1024*1024});import{homedir as le}from"node:os";import ce from"node:path";var ar,K=t(()=>{"use strict";m();d();i();ar=ce.join(le(),".openclaw","harness")});var _=t(()=>{"use strict";K();i()});var I=t(()=>{"use strict";_();i()});var M=t(()=>{"use strict"});var D=t(()=>{"use strict";M();i()});var F=t(()=>{"use strict"});var H=t(()=>{"use strict";F()});var $=t(()=>{"use strict";H();i()});var j=t(()=>{"use strict"});var L=t(()=>{"use strict"});var G=t(()=>{"use strict"});var S=t(()=>{"use strict"});var Y=t(()=>{"use strict";S()});var V=t(()=>{"use strict";D();$();j();L();g();G();Y();S();i()});var z=t(()=>{"use strict";V()});var pe,ye,J=t(()=>{"use strict";N();m();k();E();R();_();I();z();i();pe=500*1024*1024,ye=4*1024*1024*1024});var E=t(()=>{"use strict";J()});import{existsSync as ke,mkdirSync as Lt,readFileSync as Re,writeFileSync as Gt}from"node:fs";import{homedir as xe,totalmem as Vt}from"node:os";import v from"node:path";function f(){if(!ke(q))return{};try{return JSON.parse(Re(q,"utf8"))}catch{return{}}}var X,q,rn,tn,nn,m=t(()=>{"use strict";b();d();i();k();E();R();X=v.join(xe(),".kynver"),q=v.join(X,"config.json"),rn=v.join(X,"credentials");tn=500*1024*1024,nn=4*1024*1024*1024});m();b();d();import _e from"node:path";function Se(e){return _e.resolve(u(e.trim()))}function A(e,n,r){let o=e?.trim();return o?{repo:Se(o),source:n,persistedInConfig:r}:null}function Ee(e={}){let n=e.env??process.env,r=e.config??f(),o=A(r.defaultRepo,"config",!0);if(o)return o;let s=A(n.KYNVER_DEFAULT_REPO,"env_default_repo",!1);if(s)return s;let l=A(n.KYNVER_HARNESS_REPO,"env_harness_repo",!1);if(l)return l;let c=h({cwd:e.cwd,runtimeModuleUrl:e.runtimeModuleUrl});return c?{repo:c.repo,source:c.source,persistedInConfig:!1}:null}export{Ee as resolveDefaultRepo};
1
+ var t=(e,n)=>()=>(e&&(n=e(e=0)),n);function C(e){return process.platform!=="win32"?e:{windowsHide:!0,...e}}var i=t(()=>{"use strict"});var Q,Ce,P=t(()=>{"use strict";Q=["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"],Ce=new Set(Q)});import{spawnSync as Z}from"node:child_process";function w(e,n){try{let r=Z("git",n,C({cwd:e,encoding:"utf8"}));return{status:r.status,stdout:r.stdout||"",stderr:r.stderr||"",error:r.error?r.error.message:null}}catch(r){return{status:null,stdout:"",stderr:"",error:r.message}}}var g=t(()=>{"use strict";i();P()});import{homedir as O}from"node:os";import B from"node:path";function ee(e){return e==="~"?O():e.startsWith("~/")||e.startsWith("~\\")?B.join(O(),e.slice(2)):e}function u(e){return B.resolve(ee(e))}var d=t(()=>{"use strict"});import{existsSync as h,readFileSync as W}from"node:fs";import{homedir as re}from"node:os";import a from"node:path";import{fileURLToPath as te}from"node:url";function oe(e){let n=a.join(e,"package.json");if(!h(n))return null;try{let r=JSON.parse(W(n,"utf8"));return typeof r.name=="string"?r.name.trim():null}catch{return null}}function se(e){return oe(e)==="kynver"}function T(e){let n=a.resolve(e);if(!h(n))return null;let r=w(n,["rev-parse","--show-toplevel"]);if(r.status!==0)return null;let o=r.stdout.trim();return o.length?a.resolve(o):null}function ie(e=import.meta.url){let n=a.dirname(te(e));for(let r=0;r<8;r+=1){let o=a.join(n,"package.json");if(h(o))try{if(JSON.parse(W(o,"utf8")).name==="@kynver-app/runtime")return n}catch{}let s=a.dirname(n);if(s===n)break;n=s}return null}function p(e,n,r,o){if(!r)return;let s=a.resolve(r);e.has(s)||se(s)&&(e.add(s),n.push({repo:s,source:o}))}function ae(e){let n=e?.cwd??process.cwd(),r=new Set,o=[];p(r,o,T(n),"cwd_git");let s=ie(e?.runtimeModuleUrl??import.meta.url);s&&p(r,o,T(s),"runtime_checkout");let l=re();for(let c of ne)p(r,o,u(a.join(l,c)),"well_known_path");return o}function y(e){return ae(e)[0]??null}var ne,b=t(()=>{"use strict";g();d();ne=["Kynver","repos/Kynver","repos/kynver-source-main","code/Kynver","projects/Kynver"]});var k=t(()=>{"use strict"});var N=t(()=>{"use strict"});var ze,Je,U=t(()=>{"use strict";ze=25*1024*1024*1024,Je=12*1024*1024*1024});var Ze,er,R=t(()=>{"use strict";U();Ze=30*1024*1024*1024,er=15*1024*1024*1024});import{homedir as le}from"node:os";import ce from"node:path";var ar,K=t(()=>{"use strict";m();d();i();ar=ce.join(le(),".openclaw","harness")});var _=t(()=>{"use strict";K();i()});var I=t(()=>{"use strict";_();i()});var M=t(()=>{"use strict"});var D=t(()=>{"use strict";M();i()});var F=t(()=>{"use strict"});var H=t(()=>{"use strict";F()});var $=t(()=>{"use strict";H();i()});var j=t(()=>{"use strict"});var L=t(()=>{"use strict"});var G=t(()=>{"use strict"});var S=t(()=>{"use strict"});var Y=t(()=>{"use strict";S()});var V=t(()=>{"use strict";D();$();j();L();g();G();Y();S();i()});var z=t(()=>{"use strict";V()});var pe,he,J=t(()=>{"use strict";N();m();k();E();R();_();I();z();i();pe=500*1024*1024,he=4*1024*1024*1024});var E=t(()=>{"use strict";J()});import{existsSync as ke,mkdirSync as Lt,readFileSync as Re,writeFileSync as Gt}from"node:fs";import{homedir as xe,totalmem as Vt}from"node:os";import v from"node:path";function f(){if(!ke(q))return{};try{return JSON.parse(Re(q,"utf8"))}catch{return{}}}var X,q,rn,tn,nn,m=t(()=>{"use strict";b();d();i();k();E();R();X=v.join(xe(),".kynver"),q=v.join(X,"config.json"),rn=v.join(X,"credentials");tn=500*1024*1024,nn=4*1024*1024*1024});m();b();d();import _e from"node:path";function Se(e){return _e.resolve(u(e.trim()))}function A(e,n,r){let o=e?.trim();return o?{repo:Se(o),source:n,persistedInConfig:r}:null}function Ee(e={}){let n=e.env??process.env,r=e.config??f(),o=A(r.defaultRepo,"config",!0);if(o)return o;let s=A(n.KYNVER_DEFAULT_REPO,"env_default_repo",!1);if(s)return s;let l=A(n.KYNVER_HARNESS_REPO,"env_harness_repo",!1);if(l)return l;let c=y({cwd:e.cwd,runtimeModuleUrl:e.runtimeModuleUrl});return c?{repo:c.repo,source:c.source,persistedInConfig:!1}:null}export{Ee as resolveDefaultRepo};
@@ -1,2 +1,3 @@
1
1
  export { assessHeavyVerificationGate, countActiveHeavyVerificationSlots, isHeavyVerificationGateSkipped, resolveHeavyVerificationMaxConcurrent, } from "../heavy-verification/slot.js";
2
+ export { waitForHeavyVerificationSlot } from "../heavy-verification/gate.js";
2
3
  export { compareSemver } from "../memory-cost-package-version-guard.js";
@@ -1 +1 @@
1
- import{closeSync as z,existsSync as l,mkdirSync as I,openSync as Q,readdirSync as y,readFileSync as N,unlinkSync as O,writeFileSync as Z}from"node:fs";import S from"node:path";function f(e){if(!e)return!1;try{return process.kill(e,0),!0}catch{return!1}}import{mkdirSync as C}from"node:fs";import{tmpdir as b}from"node:os";import a from"node:path";import{homedir as _}from"node:os";import m from"node:path";function d(){let e=process.env.KYNVER_STATE_ROOT;return e?m.resolve(e):m.join(_(),".kynver","state")}function M(){return!!(process.env.VERCEL||process.env.VERCEL_ENV||process.env.AWS_LAMBDA_FUNCTION_NAME||process.env.AWS_EXECUTION_ENV)}function P(){let e=process.env.KYNVER_HEAVY_VERIFICATION_STATE_ROOT;return e?a.resolve(e):M()?a.join(b(),"kynver","state","heavy-verification"):a.join(d(),"heavy-verification")}function g(){return a.join(P(),"slots")}function c(){let e=g();return C(e,{recursive:!0}),e}var u=120*6e4,v=1;function V(e,r){let t=Number(e);return!Number.isFinite(t)||t<=0?r:Math.floor(t)}function E(){let e=process.env.KYNVER_HEAVY_VERIFICATION_SKIP?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function p(){let e=process.env.KYNVER_HEAVY_VERIFICATION_MAX_CONCURRENT;return e?V(e,v):v}function R(e){if(!l(e))return null;try{let r=JSON.parse(N(e,"utf8"));if(typeof r.slotId=="string"&&typeof r.pid=="number"&&typeof r.acquiredAt=="string"&&typeof r.command=="string")return r}catch{return null}return null}function k(e,r=u){if(!e||!f(e.pid))return!0;let t=Date.parse(e.acquiredAt);return Number.isNaN(t)?!0:Date.now()-t>r}function T(e,r){let t=R(e);if(k(t,r))try{O(e)}catch{}}function D(e){return I(e,{recursive:!0}),e}function h(e={}){let r=D(e.slotsDir??c()),t=e.staleMs??u,o=0;for(let n of y(r)){if(!n.endsWith(".json"))continue;let s=S.join(r,n),i=l(s);T(s,t),i&&!l(s)&&(o+=1)}return o}function w(e={}){let r=e.slotsDir??c(),t=e.staleMs??u;h({slotsDir:r,staleMs:t});let o=[];for(let n of y(r)){if(!n.endsWith(".json"))continue;let s=R(S.join(r,n));s&&!k(s,t)&&o.push(s)}return o}function A(e={}){return w(e).length}function H(e,r={}){if(E())return{admitted:!0,slotId:null,activeSlots:0,maxSlots:p(),reason:null};let t=r.slotsDir??c(),o=r.staleMs??u,n=r.maxSlots??p();h({slotsDir:t,staleMs:o});let s=A({slotsDir:t,staleMs:o}),i=s<n;return{admitted:i,slotId:null,activeSlots:s,maxSlots:n,reason:i?null:`heavy verification at capacity (${s}/${n} slots); waiting for ${e}`}}var $=["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"],oe=new Set($);var G={"@kynver-app/runtime":"0.1.83","@kynver-app/openclaw-agent-os":"0.1.43","@kynver-app/mcp-agent-os":"0.3.34"},ke=Object.keys(G);function x(e){let r=e.trim().split("-")[0]?.split("+")[0];if(!r)return null;let t=r.split(".");if(t.length<1||t.length>3)return null;let o=t.map(n=>Number.parseInt(n,10));if(o.some(n=>!Number.isFinite(n)||n<0))return null;for(;o.length<3;)o.push(0);return[o[0],o[1],o[2]]}function K(e,r){let t=x(e),o=x(r);if(!t||!o)return 0;for(let n=0;n<3;n+=1){if(t[n]>o[n])return 1;if(t[n]<o[n])return-1}return 0}export{H as assessHeavyVerificationGate,K as compareSemver,A as countActiveHeavyVerificationSlots,E as isHeavyVerificationGateSkipped,p as resolveHeavyVerificationMaxConcurrent};
1
+ import{closeSync as $,existsSync as S,mkdirSync as K,openSync as Y,readdirSync as M,readFileSync as j,unlinkSync as V,writeFileSync as F}from"node:fs";import E from"node:path";function A(e){if(!e)return!1;try{return process.kill(e,0),!0}catch{return!1}}import{mkdirSync as T}from"node:fs";import{tmpdir as D}from"node:os";import p from"node:path";import{homedir as w}from"node:os";import _ from"node:path";function C(){let e=process.env.KYNVER_STATE_ROOT;return e?_.resolve(e):_.join(w(),".kynver","state")}function H(){return!!(process.env.VERCEL||process.env.VERCEL_ENV||process.env.AWS_LAMBDA_FUNCTION_NAME||process.env.AWS_EXECUTION_ENV)}function G(){let e=process.env.KYNVER_HEAVY_VERIFICATION_STATE_ROOT;return e?p.resolve(e):H()?p.join(D(),"kynver","state","heavy-verification"):p.join(C(),"heavy-verification")}function y(){return p.join(G(),"slots")}function c(){let e=y();return T(e,{recursive:!0}),e}var l=120*6e4,b=1;function U(e,r){let t=Number(e);return!Number.isFinite(t)||t<=0?r:Math.floor(t)}function h(){let e=process.env.KYNVER_HEAVY_VERIFICATION_SKIP?.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function u(){let e=process.env.KYNVER_HEAVY_VERIFICATION_MAX_CONCURRENT;return e?U(e,b):b}function L(e){return`slot-${e}`}function W(e,r=y()){return E.join(r,`${e}.json`)}function R(e){if(!S(e))return null;try{let r=JSON.parse(j(e,"utf8"));if(typeof r.slotId=="string"&&typeof r.pid=="number"&&typeof r.acquiredAt=="string"&&typeof r.command=="string")return r}catch{return null}return null}function m(e,r=l){if(!e||!A(e.pid))return!0;let t=Date.parse(e.acquiredAt);return Number.isNaN(t)?!0:Date.now()-t>r}function B(e,r){let t=R(e);if(m(t,r))try{V(e)}catch{}}function J(e){return K(e,{recursive:!0}),e}function k(e={}){let r=J(e.slotsDir??c()),t=e.staleMs??l,o=0;for(let n of M(r)){if(!n.endsWith(".json"))continue;let s=E.join(r,n),i=S(s);B(s,t),i&&!S(s)&&(o+=1)}return o}function X(e={}){let r=e.slotsDir??c(),t=e.staleMs??l;k({slotsDir:r,staleMs:t});let o=[];for(let n of M(r)){if(!n.endsWith(".json"))continue;let s=R(E.join(r,n));s&&!m(s,t)&&o.push(s)}return o}function d(e={}){return X(e).length}function x(e,r={}){if(h())return{admitted:!0,slotId:null,activeSlots:0,maxSlots:u(),reason:null};let t=r.slotsDir??c(),o=r.staleMs??l,n=r.maxSlots??u();k({slotsDir:t,staleMs:o});for(let i=0;i<n;i+=1){let g=L(i),v=W(g,t),f=R(v);if(f&&m(f,o))try{V(v)}catch{}else if(f&&!m(f,o))continue;let N={slotId:g,pid:process.pid,acquiredAt:new Date().toISOString(),command:e};try{let a=Y(v,"wx");F(a,JSON.stringify(N,null,2),"utf8"),$(a);let O=d({slotsDir:t,staleMs:o});return{admitted:!0,slotId:g,activeSlots:O,maxSlots:n,reason:null}}catch(a){if(a.code==="EEXIST")continue;throw a}}let s=d({slotsDir:t,staleMs:o});return{admitted:!1,slotId:null,activeSlots:s,maxSlots:n,reason:`heavy verification at capacity (${s}/${n} slots)`}}function P(e,r={}){if(h())return{admitted:!0,slotId:null,activeSlots:0,maxSlots:u(),reason:null};let t=r.slotsDir??c(),o=r.staleMs??l,n=r.maxSlots??u();k({slotsDir:t,staleMs:o});let s=d({slotsDir:t,staleMs:o}),i=s<n;return{admitted:i,slotId:null,activeSlots:s,maxSlots:n,reason:i?null:`heavy verification at capacity (${s}/${n} slots); waiting for ${e}`}}import{spawnSync as q}from"node:child_process";function z(e){e<=0||q(process.execPath,["-e",`const d=Date.now()+${Math.floor(e)};while(Date.now()<d);`],{stdio:"ignore"})}function Q(e,r,t=2e3,o={}){let n=Date.now()+Math.max(0,r),s=x(e,o);for(;!s.admitted&&Date.now()<n;)z(Math.min(t,n-Date.now())),s=x(e,o);return s}var Z=["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"],Ee=new Set(Z);var ee={"@kynver-app/runtime":"0.1.83","@kynver-app/openclaw-agent-os":"0.1.43","@kynver-app/mcp-agent-os":"0.3.34"},De=Object.keys(ee);function I(e){let r=e.trim().split("-")[0]?.split("+")[0];if(!r)return null;let t=r.split(".");if(t.length<1||t.length>3)return null;let o=t.map(n=>Number.parseInt(n,10));if(o.some(n=>!Number.isFinite(n)||n<0))return null;for(;o.length<3;)o.push(0);return[o[0],o[1],o[2]]}function re(e,r){let t=I(e),o=I(r);if(!t||!o)return 0;for(let n=0;n<3;n+=1){if(t[n]>o[n])return 1;if(t[n]<o[n])return-1}return 0}export{P as assessHeavyVerificationGate,re as compareSemver,d as countActiveHeavyVerificationSlots,h as isHeavyVerificationGateSkipped,u as resolveHeavyVerificationMaxConcurrent,Q as waitForHeavyVerificationSlot};