@kynver-app/runtime 0.1.140 → 0.1.148

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,4 +1,4 @@
1
- import{createHash as u}from"node:crypto";function o(e){return JSON.stringify(i(e))}function i(e){if(Array.isArray(e))return e.map(i);if(e&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=i(e[n]);return t}return e}function L(e){return`ib1-${u("sha256").update(o(e),"utf8").digest("hex").slice(0,16)}`}function N(e){return`ib-${u("sha256").update(Buffer.from(e)).digest("hex").slice(0,12)}`}function a(e){if(!e)return null;let t=e.trim();if(!t)return null;if(/^[0-9a-fA-F]{64}$/.test(t))return new Uint8Array(t.match(/.{2}/g).map(n=>parseInt(n,16)));try{let n=Buffer.from(t,"base64");if(n.length===32)return new Uint8Array(n)}catch{}return null}function s(e){if(!e||typeof e!="object")return!1;let t=e;if(typeof t.signature!="string"||!t.signature||typeof t.publicKeyId!="string"||!t.publicKeyId)return!1;let n=t.bundle;return!(!n||typeof n!="object"||typeof n.version!="string"||!n.version||typeof n.generatedAt!="string"||!Array.isArray(n.personas)||!n.instructions||typeof n.instructions!="object"||!n.policyThresholds||typeof n.policyThresholds!="object")}var c={"ib-3bab6314f0ba":"53a2040646cd479e1f5f1aea9abf7848ce8b62e32001efb8044dfd90e8ab87ed","ib-26e6c695da06":"bb1700f25b2ee7d7cdcdb9f446f0f44ef2cc22a3096bc161232fb658e7cdaf38"};function l(e,t=process.env){let n=a(t.KYNVER_INSTRUCTION_BUNDLE_PUBLIC_KEY);if(n)return n;let r=c[e];return r?a(r):null}import{createPublicKey as f,verify as m}from"node:crypto";var g=Buffer.from("302a300506032b6570032100","hex");function y(e){return f({key:Buffer.concat([g,Buffer.from(e)]),format:"der",type:"spki"})}function d(e,t){if(!s(e))return{ok:!1,reason:"malformed signed bundle payload"};let n;try{n=Buffer.from(e.signature,"base64url")}catch{return{ok:!1,reason:"signature is not base64url"}}if(n.length!==64)return{ok:!1,reason:"signature is not a 64-byte Ed25519 signature"};try{let r=Buffer.from(o(e.bundle),"utf8");return m(null,r,y(t),n)?{ok:!0,bundle:e.bundle}:{ok:!1,reason:"Ed25519 signature mismatch"}}catch(r){return{ok:!1,reason:`signature verification failed: ${r.message}`}}}function h(e,t=process.env){if(!s(e))return{ok:!1,reason:"malformed signed bundle payload"};let n=l(e.publicKeyId,t);return n?d(e,n):{ok:!1,reason:`no verification key for publicKeyId "${e.publicKeyId}" (not pinned; set KYNVER_INSTRUCTION_BUNDLE_PUBLIC_KEY)`}}var p="embedded-1",I=[{slug:"ghost",displayName:"Ghost",description:"Orchestration persona.",dispatchLane:null,defaultRoleLane:"system"},{slug:"astra",displayName:"Astra",description:"Planning persona.",dispatchLane:"implementation",defaultRoleLane:"plan_author"},{slug:"rhea",displayName:"Rhea",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"mnemo",displayName:"Mnemo",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"sentinel",displayName:"Sentinel",description:"Review persona.",dispatchLane:"review",defaultRoleLane:"deep_reviewer"},{slug:"pixel",displayName:"Pixel",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"schema",displayName:"Schema",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"atlas",displayName:"Atlas",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"runtime_verifier"},{slug:"bridge",displayName:"Bridge",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"catalyst",displayName:"Catalyst",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"lorentz",displayName:"Lorentz",description:"Review persona.",dispatchLane:"review",defaultRoleLane:"report_reviewer"},{slug:"dalton",displayName:"Dalton",description:"Landing persona.",dispatchLane:"landing",defaultRoleLane:"implementer"}],b={"worker.prompt.core_rules":["Structured final result (recommended): record completion as JSON with summary, files, PR URLs, verification, risks, and blockers.","Completion handoff (required): before you stop, summarize the outcome in your last message and append a heartbeat line with phase `complete`. Commit your work cleanly and open a GitHub PR (draft OK) for substantial changes \u2014 never leave uncommitted changes behind without reporting them.","Review-only workers must not open new implementation PRs \u2014 review the existing PR and record a verdict in the final result.","Keep verification targeted to touched paths; avoid full-monorepo verification unless explicitly requested.","Do not run `npm publish`.","If verification fails, append a heartbeat line immediately with the failing command, reason, and next action."].join(`
1
+ import{createHash as u}from"node:crypto";function o(e){return JSON.stringify(i(e))}function i(e){if(Array.isArray(e))return e.map(i);if(e&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=i(e[n]);return t}return e}function L(e){return`ib1-${u("sha256").update(o(e),"utf8").digest("hex").slice(0,16)}`}function N(e){return`ib-${u("sha256").update(Buffer.from(e)).digest("hex").slice(0,12)}`}function a(e){if(!e)return null;let t=e.trim();if(!t)return null;if(/^[0-9a-fA-F]{64}$/.test(t))return new Uint8Array(t.match(/.{2}/g).map(n=>parseInt(n,16)));try{let n=Buffer.from(t,"base64");if(n.length===32)return new Uint8Array(n)}catch{}return null}function s(e){if(!e||typeof e!="object")return!1;let t=e;if(typeof t.signature!="string"||!t.signature||typeof t.publicKeyId!="string"||!t.publicKeyId)return!1;let n=t.bundle;return!(!n||typeof n!="object"||typeof n.version!="string"||!n.version||typeof n.generatedAt!="string"||!Array.isArray(n.personas)||!n.instructions||typeof n.instructions!="object"||!n.policyThresholds||typeof n.policyThresholds!="object")}var c={"ib-3bab6314f0ba":"53a2040646cd479e1f5f1aea9abf7848ce8b62e32001efb8044dfd90e8ab87ed","ib-26e6c695da06":"bb1700f25b2ee7d7cdcdb9f446f0f44ef2cc22a3096bc161232fb658e7cdaf38"};function l(e,t=process.env){let n=a(t.KYNVER_INSTRUCTION_BUNDLE_PUBLIC_KEY);if(n)return n;let r=c[e];return r?a(r):null}import{createPublicKey as f,verify as m}from"node:crypto";var g=Buffer.from("302a300506032b6570032100","hex");function y(e){return f({key:Buffer.concat([g,Buffer.from(e)]),format:"der",type:"spki"})}function d(e,t){if(!s(e))return{ok:!1,reason:"malformed signed bundle payload"};let n;try{n=Buffer.from(e.signature,"base64url")}catch{return{ok:!1,reason:"signature is not base64url"}}if(n.length!==64)return{ok:!1,reason:"signature is not a 64-byte Ed25519 signature"};try{let r=Buffer.from(o(e.bundle),"utf8");return m(null,r,y(t),n)?{ok:!0,bundle:e.bundle}:{ok:!1,reason:"Ed25519 signature mismatch"}}catch(r){return{ok:!1,reason:`signature verification failed: ${r.message}`}}}function h(e,t=process.env){if(!s(e))return{ok:!1,reason:"malformed signed bundle payload"};let n=l(e.publicKeyId,t);return n?d(e,n):{ok:!1,reason:`no verification key for publicKeyId "${e.publicKeyId}" (not pinned; set KYNVER_INSTRUCTION_BUNDLE_PUBLIC_KEY)`}}var p="embedded-1",I=[{slug:"ghost",displayName:"Ghost",description:"Orchestration persona.",dispatchLane:null,defaultRoleLane:"system"},{slug:"astra",displayName:"Astra",description:"Planning persona.",dispatchLane:"implementation",defaultRoleLane:"plan_author"},{slug:"rhea",displayName:"Rhea",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"mnemo",displayName:"Mnemo",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"sentinel",displayName:"Sentinel",description:"Review persona.",dispatchLane:"review",defaultRoleLane:"deep_reviewer"},{slug:"pixel",displayName:"Pixel",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"schema",displayName:"Schema",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"atlas",displayName:"Atlas",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"runtime_verifier"},{slug:"bridge",displayName:"Bridge",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"catalyst",displayName:"Catalyst",description:"Implementation persona.",dispatchLane:"implementation",defaultRoleLane:"implementer"},{slug:"lorentz",displayName:"Lorentz",description:"Review persona.",dispatchLane:"review",defaultRoleLane:"report_reviewer"},{slug:"dalton",displayName:"Dalton",description:"Landing persona.",dispatchLane:"landing",defaultRoleLane:"implementer"}],b={"worker.prompt.core_rules":["Structured final result (recommended): record completion as JSON with summary, files, PR URLs, verification, risks, and blockers.","Completion handoff (required): before you stop, summarize the outcome in your last message and append a heartbeat line with phase `complete` and a structured finalResult object. Commit your work cleanly and open a GitHub PR (draft OK) for substantial changes \u2014 never leave uncommitted changes behind without reporting them.","Review-only workers must not open new implementation PRs \u2014 review the existing PR and record a verdict in the final result.","Keep verification targeted to touched paths; avoid full-monorepo verification unless explicitly requested.","Do not run `npm publish`.","If verification fails, append a heartbeat line immediately with the failing command, reason, and next action."].join(`
2
2
  `),"worker.prompt.progress.compact":"Plan progress: when planId is set, report progress with `kynver plan progress --plan <planId> --row <rowKey> --role implementer --status in_progress|running|partial|blocked`. Do not mark rows done from the worker CLI.","worker.prompt.progress.full":["Structured plan progress (required when planId is set):","- Report checkpoints with `kynver plan progress --plan <planId> --row <rowKey> --role implementer --status in_progress|running|partial|blocked`.","- When a slice is finished, emit `partial` with evidence (`--evidence pr:<url>`, `--evidence path:<file>`, or `--evidence command:<cmd>`).","- Do not propose or confirm row `done` from the worker CLI."].join(`
3
3
  `),"worker.prompt.merge_gate.compact":"Verification cost control: prefer local verification before requesting CI runs; do not push empty commits to re-trigger CI; record verification evidence on the PR.","worker.prompt.merge_gate.full":["Verification cost control:","- Prefer local verification of touched paths before requesting any CI run.","- Do not push empty commits to re-trigger CI.","- Record verification evidence on the PR before requesting review."].join(`
4
4
  `),"worker.prompt.plan_artifacts.compact":"Plan artifacts: when authoring or revising plan documents, open a GitHub PR early and iterate from that PR branch; do not leave the canonical plan only in a local worktree.","worker.prompt.plan_artifacts.full":["Plan artifacts (when authoring or revising plan documents):","- Create a feature branch and open a GitHub PR (draft OK) before substantial drafting; commit and push the plan file.","- Iterate on that PR branch and link the PR URL on the related task and progress evidence."].join(`
@@ -2,6 +2,8 @@ import { type CliRunner, type ProviderEvidenceItem, type ProviderEvidenceWantedI
2
2
  export interface ProviderEvidenceCollectionSummary {
3
3
  attempted: number;
4
4
  collected: number;
5
+ /** Number of items served from caller-provided cache without invoking provider CLIs. */
6
+ cached: number;
5
7
  items: ProviderEvidenceItem[];
6
8
  skipped: Array<{
7
9
  provider: string;
@@ -10,9 +12,20 @@ export interface ProviderEvidenceCollectionSummary {
10
12
  reason: "no_recipe" | "provider_unavailable" | "collect_failed" | "budget_exhausted";
11
13
  }>;
12
14
  }
15
+ export interface ProviderEvidenceCollectionCache {
16
+ get(key: string, now: Date): ProviderEvidenceItem | null;
17
+ set(key: string, item: ProviderEvidenceItem, now: Date): void;
18
+ /**
19
+ * Optional live-collection gate. Return false to skip the provider CLI call
20
+ * for this item while allowing cache hits to continue flowing.
21
+ */
22
+ reserve?(item: ProviderEvidenceWantedItem, key: string, now: Date): boolean;
23
+ }
13
24
  export declare function collectProviderEvidence(wanted: ProviderEvidenceWantedItem[], opts?: {
14
25
  run?: CliRunner;
15
26
  maxSubjects?: number;
16
27
  deadlineMs?: number;
17
28
  now?: () => Date;
29
+ /** Optional TTL cache used to avoid re-polling external APIs every daemon tick. */
30
+ cache?: ProviderEvidenceCollectionCache;
18
31
  }): ProviderEvidenceCollectionSummary;
@@ -3,5 +3,6 @@ export * from "./exec.js";
3
3
  export * from "./registry.js";
4
4
  export * from "./collect.js";
5
5
  export * from "./wanted-store.js";
6
+ export * from "./shared-cache.js";
6
7
  export * from "./recipes-github.js";
7
8
  export * from "./recipes-vercel.js";
@@ -1,4 +1,5 @@
1
1
  import { type EvidenceCollectorRecipe } from "./types.js";
2
+ export declare function resetGitHubRateLimitCooldownForTests(): void;
2
3
  export declare const githubPrSnapshotRecipe: EvidenceCollectorRecipe;
3
4
  export declare const githubCommitStatusRecipe: EvidenceCollectorRecipe;
4
5
  export declare const githubBranchReachabilityRecipe: EvidenceCollectorRecipe;
@@ -0,0 +1,8 @@
1
+ import type { ProviderEvidenceCollectionCache } from "./collect.js";
2
+ export interface ProviderEvidenceSharedCache extends ProviderEvidenceCollectionCache {
3
+ flush(): void;
4
+ }
5
+ export declare function createProviderEvidenceSharedCache(runId: string, opts?: {
6
+ ttlMs?: number;
7
+ file?: string;
8
+ }): ProviderEvidenceSharedCache;
@@ -1,5 +1,13 @@
1
- import type { ProviderEvidenceWantedItem } from "./types.js";
1
+ import type { ProviderEvidenceCollectionCache } from "./collect.js";
2
+ import { type ProviderEvidenceWantedItem } from "./types.js";
2
3
  export declare function loadPersistedProviderEvidenceWanted(runId: string): ProviderEvidenceWantedItem[];
3
4
  export declare function persistProviderEvidenceWanted(runId: string, wanted: ProviderEvidenceWantedItem[]): void;
5
+ export interface ProviderEvidenceRunCache extends ProviderEvidenceCollectionCache {
6
+ flush(): void;
7
+ }
8
+ export declare function createProviderEvidenceRunCache(runId: string, opts?: {
9
+ ttlMs?: number;
10
+ }): ProviderEvidenceRunCache;
11
+ export declare function providerEvidenceWantedKey(item: ProviderEvidenceWantedItem): string;
4
12
  /** Extract `providerEvidenceWanted` from an operator-tick response body. */
5
13
  export declare function extractProviderEvidenceWanted(tickResponse: unknown): ProviderEvidenceWantedItem[] | null;
@@ -1,16 +1,16 @@
1
- var R=(e,r)=>()=>(e&&(r=e(e=0)),r);import{existsSync as So,mkdirSync as _o,readFileSync as st,readdirSync as _a,statSync as it,writeFileSync as Co}from"node:fs";import vo from"node:path";function yr(e){console.error(e),process.exit(1)}function br(e){return process.platform!=="win32"?e:{windowsHide:!0,...e}}function Me(e){try{return JSON.parse(e)}catch{return null}}function v(e,r){try{return JSON.parse(st(e,"utf8"))}catch(t){if(arguments.length>1)return r;yr(`failed to read ${e}: ${t.message}`)}}function at(e,r){_o(vo.dirname(e),{recursive:!0}),Co(e,`${JSON.stringify(r,null,2)}
2
- `)}function _(e){return String(e||"").toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"worker"}function Te(e){try{return it(e).size}catch{return 0}}function Ue(e){try{return it(e).mtime.toISOString()}catch{return null}}function ut(e,r){return So(e)?st(e,"utf8").split(`
1
+ var g=(e,r,t)=>()=>{if(t)throw t[0];try{return e&&(r=e(e=0)),r}catch(n){throw t=[n],n}};import{existsSync as Io,mkdirSync as Uo,readFileSync as it,readdirSync as Ka,statSync as at,writeFileSync as To}from"node:fs";import Bo from"node:path";function Rr(e){console.error(e),process.exit(1)}function br(e){return process.platform!=="win32"?e:{windowsHide:!0,...e}}function Ue(e){try{return JSON.parse(e)}catch{return null}}function x(e,r){try{return JSON.parse(it(e,"utf8"))}catch(t){if(arguments.length>1)return r;Rr(`failed to read ${e}: ${t.message}`)}}function ut(e,r){Uo(Bo.dirname(e),{recursive:!0}),To(e,`${JSON.stringify(r,null,2)}
2
+ `)}function v(e){return String(e||"").toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"worker"}function Te(e){try{return at(e).size}catch{return 0}}function Be(e){try{return at(e).mtime.toISOString()}catch{return null}}function lt(e,r){return Io(e)?it(e,"utf8").split(`
3
3
  `).slice(-r).join(`
4
- `):""}function z(e){if(!e)return!1;try{return process.kill(e,0),!0}catch{return!1}}function lt(e){let r=null,t=-1/0;for(let n of e){if(!n)continue;let o=Date.parse(n);Number.isFinite(o)&&o>t&&(t=o,r=n)}return r}function Sr(e){return Math.max(0,Math.round((Date.now()-e)/1e3))}var S=R(()=>{"use strict"});var xo,xa,ct=R(()=>{"use strict";xo=["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"],xa=new Set(xo)});import{spawnSync as pt}from"node:child_process";function Re(e,r,t={}){let n=pt("git",r,br({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);yr(o)}return n.stdout||""}function ye(e){return Re(e,["status","--short"],{allowFailure:!0}).split(`
5
- `).map(r=>r.trim()).filter(Boolean)}function x(e,r){try{let t=pt("git",r,br({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 dt(e,r,t){let n=x(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 Be(e,r="origin/main"){let t=typeof r=="string"?{base:r}:r,n=t.baseCommit?.trim()||t.base?.trim()||"origin/main",o=t.baseCommit?.trim()||null;if(!e)return _r(n,"missing worktree path");let s=x(e,["rev-parse","HEAD"]);if(s.status!==0)return _r(n,s.error||s.stderr||s.stdout||"failed to resolve HEAD");let i;if(o)i=o;else{let m=x(e,["rev-parse",n]);if(m.status!==0)return _r(n,m.error||m.stderr||m.stdout||`failed to resolve ${n}`,s.stdout.trim());i=m.stdout.trim()}let a=s.stdout.trim();if(a===i)return{checked:!0,base:n,head:a,baseHead:i,baseIsAncestorOfHead:!0,headIsAncestorOfBase:!0,relation:"synced"};let u=dt(e,i,a),l=dt(e,a,i),c=u.error||l.error||void 0;if(u.isAncestor==null||l.isAncestor==null)return{checked:!1,base:n,head:a,baseHead:i,baseIsAncestorOfHead:u.isAncestor,headIsAncestorOfBase:l.isAncestor,relation:"unknown",...c?{error:c}:{}};let d=u.isAncestor?"ahead":l.isAncestor?"merged":"diverged";return{checked:!0,base:n,head:a,baseHead:i,baseIsAncestorOfHead:u.isAncestor,headIsAncestorOfBase:l.isAncestor,relation:d,...c?{error:c}:{}}}function _r(e,r,t=null){return{checked:!1,base:e,head:t,baseHead:null,baseIsAncestorOfHead:null,headIsAncestorOfBase:null,relation:"unknown",error:r}}var K=R(()=>{"use strict";S();ct()});import{homedir as mt}from"node:os";import ft from"node:path";function wo(e){return e==="~"?mt():e.startsWith("~/")||e.startsWith("~\\")?ft.join(mt(),e.slice(2)):e}function He(e){return ft.resolve(wo(e))}var be=R(()=>{"use strict"});var Cr=R(()=>{"use strict";K();be()});var vr=R(()=>{"use strict"});var gt=R(()=>{"use strict"});import{existsSync as Ao,readFileSync as Eo,statfsSync as Po}from"node:fs";function xr(){if(process.platform!=="linux")return!1;for(let e of["/proc/sys/kernel/osrelease","/proc/version"])try{if(!Ao(e))continue;let r=Eo(e,"utf8");if(/microsoft|wsl/i.test(r))return!0}catch{}return!1}function ht(e={}){if(!(e.forceWsl===void 0?xr():e.forceWsl))return null;let t=e.wslHostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||ce,n=e.wslHostFreeWarnBytes??Wo,o=e.wslHostFreeCriticalBytes??Do,s=e.statfs??Po,i;try{i=s(t)}catch(y){return{ok:!1,path:t,freeBytes:0,totalBytes:0,usedPercent:100,warnBelowBytes:n,criticalBelowBytes:o,reason:`Windows host disk probe failed at ${t}: ${y.message}`,probeError:y.message}}let a=Number(i.bavail)*Number(i.bsize),u=Number(i.blocks)*Number(i.bsize),l=u>0?(u-a)/u*100:100,c=a<n,d=a<o,m=!c&&!d,f=(a/(1024*1024*1024)).toFixed(1),p=null;return m||(p=`Windows host disk ${t} at ${d?"critical":"warning"}: ${f} GiB free (<${(d?o:n)/1024/1024/1024} GiB); WSL VHDX cannot grow safely. ${Oo()}`),{ok:m,path:t,freeBytes:a,totalBytes:u,usedPercent:l,warnBelowBytes:n,criticalBelowBytes:o,reason:p,probeError:null}}function Oo(){return"Recovery: 1) free Windows C: (empty Recycle Bin / Storage Sense / clear %TEMP% and %LOCALAPPDATA%\\Temp\\wsl-crashes); 2) shut down WSL (`wsl --shutdown`) then compact the VHDX (`Optimize-VHD` or `diskpart compact vdisk`); 3) clear local node_modules / .next / harness worktrees before restarting workers; 4) disable recurring dumps via `%USERPROFILE%/.wslconfig` (`maxCrashDumpCount=-1`) or `kynver wsl-crashes --execute`. Full runbook: docs/runbooks/wsl-disk-pressure.md."}var Wo,Do,ce,wr=R(()=>{"use strict";Wo=25*1024*1024*1024,Do=12*1024*1024*1024,ce="/mnt/c"});import{execFileSync as kt}from"node:child_process";import{existsSync as Le,readFileSync as Rt,readdirSync as No,statSync as Io}from"node:fs";import Ar from"node:path";function Fe(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function yt(){let e=process.env.KYNVER_WSL_WIN_USER?.trim();if(e)return e;try{let n=kt("cmd.exe",["/c","echo","%USERNAME%"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(n&&n!=="%USERNAME%"&&!n.includes("%"))return n}catch{}let r=process.env.USER?.trim()||process.env.LOGNAME?.trim(),t=process.env.KYNVER_WSL_HOST_MOUNT?.trim()||ce;return r&&Le(Ar.join(t,"Users",r))?r:null}function Ho(e={}){let r=e.crashDumpDir?.trim()||process.env.KYNVER_WSL_CRASH_DUMP_DIR?.trim();if(r)return r;let t=e.hostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||ce,n=e.windowsUser??yt();return n?`${t.replace(/\\/g,"/").replace(/\/$/,"")}/Users/${n}/AppData/Local/Temp/wsl-crashes`:null}function Fo(e){let r=/^wsl-crash-\d+-(\d+)-(.+)-(\d+)\.dmp$/i.exec(e);if(!r)return{executableHint:null,signal:null,pid:null};let t=Number(r[1]),n=r[2]??"",o=Number(r[3]),s=n.split("_").filter(Boolean);return{executableHint:s.length>0?s[s.length-1]:null,signal:Number.isFinite(o)?o:null,pid:Number.isFinite(t)?t:null}}function Lo(){try{if(Le("/proc/sys/kernel/core_pattern"))return Rt("/proc/sys/kernel/core_pattern","utf8").trim()}catch{}try{return kt("sysctl",["-n","kernel.core_pattern"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function Ko(e){return!!(e&&/wsl-capture-crash/i.test(e))}function jo(e,r=ce){let t=Ar.join(r,"Users",e,".wslconfig");if(!Le(t))return{maxCrashDumpCount:null,crashDumpFolder:null};let n;try{n=Rt(t,"utf8")}catch{return null}let o=null,s=null;for(let i of n.split(/\r?\n/)){let a=i.replace(/#.*$/,"").trim();if(!a||a.startsWith("["))continue;let u=a.indexOf("=");if(u<0)continue;let l=a.slice(0,u).trim().toLowerCase(),c=a.slice(u+1).trim();if(l==="maxcrashdumpcount"){let d=Number(c);o=Number.isFinite(d)?d:null}else l==="crashdumpfolder"&&(s=c.replace(/^["']|["']$/g,"")||null)}return{maxCrashDumpCount:o,crashDumpFolder:s}}function $o(e){if(!Le(e))return[];let r=No(e,{withFileTypes:!0}),t=[];for(let n of r){if(!n.isFile()||!n.name.toLowerCase().endsWith(".dmp"))continue;let o=Ar.join(e,n.name);try{let s=Io(o),i=Fo(n.name);t.push({name:n.name,path:o,bytes:s.size,mtimeMs:s.mtimeMs,executableHint:i.executableHint,signal:i.signal,pid:i.pid})}catch{}}return t.sort((n,o)=>o.mtimeMs-n.mtimeMs),t}function de(e={}){if(!(e.forceWsl===void 0?xr():e.forceWsl))return null;let t=e.hostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||ce,n=e.windowsUser??yt(),o=e.warnBelowBytes??Fe("KYNVER_WSL_CRASH_DUMP_WARN_BYTES",Mo),s=e.criticalBelowBytes??Fe("KYNVER_WSL_CRASH_DUMP_CRITICAL_BYTES",To),i=e.warnCount??Fe("KYNVER_WSL_CRASH_DUMP_WARN_COUNT",Uo),a=e.criticalCount??Fe("KYNVER_WSL_CRASH_DUMP_CRITICAL_COUNT",Bo),u=(e.readCorePattern??Lo)(),l=Ko(u),c=null;n&&(c=(e.readWslConfig??jo)(n,t));let d=c?.maxCrashDumpCount??null,m=d===-1,f=Ho({hostMount:t,windowsUser:n,crashDumpDir:e.crashDumpDir});if(!f)return{ok:!0,path:null,windowsUser:n,dumpCount:0,totalBytes:0,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:[],executables:[],corePattern:u,wslCaptureEnabled:l,maxCrashDumpCount:d,dumpsDisabledInWslConfig:m,reason:null,probeError:"windows_user_unresolved"};let p;try{p=(e.listDumps??$o)(f)}catch(A){return{ok:!1,path:f,windowsUser:n,dumpCount:0,totalBytes:0,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:[],executables:[],corePattern:u,wslCaptureEnabled:l,maxCrashDumpCount:d,dumpsDisabledInWslConfig:m,reason:`WSL crash dump probe failed at ${f}: ${A.message}`,probeError:A.message}}let y=p.reduce((A,g)=>A+g.bytes,0),b=p.length,k=[...new Set(p.map(A=>A.executableHint).filter(A=>!!A))],w=y>=s,F=y>=o,T=b>=a,Oe=b>=i,Q=!(w||T||F||Oe),Z=null;if(!Q){let A=w||T?"critical":"warning",g=(y/1024**3).toFixed(1),V=k.length>0?k.join(", "):"unknown";Z=`WSL crash dumps ${A}: ${b} file(s), ${g} GiB at ${f} (executables: ${V}). `+Go({wslCaptureEnabled:l,dumpsDisabledInWslConfig:m})}return{ok:Q,path:f,windowsUser:n,dumpCount:b,totalBytes:y,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:p,executables:k,corePattern:u,wslCaptureEnabled:l,maxCrashDumpCount:d,dumpsDisabledInWslConfig:m,reason:Z,probeError:null}}function Go(e={}){let r=["Recovery:","1) run `kynver wsl-crashes --execute` or scripts/cleanup-wsl-crashes.ps1 to prune old .dmp files;"];return e.dumpsDisabledInWslConfig||r.push("2) add `[wsl2]\\nmaxCrashDumpCount=-1` to %USERPROFILE%/.wslconfig then `wsl --shutdown` to disable future dumps;"),e.wslCaptureEnabled&&r.push("3) investigate crashing executables (node OOM/SIGBUS often follows Windows C: pressure \u2014 see docs/runbooks/wsl-disk-pressure.md);"),r.push("full runbook: docs/runbooks/wsl-disk-pressure.md."),r.join(" ")}var Mo,To,Uo,Bo,Ke=R(()=>{"use strict";wr();Mo=5*1024*1024*1024,To=10*1024*1024*1024,Uo=2,Bo=4});import{statfsSync as Yo}from"node:fs";function je(e={}){let r=e.diskPath?.trim()||"/",t=e.diskFreeWarnBytes??Vo,n=e.diskFreeCriticalBytes??zo,o=e.diskMaxUsedPercent??Jo,s=e.diskHardMaxUsedPercent??qo,i=Yo(r),a=Number(i.bavail)*Number(i.bsize),u=Number(i.blocks)*Number(i.bsize),l=u>0?(u-a)/u*100:100,c=a<t,d=a<n,m=a<t*2,f=m&&l>o,p=m&&l>s,y=!c&&!d&&!f&&!p,b=e.skipWslHostCheck?null:ht(e.wslHost),k=e.skipWslCrashDumpCheck?null:de(e.wslCrashDumps),w=y&&(b?b.ok:!0)&&(k?k.ok:!0),F=null;return w||(F=[d?`free space below critical ${n} bytes`:null,c?`free space below warning ${t} bytes`:null,p?`used percent above hard cap ${s}%`:null,f?`used percent above cap ${o}%`:null,b&&!b.ok?b.reason:null,k&&!k.ok?k.reason:null].filter(Boolean).join("; ")),Xo({ok:w,path:r,freeBytes:a,totalBytes:u,usedPercent:l,warnBelowBytes:t,criticalBelowBytes:n,maxUsedPercent:o,hardMaxUsedPercent:s,reason:F,wslHost:b,wslCrashDumps:k?{ok:k.ok,path:k.path,dumpCount:k.dumpCount,totalBytes:k.totalBytes,executables:k.executables,wslCaptureEnabled:k.wslCaptureEnabled,dumpsDisabledInWslConfig:k.dumpsDisabledInWslConfig,reason:k.reason,probeError:k.probeError}:null})}function Xo(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 Vo,zo,Jo,qo,$e=R(()=>{"use strict";Ke();wr();Vo=30*1024*1024*1024,zo=15*1024*1024*1024,Jo=80,qo=90});import{existsSync as Qo,readdirSync as Zo,statSync as es}from"node:fs";import Er from"node:path";function Ge(){return St()}function Pr(){let{runsDir:e}=Ge();return bt(e)}function Ye(e){return bt(j(e))}function rs(e){try{return es(e).isDirectory()}catch{return!1}}function bt(e){if(!Qo(e))return[];let r=[];for(let t of Zo(e,{withFileTypes:!0})){if(t.name==="runs")continue;let n=Er.join(e,t.name);if(!rs(n))continue;let o=v(Er.join(n,"run.json"),void 0);o?.id&&r.push(o)}return r}function Wr(e){let{runsDir:r}=Ge();at(Er.join(Dr(r,e.id),"run.json"),e)}function Se(e){let{harnessRoot:r}=Ge();return _e(r,e)}function _e(e,r){return Dr(j(e),_(r))}var ee=R(()=>{"use strict";$();S()});import{existsSync as ts,readdirSync as ns}from"node:fs";import os from"node:path";function Or(e){let r=new Set;for(let n of Object.keys(e.workers||{}))r.add(_(n));let t=os.join(Se(e.id),"workers");if(!ts(t))return[...r];for(let n of ns(t,{withFileTypes:!0}))n.isDirectory()&&r.add(_(n.name));return[...r]}var Nr=R(()=>{"use strict";ee();S()});function Ir(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 _t(e){let r=e.trim();if(!r)return null;let t=Ir(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let u=Ir(s[1]??"");u&&n.push(u)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let u=Ir(r.slice(i,a+1));u&&n.push(u)}return n.length>0?n[n.length-1]:null}function Ct(e){let r=e.finalResult??e.final_result;if(r!=null)return typeof r=="string"?_t(r)??(r.trim()||null):r;let t=typeof e.summary=="string"?e.summary.trim():"";if(!t)return null;let n=_t(t);return n||t}var vt=R(()=>{"use strict"});import{existsSync as ss,readFileSync as is}from"node:fs";function xt(e){return e==="complete"}function wt(e){return xt(e.lastHeartbeatPhase)?e.terminalFinalResult!==void 0&&e.terminalFinalResult!==null?e.terminalFinalResult:e.lastHeartbeatSummary?.trim()||"completed":null}function pe(e){let r={heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,terminalFinalResult:null,heartbeatBlocker:null,timestampAnomalies:[],lastBoxResourceSnapshot:null,lastPrEvidence:[]};if(!ss(e))return r;let t=Date.now()+as,n=new Date(t).toISOString(),o=is(e,"utf8").split(`
6
- `).filter(Boolean);for(let s of o){let i=Me(s);if(!i||typeof i!="object"||Array.isArray(i))continue;let a=i;if(r.heartbeatCount++,a.ts){let u=String(a.ts),l=Date.parse(u);Number.isFinite(l)&&l>t?r.timestampAnomalies.push({kind:"future_heartbeat_timestamp",observedAt:u,clampedTo:n}):r.lastHeartbeatAt=u}a.phase!==void 0&&a.phase!==null&&(r.lastHeartbeatPhase=String(a.phase)),a.summary!==void 0&&a.summary!==null&&(r.lastHeartbeatSummary=String(a.summary)),xt(r.lastHeartbeatPhase)&&(r.terminalFinalResult=Ct(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 as,Ve=R(()=>{"use strict";vt();S();as=6e4});function ls(e){return e?(e.split("/").pop()??e).replace(/\.exe$/i,"").toLowerCase():null}function cs(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 ds(e){let r=ls(e[0]);return!!(r&&us.has(r))}function Mr(e){return!e||e.includes("/")||e.includes("*")?!1:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(e)}function Tr(e){if(!e)return!1;let r=e.trim();return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")}function ps(e){if(!e.startsWith("--glob="))return e;let r=e.slice(7);return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")?`--glob=${r}/**`:e}function ms(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;At.has(n)&&(t+=1);continue}r.push(n)}}return r}function fs(e){let r=!1,t=e.map((o,s)=>{let i=ps(o),a=e[s-1];return a&&At.has(a)&&o.startsWith("!")&&!o.includes("/")&&!o.endsWith("/**")&&(i=`${o}/**`),i!==o&&(r=!0),i}),n=ms(t);if(n.length===2){let[o,s]=n;if(Tr(s))return{argv:[t[0]??"rg",o,"-g",`${s}/**`,"."],changed:!0};if(Mr(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 Ur(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=cs(i.trim());if(!a.length||!ds(a))return i;let u=fs(a);return u.changed?(o=!0,u.argv.join(" ")):i});return o?{command:s.join(t),changed:!0}:{command:r,changed:!1}}function Et(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 gs(e){let{pattern:r,target:t}=Et(e);return r?Tr(t)?{kind:"rg_exclude_syntax",pattern:r,target:t}:Mr(t)?{kind:"bad_scope",pattern:r,target:t}:{kind:"not_repo_search",pattern:r,target:t}:{kind:"not_repo_search"}}function hs(e){let{pattern:r,target:t}=Et(e);if(!r)return null;if(Tr(t)){let n=`${t.trim()}/**`;return{command:`rg "${r}" -g '${n}' .`,changed:!0}}return t&&Mr(t)?{command:`rg -g ${t} "${r}" .`,changed:!0}:null}function ks(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 Rs(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 Br(e){let r=e.meta?.trim()||(e.command?Rs(e.command):null)||null;if(r){let t=gs(r),n=ks(t);if(n)return n;let o=hs(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=Ur(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 us,At,Pt=R(()=>{"use strict";us=new Set(["rg","ripgrep","grep"]),At=new Set(["-e","--regexp","-f","--file","-m","--max-count","-A","--after-context","-B","--before-context","-C","--context","-g","--glob","--iglob"])});function Ce(e,r=200){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function _s(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 ve(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Cs(e){let r=e.metadata;if(!ve(r))return null;let t=r.vulnerabilities;if(!ve(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 vs(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 xs(e,r){let t=e.error;if(ve(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?Ce(o.split(`
7
- `).find(Boolean)??o,160):"npm audit failed"}function ws(e){let r=`${e.stdout}
8
- ${e.stderr}`.trim(),t=_s(r);if(!t||!ve(t)){let o=Ce(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(ve(t.error))return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit command failed: ${xs(t,e.stderr)}`};let n=Cs(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:vs(n),audit:n}:{kind:"command_failure",exitCode:e.exitCode,summary:"npm audit failed: JSON response missing vulnerability metadata",parseError:"missing_metadata"}}function As(e){return ys.test(e)}function Es(e){return bs.test(e)}function Ps(e){let r=Br({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&&Ss.test(n)){let i=Ce(n,160);return{kind:"command_failure",exitCode:1,summary:r??`ripgrep failed (exit 1): ${i}`}}let o=Ur(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=Ce(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 Wt(e){let r=e.stdout??"",t=e.stderr??"",n=e.interleavedOutput??"";if(As(e.command)){let i=r.trim()||n.trim()||t.trim();return ws({exitCode:e.exitCode,stdout:i,stderr:t})}if(Es(e.command))return Ps({command:e.command,exitCode:e.exitCode,stdout:r,stderr:t,interleaved:n});let o=Br({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=Ce(n||r||t||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:`command failed (exit ${e.exitCode}): ${s}`}}var ys,bs,Ss,Dt=R(()=>{"use strict";Pt();ys=/\bnpm\s+audit\b/i,bs=/\b(rg|ripgrep)\b/i,Ss=/\b(error|invalid|unknown|panic|not found)\b/i});import{existsSync as Ws,readFileSync as Ds}from"node:fs";function Os(e){let r=e.timestamp_ms;return e.timestamp||e.ts||(r?new Date(r).toISOString():void 0)}function Ns(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 Is(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 Ms(e){if(e.type!=="tool_call"||e.subtype!=="completed")return null;let t=(e.tool_call&&typeof e.tool_call=="object"&&!Array.isArray(e.tool_call)?e.tool_call:null)?.shellToolCall;if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,o=n.args,s=o&&typeof o=="object"&&!Array.isArray(o)&&typeof o.command=="string"?String(o.command):"",i=n.result;if(!i||typeof i!="object"||Array.isArray(i))return null;let a=i.success??i.failure;if(!a||typeof a!="object"||Array.isArray(a))return null;let u=a,l=typeof u.exitCode=="number"?u.exitCode:0;return{command:s,exitCode:l,stdout:typeof u.stdout=="string"?u.stdout:"",stderr:typeof u.stderr=="string"?u.stderr:"",interleaved:typeof u.interleavedOutput=="string"?u.interleavedOutput:""}}function Ts(e,r){r.kind==="success"||r.kind==="search_no_matches"||(e.lastShellOutcome=r)}function Ot(e){let r={firstEventAt:null,lastEventAt:null,currentTool:null,finalResult:null,error:null,lastShellOutcome:null};if(!Ws(e))return r;let t=Ds(e,"utf8").split(`
9
- `).filter(Boolean);for(let n of t){let o=Me(n);if(!o)continue;let s=Os(o);if(s&&(r.firstEventAt||=s,r.lastEventAt=s),o.type==="stream_event"&&o.event&&typeof o.event=="object"&&o.event.type==="content_block_start"){let a=o.event.content_block;a?.type==="tool_use"&&(r.currentTool=String(a.name||"tool"))}if(o.type==="assistant"&&o.message&&typeof o.message=="object"){let a=o.message.content;if(Array.isArray(a)){let u=a.find(l=>l?.type==="tool_use");u&&(r.currentTool=String(u.name||r.currentTool))}}if(o.type==="tool_call"&&o.subtype==="started"){let a=o.tool_call&&typeof o.tool_call=="object"&&!Array.isArray(o.tool_call)?o.tool_call:void 0,u=Ns(a);u&&(r.currentTool=u)}let i=Ms(o);i&&Ts(r,Wt({command:i.command,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr,interleavedOutput:i.interleaved})),o.type==="result"&&Is(r,o)}return r}var Nt=R(()=>{"use strict";Dt();S()});function Bs(e,r=240){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function It(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}: ${Bs(r)}`};return null}var Us,Mt=R(()=>{"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 Tt(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function Hs(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 Fs(e){return!e?.checked||e.headIsAncestorOfBase!==!1?null:Tt(e.head)}function Ls(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 Ut(e){if(e.alive||Hs(e.finalResult))return null;let r=(e.changedFiles??[]).filter(i=>i.trim()).length,t=Tt(e.headCommit)??Fs(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:Ls(s,r,t)}}var Bt=R(()=>{"use strict"});function xe(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function Ks(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 js(e){if(xe(e.headCommit)||xe(e.prUrl)||xe(e.artifactBundlePath)||xe(e.patchPath))return!0;let r=e.gitAncestry;return!!(r?.checked&&r.headIsAncestorOfBase===!1&&xe(r.head))}function me(e){return Ks(e.finalResult)?e.changedFiles.length===0?{blocked:!1}:js(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 Ht(e){if(e.blocked)return e.detail??e.reason??"dirty_worktree_no_pr"}var ze=R(()=>{"use strict"});function Hr(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 Ft(e){let r=e.targetPrReconciliation??e.target_pr_reconciliation??e.targetPrs??e.target_prs;return Array.isArray(r)?r.length:0}function Je(e){let r=e.trim();if(!r)return null;let t=Hr(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let c=Hr(s[1]??"");c&&n.push(c)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let c=Hr(r.slice(i,a+1));c&&n.push(c)}if(n.length===0)return null;let u=n[n.length-1],l=Ft(u);for(let c of n){let d=Ft(c);d>l&&(u=c,l=d)}return u}var Fr=R(()=>{"use strict"});function fe(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function $s(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"?Object.keys(e).length>0:!0}function re(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`https://github.com/${r[1]}/pull/${r[2]}`:fe(e)}function qe(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function Lt(e){let r=null;if(typeof e=="string"){let o=Je(e);o&&(r=o)}else e&&typeof e=="object"&&!Array.isArray(e)&&(r=e);if(!r)return[];let t=r.targetPrReconciliation??r.target_pr_reconciliation;if(!Array.isArray(t))return[];let n=[];for(let o of t){if(!o||typeof o!="object"||Array.isArray(o))continue;let s=o,i=re(String(s.prUrl??s.pr_url??"")),a=fe(s.outcome);!i||a!=="merged"&&a!=="skipped"&&a!=="blocked"||n.push({prUrl:i,outcome:a,mergeCommit:fe(s.mergeCommit??s.merge_commit),reason:fe(s.reason)})}return n}function Kt(e,r){let t=[],n=re(fe(e.prUrl)??"");if(n&&t.push(n),r&&typeof r=="object"&&!Array.isArray(r)){let o=r,s=re(String(o.prUrl??o.pr_url??""));s&&t.push(s)}return[...new Set(t)]}function jt(e){let{contract:r,snapshot:t}=e,n=e.finalResult??t.finalResult;if(!r.landingOnly&&r.targetPrUrls.length===0&&!r.repairEnforceOriginalPr)return{blocked:!1};if(!$s(n))return(r.requiresTargetPrReconciliation??(r.landingOnly||!!r.repairEnforceOriginalPr||r.targetPrUrls.length>0))&&r.targetPrUrls.length>0?{blocked:!0,reason:"missing_target_pr_reconciliation",detail:`Final result required to reconcile target PR(s): ${r.targetPrUrls.join(", ")}`}:{blocked:!1};if(!(r.requiresTargetPrReconciliation??(r.landingOnly||!!r.repairEnforceOriginalPr||r.targetPrUrls.length>0))&&!r.repairEnforceOriginalPr)return{blocked:!1};let s=r.repairEnforceOriginalPr?re(fe(r.targetPrUrl)??"")??(r.targetPrUrls.length===1?re(r.targetPrUrls[0]):null):null;if(s){let d=Kt(t,n);if(!(n&&typeof n=="object"&&!Array.isArray(n)&&n.supersedesOriginalTargetPr===!0)){for(let y of d)if(y!==s)return{blocked:!0,reason:"duplicate_repair_pr",detail:`Repair worker opened or attached PR ${y} instead of canonical target ${s}`}}let p=Lt(n).find(y=>y.prUrl===s);if(!p||p.outcome!=="merged"&&!(p.reason?.trim()&&(p.outcome==="skipped"||p.outcome==="blocked")))return{blocked:!0,reason:"missing_repair_target_reconciliation",detail:`Repair worker must reconcile target PR ${s}`}}let i=Lt(n),a=new Map(i.map(d=>[qe(d.prUrl),d])),u=new Set(r.targetPrUrls.map(d=>qe(re(d)??d)).filter(Boolean)),l=Kt(t,n);if(r.landingOnly)for(let d of l){if(u.size>0&&!u.has(qe(d)))return{blocked:!0,reason:"unrelated_implementation_pr",detail:`Landing-only worker attached unrelated PR ${d}`};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 c=[];for(let d of r.targetPrUrls){let m=qe(re(d)??d),f=a.get(m);if(!f){c.push(m);continue}f.outcome!=="merged"&&!f.reason?.trim()&&c.push(m)}return c.length>0?{blocked:!0,reason:c.every(d=>a.has(d))?"incomplete_target_pr_landing":"missing_target_pr_reconciliation",detail:`Target PR reconciliation incomplete: ${c.join(", ")}`}:{blocked:!1}}function $t(e){if(e.blocked)return e.detail??e.reason}var Gt=R(()=>{"use strict";Fr()});function Vs(e){let r=Date.now();if(e.completionBlocker&&!Yt(e.completionBlocker))return{state:"blocked",reason:e.completionBlocker};if(e.finalResult){if(e.localOnly&&Js(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=me(o);if(s.blocked){let i=Ht(s);return{state:"needs_attention",reason:s.reason?`landing blocked (${s.reason}): ${i}`:`landing blocked: ${i}`}}if(e.landingContract){let i=jt({contract:e.landingContract,snapshot:o,finalResult:e.finalResult}),a=$t(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(zs(e))return{state:"done",reason:"empty abandoned worker record"};let o=It(e.error);if(o)return{state:"blocked",reason:o.reason};let s=Ut({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>Gs)return{state:"needs_attention",reason:`no first stream event ${Sr(t)}s after start`};let n=e.lastActivityAt?Date.parse(e.lastActivityAt):NaN;return Number.isFinite(n)&&r-n>Ys?{state:"stale",reason:`no log/event/heartbeat activity for ${Sr(n)}s`}:{state:"ok",reason:"recent activity"}}function Yt(e){let r=e?.trim();return r?/completion acknowledged but board not advanced/i.test(r)&&/task already terminal/i.test(r):!1}function zs(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 Js(e){let r=null;if(typeof e=="string"?r=Je(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 qs(e,r,t){let n=e.completionSnapshot?.finalResult;return e.completionAckSource==="local-pr-merged-reconcile"&&n!==void 0&&n!==null?n:r||(n??wt(t))}function we(e,r={}){let t=Ot(e.stdoutPath),n=pe(e.heartbeatPath),o=typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim().length>0,s=qs(e,t.finalResult,n),i=o?!1:z(e.pid),a=Te(e.stdoutPath),u=Te(e.stderrPath),l=Te(e.heartbeatPath),c=ye(e.worktreePath),d=Be(e.worktreePath,{base:r.base,baseCommit:r.baseCommit}),m=lt([t.lastEventAt,n.lastHeartbeatAt,Ue(e.stdoutPath),Ue(e.stderrPath),Ue(e.heartbeatPath)]),f=t.error||!i&&!s&&ut(e.stderrPath,10).trim()||void 0,p=typeof e.completionBlocker=="string"&&e.completionBlocker.trim()?e.completionBlocker.trim():null,y=Yt(p)?null:p,b=e.repairTargetPrUrl?{landingOnly:!1,targetPrUrls:[e.repairTargetPrUrl],targetPrUrl:e.repairTargetPrUrl,repairEnforceOriginalPr:!0}:null,k=Vs({alive:i,finalResult:s,firstEventAt:t.firstEventAt,stdoutBytes:a,stderrBytes:u,heartbeatBytes:l,lastActivityAt:m,heartbeatBlocker:n.heartbeatBlocker,startedAt:e.startedAt,error:f,changedFiles:c,gitAncestry:d,completionBlocker:y,landingContract:b,prUrl:e.repairTargetPrUrl??e.taskPrUrl??null,localOnly:e.localOnly===!0,taskId:e.taskId??null,agentOsId:e.agentOsId??null,reconcileReason:e.reconcileReason??null}),w=y||k.state==="blocked"?"blocked":o||k.state==="done"?"done":s?"exited":i?"running":"exited";return{runId:e.runId,worker:e.name,pid:e.pid,alive:i,status:w,attention:k,branch:e.branch,worktreePath:e.worktreePath,ownedPaths:e.ownedPaths,stdoutBytes:a,stderrBytes:u,heartbeatBytes:l,firstEventAt:t.firstEventAt,lastEventAt:t.lastEventAt,lastActivityAt:m,currentTool:o?null:t.currentTool,heartbeatCount:n.heartbeatCount,lastHeartbeatAt:n.lastHeartbeatAt,lastHeartbeatPhase:n.lastHeartbeatPhase,lastHeartbeatSummary:n.lastHeartbeatSummary,heartbeatBlocker:n.heartbeatBlocker,timestampAnomalies:n.timestampAnomalies,finalResult:s,error:f,changedFiles:c,gitAncestry:d,instructionPolicyFingerprint:e.instructionPolicyFingerprint??null,instructionPolicyEvidence:e.instructionPolicyEvidence??null,model:e.model??e.orchestrationAudit?.model??null,provider:e.orchestrationAudit?.provider??null,boxKind:e.boxKind??null,boxId:e.boxId??null,runtimeId:e.runtimeId??null,personaSlug:e.personaSlug??null,dispatched:e.dispatched??null,localOnly:e.localOnly??null}}function te(e){return!!(e.finalResult||e.alive===!1||e.status==="exited"||e.status==="done")}function Vt(e){return e.finalResult?e.attention.state==="needs_attention"||e.attention.state==="blocked":!1}var Gs,Ys,ne=R(()=>{"use strict";Ve();Nt();Mt();Bt();K();ze();Gt();Fr();S();Gs=18e4,Ys=6e5});var zt=R(()=>{"use strict";ne()});var Xs,Qs,Jt=R(()=>{"use strict";gt();Qe();vr();Lr();$e();ee();Nr();zt();S();Xs=500*1024*1024,Qs=4*1024*1024*1024});var Lr=R(()=>{"use strict";Jt()});import{existsSync as ni,mkdirSync as dl,readFileSync as oi,writeFileSync as pl}from"node:fs";import{homedir as si,totalmem as fl}from"node:os";import Kr from"node:path";function Xe(){if(!ni(qt))return{};try{return JSON.parse(oi(qt,"utf8"))}catch{return{}}}var Xt,qt,_l,Cl,vl,Qe=R(()=>{"use strict";Cr();be();S();vr();Lr();$e();Xt=Kr.join(si(),".kynver"),qt=Kr.join(Xt,"config.json"),_l=Kr.join(Xt,"credentials");Cl=500*1024*1024,vl=4*1024*1024*1024});import{existsSync as Qt}from"node:fs";import{homedir as en}from"node:os";import J from"node:path";function P(e){let r=J.resolve(He(e.trim()));for(;ii.has(J.basename(r));)r=J.dirname(r);return r}function q(){let e=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(e)return P(e);let r=Xe().harnessRoot?.trim();if(r)return P(r);let t=J.join(en(),".kynver","harness");return Qt(t)?t:Qt(Zt)?Zt:t}function j(e){return J.join(P(e),"runs")}function ge(e){return J.join(P(e),"worktrees")}function St(){let e=q();return{harnessRoot:e,runsDir:j(e),worktreesDir:ge(e)}}function Dr(e,r){return J.join(e,_(r))}var Zt,ii,$=R(()=>{"use strict";Qe();be();S();Zt=J.join(en(),".openclaw","harness"),ii=new Set(["runs","worktrees"])});$();import N from"node:path";ze();import tr from"node:path";K();ne();var jr=[".next",".turbo","dist","build",".cache","node_modules/.cache"];function rn(e){let r=e.replace(/\\/g,"/").replace(/\/+$/,"");if(r==="node_modules"||r.startsWith("node_modules/"))return!0;for(let t of jr)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!rn(n)})}function oe(e){if(typeof e=="string")return e.match(/https:\/\/github\.com\/[^\s]+\/pull\/\d+/i)?.[0]??null;if(e&&typeof e=="object"){let r=e;for(let t of["prUrl","pr_url","pullRequestUrl"]){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}}return null}function Ae(e){let r=e.gitAncestry?.relation;return r==="merged"||r==="synced"?W(e.changedFiles).length>0:!!(oe(e.finalResult)||r==="ahead"||r==="diverged"||e.changedFiles.length>0&&e.finalResult)}S();function Ee(e){return e.status||(e.status=we(e.worker,{base:e.run.base,baseCommit:e.run.baseCommit})),e.status}function $r(e,r){if(e.status)return W(e.status.changedFiles).length>0;let t=r?r.porcelain(e.worktreePath):ye(e.worktreePath);return W(t).length>0}function ai(e){let r=e.worker.completionSnapshot?.finalResult;return r??(e.worker.taskPrUrl?{prUrl:e.worker.taskPrUrl}:null)}function Gr(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=ai(e);if(o&&!z(t.pid)){let i=r?.gitStatusCache?r.gitStatusCache.porcelain(e.worktreePath):ye(e.worktreePath),a=e.run.baseCommit?.trim()||e.run.base?.trim()||"origin/main",l=r?.gitRevCache?.countAheadOfMain(e.worktreePath,a)===0?{checked:!0,base:a,relation:"synced"}:Be(e.worktreePath,{base:e.run.base,baseCommit:e.run.baseCommit}),c={runId:e.runId,worker:e.workerName,pid:t.pid,alive:!1,status:t.status??(n?"done":"exited"),attention:{state:n?"done":"stale"},branch:t.branch,worktreePath:e.worktreePath,ownedPaths:t.ownedPaths,stdoutBytes:0,stderrBytes:0,heartbeatBytes:0,firstEventAt:null,lastEventAt:null,lastActivityAt:t.completionReportedAt??null,currentTool:null,heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,heartbeatBlocker:null,changedFiles:i,gitAncestry:l,finalResult:s,completionBlocker:typeof t.completionBlocker=="string"&&t.completionBlocker.trim()||null,prUrl:t.repairTargetPrUrl??t.taskPrUrl??oe(s)};return e.status=c,c}return Ee(e)}ne();ee();Nr();ne();S();import ui from"node:path";var li=new Set(["running","dispatching","pending","queued","needs_attention"]),se=new Set(["completed","failed","cancelled","done"]);function ie(e){let r=Or(e);if(r.length===0)return"failed";let t=!1,n=!1,o=!1,s=!1;for(let i of r){let a=v(ui.join(Se(e.id),"workers",_(i),"worker.json"),void 0);if(!a)continue;let u=we(a,{base:e.base,baseCommit:e.baseCommit});if(u.alive&&!u.finalResult){t=!0;break}typeof a.completionBlocker=="string"&&a.completionBlocker&&(o=!0),Vt(u)&&(s=!0),u.finalResult&&u.attention.state==="done"&&(n=!0)}return t||o||s?null:n?"completed":"failed"}function tn(){let e=[];for(let r of Pr()){if(!li.has(r.status))continue;let t=ie(r);if(!t||t===r.status)continue;let n=r.status;r.status=t,Wr(r),e.push({runId:r.id,from:n,to:t})}return e}ne();Ve();import{existsSync as Ze,mkdirSync as lc,readdirSync as sn,renameSync as cc,statSync as ci}from"node:fs";import ae from"node:path";Qe();Cr();be();Ve();$();ee();$();S();import X from"node:path";var oc=`${X.sep}runs${X.sep}runs${X.sep}`;function nn(e){return{workerJsonPath:X.join(e,"worker.json"),stdoutPath:X.join(e,"stdout.jsonl"),stderrPath:X.join(e,"stderr.log"),heartbeatPath:X.join(e,"heartbeat.jsonl"),lastStatusPath:X.join(e,"last-status.json")}}S();var Pe=900*1e3,Rc=3600*1e3;function an(e,r){let t=ae.resolve(e),n=ae.resolve(j(r)),o=ae.relative(n,t);return o!==".."&&!o.startsWith("..")&&!ae.isAbsolute(o)}function di(e){if(!Ze(e))return[];try{return sn(e,{withFileTypes:!0}).filter(r=>r.isDirectory()&&r.name!=="runs").map(r=>r.name)}catch{return[]}}function pi(e){let r=ae.join(e,"workers");if(!Ze(r))return[];try{return sn(r,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}}function on(e,r,t){if(!Ze(e))return!1;try{let n=r-ci(e).mtimeMs;return Number.isFinite(n)&&n>=0&&n<t}catch{return!1}}function mi(e,r=Date.now(),t=Pe){if(!Ze(e))return!1;let n=nn(e),o=v(n.workerJsonPath,void 0);if(o?.status==="running"&&z(o.pid))return!0;let s=pe(n.heartbeatPath);if(s.lastHeartbeatAt){let i=r-Date.parse(s.lastHeartbeatAt);if(Number.isFinite(i)&&i>=0&&i<t)return!0}return!!(on(n.stdoutPath,r,t)||on(n.heartbeatPath,r,t))}function fi(e,r=Date.now(),t=Pe){for(let n of pi(e))if(mi(ae.join(e,"workers",n),r,t))return!0;return!1}function un(e,r=Date.now()){let t=new Set,n=j(e);for(let o of di(n)){let s=ae.join(n,o);fi(s,r)&&t.add(`${e}\0${o}`)}return t}S();function Yr(e,r=Date.now(),t=Pe){let n=pe(e.heartbeatPath);if(!n.lastHeartbeatAt)return!1;let o=r-Date.parse(n.lastHeartbeatAt);return Number.isFinite(o)&&o>=0&&o<t}function er(e,r=Date.now(),t=Pe){return z(e.pid)?!0:Yr(e,r,t)}function gi(e,r){return r?r.runTerminalCache.derive(e.run):ie(e.run)}function G(e,r=Date.now()){return er(e.worker,r)}function Vr(e,r){return se.has(e.run.status)?!1:gi(e,r)!==null}function ln(e,r,t=Date.now()){if(G(e,t))return!0;if(se.has(e.run.status)||Vr(e,r))return!1;let n=Ee(e);return te(n)?!1:!!G(e,t)}ze();ne();function cn(e,r){if(!(typeof e.worker.completionBlocker=="string"?e.worker.completionBlocker.trim():""))return!1;if(G(e))return!0;let n=r??Ee(e);return!!(!te(n)||Ae(n)||W(n.changedFiles).length>0||me({finalResult:n.finalResult,changedFiles:n.changedFiles,gitAncestry:n.gitAncestry,prUrl:oe(n.finalResult)}).blocked)}K();S();import{existsSync as pn,mkdirSync as hi,writeFileSync as dn}from"node:fs";import rr from"node:path";function mn(e,r,t){return rr.join(e,"salvage",_(r),_(t))}function fn(e){return pn(rr.join(mn(e.harnessRoot,e.runId,e.workerName),"evidence.json"))}function gn(e){let r=mn(e.harnessRoot,e.indexed.runId,e.indexed.workerName);hi(r,{recursive:!0});let t=rr.join(r,"salvage.patch"),n=!1;if(pn(e.indexed.worktreePath)){let s=x(e.indexed.worktreePath,["diff","HEAD"]),i=x(e.indexed.worktreePath,["diff","--cached"]),a=[s.stdout,i.stdout].filter(u=>u.trim()).join(`
10
- `);a.trim()&&(dn(t,a.endsWith(`
4
+ `):""}function z(e){if(!e)return!1;try{return process.kill(e,0),!0}catch{return!1}}function ct(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 Sr(e){return Math.max(0,Math.round((Date.now()-e)/1e3))}var S=g(()=>{"use strict"});var Fo,$a,dt=g(()=>{"use strict";Fo=["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"],$a=new Set(Fo)});import{spawnSync as mt}from"node:child_process";function Re(e,r,t={}){let n=mt("git",r,br({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);Rr(o)}return n.stdout||""}function be(e){return Re(e,["status","--short"],{allowFailure:!0}).split(`
5
+ `).map(r=>r.trim()).filter(Boolean)}function C(e,r){try{let t=mt("git",r,br({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 pt(e,r,t){let n=C(e,["merge-base","--is-ancestor",r,t]);return n.status===0?{isAncestor:!0,error:null}:n.status===1?{isAncestor:!1,error:null}:{isAncestor:null,error:n.error||n.stderr||n.stdout||`git exited ${n.status}`}}function Fe(e,r="origin/main"){let t=typeof r=="string"?{base:r}:r,n=t.baseCommit?.trim()||t.base?.trim()||"origin/main",o=t.baseCommit?.trim()||null;if(!e)return vr(n,"missing worktree path");let s=C(e,["rev-parse","HEAD"]);if(s.status!==0)return vr(n,s.error||s.stderr||s.stdout||"failed to resolve HEAD");let i;if(o)i=o;else{let m=C(e,["rev-parse",n]);if(m.status!==0)return vr(n,m.error||m.stderr||m.stdout||`failed to resolve ${n}`,s.stdout.trim());i=m.stdout.trim()}let a=s.stdout.trim();if(a===i)return{checked:!0,base:n,head:a,baseHead:i,baseIsAncestorOfHead:!0,headIsAncestorOfBase:!0,relation:"synced"};let u=pt(e,i,a),l=pt(e,a,i),c=u.error||l.error||void 0;if(u.isAncestor==null||l.isAncestor==null)return{checked:!1,base:n,head:a,baseHead:i,baseIsAncestorOfHead:u.isAncestor,headIsAncestorOfBase:l.isAncestor,relation:"unknown",...c?{error:c}:{}};let d=u.isAncestor?"ahead":l.isAncestor?"merged":"diverged";return{checked:!0,base:n,head:a,baseHead:i,baseIsAncestorOfHead:u.isAncestor,headIsAncestorOfBase:l.isAncestor,relation:d,...c?{error:c}:{}}}function vr(e,r,t=null){return{checked:!1,base:e,head:t,baseHead:null,baseIsAncestorOfHead:null,headIsAncestorOfBase:null,relation:"unknown",error:r}}var L=g(()=>{"use strict";S();dt()});import{homedir as ft}from"node:os";import gt from"node:path";function Ho(e){return e==="~"?ft():e.startsWith("~/")||e.startsWith("~\\")?gt.join(ft(),e.slice(2)):e}function He(e){return gt.resolve(Ho(e))}var ce=g(()=>{"use strict"});var _r=g(()=>{"use strict";L();ce()});var xr=g(()=>{"use strict"});var Cr=g(()=>{"use strict"});var ht=g(()=>{"use strict"});import{existsSync as Ko,readFileSync as Lo,statfsSync as jo}from"node:fs";function wr(){if(process.platform!=="linux")return!1;for(let e of["/proc/sys/kernel/osrelease","/proc/version"])try{if(!Ko(e))continue;let r=Lo(e,"utf8");if(/microsoft|wsl/i.test(r))return!0}catch{}return!1}function kt(e={}){if(!(e.forceWsl===void 0?wr():e.forceWsl))return null;let t=e.wslHostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||de,n=e.wslHostFreeWarnBytes??$o,o=e.wslHostFreeCriticalBytes??Go,s=e.statfs??jo,i;try{i=s(t)}catch(R){return{ok:!1,path:t,freeBytes:0,totalBytes:0,usedPercent:100,warnBelowBytes:n,criticalBelowBytes:o,reason:`Windows host disk probe failed at ${t}: ${R.message}`,probeError:R.message}}let a=Number(i.bavail)*Number(i.bsize),u=Number(i.blocks)*Number(i.bsize),l=u>0?(u-a)/u*100:100,c=a<n,d=a<o,m=!c&&!d,f=(a/(1024*1024*1024)).toFixed(1),p=null;return m||(p=`Windows host disk ${t} at ${d?"critical":"warning"}: ${f} GiB free (<${(d?o:n)/1024/1024/1024} GiB); WSL VHDX cannot grow safely. ${Yo()}`),{ok:m,path:t,freeBytes:a,totalBytes:u,usedPercent:l,warnBelowBytes:n,criticalBelowBytes:o,reason:p,probeError:null}}function Yo(){return"Recovery: 1) free Windows C: (empty Recycle Bin / Storage Sense / clear %TEMP% and %LOCALAPPDATA%\\Temp\\wsl-crashes); 2) shut down WSL (`wsl --shutdown`) then compact the VHDX (`Optimize-VHD` or `diskpart compact vdisk`); 3) clear local node_modules / .next / harness worktrees before restarting workers; 4) disable recurring dumps via `%USERPROFILE%/.wslconfig` (`maxCrashDumpCount=-1`) or `kynver wsl-crashes --execute`. Full runbook: docs/runbooks/wsl-disk-pressure.md."}var $o,Go,de,Er=g(()=>{"use strict";$o=25*1024*1024*1024,Go=12*1024*1024*1024,de="/mnt/c"});import{execFileSync as yt}from"node:child_process";import{existsSync as Le,readFileSync as Rt,readdirSync as Vo,statSync as zo}from"node:fs";import Ar from"node:path";function Ke(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function bt(){let e=process.env.KYNVER_WSL_WIN_USER?.trim();if(e)return e;try{let n=yt("cmd.exe",["/c","echo","%USERNAME%"],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"]}).trim();if(n&&n!=="%USERNAME%"&&!n.includes("%"))return n}catch{}let r=process.env.USER?.trim()||process.env.LOGNAME?.trim(),t=process.env.KYNVER_WSL_HOST_MOUNT?.trim()||de;return r&&Le(Ar.join(t,"Users",r))?r:null}function Zo(e={}){let r=e.crashDumpDir?.trim()||process.env.KYNVER_WSL_CRASH_DUMP_DIR?.trim();if(r)return r;let t=e.hostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||de,n=e.windowsUser??bt();return n?`${t.replace(/\\/g,"/").replace(/\/$/,"")}/Users/${n}/AppData/Local/Temp/wsl-crashes`:null}function es(e){let r=/^wsl-crash-\d+-(\d+)-(.+)-(\d+)\.dmp$/i.exec(e);if(!r)return{executableHint:null,signal:null,pid:null};let t=Number(r[1]),n=r[2]??"",o=Number(r[3]),s=n.split("_").filter(Boolean);return{executableHint:s.length>0?s[s.length-1]:null,signal:Number.isFinite(o)?o:null,pid:Number.isFinite(t)?t:null}}function rs(){try{if(Le("/proc/sys/kernel/core_pattern"))return Rt("/proc/sys/kernel/core_pattern","utf8").trim()}catch{}try{return yt("sysctl",["-n","kernel.core_pattern"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function ts(e){return!!(e&&/wsl-capture-crash/i.test(e))}function ns(e,r=de){let t=Ar.join(r,"Users",e,".wslconfig");if(!Le(t))return{maxCrashDumpCount:null,crashDumpFolder:null};let n;try{n=Rt(t,"utf8")}catch{return null}let o=null,s=null;for(let i of n.split(/\r?\n/)){let a=i.replace(/#.*$/,"").trim();if(!a||a.startsWith("["))continue;let u=a.indexOf("=");if(u<0)continue;let l=a.slice(0,u).trim().toLowerCase(),c=a.slice(u+1).trim();if(l==="maxcrashdumpcount"){let d=Number(c);o=Number.isFinite(d)?d:null}else l==="crashdumpfolder"&&(s=c.replace(/^["']|["']$/g,"")||null)}return{maxCrashDumpCount:o,crashDumpFolder:s}}function os(e){if(!Le(e))return[];let r=Vo(e,{withFileTypes:!0}),t=[];for(let n of r){if(!n.isFile()||!n.name.toLowerCase().endsWith(".dmp"))continue;let o=Ar.join(e,n.name);try{let s=zo(o),i=es(n.name);t.push({name:n.name,path:o,bytes:s.size,mtimeMs:s.mtimeMs,executableHint:i.executableHint,signal:i.signal,pid:i.pid})}catch{}}return t.sort((n,o)=>o.mtimeMs-n.mtimeMs),t}function pe(e={}){if(!(e.forceWsl===void 0?wr():e.forceWsl))return null;let t=e.hostMount?.trim()||process.env.KYNVER_WSL_HOST_MOUNT?.trim()||de,n=e.windowsUser??bt(),o=e.warnBelowBytes??Ke("KYNVER_WSL_CRASH_DUMP_WARN_BYTES",Jo),s=e.criticalBelowBytes??Ke("KYNVER_WSL_CRASH_DUMP_CRITICAL_BYTES",Xo),i=e.warnCount??Ke("KYNVER_WSL_CRASH_DUMP_WARN_COUNT",qo),a=e.criticalCount??Ke("KYNVER_WSL_CRASH_DUMP_CRITICAL_COUNT",Qo),u=(e.readCorePattern??rs)(),l=ts(u),c=null;n&&(c=(e.readWslConfig??ns)(n,t));let d=c?.maxCrashDumpCount??null,m=d===-1,f=Zo({hostMount:t,windowsUser:n,crashDumpDir:e.crashDumpDir});if(!f)return{ok:!0,path:null,windowsUser:n,dumpCount:0,totalBytes:0,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:[],executables:[],corePattern:u,wslCaptureEnabled:l,maxCrashDumpCount:d,dumpsDisabledInWslConfig:m,reason:null,probeError:"windows_user_unresolved"};let p;try{p=(e.listDumps??os)(f)}catch(E){return{ok:!1,path:f,windowsUser:n,dumpCount:0,totalBytes:0,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:[],executables:[],corePattern:u,wslCaptureEnabled:l,maxCrashDumpCount:d,dumpsDisabledInWslConfig:m,reason:`WSL crash dump probe failed at ${f}: ${E.message}`,probeError:E.message}}let R=p.reduce((E,h)=>E+h.bytes,0),b=p.length,y=[...new Set(p.map(E=>E.executableHint).filter(E=>!!E))],w=R>=s,H=R>=o,U=b>=a,Me=b>=i,Q=!(w||U||H||Me),Z=null;if(!Q){let E=w||U?"critical":"warning",h=(R/1024**3).toFixed(1),V=y.length>0?y.join(", "):"unknown";Z=`WSL crash dumps ${E}: ${b} file(s), ${h} GiB at ${f} (executables: ${V}). `+ss({wslCaptureEnabled:l,dumpsDisabledInWslConfig:m})}return{ok:Q,path:f,windowsUser:n,dumpCount:b,totalBytes:R,warnBelowBytes:o,criticalBelowBytes:s,warnCount:i,criticalCount:a,dumps:p,executables:y,corePattern:u,wslCaptureEnabled:l,maxCrashDumpCount:d,dumpsDisabledInWslConfig:m,reason:Z,probeError:null}}function ss(e={}){let r=["Recovery:","1) run `kynver wsl-crashes --execute` or scripts/cleanup-wsl-crashes.ps1 to prune old .dmp files;"];return e.dumpsDisabledInWslConfig||r.push("2) add `[wsl2]\\nmaxCrashDumpCount=-1` to %USERPROFILE%/.wslconfig then `wsl --shutdown` to disable future dumps;"),e.wslCaptureEnabled&&r.push("3) investigate crashing executables (node OOM/SIGBUS often follows Windows C: pressure \u2014 see docs/runbooks/wsl-disk-pressure.md);"),r.push("full runbook: docs/runbooks/wsl-disk-pressure.md."),r.join(" ")}var Jo,Xo,qo,Qo,je=g(()=>{"use strict";Er();Jo=5*1024*1024*1024,Xo=10*1024*1024*1024,qo=2,Qo=4});import{statfsSync as is}from"node:fs";function $e(e={}){let r=e.diskPath?.trim()||"/",t=e.diskFreeWarnBytes??as,n=e.diskFreeCriticalBytes??us,o=e.diskMaxUsedPercent??ls,s=e.diskHardMaxUsedPercent??cs,i=is(r),a=Number(i.bavail)*Number(i.bsize),u=Number(i.blocks)*Number(i.bsize),l=u>0?(u-a)/u*100:100,c=a<t,d=a<n,m=a<t*2,f=m&&l>o,p=m&&l>s,R=!c&&!d&&!f&&!p,b=e.skipWslHostCheck?null:kt(e.wslHost),y=e.skipWslCrashDumpCheck?null:pe(e.wslCrashDumps),w=R&&(b?b.ok:!0)&&(y?y.ok:!0),H=null;return w||(H=[d?`free space below critical ${n} bytes`:null,c?`free space below warning ${t} bytes`:null,p?`used percent above hard cap ${s}%`:null,f?`used percent above cap ${o}%`:null,b&&!b.ok?b.reason:null,y&&!y.ok?y.reason:null].filter(Boolean).join("; ")),ds({ok:w,path:r,freeBytes:a,totalBytes:u,usedPercent:l,warnBelowBytes:t,criticalBelowBytes:n,maxUsedPercent:o,hardMaxUsedPercent:s,reason:H,wslHost:b,wslCrashDumps:y?{ok:y.ok,path:y.path,dumpCount:y.dumpCount,totalBytes:y.totalBytes,executables:y.executables,wslCaptureEnabled:y.wslCaptureEnabled,dumpsDisabledInWslConfig:y.dumpsDisabledInWslConfig,reason:y.reason,probeError:y.probeError}:null})}function ds(e){let r=process.env.KYNVER_DISPATCH_DISK_GATE_FORCE?.trim().toLowerCase();return r?r==="ok"||r==="open"||r==="none"?e.ok?e:{...e,ok:!0,reason:`disk gate forced open by KYNVER_DISPATCH_DISK_GATE_FORCE (suppressed: ${e.reason??"no reason"})`}:r==="block"||r==="pressured"?{...e,ok:!1,reason:`disk gate forced closed by KYNVER_DISPATCH_DISK_GATE_FORCE${e.reason?` (underlying: ${e.reason})`:""}`}:e:e}var as,us,ls,cs,Ge=g(()=>{"use strict";je();Er();as=30*1024*1024*1024,us=15*1024*1024*1024,ls=80,cs=90});import{existsSync as ps,readdirSync as ms,statSync as fs}from"node:fs";import Pr from"node:path";function Ye(){return vt()}function Wr(){let{runsDir:e}=Ye();return St(e)}function Ve(e){return St(j(e))}function gs(e){try{return fs(e).isDirectory()}catch{return!1}}function St(e){if(!ps(e))return[];let r=[];for(let t of ms(e,{withFileTypes:!0})){if(t.name==="runs")continue;let n=Pr.join(e,t.name);if(!gs(n))continue;let o=x(Pr.join(n,"run.json"),void 0);o?.id&&r.push(o)}return r}function Dr(e){let{runsDir:r}=Ye();ut(Pr.join(Or(r,e.id),"run.json"),e)}function Se(e){let{harnessRoot:r}=Ye();return ve(r,e)}function ve(e,r){return Or(j(e),v(r))}var ee=g(()=>{"use strict";$();S()});import{existsSync as hs,readdirSync as ks}from"node:fs";import ys from"node:path";function Mr(e){let r=new Set;for(let n of Object.keys(e.workers||{}))r.add(v(n));let t=ys.join(Se(e.id),"workers");if(!hs(t))return[...r];for(let n of ks(t,{withFileTypes:!0}))n.isDirectory()&&r.add(v(n.name));return[...r]}var Nr=g(()=>{"use strict";ee();S()});function Ir(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 _t(e){let r=e.trim();if(!r)return null;let t=Ir(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let u=Ir(s[1]??"");u&&n.push(u)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let u=Ir(r.slice(i,a+1));u&&n.push(u)}return n.length>0?n[n.length-1]:null}function xt(e){let r=e.finalResult??e.final_result;if(r!=null)return typeof r=="string"?_t(r)??(r.trim()||null):r;let t=typeof e.summary=="string"?e.summary.trim():"";if(!t)return null;let n=_t(t);return n||t}var Ct=g(()=>{"use strict"});import{existsSync as Rs,readFileSync as bs}from"node:fs";function wt(e){return e==="complete"}function Et(e){return wt(e.lastHeartbeatPhase)?e.terminalFinalResult!==void 0&&e.terminalFinalResult!==null?e.terminalFinalResult:e.lastHeartbeatSummary?.trim()||"completed":null}function me(e){let r={heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,terminalFinalResult:null,heartbeatBlocker:null,timestampAnomalies:[],lastBoxResourceSnapshot:null,lastPrEvidence:[]};if(!Rs(e))return r;let t=Date.now()+Ss,n=new Date(t).toISOString(),o=bs(e,"utf8").split(`
6
+ `).filter(Boolean);for(let s of o){let i=Ue(s);if(!i||typeof i!="object"||Array.isArray(i))continue;let a=i;if(r.heartbeatCount++,a.ts){let u=String(a.ts),l=Date.parse(u);Number.isFinite(l)&&l>t?r.timestampAnomalies.push({kind:"future_heartbeat_timestamp",observedAt:u,clampedTo:n}):r.lastHeartbeatAt=u}a.phase!==void 0&&a.phase!==null&&(r.lastHeartbeatPhase=String(a.phase)),a.summary!==void 0&&a.summary!==null&&(r.lastHeartbeatSummary=String(a.summary)),wt(r.lastHeartbeatPhase)&&(r.terminalFinalResult=xt(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 Ss,ze=g(()=>{"use strict";Ct();S();Ss=6e4});function _s(e){return e?(e.split("/").pop()??e).replace(/\.exe$/i,"").toLowerCase():null}function xs(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 Cs(e){let r=_s(e[0]);return!!(r&&vs.has(r))}function Ur(e){return!e||e.includes("/")||e.includes("*")?!1:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(e)}function Tr(e){if(!e)return!1;let r=e.trim();return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")}function ws(e){if(!e.startsWith("--glob="))return e;let r=e.slice(7);return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")?`--glob=${r}/**`:e}function Es(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;At.has(n)&&(t+=1);continue}r.push(n)}}return r}function As(e){let r=!1,t=e.map((o,s)=>{let i=ws(o),a=e[s-1];return a&&At.has(a)&&o.startsWith("!")&&!o.includes("/")&&!o.endsWith("/**")&&(i=`${o}/**`),i!==o&&(r=!0),i}),n=Es(t);if(n.length===2){let[o,s]=n;if(Tr(s))return{argv:[t[0]??"rg",o,"-g",`${s}/**`,"."],changed:!0};if(Ur(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 Br(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=xs(i.trim());if(!a.length||!Cs(a))return i;let u=As(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 Ps(e){let{pattern:r,target:t}=Pt(e);return r?Tr(t)?{kind:"rg_exclude_syntax",pattern:r,target:t}:Ur(t)?{kind:"bad_scope",pattern:r,target:t}:{kind:"not_repo_search",pattern:r,target:t}:{kind:"not_repo_search"}}function Ws(e){let{pattern:r,target:t}=Pt(e);if(!r)return null;if(Tr(t)){let n=`${t.trim()}/**`;return{command:`rg "${r}" -g '${n}' .`,changed:!0}}return t&&Ur(t)?{command:`rg -g ${t} "${r}" .`,changed:!0}:null}function Ds(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 Os(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 Fr(e){let r=e.meta?.trim()||(e.command?Os(e.command):null)||null;if(r){let t=Ps(r),n=Ds(t);if(n)return n;let o=Ws(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=Br(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 vs,At,Wt=g(()=>{"use strict";vs=new Set(["rg","ripgrep","grep"]),At=new Set(["-e","--regexp","-f","--file","-m","--max-count","-A","--after-context","-B","--before-context","-C","--context","-g","--glob","--iglob"])});function _e(e,r=200){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function Us(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 xe(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ts(e){let r=e.metadata;if(!xe(r))return null;let t=r.vulnerabilities;if(!xe(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 Bs(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 Fs(e,r){let t=e.error;if(xe(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?_e(o.split(`
7
+ `).find(Boolean)??o,160):"npm audit failed"}function Hs(e){let r=`${e.stdout}
8
+ ${e.stderr}`.trim(),t=Us(r);if(!t||!xe(t)){let o=_e(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(xe(t.error))return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit command failed: ${Fs(t,e.stderr)}`};let n=Ts(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:Bs(n),audit:n}:{kind:"command_failure",exitCode:e.exitCode,summary:"npm audit failed: JSON response missing vulnerability metadata",parseError:"missing_metadata"}}function Ks(e){return Ms.test(e)}function Ls(e){return Ns.test(e)}function js(e){let r=Fr({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&&Is.test(n)){let i=_e(n,160);return{kind:"command_failure",exitCode:1,summary:r??`ripgrep failed (exit 1): ${i}`}}let o=Br(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=_e(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 Dt(e){let r=e.stdout??"",t=e.stderr??"",n=e.interleavedOutput??"";if(Ks(e.command)){let i=r.trim()||n.trim()||t.trim();return Hs({exitCode:e.exitCode,stdout:i,stderr:t})}if(Ls(e.command))return js({command:e.command,exitCode:e.exitCode,stdout:r,stderr:t,interleaved:n});let o=Fr({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=_e(n||r||t||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:`command failed (exit ${e.exitCode}): ${s}`}}var Ms,Ns,Is,Ot=g(()=>{"use strict";Wt();Ms=/\bnpm\s+audit\b/i,Ns=/\b(rg|ripgrep)\b/i,Is=/\b(error|invalid|unknown|panic|not found)\b/i});import{existsSync as $s,readFileSync as Gs}from"node:fs";function Ys(e){let r=e.timestamp_ms;return e.timestamp||e.ts||(r?new Date(r).toISOString():void 0)}function Vs(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 zs(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 Js(e){if(e.type!=="tool_call"||e.subtype!=="completed")return null;let t=(e.tool_call&&typeof e.tool_call=="object"&&!Array.isArray(e.tool_call)?e.tool_call:null)?.shellToolCall;if(!t||typeof t!="object"||Array.isArray(t))return null;let n=t,o=n.args,s=o&&typeof o=="object"&&!Array.isArray(o)&&typeof o.command=="string"?String(o.command):"",i=n.result;if(!i||typeof i!="object"||Array.isArray(i))return null;let a=i.success??i.failure;if(!a||typeof a!="object"||Array.isArray(a))return null;let u=a,l=typeof u.exitCode=="number"?u.exitCode:0;return{command:s,exitCode:l,stdout:typeof u.stdout=="string"?u.stdout:"",stderr:typeof u.stderr=="string"?u.stderr:"",interleaved:typeof u.interleavedOutput=="string"?u.interleavedOutput:""}}function Xs(e,r){r.kind==="success"||r.kind==="search_no_matches"||(e.lastShellOutcome=r)}function Mt(e){let r={firstEventAt:null,lastEventAt:null,currentTool:null,finalResult:null,error:null,lastShellOutcome:null};if(!$s(e))return r;let t=Gs(e,"utf8").split(`
9
+ `).filter(Boolean);for(let n of t){let o=Ue(n);if(!o)continue;let s=Ys(o);if(s&&(r.firstEventAt||=s,r.lastEventAt=s),o.type==="stream_event"&&o.event&&typeof o.event=="object"&&o.event.type==="content_block_start"){let a=o.event.content_block;a?.type==="tool_use"&&(r.currentTool=String(a.name||"tool"))}if(o.type==="assistant"&&o.message&&typeof o.message=="object"){let a=o.message.content;if(Array.isArray(a)){let u=a.find(l=>l?.type==="tool_use");u&&(r.currentTool=String(u.name||r.currentTool))}}if(o.type==="tool_call"&&o.subtype==="started"){let a=o.tool_call&&typeof o.tool_call=="object"&&!Array.isArray(o.tool_call)?o.tool_call:void 0,u=Vs(a);u&&(r.currentTool=u)}let i=Js(o);i&&Xs(r,Dt({command:i.command,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr,interleavedOutput:i.interleaved})),o.type==="result"&&zs(r,o)}return r}var Nt=g(()=>{"use strict";Ot();S()});function Qs(e,r=240){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function It(e){let r=(e??"").trim();if(!r)return null;for(let t of qs)if(t.test.test(r))return{blocked:!0,reason:`${t.label}: ${Qs(r)}`};return null}var qs,Ut=g(()=>{"use strict";qs=[{test:/\b(?:invalid|unknown|unsupported|unrecognized)\b[^.\n]*\bmodel\b/i,label:"provider rejected the requested model"},{test:/\bmodel\b[^.\n]*\b(?:not\s+(?:found|supported|available|recognized|valid)|is\s+not\s+valid|does\s+not\s+exist)/i,label:"provider rejected the requested model"},{test:/\b(?:did you mean|available models|choose (?:a|one of)|supported models)\b/i,label:"provider rejected the requested model"},{test:/model preflight failed/i,label:"model/provider preflight failed"},{test:/\b(?:command not found|ENOENT|is the .*CLI on PATH|executable not found|no such file or directory)\b/i,label:"provider CLI is missing or not on PATH"},{test:/\bfailed to spawn\b/i,label:"provider failed to spawn the worker process"},{test:/\b(?:not logged in|unauthorized|authentication (?:failed|required)|invalid api key|missing api key|401)\b/i,label:"provider authentication failed"}]});function Tt(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function Zs(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="boolean"?e:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function ei(e){return!e?.checked||e.headIsAncestorOfBase!==!1?null:Tt(e.head)}function ri(e,r,t){let n=["exited_with_changes_salvage"];if((e==="uncommitted"||e==="both")&&n.push(`${r} uncommitted change${r===1?"":"s"} with no final result`),(e==="committed_ahead"||e==="both")&&t){let o=t.length>12?t.slice(0,12):t;n.push(`commit ${o} ahead of base with no final result`)}return n.push("review worktree \u2014 commit, open a PR, or run a salvage worker before discarding"),n.join(": ")}function Bt(e){if(e.alive||Zs(e.finalResult))return null;let r=(e.changedFiles??[]).filter(i=>i.trim()).length,t=Tt(e.headCommit)??ei(e.gitAncestry),n=r>0,o=!!t;if(!n&&!o)return{kind:"none",salvageable:!1,uncommittedCount:0,headCommit:null,attentionReason:"process exited without a final result"};let s=n&&o?"both":n?"uncommitted":"committed_ahead";return{kind:s,salvageable:!0,uncommittedCount:r,headCommit:t,attentionReason:ri(s,r,t)}}var Ft=g(()=>{"use strict"});function Ce(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function ti(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="boolean"?e:Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function ni(e){if(Ce(e.headCommit)||Ce(e.prUrl)||Ce(e.artifactBundlePath)||Ce(e.patchPath))return!0;let r=e.gitAncestry;return!!(r?.checked&&r.headIsAncestorOfBase===!1&&Ce(r.head))}function fe(e){return ti(e.finalResult)?e.changedFiles.length===0?{blocked:!1}:ni(e)?{blocked:!0,detail:`Worktree has ${e.changedFiles.length} uncommitted change(s); commit or discard before landing`}:{blocked:!0,reason:"dirty_worktree_no_pr",detail:`Worktree has ${e.changedFiles.length} uncommitted change(s) with no commit or PR; commit, open a PR, or discard before landing`}:{blocked:!1}}function Ht(e){if(e.blocked)return e.detail??e.reason??"dirty_worktree_no_pr"}var Je=g(()=>{"use strict"});function Hr(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 Kt(e){let r=e.targetPrReconciliation??e.target_pr_reconciliation??e.targetPrs??e.target_prs;return Array.isArray(r)?r.length:0}function Xe(e){let r=e.trim();if(!r)return null;let t=Hr(r);if(t)return t;let n=[],o=/```(?:json)?\s*([\s\S]*?)```/gi,s;for(;(s=o.exec(r))!==null;){let c=Hr(s[1]??"");c&&n.push(c)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let c=Hr(r.slice(i,a+1));c&&n.push(c)}if(n.length===0)return null;let u=n[n.length-1],l=Kt(u);for(let c of n){let d=Kt(c);d>l&&(u=c,l=d)}return u}var Kr=g(()=>{"use strict"});function Lt(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`https://github.com/${r[1]}/pull/${r[2]}`:e.trim()||null}function jt(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function oi(e){return new Set(e.map(r=>jt(Lt(r)??r)).filter(Boolean))}function $t(e,r,t){let n=Lt(e)??e;if(!n)return"unrelated";let o=jt(n);return oi(r).has(o)?"contract":t?(t.outcome==="skipped"||t.outcome==="blocked")&&t.reason?.trim()?"support":(t.outcome==="merged","unrelated"):"unrelated"}var Gt=g(()=>{"use strict"});function ge(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function si(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"?Object.keys(e).length>0:!0}function re(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`https://github.com/${r[1]}/pull/${r[2]}`:ge(e)}function qe(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function Yt(e){let r=null;if(typeof e=="string"){let o=Xe(e);o&&(r=o)}else e&&typeof e=="object"&&!Array.isArray(e)&&(r=e);if(!r)return[];let t=r.targetPrReconciliation??r.target_pr_reconciliation;if(!Array.isArray(t))return[];let n=[];for(let o of t){if(!o||typeof o!="object"||Array.isArray(o))continue;let s=o,i=re(String(s.prUrl??s.pr_url??"")),a=ge(s.outcome);!i||a!=="merged"&&a!=="skipped"&&a!=="blocked"||n.push({prUrl:i,outcome:a,mergeCommit:ge(s.mergeCommit??s.merge_commit),reason:ge(s.reason)})}return n}function Vt(e,r){let t=[],n=re(ge(e.prUrl)??"");if(n&&t.push(n),r&&typeof r=="object"&&!Array.isArray(r)){let o=r,s=re(String(o.prUrl??o.pr_url??""));s&&t.push(s)}return[...new Set(t)]}function zt(e){let{contract:r,snapshot:t}=e,n=e.finalResult??t.finalResult;if(!r.landingOnly&&r.targetPrUrls.length===0&&!r.repairEnforceOriginalPr)return{blocked:!1};if(!si(n))return(r.requiresTargetPrReconciliation??(r.landingOnly||!!r.repairEnforceOriginalPr||r.targetPrUrls.length>0))&&r.targetPrUrls.length>0?{blocked:!0,reason:"missing_target_pr_reconciliation",detail:`Final result required to reconcile target PR(s): ${r.targetPrUrls.join(", ")}`}:{blocked:!1};if(!(r.requiresTargetPrReconciliation??(r.landingOnly||!!r.repairEnforceOriginalPr||r.targetPrUrls.length>0))&&!r.repairEnforceOriginalPr)return{blocked:!1};let s=r.repairEnforceOriginalPr?re(ge(r.targetPrUrl)??"")??(r.targetPrUrls.length===1?re(r.targetPrUrls[0]):null):null;if(s){let d=Vt(t,n);if(!(n&&typeof n=="object"&&!Array.isArray(n)&&n.supersedesOriginalTargetPr===!0)){for(let R of d)if(R!==s)return{blocked:!0,reason:"duplicate_repair_pr",detail:`Repair worker opened or attached PR ${R} instead of canonical target ${s}`}}let p=Yt(n).find(R=>R.prUrl===s);if(!p||p.outcome!=="merged"&&!(p.reason?.trim()&&(p.outcome==="skipped"||p.outcome==="blocked")))return{blocked:!0,reason:"missing_repair_target_reconciliation",detail:`Repair worker must reconcile target PR ${s}`}}let i=Yt(n),a=new Map(i.map(d=>[qe(d.prUrl),d])),u=new Set(r.targetPrUrls.map(d=>qe(re(d)??d)).filter(Boolean)),l=Vt(t,n);if(r.landingOnly)for(let d of l){let m=a.get(qe(d)),f=$t(d,r.targetPrUrls,m);if(!(f==="contract"||f==="support"))return u.size>0?{blocked:!0,reason:"unrelated_implementation_pr",detail:`Landing-only worker attached unrelated PR ${d}`}:{blocked:!0,reason:"unrelated_implementation_pr",detail:"Landing-only worker must not open new implementation PRs"}}if(r.targetPrUrls.length===0)return{blocked:!1};let c=[];for(let d of r.targetPrUrls){let m=qe(re(d)??d),f=a.get(m);if(!f){c.push(m);continue}f.outcome!=="merged"&&!f.reason?.trim()&&c.push(m)}return c.length>0?{blocked:!0,reason:c.every(d=>a.has(d))?"incomplete_target_pr_landing":"missing_target_pr_reconciliation",detail:`Target PR reconciliation incomplete: ${c.join(", ")}`}:{blocked:!1}}function Jt(e){if(e.blocked)return e.detail??e.reason}var Xt=g(()=>{"use strict";Kr();Gt()});function ui(e){let r=Date.now();if(e.completionBlocker&&!qt(e.completionBlocker))return{state:"blocked",reason:e.completionBlocker};if(e.finalResult){if(e.localOnly&&ci(e.finalResult))return{state:"done",reason:"local-only worker superseded by merged PR"};let o={finalResult:e.finalResult,changedFiles:e.changedFiles??[],gitAncestry:e.gitAncestry??null,prUrl:e.prUrl??null},s=fe(o);if(s.blocked){let i=Ht(s);return{state:"needs_attention",reason:s.reason?`landing blocked (${s.reason}): ${i}`:`landing blocked: ${i}`}}if(e.landingContract){let i=zt({contract:e.landingContract,snapshot:o,finalResult:e.finalResult}),a=Jt(i);if(a)return{state:"needs_attention",reason:i.reason?`landing contract (${i.reason}): ${a}`:`landing contract: ${a}`}}return{state:"done",reason:"final result recorded"}}if(!e.alive){if(li(e))return{state:"done",reason:"empty abandoned worker record"};let o=It(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>ii)return{state:"needs_attention",reason:`no first stream event ${Sr(t)}s after start`};let n=e.lastActivityAt?Date.parse(e.lastActivityAt):NaN;return Number.isFinite(n)&&r-n>ai?{state:"stale",reason:`no log/event/heartbeat activity for ${Sr(n)}s`}:{state:"ok",reason:"recent activity"}}function qt(e){let r=e?.trim();return r?/completion acknowledged but board not advanced/i.test(r)&&/task already terminal/i.test(r):!1}function li(e){return e.finalResult||e.taskId||e.agentOsId||e.stdoutBytes>0||(e.stderrBytes??0)>0||e.heartbeatBytes>0||e.error?.trim()||(e.changedFiles??[]).some(r=>r.trim())?!1:/empty worker dir|marked abandoned/i.test(e.reconcileReason??"")}function ci(e){let r=null;if(typeof e=="string"?r=Xe(e):e&&typeof e=="object"&&!Array.isArray(e)&&(r=e),!r)return!1;let t=r.targetPrReconciliation??r.target_pr_reconciliation;return Array.isArray(t)?t.some(n=>!n||typeof n!="object"||Array.isArray(n)?!1:String(n.outcome??"").trim()==="merged"):!1}function di(e,r,t){let n=e.completionSnapshot?.finalResult;return e.completionAckSource==="local-pr-merged-reconcile"&&n!==void 0&&n!==null?n:r||(n??Et(t))}function we(e,r={}){let t=Mt(e.stdoutPath),n=me(e.heartbeatPath),o=typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim().length>0,s=di(e,t.finalResult,n),i=o?!1:z(e.pid),a=Te(e.stdoutPath),u=Te(e.stderrPath),l=Te(e.heartbeatPath),c=be(e.worktreePath),d=Fe(e.worktreePath,{base:r.base,baseCommit:r.baseCommit}),m=ct([t.lastEventAt,n.lastHeartbeatAt,Be(e.stdoutPath),Be(e.stderrPath),Be(e.heartbeatPath)]),f=t.error||!i&&!s&&lt(e.stderrPath,10).trim()||void 0,p=typeof e.completionBlocker=="string"&&e.completionBlocker.trim()?e.completionBlocker.trim():null,R=qt(p)?null:p,b=e.repairTargetPrUrl?{landingOnly:!1,targetPrUrls:[e.repairTargetPrUrl],targetPrUrl:e.repairTargetPrUrl,repairEnforceOriginalPr:!0}:null,y=ui({alive:i,finalResult:s,firstEventAt:t.firstEventAt,stdoutBytes:a,stderrBytes:u,heartbeatBytes:l,lastActivityAt:m,heartbeatBlocker:n.heartbeatBlocker,startedAt:e.startedAt,error:f,changedFiles:c,gitAncestry:d,completionBlocker:R,landingContract:b,prUrl:e.repairTargetPrUrl??e.taskPrUrl??null,localOnly:e.localOnly===!0,taskId:e.taskId??null,agentOsId:e.agentOsId??null,reconcileReason:e.reconcileReason??null}),w=R||y.state==="blocked"?"blocked":o||y.state==="done"?"done":s?"exited":i?"running":"exited";return{runId:e.runId,worker:e.name,pid:e.pid,alive:i,status:w,attention:y,branch:e.branch,worktreePath:e.worktreePath,ownedPaths:e.ownedPaths,stdoutBytes:a,stderrBytes:u,heartbeatBytes:l,firstEventAt:t.firstEventAt,lastEventAt:t.lastEventAt,lastActivityAt:m,currentTool:o?null:t.currentTool,heartbeatCount:n.heartbeatCount,lastHeartbeatAt:n.lastHeartbeatAt,lastHeartbeatPhase:n.lastHeartbeatPhase,lastHeartbeatSummary:n.lastHeartbeatSummary,heartbeatBlocker:n.heartbeatBlocker,timestampAnomalies:n.timestampAnomalies,finalResult:s,error:f,changedFiles:c,gitAncestry:d,instructionPolicyFingerprint:e.instructionPolicyFingerprint??null,instructionPolicyEvidence:e.instructionPolicyEvidence??null,model:e.model??e.orchestrationAudit?.model??null,provider:e.orchestrationAudit?.provider??null,boxKind:e.boxKind??null,boxId:e.boxId??null,runtimeId:e.runtimeId??null,personaSlug:e.personaSlug??null,dispatched:e.dispatched??null,localOnly:e.localOnly??null}}function te(e){return!!(e.finalResult||e.alive===!1||e.status==="exited"||e.status==="done")}function Qt(e){return e.finalResult?e.attention.state==="needs_attention"||e.attention.state==="blocked":!1}var ii,ai,ne=g(()=>{"use strict";ze();Nt();Ut();Ft();L();Je();Xt();Kr();S();ii=18e4,ai=6e5});var Zt=g(()=>{"use strict";ne()});var mi,fi,en=g(()=>{"use strict";ht();Ee();xr();Cr();Lr();Ge();ee();Nr();Zt();S();mi=500*1024*1024,fi=4*1024*1024*1024});var Lr=g(()=>{"use strict";en()});import{homedir as gi}from"node:os";import hi from"node:path";var ki,rn=g(()=>{"use strict";ki=hi.join(gi(),".kynver",".env")});var tn=g(()=>{"use strict"});var nn=g(()=>{"use strict";tn()});var on=g(()=>{"use strict"});var sn=g(()=>{"use strict";nn();on()});var an=g(()=>{"use strict"});var un=g(()=>{"use strict";an()});var cn=g(()=>{"use strict";rn();ce();Ee();sn();un()});import{existsSync as vi,mkdirSync as pc,readFileSync as _i,writeFileSync as mc}from"node:fs";import{homedir as xi,totalmem as gc}from"node:os";import jr from"node:path";function Qe(){if(!vi(dn))return{};try{return JSON.parse(_i(dn,"utf8"))}catch{return{}}}var pn,dn,Cc,wc,Ec,Ee=g(()=>{"use strict";_r();ce();S();xr();Cr();Lr();Ge();cn();pn=jr.join(xi(),".kynver"),dn=jr.join(pn,"config.json"),Cc=jr.join(pn,"credentials");wc=500*1024*1024,Ec=4*1024*1024*1024});import{existsSync as mn}from"node:fs";import{homedir as gn}from"node:os";import J from"node:path";function P(e){let r=J.resolve(He(e.trim()));for(;Ci.has(J.basename(r));)r=J.dirname(r);return r}function X(){let e=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(e)return P(e);let r=Qe().harnessRoot?.trim();if(r)return P(r);let t=J.join(gn(),".kynver","harness");return mn(t)?t:mn(fn)?fn:t}function j(e){return J.join(P(e),"runs")}function he(e){return J.join(P(e),"worktrees")}function vt(){let e=X();return{harnessRoot:e,runsDir:j(e),worktreesDir:he(e)}}function Or(e,r){return J.join(e,v(r))}var fn,Ci,$=g(()=>{"use strict";Ee();ce();S();fn=J.join(gn(),".openclaw","harness"),Ci=new Set(["runs","worktrees"])});$();import M from"node:path";Je();import tr from"node:path";L();ne();var $r=[".next",".turbo","dist","build",".cache","node_modules/.cache"];function hn(e){let r=e.replace(/\\/g,"/").replace(/\/+$/,"");if(r==="node_modules"||r.startsWith("node_modules/"))return!0;for(let t of $r)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!hn(n)})}function oe(e){if(typeof e=="string")return e.match(/https:\/\/github\.com\/[^\s]+\/pull\/\d+/i)?.[0]??null;if(e&&typeof e=="object"){let r=e;for(let t of["prUrl","pr_url","pullRequestUrl"]){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}}return null}function Ae(e){let r=e.gitAncestry?.relation;return r==="merged"||r==="synced"?W(e.changedFiles).length>0:!!(oe(e.finalResult)||r==="ahead"||r==="diverged"||e.changedFiles.length>0&&e.finalResult)}S();function Pe(e){return e.status||(e.status=we(e.worker,{base:e.run.base,baseCommit:e.run.baseCommit})),e.status}function Gr(e,r){if(e.status)return W(e.status.changedFiles).length>0;let t=r?r.porcelain(e.worktreePath):be(e.worktreePath);return W(t).length>0}function wi(e){let r=e.worker.completionSnapshot?.finalResult;return r??(e.worker.taskPrUrl?{prUrl:e.worker.taskPrUrl}:null)}function Yr(e,r){if(e.status)return e.status;let t=e.worker,n=typeof t.completionReportedAt=="string"&&t.completionReportedAt.trim().length>0,o=!!(t.status&&["done","exited","blocked","failed","abandoned"].includes(t.status))||n,s=wi(e);if(o&&!z(t.pid)){let i=r?.gitStatusCache?r.gitStatusCache.porcelain(e.worktreePath):be(e.worktreePath),a=e.run.baseCommit?.trim()||e.run.base?.trim()||"origin/main",l=r?.gitRevCache?.countAheadOfMain(e.worktreePath,a)===0?{checked:!0,base:a,relation:"synced"}:Fe(e.worktreePath,{base:e.run.base,baseCommit:e.run.baseCommit}),c={runId:e.runId,worker:e.workerName,pid:t.pid,alive:!1,status:t.status??(n?"done":"exited"),attention:{state:n?"done":"stale"},branch:t.branch,worktreePath:e.worktreePath,ownedPaths:t.ownedPaths,stdoutBytes:0,stderrBytes:0,heartbeatBytes:0,firstEventAt:null,lastEventAt:null,lastActivityAt:t.completionReportedAt??null,currentTool:null,heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,heartbeatBlocker:null,changedFiles:i,gitAncestry:l,finalResult:s,completionBlocker:typeof t.completionBlocker=="string"&&t.completionBlocker.trim()||null,prUrl:t.repairTargetPrUrl??t.taskPrUrl??oe(s)};return e.status=c,c}return Pe(e)}ne();ee();Nr();ne();S();import Ei from"node:path";var Ai=new Set(["running","dispatching","pending","queued","needs_attention"]),se=new Set(["completed","failed","cancelled","done"]);function ie(e){let r=Mr(e);if(r.length===0)return"failed";let t=!1,n=!1,o=!1,s=!1;for(let i of r){let a=x(Ei.join(Se(e.id),"workers",v(i),"worker.json"),void 0);if(!a)continue;let u=we(a,{base:e.base,baseCommit:e.baseCommit});if(u.alive&&!u.finalResult){t=!0;break}typeof a.completionBlocker=="string"&&a.completionBlocker&&(o=!0),Qt(u)&&(s=!0),u.finalResult&&u.attention.state==="done"&&(n=!0)}return t||o||s?null:n?"completed":"failed"}function kn(){let e=[];for(let r of Wr()){if(!Ai.has(r.status))continue;let t=ie(r);if(!t||t===r.status)continue;let n=r.status;r.status=t,Dr(r),e.push({runId:r.id,from:n,to:t})}return e}ne();ze();import{existsSync as Ze,mkdirSync as dd,readdirSync as bn,renameSync as pd,statSync as Pi}from"node:fs";import ae from"node:path";Ee();_r();ce();ze();$();ee();$();S();import q from"node:path";var id=`${q.sep}runs${q.sep}runs${q.sep}`;function yn(e){return{workerJsonPath:q.join(e,"worker.json"),stdoutPath:q.join(e,"stdout.jsonl"),stderrPath:q.join(e,"stderr.log"),heartbeatPath:q.join(e,"heartbeat.jsonl"),lastStatusPath:q.join(e,"last-status.json")}}S();var We=900*1e3,bd=3600*1e3;function Sn(e,r){let t=ae.resolve(e),n=ae.resolve(j(r)),o=ae.relative(n,t);return o!==".."&&!o.startsWith("..")&&!ae.isAbsolute(o)}function Wi(e){if(!Ze(e))return[];try{return bn(e,{withFileTypes:!0}).filter(r=>r.isDirectory()&&r.name!=="runs").map(r=>r.name)}catch{return[]}}function Di(e){let r=ae.join(e,"workers");if(!Ze(r))return[];try{return bn(r,{withFileTypes:!0}).filter(t=>t.isDirectory()).map(t=>t.name)}catch{return[]}}function Rn(e,r,t){if(!Ze(e))return!1;try{let n=r-Pi(e).mtimeMs;return Number.isFinite(n)&&n>=0&&n<t}catch{return!1}}function Oi(e,r=Date.now(),t=We){if(!Ze(e))return!1;let n=yn(e),o=x(n.workerJsonPath,void 0);if(o?.status==="running"&&z(o.pid))return!0;let s=me(n.heartbeatPath);if(s.lastHeartbeatAt){let i=r-Date.parse(s.lastHeartbeatAt);if(Number.isFinite(i)&&i>=0&&i<t)return!0}return!!(Rn(n.stdoutPath,r,t)||Rn(n.heartbeatPath,r,t))}function Mi(e,r=Date.now(),t=We){for(let n of Di(e))if(Oi(ae.join(e,"workers",n),r,t))return!0;return!1}function vn(e,r=Date.now()){let t=new Set,n=j(e);for(let o of Wi(n)){let s=ae.join(n,o);Mi(s,r)&&t.add(`${e}\0${o}`)}return t}S();function Vr(e,r=Date.now(),t=We){let n=me(e.heartbeatPath);if(!n.lastHeartbeatAt)return!1;let o=r-Date.parse(n.lastHeartbeatAt);return Number.isFinite(o)&&o>=0&&o<t}function er(e,r=Date.now(),t=We){return z(e.pid)?!0:Vr(e,r,t)}function Ni(e,r){return r?r.runTerminalCache.derive(e.run):ie(e.run)}function G(e,r=Date.now()){return er(e.worker,r)}function zr(e,r){return se.has(e.run.status)?!1:Ni(e,r)!==null}function _n(e,r,t=Date.now()){if(G(e,t))return!0;if(se.has(e.run.status)||zr(e,r))return!1;let n=Pe(e);return te(n)?!1:!!G(e,t)}Je();ne();function xn(e,r){if(!(typeof e.worker.completionBlocker=="string"?e.worker.completionBlocker.trim():""))return!1;if(G(e))return!0;let n=r??Pe(e);return!!(!te(n)||Ae(n)||W(n.changedFiles).length>0||fe({finalResult:n.finalResult,changedFiles:n.changedFiles,gitAncestry:n.gitAncestry,prUrl:oe(n.finalResult)}).blocked)}L();S();import{existsSync as wn,mkdirSync as Ii,writeFileSync as Cn}from"node:fs";import rr from"node:path";function En(e,r,t){return rr.join(e,"salvage",v(r),v(t))}function An(e){return wn(rr.join(En(e.harnessRoot,e.runId,e.workerName),"evidence.json"))}function Pn(e){let r=En(e.harnessRoot,e.indexed.runId,e.indexed.workerName);Ii(r,{recursive:!0});let t=rr.join(r,"salvage.patch"),n=!1;if(wn(e.indexed.worktreePath)){let s=C(e.indexed.worktreePath,["diff","HEAD"]),i=C(e.indexed.worktreePath,["diff","--cached"]),a=[s.stdout,i.stdout].filter(u=>u.trim()).join(`
10
+ `);a.trim()&&(Cn(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 dn(rr.join(r,"evidence.json"),`${JSON.stringify(o,null,2)}
13
- `),o}var ki=new Set(["completion_blocked","dirty_worktree","pr_or_unmerged_commits","landing_blocked"]);function Ri(e){return!ki.has(e.skipReason)||G(e.indexed,e.now)?!1:fn({harnessRoot:e.harnessRoot,runId:e.indexed.runId,workerName:e.indexed.workerName})?!0:e.writeSalvageEvidence?(gn({harnessRoot:e.harnessRoot,indexed:e.indexed,skipReason:e.skipReason,status:e.status,now:e.now}),!0):!1}function yi(e){let{indexed:r,includeOrphans:t,worktreesAgeMs:n,terminalWorktreesAgeMs:o}=e;return r?se.has(r.run.status)||e.liveness&&Vr(r,e.liveness)||e.liveness&&te(Gr(r,e.liveness))&&!G(r)?o:n:t?o:n}function bi(e,r){if(e.harnessRoot?.trim())return tr.resolve(e.harnessRoot);let t=r.worker.workerDir;if(!t)return null;let n=`${tr.sep}runs${tr.sep}`,o=t.indexOf(n);return o<0?null:t.slice(0,o+n.length-1)}function hn(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=yi(e);if(n<=0&&!t&&u<=0)return"worktrees_disabled";if(u>0&&o<u)return"below_age_threshold";if(G(r,a))return"active_worker";let l=Gr(r,e.liveness),c=bi(e,r),d=p=>c&&Ri({indexed:r,harnessRoot:c,skipReason:p,status:l,now:a,writeSalvageEvidence:e.writeSalvageEvidence===!0})?null:p;if(cn(r,l)){let p=d("completion_blocked");if(p)return p}if($r(r,e.liveness?.gitStatusCache)){let p=d("dirty_worktree");if(p)return p}let m=e.liveness?.gitRevCache?.countAheadOfMain(e.worktreePath);if(m!=null&&m>0){let p=d("pr_or_unmerged_commits");if(p)return p}if(ln(r,e.liveness,a)||!te(l))return"run_still_active";if(Ae(l)){let p=d("pr_or_unmerged_commits");if(p)return p}if(W(l.changedFiles).length>0){let p=d("dirty_worktree");if(p)return p}if(me({finalResult:l.finalResult,changedFiles:l.changedFiles,gitAncestry:l.gitAncestry,prUrl:oe(l.finalResult)}).blocked){let p=d("landing_blocked");if(p)return p}if(i&&e.worktreePath){let p=i({worktreePath:e.worktreePath,indexed:!!r,runId:r?.runId,worker:r?.workerName});if(p)return p.detail?{reason:p.reason,detail:p.detail}:p.reason}return null}function zr(e){let{indexed:r,nodeModulesAgeMs:t,ageMs:n,worktreePath:o,activeWorktreePaths:s,diskPressure:i}=e;return!i&&n<t?"below_age_threshold":s.has(tr.resolve(o))||r&&G(r)?"active_worker":r&&$r(r,e.gitStatusCache)?"dirty_worktree":null}function kn(e){return zr(e)}var Jr=216e5,nr=6048e5;var qr=36e5,or=120;var Rn=new Set(["active_worker","run_still_active","completion_blocked","landing_blocked"]);function yn(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 Cn,readdirSync as vn,statSync as Ci}from"node:fs";import xn from"node:path";ee();$();import bn from"node:path";S();function _i(e,r){return er(e,r)}function Sn(e,r=Date.now()){let t=new Set,n=new Set;for(let o of e){for(let s of Ye(o)){let i=!1;for(let a of Object.keys(s.workers||{})){let u=v(bn.join(_e(o,s.id),"workers",_(a),"worker.json"),void 0);if(!u?.worktreePath)continue;let l=bn.resolve(u.worktreePath);_i(u,r)&&(i=!0,t.add(l))}i&&n.add(`${o}\0${s.id}`)}for(let s of un(o))n.add(s)}return{activeWorktreePaths:t,liveRunKeys:n}}function _n(e,r,t,n){return t?n.has(`${r}\0${t}`):!1}S();function vi(e,r){try{let t=Ci(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function xi(e,r){let t=xn.join(e,"runs",r,"run.json");return Cn(t)?v(t,null):null}function wn(e){try{return vn(e).length===0}catch{return!1}}function An(e){let{harnessRoot:r,runId:t,runPath:n,ageMs:o,runDirectoriesAgeMs:s,activeGuards:i}=e;if(_n(n,r,t,i.liveRunKeys)||!wn(n))return"run_still_active";let a=xi(r,t);return a&&!se.has(a.status)&&!ie(a)?"run_still_active":s>0&&o<s?"below_age_threshold":null}function En(e){if(!Cn(e.worktreesDir))return[];let r=[],t;try{t=vn(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=xn.join(e.worktreesDir,o);wn(s)&&r.push({kind:"remove_run_directory",path:s,bytes:null,harnessRoot:e.harnessRoot,runId:o,ageMs:vi(s,e.now)})}return r}K();import{existsSync as Qr,rmSync as Hn}from"node:fs";import{execFileSync as wi}from"node:child_process";import{existsSync as Pn,readdirSync as Ai,statSync as Ei}from"node:fs";import Pi from"node:path";var Wi=2500;function Di(e,r=Wi){if(!Pn(e))return 0;try{let n=wi("du",["-sb",e],{encoding:"utf8",timeout:r,stdio:["ignore","pipe","ignore"]}).trim().split(/\s+/)[0],o=Number(n);return Number.isFinite(o)&&o>=0?o:null}catch{return null}}function Y(e,r=5e4){if(!Pn(e))return 0;let t=Di(e);if(t!==null)return t;let n=0,o=0,s=[e];for(;s.length>0;){let i=s.pop(),a;try{a=Ai(i)}catch{continue}for(let u of a){if(o++>r)return null;let l=Pi.join(i,u),c;try{c=Ei(l)}catch{continue}c.isDirectory()?s.push(l):n+=c.size}}return n}import{existsSync as Mi,rmSync as Ti}from"node:fs";$();import{lstatSync as Oi,readdirSync as Ni}from"node:fs";function Wn(e){try{let r=Oi(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 Dn(e,r=32){let t=Wn(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=Wn(i);if(o+=1,a?.foreign)return!0}}catch{}return!1}import{spawnSync as Ii}from"node:child_process";import In from"node:path";import D from"node:path";function On(e,r,t,n){let o=D.resolve(e),s=`${D.sep}${n}`,i=o.endsWith(s)?o:null;if(!i)return"path_outside_harness";let a=D.relative(t,i);if(a.startsWith("..")||D.isAbsolute(a))return"path_outside_harness";let u=a.split(D.sep);return u.length<3||u[u.length-1]!==n||!o.startsWith(D.resolve(r))?"path_outside_harness":null}function sr(e,r,t){return On(e,r,t,"node_modules")}function ir(e,r,t){return On(e,r,t,".next")}function ar(e,r,t){let n=D.resolve(e),o=D.relative(t,n);return o.startsWith("..")||D.isAbsolute(o)||o.split(D.sep).length<3||!n.startsWith(D.resolve(r))?"path_outside_harness":null}function Nn(e,r,t){let n=D.resolve(e);return sr(n,r,t)===null||ir(n,r,t)===null||ar(n,r,t)===null}function Tn(){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 Mn(e){let r=Ii("sudo",["-n",...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{ok:r.status===0,stderr:`${r.stderr??""}${r.stdout??""}`.trim()}}function Un(e,r,t){if(!Nn(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=Mn(["chown","-R",`${n}:${o}`,In.resolve(e)]);if(s.ok)return{ok:!0,method:"chown_then_rm"};let i=Mn(["rm","-rf",In.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 Xr="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 Ui(e){let r=e?.code;return r==="EACCES"||r==="EPERM"}function Bn(e,r,t={}){if(!Mi(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?ge(n):null,i=e.bytes??Y(e.path)??void 0,a=t.removePath??Ti,u=t.hasForeignOwnedEntry??Dn;try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i}}catch(l){if(!Ui(l)||!n||!o)return{executed:!1,skipped:!0,skipReason:"remove_failed",error:l.message};let c=u(e.path),d=Tn();if(!(d==="force"||d==="auto"&&c))return c?{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${l.message}; ${Xr}`}:{executed:!1,skipped:!0,skipReason:"remove_failed",error:l.message};let f=Un(e.path,n,o);if(f.ok&&f.method==="sudo_rm")return{executed:!0,skipped:!1,bytes:i,privilegedReclaim:!0};if(f.ok)try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i,privilegedReclaim:!0}}catch(p){return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${p.message}; privileged chown succeeded but rm still failed`}}return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${l.message}; privileged reclaim failed: ${f.error}; ${Xr}`}}}function Zr(e){let r=e.harnessRoot;return!r||!an(e.path,r)?null:{...e,executed:!1,skipped:!0,skipReason:"run_metadata_protected"}}function et(e,r){let t=Zr(e);if(t)return t;let n=Bn(e,r);return{...e,bytes:n.bytes??e.bytes,executed:n.executed,skipped:n.skipped,skipReason:n.skipReason,error:n.error}}function Fn(e,r){return et(e,r)}function Ln(e,r){return et(e,r)}function Kn(e,r){return et(e,r)}function jn(e,r){let t=Zr(e);if(t)return t;if(!Qr(e.path))return{...e,executed:!1,skipped:!0,skipReason:"missing_worktree"};if(!r)return{...e,executed:!1,skipped:!0,skipReason:"dry_run"};try{let n=e.bytes??Y(e.path);return Hn(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 $n(e,r){let t=Zr(e);if(t)return t;if(!Qr(e.path))return{...e,executed:!1,skipped:!0,skipReason:"missing_worktree"};if(!r)return{...e,executed:!1,skipped:!0,skipReason:"dry_run"};let n=e.repo;try{let o=e.bytes??Y(e.path);return n&&Re(n,["worktree","remove","--force",e.path],{allowFailure:!0}),Qr(e.path)&&Hn(e.path,{recursive:!0,force:!0}),{...e,bytes:o,executed:!0,skipped:!1}}catch(o){return{...e,executed:!1,skipped:!0,skipReason:"remove_failed",error:o.message}}}import{existsSync as ur,readdirSync as lr,statSync as Bi}from"node:fs";import B from"node:path";function rt(e,r){try{let t=Bi(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function Yn(e,r){let t=B.relative(r,e);return t===""||!t.startsWith("..")&&!B.isAbsolute(t)}function Gn(e,r,t,n){let o=[];for(let s of jr){if(s===".next")continue;let i=B.join(e,s);if(!ur(i))continue;let a=B.resolve(i);t.has(a)||Yn(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:rt(a,r.now)}))}return o}function Vn(e){let r=[],t=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||r.push(...Gn(n.worktreePath,e,t,{runId:n.runId,worker:n.workerName,repo:n.run.repo}));if(!e.includeOrphans||!ur(e.worktreesDir))return r;for(let n of lr(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=B.join(e.worktreesDir,n.name);for(let s of lr(o,{withFileTypes:!0})){if(!s.isDirectory())continue;let i=B.join(o,s.name);r.push(...Gn(i,e,t,{runId:n.name,worker:s.name}))}}return r}function zn(e){let r=e.worktreesAgeMs>0||e.includeOrphans,t=e.includeOrphans;if(!r&&!t)return[];let n=[],o=new Set;if(r)for(let i of e.index.values()){if(e.runIdFilter&&i.runId!==e.runIdFilter)continue;let a=i.worktreePath;ur(a)&&(o.has(a)||(o.add(a),n.push({kind:"remove_worktree",path:a,bytes:null,runId:i.runId,worker:i.workerName,repo:i.run.repo,ageMs:rt(a,e.now)})))}if(!t||!ur(e.worktreesDir))return n;let s=new Set;for(let i of e.index.values())s.add(B.resolve(i.worktreePath));for(let i of lr(e.worktreesDir,{withFileTypes:!0})){if(!i.isDirectory()||e.runIdFilter&&i.name!==e.runIdFilter)continue;let a=B.join(e.worktreesDir,i.name),u;try{u=lr(a,{withFileTypes:!0})}catch{continue}for(let l of u){if(!l.isDirectory())continue;let c=B.resolve(B.join(a,l.name));o.has(c)||s.has(c)||Yn(c,e.harnessRoot)&&(o.add(c),n.push({kind:"remove_worktree",path:c,bytes:null,runId:i.name,worker:l.name,ageMs:rt(c,e.now)}))}}return n}import{existsSync as Xn,readdirSync as Jn,statSync as Hi}from"node:fs";import he from"node:path";var Fi=[{dirName:"node_modules",kind:"remove_node_modules"},{dirName:".next",kind:"remove_next_cache"}];function Li(e,r){try{let t=Hi(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function Ki(e,r){let t=he.relative(r,e);return t===""||!t.startsWith("..")&&!he.isAbsolute(t)}function ji(e,r,t,n,o,s){if(!Xn(n))return;let i=he.resolve(n);r.has(i)||Ki(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:Li(i,t.now)}))}function qn(e,r,t,n,o){for(let s of Fi)ji(e,r,t,he.join(n,s.dirName),s.kind,o)}function Qn(e){let r=[],t=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||qn(r,t,e,n.worktreePath,{runId:n.runId,worker:n.workerName,repo:n.run.repo});if(!e.includeOrphans||!Xn(e.worktreesDir))return r;for(let n of Jn(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory()||e.runIdFilter&&n.name!==e.runIdFilter)continue;let o=he.join(e.worktreesDir,n.name),s;try{s=Jn(o,{withFileTypes:!0})}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=he.join(o,i.name);qn(r,t,e,a,{runId:n.name,worker:i.name})}}return r}K();import{existsSync as Zn,statSync as $i}from"node:fs";import H from"node:path";function Gi(e,r){try{let t=$i(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function Yi(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 Vi(e,r){let t=H.relative(H.resolve(r),H.resolve(e));return t!==""&&!t.startsWith("..")&&!H.isAbsolute(t)}var zi=200;function eo(e){if(!e.includeOrphans||!Zn(e.worktreesDir))return[];let r=new Set;for(let s of e.index.values())s.run.repo&&r.add(H.resolve(s.run.repo));let t=new Set;for(let s of e.index.values())t.add(H.resolve(s.worktreePath));let n=[],o=new Set;for(let s of r){let i=0,a;try{a=Re(s,["worktree","list","--porcelain"],{allowFailure:!0})}catch{continue}let u=Yi(a);for(let l of u){if(i>=zi)break;let c=H.resolve(l.path);if(c===H.resolve(s)||!Vi(c,e.worktreesDir)||t.has(c)||o.has(c)||!Zn(c))continue;let m=H.relative(e.worktreesDir,c).split(H.sep),f=m[0],p=m[1]??"unknown";o.add(c),i+=1,n.push({kind:"remove_worktree",path:c,bytes:null,runId:f,worker:p,repo:s,ageMs:Gi(c,e.now)})}}return n}ee();S();import We from"node:path";function ro(e,r){let t=We.resolve(r),n=new Map;for(let[o,s]of e){let i=s.harnessRoot?We.resolve(s.harnessRoot):null;i&&i!==t||n.set(o,s)}return n}function to(e){let r=new Map;for(let t of Ye(e))for(let n of Object.keys(t.workers||{})){let o=We.join(_e(e,t.id),"workers",_(n),"worker.json"),s=v(o,void 0);s?.worktreePath&&r.set(We.resolve(s.worktreePath),{harnessRoot:e,worktreePath:We.resolve(s.worktreePath),runId:t.id,workerName:n,run:t,worker:s})}return r}function De(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function ue(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)&&n>=0?n:r}function no(e={}){let r=e.execute===!0||e.execute!==!1&&De("KYNVER_CLEANUP_EXECUTE"),t=e.finalizeStaleRuns!==!1&&!De("KYNVER_CLEANUP_SKIP_FINALIZE"),n=e.nodeModulesAgeMs??ue("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??ue("KYNVER_CLEANUP_WORKTREES_AGE_MS",0),i=e.terminalWorktreesAgeMs??ue("KYNVER_CLEANUP_TERMINAL_WORKTREES_AGE_MS",216e5),a=e.runDirectoriesAgeMs??ue("KYNVER_CLEANUP_RUN_DIRECTORIES_AGE_MS",36e5),u=e.maxActionsPerSweep??ue("KYNVER_CLEANUP_MAX_ACTIONS_PER_SWEEP",120),l=e.includeOrphans===!0||De("KYNVER_CLEANUP_INCLUDE_ORPHANS"),d=De("KYNVER_CLEANUP_SCOPE_ALL")||process.env.KYNVER_CLEANUP_SCOPE==="all"?e.runIdFilter:e.runIdFilter??(process.env.KYNVER_CLEANUP_RUN_ID||void 0),m=e.accountBytes!==!1&&!De("KYNVER_CLEANUP_SKIP_BYTE_ACCOUNTING"),f=ue("KYNVER_CLEANUP_STORAGE_ENTRY_CAP",2e3),p=e.storagePerRunEntryCap!==void 0?e.storagePerRunEntryCap:m&&f>0?f:null,y=ue("KYNVER_CLEANUP_BYTE_ENTRY_CAP",2e3),b=e.byteAccountingEntryCap??(Number.isFinite(y)&&y>0?Math.floor(y):2e3);return{execute:r,finalizeStaleRuns:t,scanDependencyCaches:o,nodeModulesAgeMs:n,worktreesAgeMs:s>0?s:0,terminalWorktreesAgeMs:i>=0?i:0,runDirectoriesAgeMs:a>=0?a:0,maxActionsPerSweep:Number.isFinite(u)&&u>0?Math.floor(u):120,includeOrphans:l,runIdFilter:d?String(d):void 0,accountBytes:m,storagePerRunEntryCap:p,byteAccountingEntryCap:b}}K();import{existsSync as oo}from"node:fs";import tt from"node:path";S();var qi=1800*1e3;function so(e){let r=e.now??Date.now(),t=e.heartbeatFreshMs??qi;if(!oo(e.worktreePath))return null;if(e.runId&&e.workerName){let l=tt.join(e.harnessRoot,"runs",e.runId,"workers",e.workerName),c=v(tt.join(l,"worker.json"),void 0);if(c&&Yr(c,r,t))return"active_worker"}let n=tt.join(e.worktreePath,".git");if(!oo(n))return null;let o=x(e.worktreePath,["status","--porcelain"]);if(o.status!==0)return"pr_or_unmerged_commits";let s=o.stdout.split(`
15
- `).map(l=>l.trim()).filter(l=>l.length>0);if(W(s).length>0)return"dirty_worktree";let i=x(e.worktreePath,["rev-list","--count","@{u}..HEAD"]);if(i.status===0){let l=Number(i.stdout.trim());if(Number.isFinite(l)&&l>0)return"pr_or_unmerged_commits"}let a=x(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}$();import{existsSync as Xi,readdirSync as io,statSync as Qi}from"node:fs";import Zi from"node:path";function ao(e={}){let r=P(e.harnessRoot??q()),t=ge(r),n=e.now??Date.now(),o=new Date(n).toISOString();if(!Xi(t))return{harnessRoot:r,worktreesDir:t,worktreesBytes:0,runCount:0,workerCount:0,oldestRunAt:null,scannedAt:o};let s=0,i=0,a=0,u=null,l;try{l=io(t,{withFileTypes:!0})}catch{return{harnessRoot:r,worktreesDir:t,worktreesBytes:null,runCount:0,workerCount:0,oldestRunAt:null,scannedAt:o}}for(let c of l){if(!c.isDirectory())continue;i+=1;let d=Zi.join(t,c.name);try{let m=Qi(d);u=u===null?m.mtimeMs:Math.min(u,m.mtimeMs)}catch{}try{for(let m of io(d,{withFileTypes:!0}))m.isDirectory()&&(a+=1)}catch{}if(s!==null&&e.perRunEntryCap!==null){let m=e.perRunEntryCap??5e4;if(m<=0)s=null;else{let f=Y(d,m);f===null?s=null:s+=f}}}return{harnessRoot:r,worktreesDir:t,worktreesBytes:s,runCount:i,workerCount:a,oldestRunAt:u===null?null:new Date(u).toISOString(),scannedAt:o}}$();import{existsSync as ea}from"node:fs";import{homedir as ra}from"node:os";import uo from"node:path";var ta=["/var/tmp/kynver-harness",uo.join(ra(),".openclaw","harness")];function nt(e,r,t){if(!t?.trim())return;let n=P(t.trim());e.has(n)||(e.add(n),r.push(n))}function na(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 lo(e={}){let r=new Set,t=[];nt(r,t,e.harnessRoot??q());let n=process.env.KYNVER_CLEANUP_EXTRA_ROOTS?.split(",").map(o=>o.trim()).filter(Boolean);for(let o of n??[])nt(r,t,o);if(na(e))for(let o of ta){let s=uo.resolve(o);!r.has(s)&&ea(s)&&nt(r,t,s)}return t}$e();function oa(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function sa(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function co(e={}){let r=e.diskPath?.trim()||process.env.KYNVER_DISK_GUARD_PATH?.trim()||"/",t=sa("KYNVER_DISK_GUARD_MAX_USED_PERCENT",75),n=je({...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 po(e,r){if(!r.pressured)return e;let t=e.execute||!oa("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}}Ke();import{unlinkSync as ia}from"node:fs";function cr(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function mo(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function aa(e,r,t){return e.length===0?[]:t?[...e]:e.length<=r?[]:e.slice(r)}function fo(e={}){let r=e.execute===!0||cr("KYNVER_WSL_CRASH_DUMP_EXECUTE")||cr("KYNVER_CLEANUP_EXECUTE"),t=e.purgeAll===!0||cr("KYNVER_WSL_CRASH_DUMP_PURGE_ALL"),n=Math.max(0,e.keepNewest??mo("KYNVER_WSL_CRASH_DUMP_KEEP_NEWEST",t?0:1)),o=de({forceWsl:e.forceWsl});if(!o?.path)return{observation:o,execute:r,keepNewest:n,removed:[],removedBytes:0,skipped:o?.probeError?[{path:o.path??"(unresolved)",reason:o.probeError}]:[]};let s=aa(o.dumps,n,t),i=[],a=[],u=0;for(let l of s){if(!r){a.push({path:l.path,reason:"dry_run"});continue}try{ia(l.path),i.push({path:l.path,bytes:l.bytes,name:l.name}),u+=l.bytes}catch(c){a.push({path:l.path,reason:c.message})}}return{observation:o,execute:r,keepNewest:n,removed:i,removedBytes:u,skipped:a}}function go(e){return e?cr("KYNVER_WSL_CRASH_DUMP_CLEANUP")||!e.ok?!0:e.dumpCount>mo("KYNVER_WSL_CRASH_DUMP_KEEP_NEWEST",1):!1}Ke();function O(e,r){if(process.env.KYNVER_CLEANUP_QUIET==="1")return;let t=r?`: ${r}`:"";console.error(`[kynver cleanup] ${e}${t}`)}K();var dr=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=x(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 ua}from"node:child_process";import{existsSync as la}from"node:fs";import ca from"node:path";var da=5e3;function pa(e,r){if(!la(ca.join(e,".git")))return{status:null,stdout:"",stderr:"",error:"not_a_git_repo"};try{let t=ua("git",r,{cwd:e,encoding:"utf8",timeout:da}),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 ho(e){let r=pa(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 pr=class{cache=new Map;porcelain(r){let t=r,n=this.cache.get(t);if(n!==void 0)return n;let o=ho(t)??[];return this.cache.set(t,o),o}};var mr=class{cache=new Map;derive(r){let t=this.cache.get(r.id);if(t!==void 0)return t;let n=ie(r);return this.cache.set(r.id,n),n}};function ma(e){let r={};for(let t of e)r[t.kind]=(r[t.kind]??0)+1;return r}function ko(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:ma(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 fa(e={}){let r=e.harnessRoot?P(e.harnessRoot):q(),t=lo({harnessRoot:r}),n=e.now??Date.now();return{harnessRoot:r,scanRoots:t,now:n}}function ga(e){return typeof e=="string"?{reason:e}:e}function ke(e,r,t,n){e.push({path:r,reason:t,...n?{detail:n}:{}})}function fr(e,r,t){return!r||e.bytes!=null?e:{...e,bytes:Y(e.path,t)}}function Ro(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 ha(e,r){return e.kind==="remove_next_cache"?Ln(e,r):Fn(e,r)}function ka(e,r,t){return e.kind==="remove_next_cache"?ir(e.path,r,t):sr(e.path,r,t)}function Ra(e){let r=new Map;for(let t of e)for(let[n,o]of to(t))r.set(n,o);return r}function yo(e,r){return e.runId&&e.worker?N.join(r,e.runId,e.worker):N.resolve(e.path,"..")}function ya(e={}){let r=no(e),t=co();r=po(r,t);let n=fa(e);O("scan",`${n.scanRoots.length} harness root(s)`);let o=Sn(n.scanRoots,n.now),s=r.finalizeStaleRuns?tn().map(g=>({runId:g.runId,from:g.from,to:g.to})):[];s.length>0&&O("finalize",`${s.length} stale run(s) marked terminal`),O("index","building worktree index");let i=Ra(n.scanRoots);O("index",`${i.size} indexed worktree(s)`);let a={runTerminalCache:new mr,gitStatusCache:new pr,gitRevCache:new dr},u=[],l=[],c=new Set,d=r.maxActionsPerSweep,m=()=>l.length>=d;for(let g of n.scanRoots){if(m())break;O("root",g);let V=N.join(g,"worktrees"),Ne=ro(i,g),Ie={harnessRoot:g,worktreesDir:V,nodeModulesAgeMs:r.nodeModulesAgeMs,worktreesAgeMs:r.worktreesAgeMs,includeOrphans:r.includeOrphans,runIdFilter:r.runIdFilter,index:Ne,now:n.now},gr=r.scanDependencyCaches?Qn(Ie):[];O("dependency",r.scanDependencyCaches?`${gr.length} cache candidate(s) at ${g}`:"skipped (worktree-only sweep)");let hr=0;for(let I of gr){if(m())break;hr+=1,hr%50===0&&O("dependency",`${hr}/${gr.length} evaluated`);let C=N.resolve(I.path);if(c.has(C))continue;c.add(C);let h={...I,path:C},E=ka(h,g,V);if(E){ke(u,h.path,E),l.push({...h,executed:!1,skipped:!0,skipReason:E});continue}let M=yo(h,V),le=Ne.get(N.resolve(M))??null,U=zr({indexed:le,includeOrphans:!0,nodeModulesAgeMs:r.nodeModulesAgeMs,ageMs:h.ageMs,worktreePath:M,activeWorktreePaths:o.activeWorktreePaths,diskPressure:r.diskPressure,gitStatusCache:a.gitStatusCache});if(U){ke(u,h.path,U),l.push({...h,executed:!1,skipped:!0,skipReason:U});continue}l.push(ha(fr(h,r.accountBytes,r.byteAccountingEntryCap),r.execute))}if(r.scanDependencyCaches)for(let I of Vn(Ie)){if(m())break;let C=N.resolve(I.path);if(c.has(C))continue;c.add(C);let h={...I,path:C},E=ar(h.path,g,V);if(E){ke(u,h.path,E),l.push({...h,executed:!1,skipped:!0,skipReason:E});continue}let M=yo(h,V),le=Ne.get(N.resolve(M))??null,U=kn({indexed:le,includeOrphans:!0,nodeModulesAgeMs:r.nodeModulesAgeMs,ageMs:h.ageMs,worktreePath:M,activeWorktreePaths:o.activeWorktreePaths,diskPressure:r.diskPressure,gitStatusCache:a.gitStatusCache});if(U){ke(u,h.path,U),l.push({...h,executed:!1,skipped:!0,skipReason:U});continue}l.push(Kn(fr(h,r.accountBytes,r.byteAccountingEntryCap),r.execute))}let kr=[...zn(Ie),...eo(Ie)];O("worktrees",`${kr.length} candidate(s) at ${g}`);let ot=new Set,Rr=0;for(let I of kr){if(m())break;Rr+=1,Rr%50===0&&O("worktrees",`${Rr}/${kr.length} evaluated`);let C=N.resolve(I.path);if(ot.has(C))continue;ot.add(C);let h={...I,path:C},E=Ne.get(N.resolve(h.path))??null,M=E?null:so({worktreePath:h.path,harnessRoot:g,runId:h.runId,workerName:h.worker,now:n.now}),le=hn({indexed:E,worktreePath:N.resolve(h.path),includeOrphans:r.includeOrphans,worktreesAgeMs:r.worktreesAgeMs,terminalWorktreesAgeMs:r.terminalWorktreesAgeMs,ageMs:h.ageMs,orphanSafety:M,worktreeRemovalGuard:e.worktreeRemovalGuard,liveness:a,now:n.now,harnessRoot:g,writeSalvageEvidence:r.execute});if(le){let{reason:U,detail:bo}=ga(le);ke(u,h.path,U,bo),l.push({...h,executed:!1,skipped:!0,skipReason:U});continue}l.push($n(fr(h,r.accountBytes,r.byteAccountingEntryCap),r.execute))}if(!m()&&r.runDirectoriesAgeMs>=0)for(let I of En({harnessRoot:g,worktreesDir:V,runDirectoriesAgeMs:r.runDirectoriesAgeMs,runIdFilter:r.runIdFilter,activeGuards:o,now:n.now})){if(m())break;let C=N.resolve(I.path);if(c.has(C))continue;c.add(C);let h={...I,path:C},E=h.runId??N.basename(C),M=An({harnessRoot:g,runId:E,runPath:C,ageMs:h.ageMs,runDirectoriesAgeMs:r.runDirectoriesAgeMs,activeGuards:o});if(M){ke(u,h.path,M),l.push({...h,executed:!1,skipped:!0,skipReason:M});continue}l.push(jn(fr(h,r.accountBytes,r.byteAccountingEntryCap),r.execute))}}let f=0,p=0,y=0,b=0,k=0,w=0;for(let g of l)g.bytes&&(f+=g.bytes),!g.skipped&&!g.executed&&g.bytes&&(y+=g.bytes),g.executed?(k+=1,b+=g.bytes??0,g.kind==="remove_run_directory"&&(p+=1)):g.skipped&&(w+=1,g.skipReason==="dry_run"&&g.bytes&&(y+=g.bytes));let F=r.accountBytes?ao({harnessRoot:n.harnessRoot,now:n.now,perRunEntryCap:r.storagePerRunEntryCap}):void 0,T=de(),Oe=r.execute&&go(T),L=Oe?fo({execute:!0}):null,Q=T?{observed:!0,execute:Oe,dumpCount:T.dumpCount,totalBytes:T.totalBytes,removedCount:L?.removed.length??0,removedBytes:L?.removedBytes??0,executables:T.executables,path:T.path,reason:T.reason}:void 0;L&&L.removed.length>0&&(b+=L.removedBytes,k+=L.removed.length,O("wsl-crashes",`removed ${L.removed.length} dump(s), ${L.removedBytes} bytes`)),O("complete",`${l.length} action(s), ${w} skipped, ${k} removed`);let Z=yn(l,u),A=ko({harnessRoot:n.harnessRoot,scanRoots:n.scanRoots,dryRun:!r.execute,execute:r.execute,nodeModulesAgeMs:r.nodeModulesAgeMs,worktreesAgeMs:r.worktreesAgeMs,includeOrphans:r.includeOrphans,diskPressure:r.diskPressure,diskGate:r.diskGate?{ok:r.diskGate.ok,path:r.diskGate.path,freeBytes:r.diskGate.freeBytes,usedPercent:r.diskGate.usedPercent,reason:r.diskGate.reason}:void 0,scannedAt:new Date(n.now).toISOString(),finalizedRuns:s,actions:l,skips:u,totals:{candidateBytes:f,reclaimableBytes:y,removedBytes:b,removedPaths:k,skippedPaths:w,skipReasons:Ro(l,u)},...F?{storage:F}:{},...Z.length>0?{preservedLivePaths:Z}:{},...p>0?{removedRunDirectories:p}:{},...Q?{wslCrashDumps:Q}:{}});return{harnessRoot:n.harnessRoot,scanRoots:n.scanRoots,dryRun:!r.execute,execute:r.execute,nodeModulesAgeMs:r.nodeModulesAgeMs,worktreesAgeMs:r.worktreesAgeMs,includeOrphans:r.includeOrphans,diskPressure:r.diskPressure,diskGate:r.diskGate?{ok:r.diskGate.ok,path:r.diskGate.path,freeBytes:r.diskGate.freeBytes,usedPercent:r.diskGate.usedPercent,reason:r.diskGate.reason}:void 0,scannedAt:new Date(n.now).toISOString(),finalizedRuns:s,actions:l,skips:u,totals:{candidateBytes:f,reclaimableBytes:y,removedBytes:b,removedPaths:k,skippedPaths:w,skipReasons:Ro(l,u)},...F?{storage:F}:{},...Z.length>0?{preservedLivePaths:Z}:{},...p>0?{removedRunDirectories:p}:{},...Q?{wslCrashDumps:Q}:{},compactSummary:A}}export{or as DEFAULT_MAX_ACTIONS_PER_SWEEP,Jr as DEFAULT_NODE_MODULES_AGE_MS,qr as DEFAULT_RUN_DIRECTORIES_AGE_MS,nr as DEFAULT_WORKTREES_AGE_MS,ya 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 Cn(rr.join(r,"evidence.json"),`${JSON.stringify(o,null,2)}
13
+ `),o}var Ui=new Set(["completion_blocked","dirty_worktree","pr_or_unmerged_commits","landing_blocked"]);function Ti(e){return!Ui.has(e.skipReason)||G(e.indexed,e.now)?!1:An({harnessRoot:e.harnessRoot,runId:e.indexed.runId,workerName:e.indexed.workerName})?!0:e.writeSalvageEvidence?(Pn({harnessRoot:e.harnessRoot,indexed:e.indexed,skipReason:e.skipReason,status:e.status,now:e.now}),!0):!1}function Bi(e){let{indexed:r,includeOrphans:t,worktreesAgeMs:n,terminalWorktreesAgeMs:o}=e;return r?se.has(r.run.status)||e.liveness&&zr(r,e.liveness)||e.liveness&&te(Yr(r,e.liveness))&&!G(r)?o:n:t?o:n}function Fi(e,r){if(e.harnessRoot?.trim())return tr.resolve(e.harnessRoot);let t=r.worker.workerDir;if(!t)return null;let n=`${tr.sep}runs${tr.sep}`,o=t.indexOf(n);return o<0?null:t.slice(0,o+n.length-1)}function Wn(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=Bi(e);if(n<=0&&!t&&u<=0)return"worktrees_disabled";if(u>0&&o<u)return"below_age_threshold";if(G(r,a))return"active_worker";let l=Yr(r,e.liveness),c=Fi(e,r),d=p=>c&&Ti({indexed:r,harnessRoot:c,skipReason:p,status:l,now:a,writeSalvageEvidence:e.writeSalvageEvidence===!0})?null:p;if(xn(r,l)){let p=d("completion_blocked");if(p)return p}if(Gr(r,e.liveness?.gitStatusCache)){let p=d("dirty_worktree");if(p)return p}let m=e.liveness?.gitRevCache?.countAheadOfMain(e.worktreePath);if(m!=null&&m>0){let p=d("pr_or_unmerged_commits");if(p)return p}if(_n(r,e.liveness,a)||!te(l))return"run_still_active";if(Ae(l)){let p=d("pr_or_unmerged_commits");if(p)return p}if(W(l.changedFiles).length>0){let p=d("dirty_worktree");if(p)return p}if(fe({finalResult:l.finalResult,changedFiles:l.changedFiles,gitAncestry:l.gitAncestry,prUrl:oe(l.finalResult)}).blocked){let p=d("landing_blocked");if(p)return p}if(i&&e.worktreePath){let p=i({worktreePath:e.worktreePath,indexed:!!r,runId:r?.runId,worker:r?.workerName});if(p)return p.detail?{reason:p.reason,detail:p.detail}:p.reason}return null}function Jr(e){let{indexed:r,nodeModulesAgeMs:t,ageMs:n,worktreePath:o,activeWorktreePaths:s,diskPressure:i}=e;return!i&&n<t?"below_age_threshold":s.has(tr.resolve(o))||r&&G(r)?"active_worker":r&&Gr(r,e.gitStatusCache)?"dirty_worktree":null}function Dn(e){return Jr(e)}var Xr=216e5,nr=6048e5;var qr=36e5,or=120;var On=new Set(["active_worker","run_still_active","completion_blocked","landing_blocked"]);function Mn(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)On.has(s.reason)&&o(s.path,s.reason,s.detail);for(let s of e)!s.skipped||!s.skipReason||On.has(s.skipReason)&&o(s.path,s.skipReason);return t}import{existsSync as Tn,readdirSync as Bn,statSync as Li}from"node:fs";import Fn from"node:path";ee();$();import Nn from"node:path";S();function Ki(e,r){return er(e,r)}function In(e,r=Date.now()){let t=new Set,n=new Set;for(let o of e){for(let s of Ve(o)){let i=!1;for(let a of Object.keys(s.workers||{})){let u=x(Nn.join(ve(o,s.id),"workers",v(a),"worker.json"),void 0);if(!u?.worktreePath)continue;let l=Nn.resolve(u.worktreePath);Ki(u,r)&&(i=!0,t.add(l))}i&&n.add(`${o}\0${s.id}`)}for(let s of vn(o))n.add(s)}return{activeWorktreePaths:t,liveRunKeys:n}}function Un(e,r,t,n){return t?n.has(`${r}\0${t}`):!1}S();function ji(e,r){try{let t=Li(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function $i(e,r){let t=Fn.join(e,"runs",r,"run.json");return Tn(t)?x(t,null):null}function Hn(e){try{return Bn(e).length===0}catch{return!1}}function Kn(e){let{harnessRoot:r,runId:t,runPath:n,ageMs:o,runDirectoriesAgeMs:s,activeGuards:i}=e;if(Un(n,r,t,i.liveRunKeys)||!Hn(n))return"run_still_active";let a=$i(r,t);return a&&!se.has(a.status)&&!ie(a)?"run_still_active":s>0&&o<s?"below_age_threshold":null}function Ln(e){if(!Tn(e.worktreesDir))return[];let r=[],t;try{t=Bn(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=Fn.join(e.worktreesDir,o);Hn(s)&&r.push({kind:"remove_run_directory",path:s,bytes:null,harnessRoot:e.harnessRoot,runId:o,ageMs:ji(s,e.now)})}return r}L();import{existsSync as Zr,rmSync as Zn}from"node:fs";import{execFileSync as Gi}from"node:child_process";import{existsSync as jn,readdirSync as Yi,statSync as Vi}from"node:fs";import zi from"node:path";var Ji=2500;function Xi(e,r=Ji){if(!jn(e))return 0;try{let n=Gi("du",["-sb",e],{encoding:"utf8",timeout:r,stdio:["ignore","pipe","ignore"]}).trim().split(/\s+/)[0],o=Number(n);return Number.isFinite(o)&&o>=0?o:null}catch{return null}}function Y(e,r=5e4){if(!jn(e))return 0;let t=Xi(e);if(t!==null)return t;let n=0,o=0,s=[e];for(;s.length>0;){let i=s.pop(),a;try{a=Yi(i)}catch{continue}for(let u of a){if(o++>r)return null;let l=zi.join(i,u),c;try{c=Vi(l)}catch{continue}c.isDirectory()?s.push(l):n+=c.size}}return n}import{existsSync as ea,rmSync as ra}from"node:fs";$();import{lstatSync as qi,readdirSync as Qi}from"node:fs";function $n(e){try{let r=qi(e),t=typeof process.getuid=="function"?process.getuid():null,n=typeof process.getgid=="function"?process.getgid():null,o=t!==null&&(r.uid!==t||n!==null&&r.gid!==n);return{uid:r.uid,gid:r.gid,foreign:o}}catch{return null}}function Gn(e,r=32){let t=$n(e);if(!t)return!1;if(t.foreign)return!0;try{let n=Qi(e),o=0;for(let s of n){if(o>=r)break;let i=`${e.replace(/\/$/,"")}/${s}`,a=$n(i);if(o+=1,a?.foreign)return!0}}catch{}return!1}import{spawnSync as Zi}from"node:child_process";import zn from"node:path";import D from"node:path";function Yn(e,r,t,n){let o=D.resolve(e),s=`${D.sep}${n}`,i=o.endsWith(s)?o:null;if(!i)return"path_outside_harness";let a=D.relative(t,i);if(a.startsWith("..")||D.isAbsolute(a))return"path_outside_harness";let u=a.split(D.sep);return u.length<3||u[u.length-1]!==n||!o.startsWith(D.resolve(r))?"path_outside_harness":null}function sr(e,r,t){return Yn(e,r,t,"node_modules")}function ir(e,r,t){return Yn(e,r,t,".next")}function ar(e,r,t){let n=D.resolve(e),o=D.relative(t,n);return o.startsWith("..")||D.isAbsolute(o)||o.split(D.sep).length<3||!n.startsWith(D.resolve(r))?"path_outside_harness":null}function Vn(e,r,t){let n=D.resolve(e);return sr(n,r,t)===null||ir(n,r,t)===null||ar(n,r,t)===null}function Xn(){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 Jn(e){let r=Zi("sudo",["-n",...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{ok:r.status===0,stderr:`${r.stderr??""}${r.stdout??""}`.trim()}}function qn(e,r,t){if(!Vn(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=Jn(["chown","-R",`${n}:${o}`,zn.resolve(e)]);if(s.ok)return{ok:!0,method:"chown_then_rm"};let i=Jn(["rm","-rf",zn.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 Qr="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 ta(e){let r=e?.code;return r==="EACCES"||r==="EPERM"}function Qn(e,r,t={}){if(!ea(e.path))return{executed:!1,skipped:!0,skipReason:"missing_worktree"};if(!r)return{executed:!1,skipped:!0,skipReason:"dry_run"};let n=e.harnessRoot,o=n?he(n):null,i=e.bytes??Y(e.path)??void 0,a=t.removePath??ra,u=t.hasForeignOwnedEntry??Gn;try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i}}catch(l){if(!ta(l)||!n||!o)return{executed:!1,skipped:!0,skipReason:"remove_failed",error:l.message};let c=u(e.path),d=Xn();if(!(d==="force"||d==="auto"&&c))return c?{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${l.message}; ${Qr}`}:{executed:!1,skipped:!0,skipReason:"remove_failed",error:l.message};let f=qn(e.path,n,o);if(f.ok&&f.method==="sudo_rm")return{executed:!0,skipped:!1,bytes:i,privilegedReclaim:!0};if(f.ok)try{return a(e.path,{recursive:!0,force:!0}),{executed:!0,skipped:!1,bytes:i,privilegedReclaim:!0}}catch(p){return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${p.message}; privileged chown succeeded but rm still failed`}}return{executed:!1,skipped:!0,skipReason:"foreign_owner",error:`${l.message}; privileged reclaim failed: ${f.error}; ${Qr}`}}}function et(e){let r=e.harnessRoot;return!r||!Sn(e.path,r)?null:{...e,executed:!1,skipped:!0,skipReason:"run_metadata_protected"}}function rt(e,r){let t=et(e);if(t)return t;let n=Qn(e,r);return{...e,bytes:n.bytes??e.bytes,executed:n.executed,skipped:n.skipped,skipReason:n.skipReason,error:n.error}}function eo(e,r){return rt(e,r)}function ro(e,r){return rt(e,r)}function to(e,r){return rt(e,r)}function no(e,r){let t=et(e);if(t)return t;if(!Zr(e.path))return{...e,executed:!1,skipped:!0,skipReason:"missing_worktree"};if(!r)return{...e,executed:!1,skipped:!0,skipReason:"dry_run"};try{let n=e.bytes??Y(e.path);return Zn(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 oo(e,r){let t=et(e);if(t)return t;if(!Zr(e.path))return{...e,executed:!1,skipped:!0,skipReason:"missing_worktree"};if(!r)return{...e,executed:!1,skipped:!0,skipReason:"dry_run"};let n=e.repo;try{let o=e.bytes??Y(e.path);return n&&Re(n,["worktree","remove","--force",e.path],{allowFailure:!0}),Zr(e.path)&&Zn(e.path,{recursive:!0,force:!0}),{...e,bytes:o,executed:!0,skipped:!1}}catch(o){return{...e,executed:!1,skipped:!0,skipReason:"remove_failed",error:o.message}}}import{existsSync as ur,readdirSync as lr,statSync as na}from"node:fs";import B from"node:path";function tt(e,r){try{let t=na(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function io(e,r){let t=B.relative(r,e);return t===""||!t.startsWith("..")&&!B.isAbsolute(t)}function so(e,r,t,n){let o=[];for(let s of $r){if(s===".next")continue;let i=B.join(e,s);if(!ur(i))continue;let a=B.resolve(i);t.has(a)||io(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:tt(a,r.now)}))}return o}function ao(e){let r=[],t=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||r.push(...so(n.worktreePath,e,t,{runId:n.runId,worker:n.workerName,repo:n.run.repo}));if(!e.includeOrphans||!ur(e.worktreesDir))return r;for(let n of lr(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory())continue;let o=B.join(e.worktreesDir,n.name);for(let s of lr(o,{withFileTypes:!0})){if(!s.isDirectory())continue;let i=B.join(o,s.name);r.push(...so(i,e,t,{runId:n.name,worker:s.name}))}}return r}function uo(e){let r=e.worktreesAgeMs>0||e.includeOrphans,t=e.includeOrphans;if(!r&&!t)return[];let n=[],o=new Set;if(r)for(let i of e.index.values()){if(e.runIdFilter&&i.runId!==e.runIdFilter)continue;let a=i.worktreePath;ur(a)&&(o.has(a)||(o.add(a),n.push({kind:"remove_worktree",path:a,bytes:null,runId:i.runId,worker:i.workerName,repo:i.run.repo,ageMs:tt(a,e.now)})))}if(!t||!ur(e.worktreesDir))return n;let s=new Set;for(let i of e.index.values())s.add(B.resolve(i.worktreePath));for(let i of lr(e.worktreesDir,{withFileTypes:!0})){if(!i.isDirectory()||e.runIdFilter&&i.name!==e.runIdFilter)continue;let a=B.join(e.worktreesDir,i.name),u;try{u=lr(a,{withFileTypes:!0})}catch{continue}for(let l of u){if(!l.isDirectory())continue;let c=B.resolve(B.join(a,l.name));o.has(c)||s.has(c)||io(c,e.harnessRoot)&&(o.add(c),n.push({kind:"remove_worktree",path:c,bytes:null,runId:i.name,worker:l.name,ageMs:tt(c,e.now)}))}}return n}import{existsSync as po,readdirSync as lo,statSync as oa}from"node:fs";import ke from"node:path";var sa=[{dirName:"node_modules",kind:"remove_node_modules"},{dirName:".next",kind:"remove_next_cache"}];function ia(e,r){try{let t=oa(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function aa(e,r){let t=ke.relative(r,e);return t===""||!t.startsWith("..")&&!ke.isAbsolute(t)}function ua(e,r,t,n,o,s){if(!po(n))return;let i=ke.resolve(n);r.has(i)||aa(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:ia(i,t.now)}))}function co(e,r,t,n,o){for(let s of sa)ua(e,r,t,ke.join(n,s.dirName),s.kind,o)}function mo(e){let r=[],t=new Set;for(let n of e.index.values())e.runIdFilter&&n.runId!==e.runIdFilter||co(r,t,e,n.worktreePath,{runId:n.runId,worker:n.workerName,repo:n.run.repo});if(!e.includeOrphans||!po(e.worktreesDir))return r;for(let n of lo(e.worktreesDir,{withFileTypes:!0})){if(!n.isDirectory()||e.runIdFilter&&n.name!==e.runIdFilter)continue;let o=ke.join(e.worktreesDir,n.name),s;try{s=lo(o,{withFileTypes:!0})}catch{continue}for(let i of s){if(!i.isDirectory())continue;let a=ke.join(o,i.name);co(r,t,e,a,{runId:n.name,worker:i.name})}}return r}L();import{existsSync as fo,statSync as la}from"node:fs";import F from"node:path";function ca(e,r){try{let t=la(e).mtimeMs;return Math.max(0,r-t)}catch{return 0}}function da(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 pa(e,r){let t=F.relative(F.resolve(r),F.resolve(e));return t!==""&&!t.startsWith("..")&&!F.isAbsolute(t)}var ma=200;function go(e){if(!e.includeOrphans||!fo(e.worktreesDir))return[];let r=new Set;for(let s of e.index.values())s.run.repo&&r.add(F.resolve(s.run.repo));let t=new Set;for(let s of e.index.values())t.add(F.resolve(s.worktreePath));let n=[],o=new Set;for(let s of r){let i=0,a;try{a=Re(s,["worktree","list","--porcelain"],{allowFailure:!0})}catch{continue}let u=da(a);for(let l of u){if(i>=ma)break;let c=F.resolve(l.path);if(c===F.resolve(s)||!pa(c,e.worktreesDir)||t.has(c)||o.has(c)||!fo(c))continue;let m=F.relative(e.worktreesDir,c).split(F.sep),f=m[0],p=m[1]??"unknown";o.add(c),i+=1,n.push({kind:"remove_worktree",path:c,bytes:null,runId:f,worker:p,repo:s,ageMs:ca(c,e.now)})}}return n}ee();S();import De from"node:path";function ho(e,r){let t=De.resolve(r),n=new Map;for(let[o,s]of e){let i=s.harnessRoot?De.resolve(s.harnessRoot):null;i&&i!==t||n.set(o,s)}return n}function ko(e){let r=new Map;for(let t of Ve(e))for(let n of Object.keys(t.workers||{})){let o=De.join(ve(e,t.id),"workers",v(n),"worker.json"),s=x(o,void 0);s?.worktreePath&&r.set(De.resolve(s.worktreePath),{harnessRoot:e,worktreePath:De.resolve(s.worktreePath),runId:t.id,workerName:n,run:t,worker:s})}return r}function Oe(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function ue(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)&&n>=0?n:r}function yo(e={}){let r=e.execute===!0||e.execute!==!1&&Oe("KYNVER_CLEANUP_EXECUTE"),t=e.finalizeStaleRuns!==!1&&!Oe("KYNVER_CLEANUP_SKIP_FINALIZE"),n=e.nodeModulesAgeMs??ue("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??ue("KYNVER_CLEANUP_WORKTREES_AGE_MS",0),i=e.terminalWorktreesAgeMs??ue("KYNVER_CLEANUP_TERMINAL_WORKTREES_AGE_MS",216e5),a=e.runDirectoriesAgeMs??ue("KYNVER_CLEANUP_RUN_DIRECTORIES_AGE_MS",36e5),u=e.maxActionsPerSweep??ue("KYNVER_CLEANUP_MAX_ACTIONS_PER_SWEEP",120),l=e.includeOrphans===!0||Oe("KYNVER_CLEANUP_INCLUDE_ORPHANS"),d=Oe("KYNVER_CLEANUP_SCOPE_ALL")||process.env.KYNVER_CLEANUP_SCOPE==="all"?e.runIdFilter:e.runIdFilter??(process.env.KYNVER_CLEANUP_RUN_ID||void 0),m=e.accountBytes!==!1&&!Oe("KYNVER_CLEANUP_SKIP_BYTE_ACCOUNTING"),f=ue("KYNVER_CLEANUP_STORAGE_ENTRY_CAP",2e3),p=e.storagePerRunEntryCap!==void 0?e.storagePerRunEntryCap:m&&f>0?f:null,R=ue("KYNVER_CLEANUP_BYTE_ENTRY_CAP",2e3),b=e.byteAccountingEntryCap??(Number.isFinite(R)&&R>0?Math.floor(R):2e3);return{execute:r,finalizeStaleRuns:t,scanDependencyCaches:o,nodeModulesAgeMs:n,worktreesAgeMs:s>0?s:0,terminalWorktreesAgeMs:i>=0?i:0,runDirectoriesAgeMs:a>=0?a:0,maxActionsPerSweep:Number.isFinite(u)&&u>0?Math.floor(u):120,includeOrphans:l,runIdFilter:d?String(d):void 0,accountBytes:m,storagePerRunEntryCap:p,byteAccountingEntryCap:b}}L();import{existsSync as Ro}from"node:fs";import nt from"node:path";S();var ga=1800*1e3;function bo(e){let r=e.now??Date.now(),t=e.heartbeatFreshMs??ga;if(!Ro(e.worktreePath))return null;if(e.runId&&e.workerName){let l=nt.join(e.harnessRoot,"runs",e.runId,"workers",e.workerName),c=x(nt.join(l,"worker.json"),void 0);if(c&&Vr(c,r,t))return"active_worker"}let n=nt.join(e.worktreePath,".git");if(!Ro(n))return null;let o=C(e.worktreePath,["status","--porcelain"]);if(o.status!==0)return"pr_or_unmerged_commits";let s=o.stdout.split(`
15
+ `).map(l=>l.trim()).filter(l=>l.length>0);if(W(s).length>0)return"dirty_worktree";let i=C(e.worktreePath,["rev-list","--count","@{u}..HEAD"]);if(i.status===0){let l=Number(i.stdout.trim());if(Number.isFinite(l)&&l>0)return"pr_or_unmerged_commits"}let a=C(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}$();import{existsSync as ha,readdirSync as So,statSync as ka}from"node:fs";import ya from"node:path";function vo(e={}){let r=P(e.harnessRoot??X()),t=he(r),n=e.now??Date.now(),o=new Date(n).toISOString();if(!ha(t))return{harnessRoot:r,worktreesDir:t,worktreesBytes:0,runCount:0,workerCount:0,oldestRunAt:null,scannedAt:o};let s=0,i=0,a=0,u=null,l;try{l=So(t,{withFileTypes:!0})}catch{return{harnessRoot:r,worktreesDir:t,worktreesBytes:null,runCount:0,workerCount:0,oldestRunAt:null,scannedAt:o}}for(let c of l){if(!c.isDirectory())continue;i+=1;let d=ya.join(t,c.name);try{let m=ka(d);u=u===null?m.mtimeMs:Math.min(u,m.mtimeMs)}catch{}try{for(let m of So(d,{withFileTypes:!0}))m.isDirectory()&&(a+=1)}catch{}if(s!==null&&e.perRunEntryCap!==null){let m=e.perRunEntryCap??5e4;if(m<=0)s=null;else{let f=Y(d,m);f===null?s=null:s+=f}}}return{harnessRoot:r,worktreesDir:t,worktreesBytes:s,runCount:i,workerCount:a,oldestRunAt:u===null?null:new Date(u).toISOString(),scannedAt:o}}$();import{existsSync as Ra}from"node:fs";import{homedir as ba}from"node:os";import _o from"node:path";var Sa=["/var/tmp/kynver-harness",_o.join(ba(),".openclaw","harness")];function ot(e,r,t){if(!t?.trim())return;let n=P(t.trim());e.has(n)||(e.add(n),r.push(n))}function va(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 xo(e={}){let r=new Set,t=[];ot(r,t,e.harnessRoot??X());let n=process.env.KYNVER_CLEANUP_EXTRA_ROOTS?.split(",").map(o=>o.trim()).filter(Boolean);for(let o of n??[])ot(r,t,o);if(va(e))for(let o of Sa){let s=_o.resolve(o);!r.has(s)&&Ra(s)&&ot(r,t,s)}return t}Ge();function _a(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function xa(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function Co(e={}){let r=e.diskPath?.trim()||process.env.KYNVER_DISK_GUARD_PATH?.trim()||"/",t=xa("KYNVER_DISK_GUARD_MAX_USED_PERCENT",75),n=$e({...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 wo(e,r){if(!r.pressured)return e;let t=e.execute||!_a("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}}je();import{unlinkSync as Ca}from"node:fs";function cr(e){let r=process.env[e];return r==="1"||r==="true"||r==="yes"}function Eo(e,r){let t=process.env[e];if(!t)return r;let n=Number(t);return Number.isFinite(n)?n:r}function wa(e,r,t){return e.length===0?[]:t?[...e]:e.length<=r?[]:e.slice(r)}function Ao(e={}){let r=e.execute===!0||cr("KYNVER_WSL_CRASH_DUMP_EXECUTE")||cr("KYNVER_CLEANUP_EXECUTE"),t=e.purgeAll===!0||cr("KYNVER_WSL_CRASH_DUMP_PURGE_ALL"),n=Math.max(0,e.keepNewest??Eo("KYNVER_WSL_CRASH_DUMP_KEEP_NEWEST",t?0:1)),o=pe({forceWsl:e.forceWsl});if(!o?.path)return{observation:o,execute:r,keepNewest:n,removed:[],removedBytes:0,skipped:o?.probeError?[{path:o.path??"(unresolved)",reason:o.probeError}]:[]};let s=wa(o.dumps,n,t),i=[],a=[],u=0;for(let l of s){if(!r){a.push({path:l.path,reason:"dry_run"});continue}try{Ca(l.path),i.push({path:l.path,bytes:l.bytes,name:l.name}),u+=l.bytes}catch(c){a.push({path:l.path,reason:c.message})}}return{observation:o,execute:r,keepNewest:n,removed:i,removedBytes:u,skipped:a}}function Po(e){return e?cr("KYNVER_WSL_CRASH_DUMP_CLEANUP")||!e.ok?!0:e.dumpCount>Eo("KYNVER_WSL_CRASH_DUMP_KEEP_NEWEST",1):!1}je();function O(e,r){if(process.env.KYNVER_CLEANUP_QUIET==="1")return;let t=r?`: ${r}`:"";console.error(`[kynver cleanup] ${e}${t}`)}L();var dr=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=C(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 Ea}from"node:child_process";import{existsSync as Aa}from"node:fs";import Pa from"node:path";var Wa=5e3;function Da(e,r){if(!Aa(Pa.join(e,".git")))return{status:null,stdout:"",stderr:"",error:"not_a_git_repo"};try{let t=Ea("git",r,{cwd:e,encoding:"utf8",timeout:Wa}),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 Wo(e){let r=Da(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 pr=class{cache=new Map;porcelain(r){let t=r,n=this.cache.get(t);if(n!==void 0)return n;let o=Wo(t)??[];return this.cache.set(t,o),o}};var mr=class{cache=new Map;derive(r){let t=this.cache.get(r.id);if(t!==void 0)return t;let n=ie(r);return this.cache.set(r.id,n),n}};function Oa(e){let r={};for(let t of e)r[t.kind]=(r[t.kind]??0)+1;return r}function Do(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:Oa(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 Ma(e={}){let r=e.harnessRoot?P(e.harnessRoot):X(),t=xo({harnessRoot:r}),n=e.now??Date.now();return{harnessRoot:r,scanRoots:t,now:n}}function Na(e){return typeof e=="string"?{reason:e}:e}function ye(e,r,t,n){e.push({path:r,reason:t,...n?{detail:n}:{}})}function fr(e,r,t){return!r||e.bytes!=null?e:{...e,bytes:Y(e.path,t)}}function Oo(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 Ia(e,r){return e.kind==="remove_next_cache"?ro(e,r):eo(e,r)}function Ua(e,r,t){return e.kind==="remove_next_cache"?ir(e.path,r,t):sr(e.path,r,t)}function Ta(e){let r=new Map;for(let t of e)for(let[n,o]of ko(t))r.set(n,o);return r}function Mo(e,r){return e.runId&&e.worker?M.join(r,e.runId,e.worker):M.resolve(e.path,"..")}function Ba(e={}){let r=yo(e),t=Co();r=wo(r,t);let n=Ma(e);O("scan",`${n.scanRoots.length} harness root(s)`);let o=In(n.scanRoots,n.now),s=r.finalizeStaleRuns?kn().map(h=>({runId:h.runId,from:h.from,to:h.to})):[];s.length>0&&O("finalize",`${s.length} stale run(s) marked terminal`),O("index","building worktree index");let i=Ta(n.scanRoots);O("index",`${i.size} indexed worktree(s)`);let a={runTerminalCache:new mr,gitStatusCache:new pr,gitRevCache:new dr},u=[],l=[],c=new Set,d=r.maxActionsPerSweep,m=()=>l.length>=d;for(let h of n.scanRoots){if(m())break;O("root",h);let V=M.join(h,"worktrees"),Ne=ho(i,h),Ie={harnessRoot:h,worktreesDir:V,nodeModulesAgeMs:r.nodeModulesAgeMs,worktreesAgeMs:r.worktreesAgeMs,includeOrphans:r.includeOrphans,runIdFilter:r.runIdFilter,index:Ne,now:n.now},gr=r.scanDependencyCaches?mo(Ie):[];O("dependency",r.scanDependencyCaches?`${gr.length} cache candidate(s) at ${h}`:"skipped (worktree-only sweep)");let hr=0;for(let N of gr){if(m())break;hr+=1,hr%50===0&&O("dependency",`${hr}/${gr.length} evaluated`);let _=M.resolve(N.path);if(c.has(_))continue;c.add(_);let k={...N,path:_},A=Ua(k,h,V);if(A){ye(u,k.path,A),l.push({...k,executed:!1,skipped:!0,skipReason:A});continue}let I=Mo(k,V),le=Ne.get(M.resolve(I))??null,T=Jr({indexed:le,includeOrphans:!0,nodeModulesAgeMs:r.nodeModulesAgeMs,ageMs:k.ageMs,worktreePath:I,activeWorktreePaths:o.activeWorktreePaths,diskPressure:r.diskPressure,gitStatusCache:a.gitStatusCache});if(T){ye(u,k.path,T),l.push({...k,executed:!1,skipped:!0,skipReason:T});continue}l.push(Ia(fr(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}if(r.scanDependencyCaches)for(let N of ao(Ie)){if(m())break;let _=M.resolve(N.path);if(c.has(_))continue;c.add(_);let k={...N,path:_},A=ar(k.path,h,V);if(A){ye(u,k.path,A),l.push({...k,executed:!1,skipped:!0,skipReason:A});continue}let I=Mo(k,V),le=Ne.get(M.resolve(I))??null,T=Dn({indexed:le,includeOrphans:!0,nodeModulesAgeMs:r.nodeModulesAgeMs,ageMs:k.ageMs,worktreePath:I,activeWorktreePaths:o.activeWorktreePaths,diskPressure:r.diskPressure,gitStatusCache:a.gitStatusCache});if(T){ye(u,k.path,T),l.push({...k,executed:!1,skipped:!0,skipReason:T});continue}l.push(to(fr(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}let kr=[...uo(Ie),...go(Ie)];O("worktrees",`${kr.length} candidate(s) at ${h}`);let st=new Set,yr=0;for(let N of kr){if(m())break;yr+=1,yr%50===0&&O("worktrees",`${yr}/${kr.length} evaluated`);let _=M.resolve(N.path);if(st.has(_))continue;st.add(_);let k={...N,path:_},A=Ne.get(M.resolve(k.path))??null,I=A?null:bo({worktreePath:k.path,harnessRoot:h,runId:k.runId,workerName:k.worker,now:n.now}),le=Wn({indexed:A,worktreePath:M.resolve(k.path),includeOrphans:r.includeOrphans,worktreesAgeMs:r.worktreesAgeMs,terminalWorktreesAgeMs:r.terminalWorktreesAgeMs,ageMs:k.ageMs,orphanSafety:I,worktreeRemovalGuard:e.worktreeRemovalGuard,liveness:a,now:n.now,harnessRoot:h,writeSalvageEvidence:r.execute});if(le){let{reason:T,detail:No}=Na(le);ye(u,k.path,T,No),l.push({...k,executed:!1,skipped:!0,skipReason:T});continue}l.push(oo(fr(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}if(!m()&&r.runDirectoriesAgeMs>=0)for(let N of Ln({harnessRoot:h,worktreesDir:V,runDirectoriesAgeMs:r.runDirectoriesAgeMs,runIdFilter:r.runIdFilter,activeGuards:o,now:n.now})){if(m())break;let _=M.resolve(N.path);if(c.has(_))continue;c.add(_);let k={...N,path:_},A=k.runId??M.basename(_),I=Kn({harnessRoot:h,runId:A,runPath:_,ageMs:k.ageMs,runDirectoriesAgeMs:r.runDirectoriesAgeMs,activeGuards:o});if(I){ye(u,k.path,I),l.push({...k,executed:!1,skipped:!0,skipReason:I});continue}l.push(no(fr(k,r.accountBytes,r.byteAccountingEntryCap),r.execute))}}let f=0,p=0,R=0,b=0,y=0,w=0;for(let h of l)h.bytes&&(f+=h.bytes),!h.skipped&&!h.executed&&h.bytes&&(R+=h.bytes),h.executed?(y+=1,b+=h.bytes??0,h.kind==="remove_run_directory"&&(p+=1)):h.skipped&&(w+=1,h.skipReason==="dry_run"&&h.bytes&&(R+=h.bytes));let H=r.accountBytes?vo({harnessRoot:n.harnessRoot,now:n.now,perRunEntryCap:r.storagePerRunEntryCap}):void 0,U=pe(),Me=r.execute&&Po(U),K=Me?Ao({execute:!0}):null,Q=U?{observed:!0,execute:Me,dumpCount:U.dumpCount,totalBytes:U.totalBytes,removedCount:K?.removed.length??0,removedBytes:K?.removedBytes??0,executables:U.executables,path:U.path,reason:U.reason}:void 0;K&&K.removed.length>0&&(b+=K.removedBytes,y+=K.removed.length,O("wsl-crashes",`removed ${K.removed.length} dump(s), ${K.removedBytes} bytes`)),O("complete",`${l.length} action(s), ${w} skipped, ${y} removed`);let Z=Mn(l,u),E=Do({harnessRoot:n.harnessRoot,scanRoots:n.scanRoots,dryRun:!r.execute,execute:r.execute,nodeModulesAgeMs:r.nodeModulesAgeMs,worktreesAgeMs:r.worktreesAgeMs,includeOrphans:r.includeOrphans,diskPressure:r.diskPressure,diskGate:r.diskGate?{ok:r.diskGate.ok,path:r.diskGate.path,freeBytes:r.diskGate.freeBytes,usedPercent:r.diskGate.usedPercent,reason:r.diskGate.reason}:void 0,scannedAt:new Date(n.now).toISOString(),finalizedRuns:s,actions:l,skips:u,totals:{candidateBytes:f,reclaimableBytes:R,removedBytes:b,removedPaths:y,skippedPaths:w,skipReasons:Oo(l,u)},...H?{storage:H}:{},...Z.length>0?{preservedLivePaths:Z}:{},...p>0?{removedRunDirectories:p}:{},...Q?{wslCrashDumps:Q}:{}});return{harnessRoot:n.harnessRoot,scanRoots:n.scanRoots,dryRun:!r.execute,execute:r.execute,nodeModulesAgeMs:r.nodeModulesAgeMs,worktreesAgeMs:r.worktreesAgeMs,includeOrphans:r.includeOrphans,diskPressure:r.diskPressure,diskGate:r.diskGate?{ok:r.diskGate.ok,path:r.diskGate.path,freeBytes:r.diskGate.freeBytes,usedPercent:r.diskGate.usedPercent,reason:r.diskGate.reason}:void 0,scannedAt:new Date(n.now).toISOString(),finalizedRuns:s,actions:l,skips:u,totals:{candidateBytes:f,reclaimableBytes:R,removedBytes:b,removedPaths:y,skippedPaths:w,skipReasons:Oo(l,u)},...H?{storage:H}:{},...Z.length>0?{preservedLivePaths:Z}:{},...p>0?{removedRunDirectories:p}:{},...Q?{wslCrashDumps:Q}:{},compactSummary:E}}export{or as DEFAULT_MAX_ACTIONS_PER_SWEEP,Xr as DEFAULT_NODE_MODULES_AGE_MS,qr as DEFAULT_RUN_DIRECTORIES_AGE_MS,nr as DEFAULT_WORKTREES_AGE_MS,Ba as runHarnessCleanup};