@kynver-app/runtime 0.2.93 → 0.2.96

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,7 +1,7 @@
1
- var a=(e,r,t)=>()=>{if(t)throw t[0];try{return e&&(r=e(e=0)),r}catch(n){throw t=[n],n}};import{homedir as Tr}from"node:os";import Nr from"node:path";function Cn(e){return e==="~"?Tr():e.startsWith("~/")||e.startsWith("~\\")?Nr.join(Tr(),e.slice(2)):e}function K(e){return Nr.resolve(Cn(e))}var V=a(()=>{"use strict"});var Pr=a(()=>{"use strict"});import{existsSync as ri,mkdirSync as An,readFileSync as wn,readdirSync as ti,renameSync as On,rmSync as In,statSync as ni,writeFileSync as Tn}from"node:fs";import{randomBytes as Nn}from"node:crypto";import Pn from"node:path";function Le(e){console.error(e),process.exit(1)}function Q(e,r){try{return JSON.parse(wn(e,"utf8"))}catch(t){if(arguments.length>1)return r;Le(`failed to read ${e}: ${t.message}`)}}function oe(e,r){An(Pn.dirname(e),{recursive:!0});let t=`${e}.${process.pid}.${Nn(4).toString("hex")}.tmp`;try{Tn(t,`${JSON.stringify(r,null,2)}
2
- `),On(t,e)}catch(n){try{In(t,{force:!0})}catch{}throw n}}function se(e){return String(e).replace(/\/+$/,"")}var k=a(()=>{"use strict";Pr()});var Dn,li,Ln,ci,Dr=a(()=>{"use strict";Dn=["ANTHROPIC_API_KEY","ANALYST_API_KEY","RECRUITER_API_KEY","AUTH_SECRET","NEXTAUTH_SECRET","DATABASE_URL","PRODUCTION_DATABASE_URL","KYNVER_PRODUCTION_DATABASE_URL","REDIS_URL","GOOGLE_CLIENT_SECRET","GITHUB_CLIENT_SECRET","KYNVER_API_KEY","KYNVER_SERVICE_SECRET","KYNVER_RUNTIME_SECRET","KYNVER_CRON_SECRET","OPENCLAW_CRON_SECRET","QSTASH_TOKEN","QSTASH_CURRENT_SIGNING_KEY","QSTASH_NEXT_SIGNING_KEY","TOOL_SECRETS_KEK","TOOL_EXECUTOR_DISPATCH_SECRET","CLOUDFLARE_API_TOKEN","STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_IDENTITY_WEBHOOK_SECRET","VOYAGE_API_KEY","PERPLEXITY_API_KEY","FRED_API_KEY","FMP_API_KEY","CURSOR_API_KEY","MEMORY_CONTENT_KEK","LLM_BYOK_KEK","KYNVER_COMMAND_AUTH_KEY","KYNVER_INSTRUCTION_BUNDLE_KEY","KYNVER_MEMORY_LEDGER_KEY","KYNVER_JWKS_PRIVATE_KEY_JWK"],li=new Set(Dn),Ln=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY","GEMINI_API_KEY"],ci=new Set(Ln)});var ie=a(()=>{"use strict";V();k();Dr()});var Lr=a(()=>{"use strict";ie()});var Me=a(()=>{"use strict";ie();V();Lr()});function Fr(e){let r=se(e);try{let t=new URL(r);return t.hostname.toLowerCase()===Mr?(t.hostname=`www.${Mr}`,se(t.toString())):r}catch{return r}}function Ke(e){if(e?.trim())return Fr(se(e.trim()))}async function ae(e,r,t=fetch){let n=Fr(e),o=new Headers(r?.headers),s=0;for(;s<=Kr;){let i=await t(n,{...r,headers:o,redirect:"manual"});if(![301,302,303,307,308].includes(i.status))return i;let l=i.headers.get("location");if(!l)return i;let u=new URL(l,n);if(u.origin!==new URL(n).origin||u.username||u.password)throw await i.body?.cancel(),new Error("kynver API fetch refused unsafe redirect (origin change or embedded credentials)");let c=(r?.method??"GET").toUpperCase();if(!["GET","HEAD"].includes(c)&&i.status!==307&&i.status!==308)return i;await i.body?.cancel(),n=u.toString(),s+=1}throw new Error(`kynver API fetch exceeded ${Kr} redirects for ${e}`)}var Mr,Kr,le=a(()=>{"use strict";k();Mr="kynver.com";Kr=10});function F(e){let r=(e??"").trim().toLowerCase();return r==="ghost"||r==="forge"||r==="box"?r:r.includes("forge")?"forge":r.includes("ghost")||r.includes("openclaw")?"ghost":"box"}function ce(e,r){return e[r]?.trim()||null}function Ur(e){let r=e?.split(":")[0]?.trim();return r?F(r):null}function G(e=process.env,r={}){let t=[],n=Ur(r.boxId),o=Ur(ce(e,"KYNVER_BOX_ID")),s=r.boxKind?.trim();if(s)return n&&n!==F(s)&&t.push(`config.boxId=${r.boxId} conflicts with boxKind=${s}; using explicit boxKind=${s}`),{boxKind:F(s),source:"config",slugInferenceBlocked:!1,warnings:t};let i=ce(e,"KYNVER_BOX_KIND");if(i)return o&&o!==F(i)&&t.push(`KYNVER_BOX_ID=${ce(e,"KYNVER_BOX_ID")} conflicts with KYNVER_BOX_KIND=${i}; using explicit KYNVER_BOX_KIND=${i}`),{boxKind:F(i),source:"env",slugInferenceBlocked:!1,warnings:t};if(n)return{boxKind:n,source:"config",slugInferenceBlocked:!1,warnings:t};if(o)return{boxKind:o,source:"env",slugInferenceBlocked:!1,warnings:t};let l=ce(e,"KYNVER_AGENT_OS_SLUG");return l&&t.push(`KYNVER_AGENT_OS_SLUG=${l} is a workspace slug, not box identity \u2014 operators set boxKind via \`kynver setup --box-kind forge|ghost\` or KYNVER_BOX_KIND; customers default to box`),{boxKind:"box",source:"default",slugInferenceBlocked:!!l,warnings:t}}var M=a(()=>{"use strict"});function Fe(e,r){return e==="forge"?4:Math.max(1,r)}function ue(e,r){return e==="forge"?Math.min(Math.max(1,r),4):Math.max(1,r)}var de=a(()=>{"use strict"});var Br=a(()=>{"use strict"});var Ii,Ti,Ue=a(()=>{"use strict";Ii=25*1024*1024*1024,Ti=12*1024*1024*1024});var Mi,Ki,Wr=a(()=>{"use strict";Ue();Mi=5*1024*1024*1024,Ki=10*1024*1024*1024});var Hi,ji,Be=a(()=>{"use strict";Wr();Ue();Hi=30*1024*1024*1024,ji=15*1024*1024*1024});function $r(){return jr()}var pe=a(()=>{"use strict";$e();k()});var Yr=a(()=>{"use strict";pe();k()});var Vr=a(()=>{"use strict"});var Gr=a(()=>{"use strict";Vr();k()});var qr=a(()=>{"use strict"});var Jr=a(()=>{"use strict";qr()});var me=a(()=>{"use strict"});var zr=a(()=>{"use strict";Jr();k();me()});var Xr=a(()=>{"use strict";me()});var Qr=a(()=>{"use strict"});var Zr=a(()=>{"use strict"});var He=a(()=>{"use strict"});var et=a(()=>{"use strict"});var rt=a(()=>{"use strict";He();et()});var tt=a(()=>{"use strict";Gr();zr();me();Xr();Qr();ie();Zr();rt();He();k()});var nt=a(()=>{"use strict";tt()});function ot(e,r={}){let t=r.perWorkerMemBytes??je,n=r.memReserveBytes??Ye,o=r.memUtilization??Ve,s=Math.max(0,Math.floor(e*o)-n),i=Math.max(1,Math.floor(s/t));return Math.min(i,fe)}var je,Ye,Ve,fe,st=a(()=>{"use strict";Br();I();M();de();ge();Be();pe();Yr();nt();k();je=500*1024*1024,Ye=4*1024*1024*1024,Ve=.85,fe=64});function Z(e,r){let t=Number(e);return!Number.isFinite(t)||t<=0?r:Math.floor(t)}function Ge(e){let r=e.config??{},t=e.env??process.env,n=Z(r.perWorkerMemBytes,je),o=Z(r.memReserveBytes,Ye),s=Math.min(1,Math.max(.1,Number(r.memUtilization)>0?Number(r.memUtilization):Ve)),i=ot(e.totalMemBytes,{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s});if(e.configuredMaxWorkersOverride!==void 0&&e.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:Z(e.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(r.maxConcurrentWorkers!==void 0&&r.maxConcurrentWorkers!==null){let c=Z(r.maxConcurrentWorkers,0)||null;if(c)return{configuredMaxWorkers:Math.min(c,fe),autoCap:i,workerCapSource:"config"}}let u=(t.KYNVER_MAX_WORKERS_INTENTIONAL==="1"||t.KYNVER_MAX_WORKERS_INTENTIONAL==="true")&&t.KYNVER_MAX_WORKERS&&Z(t.KYNVER_MAX_WORKERS,0)||null;return u?{configuredMaxWorkers:Math.min(u,fe),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var ge=a(()=>{"use strict";st()});import{homedir as jn}from"node:os";import Yn from"node:path";var it,qe=a(()=>{"use strict";it=Yn.join(jn(),".kynver",".env")});var at=a(()=>{"use strict"});var lt=a(()=>{"use strict";at()});var ct=a(()=>{"use strict"});var ut=a(()=>{"use strict";k()});var Je=a(()=>{"use strict";lt();ct();ut()});var dt=a(()=>{"use strict"});var pt=a(()=>{"use strict";dt()});var he=a(()=>{"use strict";qe();V();I();Je();pt()});var mt=a(()=>{"use strict";M();M()});var ft=a(()=>{"use strict";qe();Je();he()});function yt(e){if(!ht)return e;if(!gt)throw new ze;return gt}function Qe(){if(ht)throw new Xe}var ze,Xe,ht,gt,Ze=a(()=>{"use strict";ze=class extends Error{constructor(){super("desktop credential provider is not installed; refusing to fall back to file or env credentials"),this.name="DesktopCredentialProviderMissingError"}},Xe=class extends Error{constructor(){super("the credentials file is disabled in desktop mode"),this.name="LegacyCredentialStoreDisabledError"}},ht=!1,gt=null});import{existsSync as T,mkdirSync as Jn,readdirSync as ye,renameSync as Rt,statSync as zn}from"node:fs";import N from"node:path";function bt(e){try{return zn(e).isDirectory()}catch{return!1}}function Xn(e){if(!T(e))return!0;for(let r of St){let t=N.join(e,r);if(T(t)&&(!bt(t)||ye(t).length>0))return!1}return!0}function Qn(e){let r=N.join(e,"runs");if(!T(r)||!bt(r))return!1;for(let t of ye(r,{withFileTypes:!0})){if(!t.isDirectory()||t.name==="runs")continue;let n=N.join(r,t.name,"run.json");if(Q(n,void 0)?.id)return!0}return!1}function Zn(e){let r=N.join(e,"runs");if(!T(r))return!1;for(let t of ye(r,{withFileTypes:!0})){if(!t.isDirectory())continue;if(Q(N.join(r,t.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function eo(e){let r=N.join(e,"ghost");return T(r)?!T(N.join(r,"runs")):Zn(e)}function kt(e){return Qn(e.sharedRoot)?Xn(e.forgeRoot)?eo(e.sharedRoot)?{action:"blocked",blocker:"Forge legacy harness migration blocked: Ghost pool is co-hosted on this host (ghost namespace or ghost-attributed runs under ~/.kynver/harness). Drain in-flight Ghost runs from the shared root, or get operator sign-off for a fresh Forge cutover before enabling box-scoped isolation."}:{action:"migrate"}:{action:"none"}:{action:"none"}}function vt(e,r){Jn(r,{recursive:!0});for(let t of St){let n=N.join(e,t),o=N.join(r,t);if(T(n)){if(T(o)&&ye(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(T(o)){Rt(n,o);continue}Rt(n,o)}}}var St,xt=a(()=>{"use strict";k();St=["runs","worktrees"]});import{existsSync as b}from"node:fs";import{homedir as ro}from"node:os";import S from"node:path";function er(e=process.env){return e.HOME?.trim()||ro()}function rr(e=process.env){return S.join(er(e),".kynver","harness")}function Re(e){let r=S.resolve(K(e.trim()));for(;to.has(S.basename(r));)r=S.dirname(r);return r}function no(e,r=process.env){return S.join(rr(r),e)}function oo(e=process.env){let r=rr(e);if(b(S.join(r,"runs")))return!0;if(b(r)&&!b(S.join(r,"ghost"))&&!b(S.join(r,"forge")))return b(r);let t=S.join(er(e),_t);return b(t)}function Se(e){let r=e.env??process.env,t=r.KYNVER_HARNESS_ROOT?.trim()||r.OPUS_HARNESS_ROOT?.trim();if(t)return{harnessRoot:Re(t),source:"env"};let n=e.configuredHarnessRoot?.trim();if(n)return{harnessRoot:Re(n),source:"config"};let o=no(e.boxKind,r);if(b(S.join(o,"runs"))||b(o)&&!so(o))return{harnessRoot:o,source:"box_scoped"};let i=rr(r);if(e.boxKind==="forge"){let l=kt({sharedRoot:i,forgeRoot:o});if(l.action==="blocked")return{harnessRoot:o,source:"box_scoped",migrationBlocker:l.blocker};if(l.action==="migrate")return e.allowForgeLegacyMigration!==!1&&vt(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(e.boxKind==="ghost"&&oo(r)){if(b(S.join(i,"runs")))return{harnessRoot:i,source:"legacy_shared"};if(b(i)&&!b(S.join(i,"ghost"))&&!b(S.join(i,"forge")))return{harnessRoot:i,source:"legacy_shared"};let u=S.join(er(r),_t);if(b(u))return{harnessRoot:u,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function so(e){if(!b(e))return!0;for(let r of["runs","worktrees"]){let t=S.join(e,r);if(b(t))return!1}return!0}var _t,to,tr=a(()=>{"use strict";V();xt();_t=S.join(".openclaw","harness");to=new Set(["runs","worktrees"])});import Et from"node:os";function be(e){return e?.trim()?e.trim():null}function io(e,r){let t=r.trim().toLowerCase()||"host";return`${e}-${t}`.replace(/[^a-z0-9._-]+/g,"-")}function ao(e){return e.KYNVER_DISPATCH_STRICT_IDENTITY==="1"||e.KYNVER_DISPATCH_STRICT_IDENTITY==="true"||e.KYNVER_DAEMON_STRICT_IDENTITY==="1"||e.KYNVER_DAEMON_STRICT_IDENTITY==="true"}function ke(e=_(),r=process.env,t={}){let n=G(r,e),o=[...n.warnings],s=[],i=!!(e.boxKind?.trim()||be(r.KYNVER_BOX_KIND)),l=t.strict===!0||ao(r);if((t.requireExplicitBoxKind||l)&&!i&&s.push("boxKind is not persisted in ~/.kynver/config.json and KYNVER_BOX_KIND is unset \u2014 run `kynver setup` (customers: boxKind=box) or `kynver setup --box-kind forge|ghost` for operator pools before dispatch"),n.slugInferenceBlocked&&!i){let H="ambiguous box identity: KYNVER_AGENT_OS_SLUG is set without KYNVER_BOX_KIND or config.boxKind";l||t.requireExplicitBoxKind?s.push(H):o.push(`${H} \u2014 defaulting box kind to box (customer), not forge/ghost`)}let u=be(e.runnerId),c=be(r.KYNVER_RUNTIME_ID)??be(r.OPENCLAW_RUNTIME_ID),p=u??c??io(n.boxKind,Et.hostname()),m=u?"config":c?"env":"derived";m==="derived"&&o.push(`runnerId not persisted \u2014 using derived id "${p}"; run \`kynver setup --box-kind ${n.boxKind}\` to persist runner identity`);let d=Ge({config:e,env:r,totalMemBytes:Et.totalmem()}),$=ue(n.boxKind,d.configuredMaxWorkers??Fe(n.boxKind,d.autoCap)),v=Se({boxKind:n.boxKind,configuredHarnessRoot:e.harnessRoot,env:r});return v.migrationBlocker&&s.push(v.migrationBlocker),s.length>0?{ok:!1,identity:null,errors:s,warnings:o}:{ok:!0,identity:{boxKind:n.boxKind,boxKindSource:n.source,runnerId:p,runnerIdSource:m,maxConcurrentWorkers:$,workerCapSource:d.workerCapSource,harnessRoot:v.harnessRoot,harnessRootSource:v.source},errors:s,warnings:o}}var ve=a(()=>{"use strict";I();M();de();ge();tr()});var Ct=a(()=>{"use strict";Me();M();mt();I();he();ft();le();Ze();ve()});var uo,Hc,At=a(()=>{"use strict";uo=["claude","cursor","codex","gemini","gemini-api","openai-compatible"],Hc=uo.join("|")});import{existsSync as It,mkdirSync as po,readFileSync as Tt,writeFileSync as mo}from"node:fs";import{homedir as fo,totalmem as Zc}from"node:os";import or from"node:path";function go(e){return{...e,...e.harnessRoot?.trim()?{harnessRoot:K(e.harnessRoot.trim())}:{},...e.defaultRepo?.trim()?{defaultRepo:K(e.defaultRepo.trim())}:{}}}function _(){if(!It(wt))return{};try{return go(JSON.parse(Tt(wt,"utf8")))}catch{return{}}}function xe(){if(Qe(),!It(nr))return{};try{return JSON.parse(Tt(nr,"utf8"))}catch{return{}}}function Ot(e){Qe(),po(sr,{recursive:!0}),mo(nr,`${JSON.stringify(e,null,2)}
3
- `,{mode:384})}function Nt(){return yt(ho)}function Pt(){return Nt().getApiKey()}function yo(e,r){Nt().persistRunnerToken(e,r)}function Ro(e){let r=Dt(e);return r||bo("requires --base-url, KYNVER_API_URL, KYNVER_CRON_FIRE_BASE_URL, or ~/.kynver/config.json apiBaseUrl"),r}function Dt(e){let r=e||process.env.KYNVER_API_URL||process.env.KYNVER_CRON_FIRE_BASE_URL||process.env.OPENCLAW_CRON_FIRE_BASE_URL||_().apiBaseUrl;return Ke(r)}async function Lt(e,r,t){let n=Pt(),o=Dt(t?.baseUrl);if(!n)return{ok:!1,reason:"KYNVER_API_KEY is required to refresh a rejected runner token"};if(!r)return{ok:!1,reason:"agentOsId is required to refresh a rejected runner token"};if(!o)return{ok:!1,reason:"KYNVER_API_URL or --base-url is required to refresh a rejected runner token"};try{let s=await So(r,{baseUrl:o,apiKey:n});return s&&s!==e?(yo(r,s),{ok:!0,token:s}):{ok:!1,reason:"runner credential refresh returned the rejected token"}}catch(s){return{ok:!1,reason:s.message}}}async function So(e,r){let t=r?.apiKey||Pt();if(!t)throw new Error("API key required \u2014 run `kynver login` first");let o=`${Ro(r?.baseUrl)}/api/agent-os/by-id/${encodeURIComponent(e)}/runner-credentials`,s=await ae(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r?.enableMcpUpdates?{enableMcpUpdates:!0}:{})}),i=await s.text(),l=null;try{l=JSON.parse(i)}catch{l=null}if(!s.ok||!l?.token)throw new Error(`runner credential mint failed (${s.status}): ${l?.error??i.slice(0,200)}`);return l.token}function bo(e){console.error(e),process.exit(1)}var sr,wt,nr,mu,fu,ho,I=a(()=>{"use strict";Me();V();le();M();de();ge();Be();he();Ct();At();ve();Ze();sr=or.join(fo(),".kynver"),wt=or.join(sr,"config.json"),nr=or.join(sr,"credentials");mu=500*1024*1024,fu=4*1024*1024*1024;ho={kind:"file",getApiKey(){return process.env.KYNVER_API_KEY?process.env.KYNVER_API_KEY:xe().apiKey},getRunnerToken(e){let r=xe();if(!!r.runnerToken&&!!e&&r.runnerTokenAgentOsId===e)return r.runnerToken;let n=process.env.KYNVER_RUNNER_TOKEN?.trim();if(n)return n;if(r.runnerToken&&!(e&&r.runnerTokenAgentOsId&&r.runnerTokenAgentOsId!==e))return r.runnerToken},persistApiKey(e){Ot({...xe(),apiKey:e})},persistRunnerToken(e,r){Ot({...xe(),runnerToken:r,runnerTokenAgentOsId:e})}}});import Mt from"node:path";function _e(e){return Re(e)}function ir(){let e=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(e)return _e(e);let r=_(),t=r.harnessRoot?.trim();if(t)return _e(t);let n=ke(r,process.env);return n.identity?n.identity.harnessRoot:Se({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function Hr(e){return Mt.join(_e(e),"runs")}function ko(e){return Mt.join(_e(e),"worktrees")}function jr(){let e=ir();return{harnessRoot:e,runsDir:Hr(e),worktreesDir:ko(e)}}var $e=a(()=>{"use strict";I();tr();ve();k()});import{existsSync as sn,realpathSync as an,readFileSync as ln}from"node:fs";import wr from"node:path";var cn=new Set(["ext4","ext3","ext2","btrfs","xfs","f2fs","zfs","tmpfs","overlay","overlayfs"]),un=new Set(["9p","drvfs","nfs","nfs4","cifs","smb","smbfs","smb3","sshfs","fuse.sshfs","davfs","davfs2","glusterfs","ceph","lustre","afs","vboxsf","prl_fs","virtiofs"]);function dn(){try{return ln("/proc/self/mounts","utf8")}catch{return null}}function pn(e){let r=wr.resolve(e);for(let t=0;t<64;t+=1){if(sn(r))try{return an.native(r)}catch{return r}let n=wr.dirname(r);if(n===r)return r;r=n}return r}function mn(e){return e.replace(/\\(\d{3})/g,(r,t)=>String.fromCharCode(Number.parseInt(t,8)))}function fn(e){let r=[];for(let t of e.split(`
4
- `)){let n=t.trim().split(/\s+/);n.length<3||r.push({mountPoint:mn(n[1]),fsType:n[2]})}return r}function Or(e,r=process.platform){return r==="win32"?e.replace(/\\/g,"/"):e}function gn(e,r){let t=null,n=Or(e);for(let o of r){let s=Or(o.mountPoint),i=s.endsWith("/")?s:`${s}/`;(n===s||`${n}/`.startsWith(i))&&(!t||o.mountPoint.length>t.mountPoint.length)&&(t=o)}return t}function Ne(e,r){let n=(r?.resolveRealPath??pn)(e),o=(r?.mountsSource??dn)();if(o===null)return{verdict:"rejected",reason:"Mount information unavailable \u2014 the filesystem type cannot be established safely, so WAL mode is refused (fail closed).",filesystemType:null,mountPoint:null,resolvedPath:n};let s=gn(n,fn(o));if(!s)return{verdict:"rejected",reason:"No mount entry covers the resolved database path \u2014 refusing WAL mode (fail closed).",filesystemType:null,mountPoint:null,resolvedPath:n};let i=s.fsType.toLowerCase();return un.has(i)||i.startsWith("fuse.")?{verdict:"rejected",reason:`Filesystem '${i}' is network-like or crosses an OS boundary; SQLite WAL locking is not safe there.`,filesystemType:i,mountPoint:s.mountPoint,resolvedPath:n}:cn.has(i)?{verdict:"accepted",reason:`Local filesystem '${i}' accepted for WAL mode.`,filesystemType:i,mountPoint:s.mountPoint,resolvedPath:n}:{verdict:"rejected",reason:`Filesystem '${i}' is unknown to the qualification policy; WAL mode is refused rather than guessed (fail closed).`,filesystemType:i,mountPoint:s.mountPoint,resolvedPath:n}}var Pe=1,ne=class extends Error{constructor(r,t){super(`local-run-store schema version ${r} is newer than this runtime supports (${t}); refusing to open. Upgrade the runtime or quarantine the database deliberately.`),this.name="SchemaDowngradeRefusedError"}},hn=[`CREATE TABLE IF NOT EXISTS local_meta (
1
+ var l=(e,r,t)=>()=>{if(t)throw t[0];try{return e&&(r=e(e=0)),r}catch(n){throw t=[n],n}};import{homedir as Tr}from"node:os";import Nr from"node:path";function An(e){return e==="~"?Tr():e.startsWith("~/")||e.startsWith("~\\")?Nr.join(Tr(),e.slice(2)):e}function K(e){return Nr.resolve(An(e))}var V=l(()=>{"use strict"});var Pr=l(()=>{"use strict"});import{existsSync as ti,mkdirSync as wn,readFileSync as On,readdirSync as ni,renameSync as In,rmSync as Tn,statSync as oi,writeFileSync as Nn}from"node:fs";import{randomBytes as Pn}from"node:crypto";import Dn from"node:path";function Le(e){console.error(e),process.exit(1)}function Q(e,r){try{return JSON.parse(On(e,"utf8"))}catch(t){if(arguments.length>1)return r;Le(`failed to read ${e}: ${t.message}`)}}function oe(e,r){wn(Dn.dirname(e),{recursive:!0});let t=`${e}.${process.pid}.${Pn(4).toString("hex")}.tmp`;try{Nn(t,`${JSON.stringify(r,null,2)}
2
+ `),In(t,e)}catch(n){try{Tn(t,{force:!0})}catch{}throw n}}function se(e){return String(e).replace(/\/+$/,"")}var k=l(()=>{"use strict";Pr()});var Ln,ci,Mn,ui,Dr=l(()=>{"use strict";Ln=["ANTHROPIC_API_KEY","ANALYST_API_KEY","RECRUITER_API_KEY","AUTH_SECRET","NEXTAUTH_SECRET","DATABASE_URL","PRODUCTION_DATABASE_URL","KYNVER_PRODUCTION_DATABASE_URL","REDIS_URL","GOOGLE_CLIENT_SECRET","GITHUB_CLIENT_SECRET","KYNVER_API_KEY","KYNVER_SERVICE_SECRET","KYNVER_RUNTIME_SECRET","KYNVER_CRON_SECRET","OPENCLAW_CRON_SECRET","QSTASH_TOKEN","QSTASH_CURRENT_SIGNING_KEY","QSTASH_NEXT_SIGNING_KEY","TOOL_SECRETS_KEK","TOOL_EXECUTOR_DISPATCH_SECRET","CLOUDFLARE_API_TOKEN","STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_IDENTITY_WEBHOOK_SECRET","VOYAGE_API_KEY","PERPLEXITY_API_KEY","FRED_API_KEY","FMP_API_KEY","CURSOR_API_KEY","MEMORY_CONTENT_KEK","LLM_BYOK_KEK","KYNVER_COMMAND_AUTH_KEY","KYNVER_INSTRUCTION_BUNDLE_KEY","KYNVER_MEMORY_LEDGER_KEY","KYNVER_JWKS_PRIVATE_KEY_JWK"],ci=new Set(Ln),Mn=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY","GEMINI_API_KEY"],ui=new Set(Mn)});var ie=l(()=>{"use strict";V();k();Dr()});var Lr=l(()=>{"use strict";ie()});var Me=l(()=>{"use strict";ie();V();Lr()});function Fr(e){let r=se(e);try{let t=new URL(r);return t.hostname.toLowerCase()===Mr?(t.hostname=`www.${Mr}`,se(t.toString())):r}catch{return r}}function Ke(e){if(e?.trim())return Fr(se(e.trim()))}async function ae(e,r,t=fetch){let n=Fr(e),o=new Headers(r?.headers),s=0;for(;s<=Kr;){let i=await t(n,{...r,headers:o,redirect:"manual"});if(![301,302,303,307,308].includes(i.status))return i;let a=i.headers.get("location");if(!a)return i;let u=new URL(a,n);if(u.origin!==new URL(n).origin||u.username||u.password)throw await i.body?.cancel(),new Error("kynver API fetch refused unsafe redirect (origin change or embedded credentials)");let c=(r?.method??"GET").toUpperCase();if(!["GET","HEAD"].includes(c)&&i.status!==307&&i.status!==308)return i;await i.body?.cancel(),n=u.toString(),s+=1}throw new Error(`kynver API fetch exceeded ${Kr} redirects for ${e}`)}var Mr,Kr,le=l(()=>{"use strict";k();Mr="kynver.com";Kr=10});function F(e){let r=(e??"").trim().toLowerCase();return r==="ghost"||r==="forge"||r==="box"?r:r.includes("forge")?"forge":r.includes("ghost")||r.includes("openclaw")?"ghost":"box"}function ce(e,r){return e[r]?.trim()||null}function Ur(e){let r=e?.split(":")[0]?.trim();return r?F(r):null}function G(e=process.env,r={}){let t=[],n=Ur(r.boxId),o=Ur(ce(e,"KYNVER_BOX_ID")),s=r.boxKind?.trim();if(s)return n&&n!==F(s)&&t.push(`config.boxId=${r.boxId} conflicts with boxKind=${s}; using explicit boxKind=${s}`),{boxKind:F(s),source:"config",slugInferenceBlocked:!1,warnings:t};let i=ce(e,"KYNVER_BOX_KIND");if(i)return o&&o!==F(i)&&t.push(`KYNVER_BOX_ID=${ce(e,"KYNVER_BOX_ID")} conflicts with KYNVER_BOX_KIND=${i}; using explicit KYNVER_BOX_KIND=${i}`),{boxKind:F(i),source:"env",slugInferenceBlocked:!1,warnings:t};if(n)return{boxKind:n,source:"config",slugInferenceBlocked:!1,warnings:t};if(o)return{boxKind:o,source:"env",slugInferenceBlocked:!1,warnings:t};let a=ce(e,"KYNVER_AGENT_OS_SLUG");return a&&t.push(`KYNVER_AGENT_OS_SLUG=${a} is a workspace slug, not box identity \u2014 operators set boxKind via \`kynver setup --box-kind forge|ghost\` or KYNVER_BOX_KIND; customers default to box`),{boxKind:"box",source:"default",slugInferenceBlocked:!!a,warnings:t}}var M=l(()=>{"use strict"});function Fe(e,r){return e==="forge"?4:Math.max(1,r)}function ue(e,r){return e==="forge"?Math.min(Math.max(1,r),4):Math.max(1,r)}var de=l(()=>{"use strict"});var Br=l(()=>{"use strict"});var Ti,Ni,Ue=l(()=>{"use strict";Ti=25*1024*1024*1024,Ni=12*1024*1024*1024});var Ki,Fi,Wr=l(()=>{"use strict";Ue();Ki=5*1024*1024*1024,Fi=10*1024*1024*1024});var ji,Yi,Be=l(()=>{"use strict";Wr();Ue();ji=30*1024*1024*1024,Yi=15*1024*1024*1024});function $r(){return jr()}var pe=l(()=>{"use strict";$e();k()});var Yr=l(()=>{"use strict";pe();k()});var Vr=l(()=>{"use strict"});var Gr=l(()=>{"use strict";Vr();k()});var qr=l(()=>{"use strict"});var Jr=l(()=>{"use strict";qr()});var me=l(()=>{"use strict"});var zr=l(()=>{"use strict";Jr();k();me()});var Xr=l(()=>{"use strict";me()});var Qr=l(()=>{"use strict"});var Zr=l(()=>{"use strict"});var He=l(()=>{"use strict"});var et=l(()=>{"use strict"});var rt=l(()=>{"use strict";He();et()});var tt=l(()=>{"use strict";Gr();zr();me();Xr();Qr();ie();Zr();rt();He();k()});var nt=l(()=>{"use strict";tt()});function ot(e,r={}){let t=r.perWorkerMemBytes??je,n=r.memReserveBytes??Ye,o=r.memUtilization??Ve,s=Math.max(0,Math.floor(e*o)-n),i=Math.max(1,Math.floor(s/t));return Math.min(i,fe)}var je,Ye,Ve,fe,st=l(()=>{"use strict";Br();I();M();de();ge();Be();pe();Yr();nt();k();je=500*1024*1024,Ye=4*1024*1024*1024,Ve=.85,fe=64});function Z(e,r){let t=Number(e);return!Number.isFinite(t)||t<=0?r:Math.floor(t)}function Ge(e){let r=e.config??{},t=e.env??process.env,n=Z(r.perWorkerMemBytes,je),o=Z(r.memReserveBytes,Ye),s=Math.min(1,Math.max(.1,Number(r.memUtilization)>0?Number(r.memUtilization):Ve)),i=ot(e.totalMemBytes,{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s});if(e.configuredMaxWorkersOverride!==void 0&&e.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:Z(e.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(r.maxConcurrentWorkers!==void 0&&r.maxConcurrentWorkers!==null){let c=Z(r.maxConcurrentWorkers,0)||null;if(c)return{configuredMaxWorkers:Math.min(c,fe),autoCap:i,workerCapSource:"config"}}let u=(t.KYNVER_MAX_WORKERS_INTENTIONAL==="1"||t.KYNVER_MAX_WORKERS_INTENTIONAL==="true")&&t.KYNVER_MAX_WORKERS&&Z(t.KYNVER_MAX_WORKERS,0)||null;return u?{configuredMaxWorkers:Math.min(u,fe),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var ge=l(()=>{"use strict";st()});import{homedir as Yn}from"node:os";import Vn from"node:path";var it,qe=l(()=>{"use strict";it=Vn.join(Yn(),".kynver",".env")});var at=l(()=>{"use strict"});var lt=l(()=>{"use strict";at()});var ct=l(()=>{"use strict"});var ut=l(()=>{"use strict";k()});var Je=l(()=>{"use strict";lt();ct();ut()});var dt=l(()=>{"use strict"});var pt=l(()=>{"use strict";dt()});var he=l(()=>{"use strict";qe();V();I();Je();pt()});var mt=l(()=>{"use strict";M();M()});var ft=l(()=>{"use strict";qe();Je();he()});function yt(e){if(!ht)return e;if(!gt)throw new ze;return gt}function Qe(){if(ht)throw new Xe}var ze,Xe,ht,gt,Ze=l(()=>{"use strict";ze=class extends Error{constructor(){super("desktop credential provider is not installed; refusing to fall back to file or env credentials"),this.name="DesktopCredentialProviderMissingError"}},Xe=class extends Error{constructor(){super("the credentials file is disabled in desktop mode"),this.name="LegacyCredentialStoreDisabledError"}},ht=!1,gt=null});import{existsSync as T,mkdirSync as zn,readdirSync as ye,renameSync as Rt,statSync as Xn}from"node:fs";import N from"node:path";function bt(e){try{return Xn(e).isDirectory()}catch{return!1}}function Qn(e){if(!T(e))return!0;for(let r of St){let t=N.join(e,r);if(T(t)&&(!bt(t)||ye(t).length>0))return!1}return!0}function Zn(e){let r=N.join(e,"runs");if(!T(r)||!bt(r))return!1;for(let t of ye(r,{withFileTypes:!0})){if(!t.isDirectory()||t.name==="runs")continue;let n=N.join(r,t.name,"run.json");if(Q(n,void 0)?.id)return!0}return!1}function eo(e){let r=N.join(e,"runs");if(!T(r))return!1;for(let t of ye(r,{withFileTypes:!0})){if(!t.isDirectory())continue;if(Q(N.join(r,t.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function ro(e){let r=N.join(e,"ghost");return T(r)?!T(N.join(r,"runs")):eo(e)}function kt(e){return Zn(e.sharedRoot)?Qn(e.forgeRoot)?ro(e.sharedRoot)?{action:"blocked",blocker:"Forge legacy harness migration blocked: Ghost pool is co-hosted on this host (ghost namespace or ghost-attributed runs under ~/.kynver/harness). Drain in-flight Ghost runs from the shared root, or get operator sign-off for a fresh Forge cutover before enabling box-scoped isolation."}:{action:"migrate"}:{action:"none"}:{action:"none"}}function vt(e,r){zn(r,{recursive:!0});for(let t of St){let n=N.join(e,t),o=N.join(r,t);if(T(n)){if(T(o)&&ye(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(T(o)){Rt(n,o);continue}Rt(n,o)}}}var St,xt=l(()=>{"use strict";k();St=["runs","worktrees"]});import{existsSync as b}from"node:fs";import{homedir as to}from"node:os";import S from"node:path";function er(e=process.env){return e.HOME?.trim()||to()}function rr(e=process.env){return S.join(er(e),".kynver","harness")}function Re(e){let r=S.resolve(K(e.trim()));for(;no.has(S.basename(r));)r=S.dirname(r);return r}function oo(e,r=process.env){return S.join(rr(r),e)}function so(e=process.env){let r=rr(e);if(b(S.join(r,"runs")))return!0;if(b(r)&&!b(S.join(r,"ghost"))&&!b(S.join(r,"forge")))return b(r);let t=S.join(er(e),_t);return b(t)}function Se(e){let r=e.env??process.env,t=r.KYNVER_HARNESS_ROOT?.trim()||r.OPUS_HARNESS_ROOT?.trim();if(t)return{harnessRoot:Re(t),source:"env"};let n=e.configuredHarnessRoot?.trim();if(n)return{harnessRoot:Re(n),source:"config"};let o=oo(e.boxKind,r);if(b(S.join(o,"runs"))||b(o)&&!io(o))return{harnessRoot:o,source:"box_scoped"};let i=rr(r);if(e.boxKind==="forge"){let a=kt({sharedRoot:i,forgeRoot:o});if(a.action==="blocked")return{harnessRoot:o,source:"box_scoped",migrationBlocker:a.blocker};if(a.action==="migrate")return e.allowForgeLegacyMigration!==!1&&vt(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(e.boxKind==="ghost"&&so(r)){if(b(S.join(i,"runs")))return{harnessRoot:i,source:"legacy_shared"};if(b(i)&&!b(S.join(i,"ghost"))&&!b(S.join(i,"forge")))return{harnessRoot:i,source:"legacy_shared"};let u=S.join(er(r),_t);if(b(u))return{harnessRoot:u,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function io(e){if(!b(e))return!0;for(let r of["runs","worktrees"]){let t=S.join(e,r);if(b(t))return!1}return!0}var _t,no,tr=l(()=>{"use strict";V();xt();_t=S.join(".openclaw","harness");no=new Set(["runs","worktrees"])});import Et from"node:os";function be(e){return e?.trim()?e.trim():null}function ao(e,r){let t=r.trim().toLowerCase()||"host";return`${e}-${t}`.replace(/[^a-z0-9._-]+/g,"-")}function lo(e){return e.KYNVER_DISPATCH_STRICT_IDENTITY==="1"||e.KYNVER_DISPATCH_STRICT_IDENTITY==="true"||e.KYNVER_DAEMON_STRICT_IDENTITY==="1"||e.KYNVER_DAEMON_STRICT_IDENTITY==="true"}function ke(e=_(),r=process.env,t={}){let n=G(r,e),o=[...n.warnings],s=[],i=!!(e.boxKind?.trim()||be(r.KYNVER_BOX_KIND)),a=t.strict===!0||lo(r);if((t.requireExplicitBoxKind||a)&&!i&&s.push("boxKind is not persisted in ~/.kynver/config.json and KYNVER_BOX_KIND is unset \u2014 run `kynver setup` (customers: boxKind=box) or `kynver setup --box-kind forge|ghost` for operator pools before dispatch"),n.slugInferenceBlocked&&!i){let H="ambiguous box identity: KYNVER_AGENT_OS_SLUG is set without KYNVER_BOX_KIND or config.boxKind";a||t.requireExplicitBoxKind?s.push(H):o.push(`${H} \u2014 defaulting box kind to box (customer), not forge/ghost`)}let u=be(e.runnerId),c=be(r.KYNVER_RUNTIME_ID)??be(r.OPENCLAW_RUNTIME_ID),p=u??c??ao(n.boxKind,Et.hostname()),m=u?"config":c?"env":"derived";m==="derived"&&o.push(`runnerId not persisted \u2014 using derived id "${p}"; run \`kynver setup --box-kind ${n.boxKind}\` to persist runner identity`);let d=Ge({config:e,env:r,totalMemBytes:Et.totalmem()}),$=ue(n.boxKind,d.configuredMaxWorkers??Fe(n.boxKind,d.autoCap)),v=Se({boxKind:n.boxKind,configuredHarnessRoot:e.harnessRoot,env:r});return v.migrationBlocker&&s.push(v.migrationBlocker),s.length>0?{ok:!1,identity:null,errors:s,warnings:o}:{ok:!0,identity:{boxKind:n.boxKind,boxKindSource:n.source,runnerId:p,runnerIdSource:m,maxConcurrentWorkers:$,workerCapSource:d.workerCapSource,harnessRoot:v.harnessRoot,harnessRootSource:v.source},errors:s,warnings:o}}var ve=l(()=>{"use strict";I();M();de();ge();tr()});var Ct=l(()=>{"use strict";Me();M();mt();I();he();ft();le();Ze();ve()});var po,jc,At=l(()=>{"use strict";po=["claude","cursor","codex","gemini","gemini-api","openai-compatible"],jc=po.join("|")});import{existsSync as It,mkdirSync as mo,readFileSync as Tt,writeFileSync as fo}from"node:fs";import{homedir as go,totalmem as eu}from"node:os";import or from"node:path";function ho(e){return{...e,...e.harnessRoot?.trim()?{harnessRoot:K(e.harnessRoot.trim())}:{},...e.defaultRepo?.trim()?{defaultRepo:K(e.defaultRepo.trim())}:{}}}function _(){if(!It(wt))return{};try{return ho(JSON.parse(Tt(wt,"utf8")))}catch{return{}}}function xe(){if(Qe(),!It(nr))return{};try{return JSON.parse(Tt(nr,"utf8"))}catch{return{}}}function Ot(e){Qe(),mo(sr,{recursive:!0}),fo(nr,`${JSON.stringify(e,null,2)}
3
+ `,{mode:384})}function Nt(){return yt(yo)}function Pt(){return Nt().getApiKey()}function Ro(e,r){Nt().persistRunnerToken(e,r)}function So(e){let r=Dt(e);return r||ko("requires --base-url, KYNVER_API_URL, KYNVER_CRON_FIRE_BASE_URL, or ~/.kynver/config.json apiBaseUrl"),r}function Dt(e){let r=e||process.env.KYNVER_API_URL||process.env.KYNVER_CRON_FIRE_BASE_URL||process.env.OPENCLAW_CRON_FIRE_BASE_URL||_().apiBaseUrl;return Ke(r)}async function Lt(e,r,t){let n=Pt(),o=Dt(t?.baseUrl);if(!n)return{ok:!1,reason:"KYNVER_API_KEY is required to refresh a rejected runner token"};if(!r)return{ok:!1,reason:"agentOsId is required to refresh a rejected runner token"};if(!o)return{ok:!1,reason:"KYNVER_API_URL or --base-url is required to refresh a rejected runner token"};try{let s=await bo(r,{baseUrl:o,apiKey:n});return s&&s!==e?(Ro(r,s),{ok:!0,token:s}):{ok:!1,reason:"runner credential refresh returned the rejected token"}}catch(s){return{ok:!1,reason:s.message}}}async function bo(e,r){let t=r?.apiKey||Pt();if(!t)throw new Error("API key required \u2014 run `kynver login` first");let o=`${So(r?.baseUrl)}/api/agent-os/by-id/${encodeURIComponent(e)}/runner-credentials`,s=await ae(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r?.enableMcpUpdates?{enableMcpUpdates:!0}:{})}),i=await s.text(),a=null;try{a=JSON.parse(i)}catch{a=null}if(!s.ok||!a?.token)throw new Error(`runner credential mint failed (${s.status}): ${a?.error??i.slice(0,200)}`);return a.token}function ko(e){console.error(e),process.exit(1)}var sr,wt,nr,fu,gu,yo,I=l(()=>{"use strict";Me();V();le();M();de();ge();Be();he();Ct();At();ve();Ze();sr=or.join(go(),".kynver"),wt=or.join(sr,"config.json"),nr=or.join(sr,"credentials");fu=500*1024*1024,gu=4*1024*1024*1024;yo={kind:"file",getApiKey(){return process.env.KYNVER_API_KEY?process.env.KYNVER_API_KEY:xe().apiKey},getRunnerToken(e){let r=xe();if(!!r.runnerToken&&!!e&&r.runnerTokenAgentOsId===e)return r.runnerToken;let n=process.env.KYNVER_RUNNER_TOKEN?.trim();if(n)return n;if(r.runnerToken&&!(e&&r.runnerTokenAgentOsId&&r.runnerTokenAgentOsId!==e))return r.runnerToken},persistApiKey(e){Ot({...xe(),apiKey:e})},persistRunnerToken(e,r){Ot({...xe(),runnerToken:r,runnerTokenAgentOsId:e})}}});import Mt from"node:path";function _e(e){return Re(e)}function ir(){let e=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(e)return _e(e);let r=_(),t=r.harnessRoot?.trim();if(t)return _e(t);let n=ke(r,process.env);return n.identity?n.identity.harnessRoot:Se({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function Hr(e){return Mt.join(_e(e),"runs")}function vo(e){return Mt.join(_e(e),"worktrees")}function jr(){let e=ir();return{harnessRoot:e,runsDir:Hr(e),worktreesDir:vo(e)}}var $e=l(()=>{"use strict";I();tr();ve();k()});import{existsSync as an,realpathSync as ln,readFileSync as cn}from"node:fs";import wr from"node:path";var un=new Set(["ext4","ext3","ext2","btrfs","xfs","f2fs","zfs","tmpfs","overlay","overlayfs"]),dn=new Set(["9p","drvfs","nfs","nfs4","cifs","smb","smbfs","smb3","sshfs","fuse.sshfs","davfs","davfs2","glusterfs","ceph","lustre","afs","vboxsf","prl_fs","virtiofs"]);function pn(){try{return cn("/proc/self/mounts","utf8")}catch{return null}}function mn(e){let r=wr.resolve(e);for(let t=0;t<64;t+=1){if(an(r))try{return ln.native(r)}catch{return r}let n=wr.dirname(r);if(n===r)return r;r=n}return r}function fn(e){return e.replace(/\\(\d{3})/g,(r,t)=>String.fromCharCode(Number.parseInt(t,8)))}function gn(e){let r=[];for(let t of e.split(`
4
+ `)){let n=t.trim().split(/\s+/);n.length<3||r.push({mountPoint:fn(n[1]),fsType:n[2]})}return r}function Or(e,r=process.platform){return r==="win32"?e.replace(/\\/g,"/"):e}function hn(e,r){let t=null,n=Or(e);for(let o of r){let s=Or(o.mountPoint),i=s.endsWith("/")?s:`${s}/`;(n===s||`${n}/`.startsWith(i))&&(!t||o.mountPoint.length>t.mountPoint.length)&&(t=o)}return t}function Ne(e,r){let n=(r?.resolveRealPath??mn)(e),o=(r?.mountsSource??pn)();if(o===null)return{verdict:"rejected",reason:"Mount information unavailable \u2014 the filesystem type cannot be established safely, so WAL mode is refused (fail closed).",filesystemType:null,mountPoint:null,resolvedPath:n};let s=hn(n,gn(o));if(!s)return{verdict:"rejected",reason:"No mount entry covers the resolved database path \u2014 refusing WAL mode (fail closed).",filesystemType:null,mountPoint:null,resolvedPath:n};let i=s.fsType.toLowerCase();return dn.has(i)||i.startsWith("fuse.")?{verdict:"rejected",reason:`Filesystem '${i}' is network-like or crosses an OS boundary; SQLite WAL locking is not safe there.`,filesystemType:i,mountPoint:s.mountPoint,resolvedPath:n}:un.has(i)?{verdict:"accepted",reason:`Local filesystem '${i}' accepted for WAL mode.`,filesystemType:i,mountPoint:s.mountPoint,resolvedPath:n}:{verdict:"rejected",reason:`Filesystem '${i}' is unknown to the qualification policy; WAL mode is refused rather than guessed (fail closed).`,filesystemType:i,mountPoint:s.mountPoint,resolvedPath:n}}var Pe=1,ne=class extends Error{constructor(r,t){super(`local-run-store schema version ${r} is newer than this runtime supports (${t}); refusing to open. Upgrade the runtime or quarantine the database deliberately.`),this.name="SchemaDowngradeRefusedError"}},yn=[`CREATE TABLE IF NOT EXISTS local_meta (
5
5
  key TEXT PRIMARY KEY,
6
6
  value TEXT NOT NULL
7
7
  ) STRICT`,`CREATE TABLE IF NOT EXISTS process_identity (
@@ -27,7 +27,7 @@ var a=(e,r,t)=>()=>{if(t)throw t[0];try{return e&&(r=e(e=0)),r}catch(n){throw t=
27
27
  payload_json TEXT NOT NULL,
28
28
  created_at TEXT NOT NULL,
29
29
  PRIMARY KEY (scope, seq)
30
- ) STRICT`];function yn(e){if(!e.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'local_meta'").get())return null;let t=e.prepare("SELECT value FROM local_meta WHERE key = 'schema_version'").get();if(!t?.value)return null;let n=Number.parseInt(t.value,10);return Number.isFinite(n)?n:null}function Ir(e,r){let t=yn(e);if(t!==null&&t>1)throw new ne(t,1);e.exec("BEGIN IMMEDIATE");try{for(let n of hn)e.exec(n);e.prepare("INSERT INTO local_meta (key, value) VALUES ('schema_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(String(1)),e.prepare("INSERT INTO local_meta (key, value) VALUES ('schema_applied_at', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(r),e.exec("COMMIT")}catch(n){throw e.exec("ROLLBACK"),n}}import{mkdirSync as Rn}from"node:fs";import Sn from"node:path";import{DatabaseSync as bn}from"node:sqlite";var X=class extends Error{constructor(r){super(`local-run-store refused: ${r}`),this.name="FilesystemPolicyError"}},kn="local-run-store.sqlite",vn=5e3,Y=class e{db;now;databasePath;constructor(r,t,n){this.db=r,this.databasePath=t,this.now=n}static open(r){let t=Ne(r.directory,r.classifyOptions);if(t.verdict!=="accepted")throw new X(t.reason);Rn(r.directory,{recursive:!0,mode:448});let n=Sn.join(r.directory,r.filename??kn),o=new bn(n,{timeout:r.busyTimeoutMs??vn}),s=r.now??(()=>new Date);try{o.exec("PRAGMA journal_mode = WAL");let i=o.prepare("PRAGMA journal_mode").get();if(i?.journal_mode?.toLowerCase()!=="wal")throw new X(`journal_mode did not switch to WAL (got '${i?.journal_mode}') \u2014 filesystem unsuitable.`);o.exec("PRAGMA synchronous = NORMAL"),Ir(o,s().toISOString())}catch(i){throw o.close(),i}return new e(o,n,s)}inImmediateTransaction(r){this.db.exec("BEGIN IMMEDIATE");try{let t=r();return this.db.exec("COMMIT"),t}catch(t){throw this.db.exec("ROLLBACK"),t}}registerProcessIdentity(r){let t=this.now().toISOString();return this.inImmediateTransaction(()=>{this.db.prepare(`INSERT INTO process_identity
30
+ ) STRICT`];function Rn(e){if(!e.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'local_meta'").get())return null;let t=e.prepare("SELECT value FROM local_meta WHERE key = 'schema_version'").get();if(!t?.value)return null;let n=Number.parseInt(t.value,10);return Number.isFinite(n)?n:null}function Ir(e,r){let t=Rn(e);if(t!==null&&t>1)throw new ne(t,1);e.exec("BEGIN IMMEDIATE");try{for(let n of yn)e.exec(n);e.prepare("INSERT INTO local_meta (key, value) VALUES ('schema_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(String(1)),e.prepare("INSERT INTO local_meta (key, value) VALUES ('schema_applied_at', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(r),e.exec("COMMIT")}catch(n){throw e.exec("ROLLBACK"),n}}import{mkdirSync as Sn}from"node:fs";import bn from"node:path";import{DatabaseSync as kn}from"node:sqlite";var X=class extends Error{constructor(r){super(`local-run-store refused: ${r}`),this.name="FilesystemPolicyError"}},vn="local-run-store.sqlite",xn=5e3,Y=class e{db;now;databasePath;constructor(r,t,n){this.db=r,this.databasePath=t,this.now=n}static open(r){let t=Ne(r.directory,r.classifyOptions);if(t.verdict!=="accepted")throw new X(t.reason);Sn(r.directory,{recursive:!0,mode:448});let n=bn.join(r.directory,r.filename??vn),o=new kn(n,{timeout:r.busyTimeoutMs??xn}),s=r.now??(()=>new Date);try{o.exec("PRAGMA journal_mode = WAL");let i=o.prepare("PRAGMA journal_mode").get();if(i?.journal_mode?.toLowerCase()!=="wal")throw new X(`journal_mode did not switch to WAL (got '${i?.journal_mode}') \u2014 filesystem unsuitable.`);o.exec("PRAGMA synchronous = NORMAL"),Ir(o,s().toISOString())}catch(i){throw o.close(),i}return new e(o,n,s)}inImmediateTransaction(r){this.db.exec("BEGIN IMMEDIATE");try{let t=r();return this.db.exec("COMMIT"),t}catch(t){throw this.db.exec("ROLLBACK"),t}}registerProcessIdentity(r){let t=this.now().toISOString();return this.inImmediateTransaction(()=>{this.db.prepare(`INSERT INTO process_identity
31
31
  (process_key, pid, runtime_version, node_version, started_at, registered_at)
32
32
  VALUES (?, ?, ?, ?, ?, ?)
33
33
  ON CONFLICT(process_key) DO UPDATE SET
@@ -36,7 +36,7 @@ var a=(e,r,t)=>()=>{if(t)throw t[0];try{return e&&(r=e(e=0)),r}catch(n){throw t=
36
36
  node_version = excluded.node_version,
37
37
  started_at = excluded.started_at,
38
38
  registered_at = excluded.registered_at`).run(r.processKey,r.pid,r.runtimeVersion,r.nodeVersion,r.startedAt,t)}),{...r,registeredAt:t}}getProcessIdentity(r){let t=this.db.prepare(`SELECT process_key, pid, runtime_version, node_version, started_at, registered_at
39
- FROM process_identity WHERE process_key = ?`).get(r);return t?{processKey:t.process_key,pid:t.pid,runtimeVersion:t.runtime_version,nodeVersion:t.node_version,startedAt:t.started_at,registeredAt:t.registered_at}:null}tryReserveAdmission(r,t,n,o){let s=o??this.now(),i=new Date(s.getTime()+n).toISOString();return this.inImmediateTransaction(()=>{let l=this.db.prepare("SELECT reservation_key, owner, expires_at FROM admission_reservations WHERE reservation_key = ?").get(r);return l&&l.expires_at>s.toISOString()&&l.owner!==t?{acquired:!1,current:{key:r,owner:l.owner,expiresAt:l.expires_at}}:(this.db.prepare(`INSERT INTO admission_reservations (reservation_key, owner, expires_at, created_at)
39
+ FROM process_identity WHERE process_key = ?`).get(r);return t?{processKey:t.process_key,pid:t.pid,runtimeVersion:t.runtime_version,nodeVersion:t.node_version,startedAt:t.started_at,registeredAt:t.registered_at}:null}tryReserveAdmission(r,t,n,o){let s=o??this.now(),i=new Date(s.getTime()+n).toISOString();return this.inImmediateTransaction(()=>{let a=this.db.prepare("SELECT reservation_key, owner, expires_at FROM admission_reservations WHERE reservation_key = ?").get(r);return a&&a.expires_at>s.toISOString()&&a.owner!==t?{acquired:!1,current:{key:r,owner:a.owner,expiresAt:a.expires_at}}:(this.db.prepare(`INSERT INTO admission_reservations (reservation_key, owner, expires_at, created_at)
40
40
  VALUES (?, ?, ?, ?)
41
41
  ON CONFLICT(reservation_key) DO UPDATE SET
42
42
  owner = excluded.owner,
@@ -51,8 +51,8 @@ var a=(e,r,t)=>()=>{if(t)throw t[0];try{return e&&(r=e(e=0)),r}catch(n){throw t=
51
51
  LIMIT ?`).all(...s,n).map(u=>({idempotencyKey:u.idempotency_key,operation:u.operation,resultJson:u.result_json,recordedAt:u.recorded_at}))}deleteOperationReceiptsByKeys(r){return r.length===0?0:this.inImmediateTransaction(()=>{let t=this.db.prepare("DELETE FROM operation_receipts WHERE idempotency_key = ?"),n=0;for(let o of r)n+=Number(t.run(o).changes);return n})}getOperationReceipt(r){let t=this.db.prepare(`SELECT idempotency_key, operation, result_json, recorded_at
52
52
  FROM operation_receipts WHERE idempotency_key = ?`).get(r);return t?{idempotencyKey:t.idempotency_key,operation:t.operation,resultJson:t.result_json,recordedAt:t.recorded_at}:null}saveRecoveryCheckpoint(r){return this.inImmediateTransaction(()=>{let t=this.db.prepare("SELECT COALESCE(MAX(seq), 0) AS max_seq FROM recovery_checkpoints WHERE scope = ?").get(r.scope),n=Number(t.max_seq)+1;return this.db.prepare(`INSERT INTO recovery_checkpoints (scope, seq, payload_json, created_at)
53
53
  VALUES (?, ?, ?, ?)`).run(r.scope,n,r.payloadJson,this.now().toISOString()),{seq:n}})}latestRecoveryCheckpoint(r){let t=this.db.prepare(`SELECT scope, seq, payload_json, created_at FROM recovery_checkpoints
54
- WHERE scope = ? ORDER BY seq DESC LIMIT 1`).get(r);return t?{scope:t.scope,seq:t.seq,payloadJson:t.payload_json,createdAt:t.created_at}:null}localSchemaVersion(){return 1}checkpointTruncate(){this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)")}integrityCheck(){return this.db.prepare("PRAGMA integrity_check").get()?.integrity_check==="ok"}pragma(r){let t=this.db.prepare(`PRAGMA ${r}`).get();return String(Object.values(t)[0])}close(){this.db.close()}};import{existsSync as xn,renameSync as _n}from"node:fs";function En(e,r){let t=`${e}.quarantine-${r}`;for(let n of["","-wal","-shm"]){let o=`${e}${n}`;xn(o)&&_n(o,`${t}${n}`)}return t}function De(e){let r=e.quarantineStamp??(e.now??(()=>new Date))().toISOString().replace(/[:.]/g,"-"),t=null;try{let s=Y.open(e);if(s.integrityCheck())return{store:s,recovered:!1,quarantinedTo:null};s.close()}catch(s){if(s.name==="SchemaDowngradeRefusedError"||s.name==="FilesystemPolicyError")throw s;t=s}let n=`${e.directory}/${e.filename??"local-run-store.sqlite"}`,o=En(n,r);try{return{store:Y.open(e),recovered:!0,quarantinedTo:o}}catch(s){throw new AggregateError([t,s].filter(Boolean),"local-run-store rebuild after quarantine failed")}}$e();function vo(){if(process.env.KYNVER_LRS_TEST_CLASSIFY_BYPASS==="1")return{mountsSource:()=>"/dev/vda / ext4 rw 0 0",resolveRealPath:()=>"/tmp/kynver-lrs-test/db"}}function xo(){return Kt.classifyOptions??vo()}var Kt={};function _o(e){Kt=e}var Ft=300*1e3,P=null,ee=0;function Eo(e){ee+=1;try{let r=xo(),t=De({directory:e,...r?{classifyOptions:r}:{}});return{store:t.store,status:{state:"open",harnessRoot:e,databasePath:t.store.databasePath,schemaVersion:t.store.localSchemaVersion(),recovered:t.recovered,quarantinedTo:t.quarantinedTo,reason:null,openAttempts:ee},failedAtMs:null,permanentRefusal:!1}}catch(r){return{store:null,status:{state:"unavailable",harnessRoot:e,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:`${r.name}: ${r.message}`,openAttempts:ee},failedAtMs:Date.now(),permanentRefusal:r.name==="FilesystemPolicyError"||r.name==="SchemaDowngradeRefusedError"}}}function Co(e,r){return e.store||e.permanentRefusal?!1:e.failedAtMs===null?!0:r-e.failedAtMs>=Ft}function f(e=Date.now()){let r=ir();return(!P||P.status.harnessRoot!==r||Co(P,e))&&(lr(),P=Eo(r)),P.store}function Ut(){return P?P.status:{state:"unopened",harnessRoot:null,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:null,openAttempts:ee}}function ar(){return f(),Ut()}function lr(){try{P?.store?.close()}catch{}P=null}function Ao(){lr(),ee=0}I();k();import{existsSync as wo,readFileSync as Oo}from"node:fs";import{homedir as Io}from"node:os";import To from"node:path";var No=3e4,x=null;function cr(e){let r=e.replace(/[^A-Za-z0-9_-]/g,"_");return To.join(Io(),".kynver",`local-run-store-flags-${r}.json`)}function ur(e){if(!e||typeof e!="object"||Array.isArray(e))return{};let r=e,t={},n=["dispatchReceipts","admission","planOutbox","keeper","meshLease","quota"];for(let o of n){let s=r[o];(s==="off"||s==="shadow"||s==="enforce")&&(t[o]=s)}return t}function Po(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let r=e.response;if(!r||typeof r!="object"||Array.isArray(r))return null;let t=r.localRunStoreFlags;return t===void 0?null:ur(t)}function Do(e,r){try{let t=cr(e),n={contractVersion:1,agentOsId:e,flags:ur(r),deliveredAt:new Date().toISOString()};oe(t,n),x={flags:n.flags,loadedAtMs:Date.now(),file:t}}catch{}}function dr(e=Date.now()){if(process.env.KYNVER_LRS_REMOTE_FLAGS_DISABLED==="1")return{};if(x&&e-x.loadedAtMs<No)return x.flags;try{let r=_().agentOsId?.trim();if(!r)return x={flags:{},loadedAtMs:e,file:null},x.flags;let t=cr(r);if(!wo(t))return x={flags:{},loadedAtMs:e,file:t},x.flags;let n=JSON.parse(Oo(t,"utf8")),o=n?.contractVersion===1?ur(n.flags):{};return x={flags:o,loadedAtMs:e,file:t},o}catch{return x={flags:{},loadedAtMs:e,file:null},x.flags}}function Lo(){x=null}var Bt=[{key:"dispatchReceipts",env:"KYNVER_LRS_DISPATCH_RECEIPTS",milestone:"D1"},{key:"admission",env:"KYNVER_LRS_ADMISSION",milestone:"D2"},{key:"planOutbox",env:"KYNVER_LRS_PLAN_OUTBOX",milestone:"D3"},{key:"keeper",env:"KYNVER_LRS_KEEPER",milestone:"D4"},{key:"meshLease",env:"KYNVER_LRS_MESH_LEASE",milestone:"D4"},{key:"quota",env:"KYNVER_LRS_QUOTA",milestone:"D4"}];function Wt(e){let r=e?.trim().toLowerCase()??"";return r===""?{mode:"off",unknown:!1}:r==="off"||r==="shadow"||r==="enforce"?{mode:r,unknown:!1}:{mode:"off",unknown:!0}}function A(e=process.env){let r={},t={},n=[],o=dr();for(let s of Bt){let i=e[s.env];if(typeof i=="string"&&i.trim()!==""){let c=Wt(i);r[s.key]=c.mode,t[s.key]="env",c.unknown&&n.push(`${s.env}='${i}' is not off|shadow|enforce \u2014 treating as off`);continue}let u=o[s.key];if(u){r[s.key]=u,t[s.key]="server";continue}r[s.key]="off",t[s.key]="default"}return{flags:r,sources:t,warnings:n}}function Mo(e){return Object.values(e).some(r=>r!=="off")}var R={storeFailures:0,completionReplaysObserved:0,completionReplaysShortCircuited:0,agedReceiptsPruned:0};function w(e=process.env){return A(e).flags.dispatchReceipts}function pr(e){return w(e)!=="off"}function mr(e,r){return`dispatch:${e}:${r.taskId}:${r.leaseToken}`}function re(e,r,t){if(!pr())return;let n=f();if(n)try{n.recordOperationReceipt({idempotencyKey:mr(e,r),operation:`dispatch-${e}`,resultJson:t===void 0?null:JSON.stringify(t)})}catch{R.storeFailures+=1}}function Ko(e){re("claim",e,{runId:e.runId,workerName:e.workerName,provider:e.provider})}function fr(e){re("spawned",e)}function Ee(e,r){re("released",e,{reasonClass:r})}function Fo(e){re("completion-sent",e)}function Uo(e,r){re("completion-acked",e,{outcome:r})}function Bo(e){if(!pr())return!1;let r=f();if(!r)return!1;try{let t=r.getOperationReceipt(mr("completion-acked",e));if(t){let n=null;try{n=t.resultJson?JSON.parse(t.resultJson).outcome??null:null}catch{n=null}if(n==="acknowledged")return R.completionReplaysObserved+=1,!0}}catch{R.storeFailures+=1}return!1}function Wo(e){let r=String(e??"").split(":")[0]?.trim()??"";return r.length>0?r.slice(0,64):"unknown"}function $o(e){if(w()!=="enforce")return!1;let r=f();if(!r)return!1;try{let t=r.getOperationReceipt(mr("completion-acked",e));if(!t)return!1;let n=null;try{n=t.resultJson?JSON.parse(t.resultJson).outcome??null:null}catch{n=null}return n==="acknowledged"?(R.completionReplaysShortCircuited+=1,!0):!1}catch{return R.storeFailures+=1,!1}}var Ho=600*1e3;function jo(e,r){if(w()!=="enforce")return;let t=f();if(t)try{t.recordOperationReceipt({idempotencyKey:`dispatch:start-failed:${e}:${r}`,operation:"dispatch-start-failed",resultJson:JSON.stringify({runId:r})})}catch{R.storeFailures+=1}}function Yo(e,r){if(w()!=="enforce")return[];let t=f();if(!t)return[];let n=r?.nowMs??Date.now(),o=r?.windowMs??Ho;try{return t.listOperationReceipts({operation:"dispatch-start-failed",recordedAfter:new Date(n-o).toISOString(),limit:200}).filter(s=>{try{return s.resultJson?JSON.parse(s.resultJson).runId===e:!1}catch{return!1}}).map(s=>{let i=s.idempotencyKey.slice(22);return i.slice(0,i.length-(e.length+1))}).filter(s=>s.length>0)}catch{return R.storeFailures+=1,[]}}function q(e){let r=e.split(":")[0]??"",t=Number(r);return Number.isInteger(t)&&t>=0?t:null}var Vo=900*1e3,$t=10080*60*1e3,Go=1440*60*1e3,qo=500,Jo=300;function gr(e){let r={scannedClaims:0,strandedClaimCandidates:0,prunedReceipts:0};if(!pr())return r;let t=f();if(!t)return r;let n=e?.nowMs??Date.now(),o=e?.strandedAfterMs??Vo;try{let s=t.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(n-$t).toISOString(),limit:qo}),i=0,l=[];for(let c of s){let p=c.idempotencyKey.slice(15),m=Date.parse(c.recordedAt);if(!Number.isFinite(m)||n-m<o)continue;let d=t.getOperationReceipt(`dispatch:spawned:${p}`),$=t.getOperationReceipt(`dispatch:released:${p}`);if(d||$){n-m>=Go&&l.length+5<=Jo&&l.push(c.idempotencyKey,`dispatch:spawned:${p}`,`dispatch:released:${p}`,`dispatch:completion-sent:${p}`,`dispatch:completion-acked:${p}`);continue}let v=p.split(":")[0]??"",H=q(p.slice(v.length+1));if((v?t.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${v}:`,limit:10}):[]).some(h=>{if(H===null)return!0;let j=h.idempotencyKey.slice(`dispatch:completion-acked:${v}:`.length),L=q(j);return L===null||L>=H}))continue;let y=!1;if(e?.hasLiveWorker&&c.resultJson)try{let h=JSON.parse(c.resultJson);h.runId&&h.workerName&&(y=e.hasLiveWorker({runId:h.runId,workerName:h.workerName}))}catch{y=!1}y||(i+=1)}let u=l.length>0?t.deleteOperationReceiptsByKeys(l):0;if(w()==="enforce"){let c=t.listOperationReceipts({limit:100}).filter(p=>{let m=Date.parse(p.recordedAt);return Number.isFinite(m)&&n-m>=$t}).map(p=>p.idempotencyKey);if(c.length>0){let p=t.deleteOperationReceiptsByKeys(c);u+=p,R.agedReceiptsPruned+=p}}return{scannedClaims:s.length,strandedClaimCandidates:i,prunedReceipts:u}}catch{return R.storeFailures+=1,r}}function hr(){return{"dispatchReceipts.storeFailures":R.storeFailures,"dispatchReceipts.completionReplaysObserved":R.completionReplaysObserved,"dispatchReceipts.completionReplaysShortCircuited":R.completionReplaysShortCircuited,"dispatchReceipts.agedReceiptsPruned":R.agedReceiptsPruned}}function zo(){R.storeFailures=0,R.completionReplaysObserved=0,R.completionReplaysShortCircuited=0,R.agedReceiptsPruned=0}import{readdirSync as os,readFileSync as ss}from"node:fs";var U=900*1e3,Rr="admission-shadow",yr="worker-slot:",E={storeFailures:0,missingForLive:0,deadSlotsReleased:0},Ce=!1;function Xo(){Ce=!1}function B(e=process.env){return A(e).flags.admission}function Ae(e,r){return`${yr}${e}:${r}`}function Qo(e,r){if(B()==="off")return;let t=f();if(t)try{t.tryReserveAdmission(Ae(e,r),Rr,U)}catch{E.storeFailures+=1}}function Sr(e,r){if(B()==="off")return;let t=f();if(t)try{t.releaseAdmission(Ae(e,r),Rr)}catch{E.storeFailures+=1}}function Zo(e){let r={liveReservations:0,refreshed:0,deadReleased:0,missingForLive:0,orphaned:0,adoptionPass:!1};if(B()==="off")return r;let t=f();if(!t)return r;try{let n=new Set(e.liveWorkers.map(d=>Ae(d.runId,d.workerName))),o=t.listAdmissionReservations({keyPrefix:yr,limit:500}),s=new Set(o.map(d=>d.key)),i=[...n].filter(d=>!s.has(d)).length,l=o.filter(d=>!n.has(d.key)).length,u=!Ce;Ce=!0,!u&&i>0&&(E.missingForLive+=i);let c=0;for(let d of e.liveWorkers)t.tryReserveAdmission(Ae(d.runId,d.workerName),Rr,U),c+=1;let p=0;for(let d of o)n.has(d.key)||t.releaseAdmission(d.key,d.owner)&&(p+=1,E.deadSlotsReleased+=1);return{liveReservations:t.listAdmissionReservations({keyPrefix:yr,limit:500}).length,refreshed:c,deadReleased:p,missingForLive:i,orphaned:l,adoptionPass:u}}catch{return E.storeFailures+=1,r}}function br(){return{"admission.storeFailures":E.storeFailures,"admission.missingForLive":E.missingForLive,"admission.deadSlotsReleased":E.deadSlotsReleased}}function es(){E.storeFailures=0,E.missingForLive=0,E.deadSlotsReleased=0,Ce=!1}var Ie="worker-slot-n:",we=64;function Ht(e){return`${Ie}${e}`}function Oe(e,r){return`${e}:${r}`}var C={enforceStoreFailures:0,admissionsRefusedSlots:0,admissionsRefusedDiskBackstop:0};function rs(e){if(B()!=="enforce")return{admitted:!0};let r=f();if(!r)return{admitted:!0};let t=Math.max(0,Math.min(we,Math.floor(e.maxSlots)));if(e.diskActiveWorkers>=t)return C.admissionsRefusedDiskBackstop+=1,{admitted:!1,reason:"disk_backstop"};try{let n=Oe(e.runId,e.workerName);for(let o=0;o<t;o+=1)if(r.tryReserveAdmission(Ht(o),n,U).acquired)return{admitted:!0,slot:o};return C.admissionsRefusedSlots+=1,{admitted:!1,reason:"slots_exhausted"}}catch{return C.enforceStoreFailures+=1,{admitted:!0}}}function kr(e,r){if(B()==="off")return;let t=f();if(t)try{let n=Oe(e,r),o=t.listAdmissionReservations({keyPrefix:Ie,limit:we});for(let s of o)s.owner===n&&t.releaseAdmission(s.key,n)}catch{C.enforceStoreFailures+=1}}function ts(e){let r={refreshed:0,deadReleased:0,adopted:0};if(B()!=="enforce")return r;let t=f();if(!t)return r;try{let n=new Set(e.liveWorkers.map(c=>Oe(c.runId,c.workerName))),o=t.listAdmissionReservations({keyPrefix:Ie,limit:we}),s=0,i=0,l=new Set;for(let c of o)n.has(c.owner)?(t.tryReserveAdmission(c.key,c.owner,U),l.add(c.owner),s+=1):t.releaseAdmission(c.key,c.owner)&&(i+=1);let u=0;for(let c of e.liveWorkers){let p=Oe(c.runId,c.workerName);if(!l.has(p)){for(let m=0;m<we;m+=1)if(t.tryReserveAdmission(Ht(m),p,U).acquired){u+=1;break}}}return{refreshed:s,deadReleased:i,adopted:u}}catch{return C.enforceStoreFailures+=1,r}}function vr(){return{"admission.enforceStoreFailures":C.enforceStoreFailures,"admission.refusedSlotsExhausted":C.admissionsRefusedSlots,"admission.refusedDiskBackstop":C.admissionsRefusedDiskBackstop}}function ns(){C.enforceStoreFailures=0,C.admissionsRefusedSlots=0,C.admissionsRefusedDiskBackstop=0}var is="dispatch:claim:",as=900*1e3,ls=10080*60*1e3,cs=200,O={recoveredStrandedClaims:0,recoveryDeferredOrphans:0,recoveryStoreFailures:0};function jt(e){if(process.platform!=="linux"||!e.trim())return null;let r=[];try{r=os("/proc")}catch{return null}for(let t of r)if(/^\d+$/.test(t)&&Number(t)!==process.pid)try{if(ss(`/proc/${t}/cmdline`,"utf8").replace(/\0/g," ").includes(e))return Number(t)}catch{}return null}async function xr(e){let r=w(),t={mode:r,scanned:0,outcomes:[]};if(r!=="enforce")return t;let n=f();if(!n)return t;let o=e.nowMs??Date.now(),s=e.strandedAfterMs??as,i=e.findOrphanPid??jt,l=[],u;try{u=n.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(o-ls).toISOString(),limit:cs})}catch{return O.recoveryStoreFailures+=1,t}for(let c of u){let p=c.idempotencyKey.slice(is.length),m=p.split(":")[0]??"",d=p.slice(m.length+1);if(!(!m||!d))try{let $=Date.parse(c.recordedAt);if(!Number.isFinite($)||o-$<s||n.getOperationReceipt(`dispatch:spawned:${p}`)||n.getOperationReceipt(`dispatch:released:${p}`))continue;let v=q(d);if(n.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${m}:`,limit:10}).some(L=>{if(v===null)return!0;let z=q(L.idempotencyKey.slice(`dispatch:completion-acked:${m}:`.length));return z===null||z>=v}))continue;let J={};try{J=c.resultJson?JSON.parse(c.resultJson):{}}catch{J={}}let y=J.runId??null,h=J.workerName??null;if(y&&h&&e.hasLiveWorker({runId:y,workerName:h})){fr({taskId:m,leaseToken:d}),l.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"finalized_late"});continue}if(y&&h){let L=e.worktreePathFor({runId:y,workerName:h}),z=L?i(L):null;if(z!==null){O.recoveryDeferredOrphans+=1,l.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"deferred_orphan",detail:`live pid ${z} references ${L}`});continue}}if(!y){l.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"skipped",detail:"claim intent missing runId \u2014 cannot resolve lease owner"});continue}let j=await e.releaseClaim({taskId:m,leaseToken:d,runId:y});j.released?(Ee({taskId:m,leaseToken:d},"restart_recovery"),h&&(Sr(y,h),kr(y,h)),O.recoveredStrandedClaims+=1,l.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"released"})):j.transportError?l.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"deferred_transport",detail:j.detail}):(Ee({taskId:m,leaseToken:d},"restart_recovery_refused"),l.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"release_refused",detail:j.detail}))}catch{O.recoveryStoreFailures+=1}}return{mode:r,scanned:u.length,outcomes:l}}function _r(){return{"dispatchReceipts.recoveredStrandedClaims":O.recoveredStrandedClaims,"dispatchReceipts.recoveryDeferredOrphans":O.recoveryDeferredOrphans,"dispatchReceipts.recoveryStoreFailures":O.recoveryStoreFailures}}function us(){O.recoveredStrandedClaims=0,O.recoveryDeferredOrphans=0,O.recoveryStoreFailures=0}pe();import bs from"node:path";var ds="kynver-harness:",ps="@runner:";function Yt(e,r){let t=e.trim(),n=r.trim();return`${ds}${t}${ps}${n}`}I();import qt from"node:os";var ms="embedded-1",fs=[{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"}],gs={"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. Prefer `gh pr view` / `gh pr diff`; if a local checkout is needed, use a disposable ref or detached worktree, not a checked-out `pr-*` branch.","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(`
54
+ WHERE scope = ? ORDER BY seq DESC LIMIT 1`).get(r);return t?{scope:t.scope,seq:t.seq,payloadJson:t.payload_json,createdAt:t.created_at}:null}localSchemaVersion(){return 1}checkpointTruncate(){this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)")}integrityCheck(){return this.db.prepare("PRAGMA integrity_check").get()?.integrity_check==="ok"}pragma(r){let t=this.db.prepare(`PRAGMA ${r}`).get();return String(Object.values(t)[0])}close(){this.db.close()}};import{existsSync as _n,renameSync as En}from"node:fs";function Cn(e,r){let t=`${e}.quarantine-${r}`;for(let n of["","-wal","-shm"]){let o=`${e}${n}`;_n(o)&&En(o,`${t}${n}`)}return t}function De(e){let r=e.quarantineStamp??(e.now??(()=>new Date))().toISOString().replace(/[:.]/g,"-"),t=null;try{let s=Y.open(e);if(s.integrityCheck())return{store:s,recovered:!1,quarantinedTo:null};s.close()}catch(s){if(s.name==="SchemaDowngradeRefusedError"||s.name==="FilesystemPolicyError")throw s;t=s}let n=`${e.directory}/${e.filename??"local-run-store.sqlite"}`,o=Cn(n,r);try{return{store:Y.open(e),recovered:!0,quarantinedTo:o}}catch(s){throw new AggregateError([t,s].filter(Boolean),"local-run-store rebuild after quarantine failed")}}$e();function xo(){if(process.env.KYNVER_LRS_TEST_CLASSIFY_BYPASS==="1")return{mountsSource:()=>"/dev/vda / ext4 rw 0 0",resolveRealPath:()=>"/tmp/kynver-lrs-test/db"}}function _o(){return Kt.classifyOptions??xo()}var Kt={};function Eo(e){Kt=e}var Ft=300*1e3,P=null,ee=0;function Co(e){ee+=1;try{let r=_o(),t=De({directory:e,...r?{classifyOptions:r}:{}});return{store:t.store,status:{state:"open",harnessRoot:e,databasePath:t.store.databasePath,schemaVersion:t.store.localSchemaVersion(),recovered:t.recovered,quarantinedTo:t.quarantinedTo,reason:null,openAttempts:ee},failedAtMs:null,permanentRefusal:!1}}catch(r){return{store:null,status:{state:"unavailable",harnessRoot:e,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:`${r.name}: ${r.message}`,openAttempts:ee},failedAtMs:Date.now(),permanentRefusal:r.name==="FilesystemPolicyError"||r.name==="SchemaDowngradeRefusedError"}}}function Ao(e,r){return e.store||e.permanentRefusal?!1:e.failedAtMs===null?!0:r-e.failedAtMs>=Ft}function f(e=Date.now()){let r=ir();return(!P||P.status.harnessRoot!==r||Ao(P,e))&&(lr(),P=Co(r)),P.store}function Ut(){return P?P.status:{state:"unopened",harnessRoot:null,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:null,openAttempts:ee}}function ar(){return f(),Ut()}function lr(){try{P?.store?.close()}catch{}P=null}function wo(){lr(),ee=0}I();k();import{existsSync as Oo,readFileSync as Io}from"node:fs";import{homedir as To}from"node:os";import No from"node:path";var Po=3e4,x=null;function cr(e){let r=e.replace(/[^A-Za-z0-9_-]/g,"_");return No.join(To(),".kynver",`local-run-store-flags-${r}.json`)}function ur(e){if(!e||typeof e!="object"||Array.isArray(e))return{};let r=e,t={},n=["dispatchReceipts","admission","planOutbox","keeper","meshLease","quota"];for(let o of n){let s=r[o];(s==="off"||s==="shadow"||s==="enforce")&&(t[o]=s)}return t}function Do(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let r=e.response;if(!r||typeof r!="object"||Array.isArray(r))return null;let t=r.localRunStoreFlags;return t===void 0?null:ur(t)}function Lo(e,r){try{let t=cr(e),n={contractVersion:1,agentOsId:e,flags:ur(r),deliveredAt:new Date().toISOString()};oe(t,n),x={flags:n.flags,loadedAtMs:Date.now(),file:t}}catch{}}function dr(e=Date.now()){if(process.env.KYNVER_LRS_REMOTE_FLAGS_DISABLED==="1")return{};if(x&&e-x.loadedAtMs<Po)return x.flags;try{let r=_().agentOsId?.trim();if(!r)return x={flags:{},loadedAtMs:e,file:null},x.flags;let t=cr(r);if(!Oo(t))return x={flags:{},loadedAtMs:e,file:t},x.flags;let n=JSON.parse(Io(t,"utf8")),o=n?.contractVersion===1?ur(n.flags):{};return x={flags:o,loadedAtMs:e,file:t},o}catch{return x={flags:{},loadedAtMs:e,file:null},x.flags}}function Mo(){x=null}var Bt=[{key:"dispatchReceipts",env:"KYNVER_LRS_DISPATCH_RECEIPTS",milestone:"D1"},{key:"admission",env:"KYNVER_LRS_ADMISSION",milestone:"D2"},{key:"planOutbox",env:"KYNVER_LRS_PLAN_OUTBOX",milestone:"D3"},{key:"keeper",env:"KYNVER_LRS_KEEPER",milestone:"D4"},{key:"meshLease",env:"KYNVER_LRS_MESH_LEASE",milestone:"D4"},{key:"quota",env:"KYNVER_LRS_QUOTA",milestone:"D4"}];function Wt(e){let r=e?.trim().toLowerCase()??"";return r===""?{mode:"off",unknown:!1}:r==="off"||r==="shadow"||r==="enforce"?{mode:r,unknown:!1}:{mode:"off",unknown:!0}}function A(e=process.env){let r={},t={},n=[],o=dr();for(let s of Bt){let i=e[s.env];if(typeof i=="string"&&i.trim()!==""){let c=Wt(i);r[s.key]=c.mode,t[s.key]="env",c.unknown&&n.push(`${s.env}='${i}' is not off|shadow|enforce \u2014 treating as off`);continue}let u=o[s.key];if(u){r[s.key]=u,t[s.key]="server";continue}r[s.key]="off",t[s.key]="default"}return{flags:r,sources:t,warnings:n}}function Ko(e){return Object.values(e).some(r=>r!=="off")}var R={storeFailures:0,completionReplaysObserved:0,completionReplaysShortCircuited:0,agedReceiptsPruned:0};function w(e=process.env){return A(e).flags.dispatchReceipts}function pr(e){return w(e)!=="off"}function mr(e,r){return`dispatch:${e}:${r.taskId}:${r.leaseToken}`}function re(e,r,t){if(!pr())return;let n=f();if(n)try{n.recordOperationReceipt({idempotencyKey:mr(e,r),operation:`dispatch-${e}`,resultJson:t===void 0?null:JSON.stringify(t)})}catch{R.storeFailures+=1}}function Fo(e){re("claim",e,{runId:e.runId,workerName:e.workerName,provider:e.provider})}function fr(e){re("spawned",e)}function Ee(e,r){re("released",e,{reasonClass:r})}function Uo(e){re("completion-sent",e)}function Bo(e,r){re("completion-acked",e,{outcome:r})}function Wo(e){if(!pr())return!1;let r=f();if(!r)return!1;try{let t=r.getOperationReceipt(mr("completion-acked",e));if(t){let n=null;try{n=t.resultJson?JSON.parse(t.resultJson).outcome??null:null}catch{n=null}if(n==="acknowledged")return R.completionReplaysObserved+=1,!0}}catch{R.storeFailures+=1}return!1}function $o(e){let r=String(e??"").split(":")[0]?.trim()??"";return r.length>0?r.slice(0,64):"unknown"}function Ho(e){if(w()!=="enforce")return!1;let r=f();if(!r)return!1;try{let t=r.getOperationReceipt(mr("completion-acked",e));if(!t)return!1;let n=null;try{n=t.resultJson?JSON.parse(t.resultJson).outcome??null:null}catch{n=null}return n==="acknowledged"?(R.completionReplaysShortCircuited+=1,!0):!1}catch{return R.storeFailures+=1,!1}}var jo=600*1e3;function Yo(e,r){if(w()!=="enforce")return;let t=f();if(t)try{t.recordOperationReceipt({idempotencyKey:`dispatch:start-failed:${e}:${r}`,operation:"dispatch-start-failed",resultJson:JSON.stringify({runId:r})})}catch{R.storeFailures+=1}}function Vo(e,r){if(w()!=="enforce")return[];let t=f();if(!t)return[];let n=r?.nowMs??Date.now(),o=r?.windowMs??jo;try{return t.listOperationReceipts({operation:"dispatch-start-failed",recordedAfter:new Date(n-o).toISOString(),limit:200}).filter(s=>{try{return s.resultJson?JSON.parse(s.resultJson).runId===e:!1}catch{return!1}}).map(s=>{let i=s.idempotencyKey.slice(22);return i.slice(0,i.length-(e.length+1))}).filter(s=>s.length>0)}catch{return R.storeFailures+=1,[]}}function q(e){let r=e.split(":")[0]??"",t=Number(r);return Number.isInteger(t)&&t>=0?t:null}var Go=900*1e3,$t=10080*60*1e3,qo=1440*60*1e3,Jo=500,zo=300;function gr(e){let r={scannedClaims:0,strandedClaimCandidates:0,prunedReceipts:0};if(!pr())return r;let t=f();if(!t)return r;let n=e?.nowMs??Date.now(),o=e?.strandedAfterMs??Go;try{let s=t.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(n-$t).toISOString(),limit:Jo}),i=0,a=[];for(let c of s){let p=c.idempotencyKey.slice(15),m=Date.parse(c.recordedAt);if(!Number.isFinite(m)||n-m<o)continue;let d=t.getOperationReceipt(`dispatch:spawned:${p}`),$=t.getOperationReceipt(`dispatch:released:${p}`);if(d||$){n-m>=qo&&a.length+5<=zo&&a.push(c.idempotencyKey,`dispatch:spawned:${p}`,`dispatch:released:${p}`,`dispatch:completion-sent:${p}`,`dispatch:completion-acked:${p}`);continue}let v=p.split(":")[0]??"",H=q(p.slice(v.length+1));if((v?t.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${v}:`,limit:10}):[]).some(h=>{if(H===null)return!0;let j=h.idempotencyKey.slice(`dispatch:completion-acked:${v}:`.length),L=q(j);return L===null||L>=H}))continue;let y=!1;if(e?.hasLiveWorker&&c.resultJson)try{let h=JSON.parse(c.resultJson);h.runId&&h.workerName&&(y=e.hasLiveWorker({runId:h.runId,workerName:h.workerName}))}catch{y=!1}y||(i+=1)}let u=a.length>0?t.deleteOperationReceiptsByKeys(a):0;if(w()==="enforce"){let c=t.listOperationReceipts({limit:100}).filter(p=>{let m=Date.parse(p.recordedAt);return Number.isFinite(m)&&n-m>=$t}).map(p=>p.idempotencyKey);if(c.length>0){let p=t.deleteOperationReceiptsByKeys(c);u+=p,R.agedReceiptsPruned+=p}}return{scannedClaims:s.length,strandedClaimCandidates:i,prunedReceipts:u}}catch{return R.storeFailures+=1,r}}function hr(){return{"dispatchReceipts.storeFailures":R.storeFailures,"dispatchReceipts.completionReplaysObserved":R.completionReplaysObserved,"dispatchReceipts.completionReplaysShortCircuited":R.completionReplaysShortCircuited,"dispatchReceipts.agedReceiptsPruned":R.agedReceiptsPruned}}function Xo(){R.storeFailures=0,R.completionReplaysObserved=0,R.completionReplaysShortCircuited=0,R.agedReceiptsPruned=0}import{readdirSync as ss,readFileSync as is}from"node:fs";var U=900*1e3,Rr="admission-shadow",yr="worker-slot:",E={storeFailures:0,missingForLive:0,deadSlotsReleased:0},Ce=!1;function Qo(){Ce=!1}function B(e=process.env){return A(e).flags.admission}function Ae(e,r){return`${yr}${e}:${r}`}function Zo(e,r){if(B()==="off")return;let t=f();if(t)try{t.tryReserveAdmission(Ae(e,r),Rr,U)}catch{E.storeFailures+=1}}function Sr(e,r){if(B()==="off")return;let t=f();if(t)try{t.releaseAdmission(Ae(e,r),Rr)}catch{E.storeFailures+=1}}function es(e){let r={liveReservations:0,refreshed:0,deadReleased:0,missingForLive:0,orphaned:0,adoptionPass:!1};if(B()==="off")return r;let t=f();if(!t)return r;try{let n=new Set(e.liveWorkers.map(d=>Ae(d.runId,d.workerName))),o=t.listAdmissionReservations({keyPrefix:yr,limit:500}),s=new Set(o.map(d=>d.key)),i=[...n].filter(d=>!s.has(d)).length,a=o.filter(d=>!n.has(d.key)).length,u=!Ce;Ce=!0,!u&&i>0&&(E.missingForLive+=i);let c=0;for(let d of e.liveWorkers)t.tryReserveAdmission(Ae(d.runId,d.workerName),Rr,U),c+=1;let p=0;for(let d of o)n.has(d.key)||t.releaseAdmission(d.key,d.owner)&&(p+=1,E.deadSlotsReleased+=1);return{liveReservations:t.listAdmissionReservations({keyPrefix:yr,limit:500}).length,refreshed:c,deadReleased:p,missingForLive:i,orphaned:a,adoptionPass:u}}catch{return E.storeFailures+=1,r}}function br(){return{"admission.storeFailures":E.storeFailures,"admission.missingForLive":E.missingForLive,"admission.deadSlotsReleased":E.deadSlotsReleased}}function rs(){E.storeFailures=0,E.missingForLive=0,E.deadSlotsReleased=0,Ce=!1}var Ie="worker-slot-n:",we=64;function Ht(e){return`${Ie}${e}`}function Oe(e,r){return`${e}:${r}`}var C={enforceStoreFailures:0,admissionsRefusedSlots:0,admissionsRefusedDiskBackstop:0};function ts(e){if(B()!=="enforce")return{admitted:!0};let r=f();if(!r)return{admitted:!0};let t=Math.max(0,Math.min(we,Math.floor(e.maxSlots)));if(e.diskActiveWorkers>=t)return C.admissionsRefusedDiskBackstop+=1,{admitted:!1,reason:"disk_backstop"};try{let n=Oe(e.runId,e.workerName);for(let o=0;o<t;o+=1)if(r.tryReserveAdmission(Ht(o),n,U).acquired)return{admitted:!0,slot:o};return C.admissionsRefusedSlots+=1,{admitted:!1,reason:"slots_exhausted"}}catch{return C.enforceStoreFailures+=1,{admitted:!0}}}function kr(e,r){if(B()==="off")return;let t=f();if(t)try{let n=Oe(e,r),o=t.listAdmissionReservations({keyPrefix:Ie,limit:we});for(let s of o)s.owner===n&&t.releaseAdmission(s.key,n)}catch{C.enforceStoreFailures+=1}}function ns(e){let r={refreshed:0,deadReleased:0,adopted:0};if(B()!=="enforce")return r;let t=f();if(!t)return r;try{let n=new Set(e.liveWorkers.map(c=>Oe(c.runId,c.workerName))),o=t.listAdmissionReservations({keyPrefix:Ie,limit:we}),s=0,i=0,a=new Set;for(let c of o)n.has(c.owner)?(t.tryReserveAdmission(c.key,c.owner,U),a.add(c.owner),s+=1):t.releaseAdmission(c.key,c.owner)&&(i+=1);let u=0;for(let c of e.liveWorkers){let p=Oe(c.runId,c.workerName);if(!a.has(p)){for(let m=0;m<we;m+=1)if(t.tryReserveAdmission(Ht(m),p,U).acquired){u+=1;break}}}return{refreshed:s,deadReleased:i,adopted:u}}catch{return C.enforceStoreFailures+=1,r}}function vr(){return{"admission.enforceStoreFailures":C.enforceStoreFailures,"admission.refusedSlotsExhausted":C.admissionsRefusedSlots,"admission.refusedDiskBackstop":C.admissionsRefusedDiskBackstop}}function os(){C.enforceStoreFailures=0,C.admissionsRefusedSlots=0,C.admissionsRefusedDiskBackstop=0}var as="dispatch:claim:",ls=900*1e3,cs=10080*60*1e3,us=200,O={recoveredStrandedClaims:0,recoveryDeferredOrphans:0,recoveryStoreFailures:0};function jt(e){if(process.platform!=="linux"||!e.trim())return null;let r=[];try{r=ss("/proc")}catch{return null}for(let t of r)if(/^\d+$/.test(t)&&Number(t)!==process.pid)try{if(is(`/proc/${t}/cmdline`,"utf8").replace(/\0/g," ").includes(e))return Number(t)}catch{}return null}async function xr(e){let r=w(),t={mode:r,scanned:0,outcomes:[]};if(r!=="enforce")return t;let n=f();if(!n)return t;let o=e.nowMs??Date.now(),s=e.strandedAfterMs??ls,i=e.findOrphanPid??jt,a=[],u;try{u=n.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(o-cs).toISOString(),limit:us})}catch{return O.recoveryStoreFailures+=1,t}for(let c of u){let p=c.idempotencyKey.slice(as.length),m=p.split(":")[0]??"",d=p.slice(m.length+1);if(!(!m||!d))try{let $=Date.parse(c.recordedAt);if(!Number.isFinite($)||o-$<s||n.getOperationReceipt(`dispatch:spawned:${p}`)||n.getOperationReceipt(`dispatch:released:${p}`))continue;let v=q(d);if(n.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${m}:`,limit:10}).some(L=>{if(v===null)return!0;let z=q(L.idempotencyKey.slice(`dispatch:completion-acked:${m}:`.length));return z===null||z>=v}))continue;let J={};try{J=c.resultJson?JSON.parse(c.resultJson):{}}catch{J={}}let y=J.runId??null,h=J.workerName??null;if(y&&h&&e.hasLiveWorker({runId:y,workerName:h})){fr({taskId:m,leaseToken:d}),a.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"finalized_late"});continue}if(y&&h){let L=e.worktreePathFor({runId:y,workerName:h}),z=L?i(L):null;if(z!==null){O.recoveryDeferredOrphans+=1,a.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"deferred_orphan",detail:`live pid ${z} references ${L}`});continue}}if(!y){a.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"skipped",detail:"claim intent missing runId \u2014 cannot resolve lease owner"});continue}let j=await e.releaseClaim({taskId:m,leaseToken:d,runId:y});j.released?(Ee({taskId:m,leaseToken:d},"restart_recovery"),h&&(Sr(y,h),kr(y,h)),O.recoveredStrandedClaims+=1,a.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"released"})):j.transportError?a.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"deferred_transport",detail:j.detail}):(Ee({taskId:m,leaseToken:d},"restart_recovery_refused"),a.push({taskId:m,leaseToken:d,runId:y,workerName:h,action:"release_refused",detail:j.detail}))}catch{O.recoveryStoreFailures+=1}}return{mode:r,scanned:u.length,outcomes:a}}function _r(){return{"dispatchReceipts.recoveredStrandedClaims":O.recoveredStrandedClaims,"dispatchReceipts.recoveryDeferredOrphans":O.recoveryDeferredOrphans,"dispatchReceipts.recoveryStoreFailures":O.recoveryStoreFailures}}function ds(){O.recoveredStrandedClaims=0,O.recoveryDeferredOrphans=0,O.recoveryStoreFailures=0}pe();import ks from"node:path";var ps="kynver-harness:",ms="@runner:";function Yt(e,r){let t=e.trim(),n=r.trim();return`${ps}${t}${ms}${n}`}I();import qt from"node:os";var fs="embedded-1",gs=[{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"}],hs={"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. Prefer `gh pr view` / `gh pr diff`; if a local checkout is needed, use a disposable ref or detached worktree, not a checked-out `pr-*` branch.","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(`
55
55
  `),"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(`
56
56
  `),"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(`
57
57
  `),"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(`
58
- `)},hs={"harness.maxTaskAttempts":4,"harness.dispatchCooldownMs":5e3,"daemon.idleIntervalMs":5*6e4,"daemon.maxIdleStreak":10},Vt={version:ms,generatedAt:"1970-01-01T00:00:00.000Z",personas:fs,instructions:gs,policyThresholds:hs};var ys=Vt;function Gt(){return ys.version}M();function D(e){return e?.trim()?e.trim():null}function Jt(e={}){let r=e.env??process.env,t=_();return{runnerId:D(t.runnerId)??D(r.KYNVER_RUNTIME_ID)??D(r.OPENCLAW_RUNTIME_ID)??D(r.HOSTNAME)??qt.hostname(),hostname:D(r.HOSTNAME)??qt.hostname(),profile:D(r.KYNVER_RUNNER_PROFILE)??D(r.OPENCLAW_RUNNER_PROFILE),harnessRepo:D(r.KYNVER_HARNESS_REPO)??D(r.KYNVER_DEFAULT_REPO),runId:e.runId??null,instructionBundleVersion:Gt()}}function zt(e){let r=String(e).trim();return r.startsWith("krc1.")?{"Content-Type":"application/json","X-Kynver-Runner-Token":r}:{"Content-Type":"application/json","X-Kynver-Cron-Secret":r,"X-OpenClaw-Cron-Secret":r,"X-Kynver-Runtime-Secret":r}}le();I();function Qt(e){if(e!==void 0&&Number.isFinite(e)&&e>0)return Math.floor(e);let r=Number(process.env.KYNVER_CALLBACK_TIMEOUT_MS);return Number.isFinite(r)&&r>0?Math.floor(r):3e4}async function Rs(e,r){let t=Qt(r),n=new AbortController,o;try{return await Promise.race([e(n.signal),new Promise((s,i)=>{o=setTimeout(()=>{n.abort(),i(new Error(`callback timeout after ${t}ms`))},t)})])}finally{o&&clearTimeout(o)}}function Ss(e,r){let t=Qt(r);return{ok:!1,status:0,response:{error:e instanceof Error?e.message:String(e),timeoutMs:t}}}async function Xt(e,r,t,n){try{return await Rs(async o=>{let s=await ae(e,{method:"POST",headers:zt(r),body:JSON.stringify(t),signal:o}),i=null;try{i=await s.json()}catch{i=null}return{ok:s.ok,status:s.status,response:i}},n?.timeoutMs)}catch(o){return Ss(o,n?.timeoutMs)}}async function Zt(e,r,t,n){let o=await Xt(e,r,t,{timeoutMs:n.timeoutMs});if(o.ok||o.status!==401)return o;let s=await Lt(r,n.agentOsId,{baseUrl:n.baseUrl});return s.ok?{...await Xt(e,s.token,t,{timeoutMs:n.timeoutMs}),refreshedAuth:!0}:{...o,authRefreshFailure:s.reason}}async function en(e){let r=`${e.baseUrl}/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/tasks/${encodeURIComponent(e.taskId)}/release`,t;try{t=await Zt(r,e.secret,{agentOsId:e.agentOsId,leaseOwner:e.leaseOwner,...e.leaseToken?.trim()?{leaseToken:e.leaseToken.trim()}:{},...e.failureDetail?{failureDetail:e.failureDetail}:{}},{agentOsId:e.agentOsId,baseUrl:e.baseUrl})}catch(s){return{released:!1,httpOk:!1,transportError:!0,releaseResponse:{ok:!1,error:s.message}}}let n=t.response;return{released:t.ok===!0||n?.ok===!0,httpOk:t.ok===!0,transportError:!1,releaseResponse:t.response??t}}var Er=!1;function ks(){Er=!1}async function vs(e){if(Er||w()!=="enforce")return null;Er=!0;try{let r=Jt().runnerId,t=await xr({hasLiveWorker:e.hasLiveWorker,worktreePathFor:({runId:n,workerName:o})=>bs.join($r().worktreesDir,n,o),releaseClaim:async({taskId:n,leaseToken:o,runId:s})=>{let i=await en({baseUrl:e.baseUrl,secret:e.secret,agentOsId:e.agentOsId,taskId:n,leaseOwner:Yt(s,r),leaseToken:o});return{released:i.released,transportError:i.transportError,detail:i.httpOk?void 0:JSON.stringify(i.releaseResponse).slice(0,200)}}});return t.outcomes.length>0&&console.error(`[daemon] D1b claim recovery: ${t.outcomes.map(n=>`${n.taskId}:${n.action}`).join(", ")}`),t}catch{return null}}var bd=600*1e3,te={storeFailures:0,corruptItemsSeen:0,corruptItemsQuarantined:0,duplicateDrainsObserved:0,halfArchivesCompleted:0};function rn(){return{"planOutbox.storeFailures":te.storeFailures,"planOutbox.corruptItemsSeen":te.corruptItemsSeen,"planOutbox.corruptItemsQuarantined":te.corruptItemsQuarantined,"planOutbox.duplicateDrainsObserved":te.duplicateDrainsObserved,"planOutbox.halfArchivesCompleted":te.halfArchivesCompleted}}var g={keeperStoreFailures:0,meshStoreFailures:0,quotaStoreFailures:0,meshLeaseDivergences:0,meshEnforceStaleInversions:0,quotaVerdictDivergences:0};function W(e){return A(process.env).flags[e]}var tn="daemon-keeper",xs=1800*1e3;function _s(e){if(W("keeper")==="off")return;let r=f();if(r)try{r.saveRecoveryCheckpoint({scope:tn,payloadJson:JSON.stringify(e)})}catch{g.keeperStoreFailures+=1}}function Es(){if(W("keeper")!=="enforce")return null;let e=f();if(!e)return null;try{let r=e.latestRecoveryCheckpoint(tn);if(!r)return null;let t=JSON.parse(r.payloadJson),n=Date.now()-Date.parse(r.createdAt);if(!Number.isFinite(n)||n>xs)return null;let o=Number(t.consecutiveFailures);return Number.isFinite(o)&&o>=0?Math.floor(o):null}catch{return g.keeperStoreFailures+=1,null}}function Cr(e){return`mesh-cron-lease:${e}`}function Cs(e,r){if(W("meshLease")==="off")return;let t=f();if(t)try{let n=t.latestRecoveryCheckpoint(Cr(e));if(n){let o=JSON.parse(n.payloadJson);if((o.leaseToken??null)===(r.leaseToken??null)&&(o.holderBoxId??null)===(r.holderBoxId??null)&&o.authorized===r.authorized)return}t.saveRecoveryCheckpoint({scope:Cr(e),payloadJson:JSON.stringify(r)})}catch{g.meshStoreFailures+=1}}function As(e,r){let t=W("meshLease");if(t==="off")return null;let n=f();if(!n)return null;try{let o=n.latestRecoveryCheckpoint(Cr(e)),s=o?JSON.parse(o.payloadJson):null,i=s!==null&&((s.leaseToken??null)!==(r?.leaseToken??null)||(s.holderBoxId??null)!==(r?.holderBoxId??null)||(s.authorized??null)!==(r?.authorized??null));return i&&(g.meshLeaseDivergences+=1),t!=="enforce"?null:i&&r?.updatedAt&&s?.updatedAt&&Date.parse(r.updatedAt)>Date.parse(s.updatedAt)?(g.meshEnforceStaleInversions+=1,null):s}catch{return g.meshStoreFailures+=1,null}}function Te(e){return`quota-cooldown:${e}`}var nn="quota-preflight";function ws(e,r){if(W("quota")==="off")return;let t=f();if(t)try{t.tryReserveAdmission(Te(e),nn,r)}catch{g.quotaStoreFailures+=1}}function Os(e){if(W("quota")==="off")return;let r=f();if(r)try{r.releaseAdmission(Te(e),nn)}catch{g.quotaStoreFailures+=1}}function Is(e,r){let t=W("quota");if(t==="off")return null;let n=f();if(!n)return null;try{let o=n.listAdmissionReservations({keyPrefix:Te(e),limit:50}).find(i=>i.key===Te(e)),s=!!o;return s!==r&&(g.quotaVerdictDivergences+=1),t==="enforce"?{blocked:s,retryAtIso:o?.expiresAt??null}:null}catch{return g.quotaStoreFailures+=1,null}}function Ar(){return{"keeper.storeFailures":g.keeperStoreFailures,"meshLease.storeFailures":g.meshStoreFailures,"meshLease.divergences":g.meshLeaseDivergences,"meshLease.enforceStaleInversions":g.meshEnforceStaleInversions,"quota.storeFailures":g.quotaStoreFailures,"quota.verdictDivergences":g.quotaVerdictDivergences}}function Ts(){g.keeperStoreFailures=0,g.meshStoreFailures=0,g.quotaStoreFailures=0,g.meshLeaseDivergences=0,g.meshEnforceStaleInversions=0,g.quotaVerdictDivergences=0}function Ns(e){let r=ar(),t=A(e?.env??process.env),n=(e?.now??(()=>new Date))().getTime(),o={};if(t.flags.dispatchReceipts!=="off"){Object.assign(o,hr());let s=gr({nowMs:n,hasLiveWorker:e?.hasLiveWorker});o["dispatchReceipts.strandedClaimCandidates"]=s.strandedClaimCandidates,t.flags.dispatchReceipts==="enforce"&&Object.assign(o,_r())}return t.flags.planOutbox!=="off"&&Object.assign(o,rn()),t.flags.admission!=="off"&&(Object.assign(o,br()),t.flags.admission==="enforce"&&Object.assign(o,vr())),(t.flags.keeper!=="off"||t.flags.meshLease!=="off"||t.flags.quota!=="off")&&Object.assign(o,Ar()),{contractVersion:1,observedAt:new Date(n).toISOString(),state:r.state,schemaVersion:r.schemaVersion,recovered:r.recovered,unavailableClass:r.reason?r.reason.split(":")[0]??null:null,flags:t.flags,flagSources:t.sources,flagWarningCount:t.warnings.length,divergenceCounters:o}}export{U as ADMISSION_RESERVATION_TTL_MS,Ie as ADMISSION_SLOT_KEY_PREFIX,X as FilesystemPolicyError,Ft as LOCAL_RUN_STORE_OPEN_RETRY_MS,Bt as LOCAL_RUN_STORE_SURFACES,Pe as LOCAL_SCHEMA_VERSION,ne as SchemaDowngradeRefusedError,Y as SqliteLocalRunStore,ns as __resetAdmissionEnforceCountersForTests,es as __resetAdmissionShadowCountersForTests,us as __resetDispatchClaimRecoveryForTests,zo as __resetDispatchReceiptCountersForTests,Ao as __resetLocalRunStoreLifecycleForTests,Lo as __resetRemoteSurfaceFlagsCacheForTests,Ts as __resetSmallSurfaceCountersForTests,ks as __resetStartupClaimRecoveryForTests,_o as __setLocalRunStoreLifecycleTestOverrides,rs as acquireWorkerAdmissionSlot,vr as admissionEnforceCounters,br as admissionShadowCounters,Mo as anyLocalRunStoreSurfaceActive,Is as assessQuotaCooldownReservation,Ns as buildLocalRunStoreTickPosture,Ne as classifyDatabaseDirectory,Os as clearQuotaCooldownReservation,lr as closeLocalRunStore,_r as dispatchClaimRecoveryCounters,hr as dispatchReceiptCounters,w as dispatchReceiptsMode,Po as extractLocalRunStoreFlagsFromOperatorTickResponse,jt as findLiveProcessByCmdlinePath,f as getLocalRunStore,Ut as getLocalRunStoreLifecycleStatus,dr as getRemoteSurfaceFlags,q as leaseTokenAttempt,Yo as listRecentDispatchStartFailures,vs as maybeRunStartupClaimRecovery,Bo as noteCompletionReplayIfAcked,De as openSqliteLocalRunStoreWithRecovery,Wt as parseLocalRunStoreSurfaceMode,Do as persistRemoteSurfaceFlags,ar as probeLocalRunStore,As as readMeshLeaseCheckpoint,Xo as rearmAdmissionAdoptionPass,Zo as reconcileAdmissionShadow,ts as reconcileNumberedAdmissionSlots,Uo as recordCompletionAckedReceipt,Fo as recordCompletionSentReceipt,Ko as recordDispatchClaimReceipt,Ee as recordDispatchReleasedReceipt,fr as recordDispatchSpawnedReceipt,jo as recordDispatchStartFailedReceipt,ws as recordQuotaCooldownReservation,xr as recoverStrandedDispatchClaims,Wo as releaseReasonClass,kr as releaseWorkerAdmissionSlot,Sr as releaseWorkerSlotReservation,cr as remoteSurfaceFlagsPath,A as resolveLocalRunStoreSurfaceFlags,Es as restoreKeeperBackoffCheckpoint,_s as saveKeeperBackoffCheckpoint,Cs as saveMeshLeaseCheckpoint,gr as scanDispatchReceiptInvariants,$o as shouldShortCircuitCompletionReplay,Ar as smallSurfaceCounters,Qo as takeWorkerSlotReservation};
58
+ `)},ys={"harness.maxTaskAttempts":4,"harness.dispatchCooldownMs":5e3,"daemon.idleIntervalMs":5*6e4,"daemon.maxIdleStreak":10},Vt={version:fs,generatedAt:"1970-01-01T00:00:00.000Z",personas:gs,instructions:hs,policyThresholds:ys};var Rs=Vt;function Gt(){return Rs.version}M();function D(e){return e?.trim()?e.trim():null}function Jt(e={}){let r=e.env??process.env,t=_();return{runnerId:D(t.runnerId)??D(r.KYNVER_RUNTIME_ID)??D(r.OPENCLAW_RUNTIME_ID)??D(r.HOSTNAME)??qt.hostname(),hostname:D(r.HOSTNAME)??qt.hostname(),profile:D(r.KYNVER_RUNNER_PROFILE)??D(r.OPENCLAW_RUNNER_PROFILE),harnessRepo:D(r.KYNVER_HARNESS_REPO)??D(r.KYNVER_DEFAULT_REPO),runId:e.runId??null,instructionBundleVersion:Gt()}}function zt(e){let r=String(e).trim();return r.startsWith("krc1.")?{"Content-Type":"application/json","X-Kynver-Runner-Token":r}:{"Content-Type":"application/json","X-Kynver-Cron-Secret":r,"X-OpenClaw-Cron-Secret":r,"X-Kynver-Runtime-Secret":r}}le();I();function Zt(e){if(e!==void 0&&Number.isFinite(e)&&e>0)return Math.floor(e);let r=Number(process.env.KYNVER_CALLBACK_TIMEOUT_MS);return Number.isFinite(r)&&r>0?Math.floor(r):3e4}function Xt(e){return new Error(`callback timeout after ${e}ms`)}async function Ss(e,r){let t=Zt(r),n=new AbortController,o,s=!1;try{return await Promise.race([e(n.signal),new Promise((i,a)=>{o=setTimeout(()=>{s=!0,n.abort(),a(Xt(t))},t)})])}catch(i){throw s?Xt(t):i}finally{o&&clearTimeout(o)}}function bs(e,r){let t=Zt(r);return{ok:!1,status:0,response:{error:e instanceof Error?e.message:String(e),timeoutMs:t}}}async function Qt(e,r,t,n){try{return await Ss(async o=>{let s=await ae(e,{method:"POST",headers:zt(r),body:JSON.stringify(t),signal:o}),i=null;try{i=await s.json()}catch{i=null}return{ok:s.ok,status:s.status,response:i}},n?.timeoutMs)}catch(o){return bs(o,n?.timeoutMs)}}async function en(e,r,t,n){let o=await Qt(e,r,t,{timeoutMs:n.timeoutMs});if(o.ok||o.status!==401)return o;let s=await Lt(r,n.agentOsId,{baseUrl:n.baseUrl});return s.ok?{...await Qt(e,s.token,t,{timeoutMs:n.timeoutMs}),refreshedAuth:!0}:{...o,authRefreshFailure:s.reason}}async function rn(e){let r=`${e.baseUrl}/api/agent-os/by-id/${encodeURIComponent(e.agentOsId)}/tasks/${encodeURIComponent(e.taskId)}/release`,t;try{t=await en(r,e.secret,{agentOsId:e.agentOsId,leaseOwner:e.leaseOwner,...e.leaseToken?.trim()?{leaseToken:e.leaseToken.trim()}:{},...e.failureDetail?{failureDetail:e.failureDetail}:{}},{agentOsId:e.agentOsId,baseUrl:e.baseUrl})}catch(s){return{released:!1,httpOk:!1,transportError:!0,releaseResponse:{ok:!1,error:s.message}}}let n=t.response;return{released:t.ok===!0||n?.ok===!0,httpOk:t.ok===!0,transportError:!1,releaseResponse:t.response??t}}var Er=!1;function vs(){Er=!1}async function xs(e){if(Er||w()!=="enforce")return null;Er=!0;try{let r=Jt().runnerId,t=await xr({hasLiveWorker:e.hasLiveWorker,worktreePathFor:({runId:n,workerName:o})=>ks.join($r().worktreesDir,n,o),releaseClaim:async({taskId:n,leaseToken:o,runId:s})=>{let i=await rn({baseUrl:e.baseUrl,secret:e.secret,agentOsId:e.agentOsId,taskId:n,leaseOwner:Yt(s,r),leaseToken:o});return{released:i.released,transportError:i.transportError,detail:i.httpOk?void 0:JSON.stringify(i.releaseResponse).slice(0,200)}}});return t.outcomes.length>0&&console.error(`[daemon] D1b claim recovery: ${t.outcomes.map(n=>`${n.taskId}:${n.action}`).join(", ")}`),t}catch{return null}}var kd=600*1e3,te={storeFailures:0,corruptItemsSeen:0,corruptItemsQuarantined:0,duplicateDrainsObserved:0,halfArchivesCompleted:0};function tn(){return{"planOutbox.storeFailures":te.storeFailures,"planOutbox.corruptItemsSeen":te.corruptItemsSeen,"planOutbox.corruptItemsQuarantined":te.corruptItemsQuarantined,"planOutbox.duplicateDrainsObserved":te.duplicateDrainsObserved,"planOutbox.halfArchivesCompleted":te.halfArchivesCompleted}}var g={keeperStoreFailures:0,meshStoreFailures:0,quotaStoreFailures:0,meshLeaseDivergences:0,meshEnforceStaleInversions:0,quotaVerdictDivergences:0};function W(e){return A(process.env).flags[e]}var nn="daemon-keeper",_s=1800*1e3;function Es(e){if(W("keeper")==="off")return;let r=f();if(r)try{r.saveRecoveryCheckpoint({scope:nn,payloadJson:JSON.stringify(e)})}catch{g.keeperStoreFailures+=1}}function Cs(){if(W("keeper")!=="enforce")return null;let e=f();if(!e)return null;try{let r=e.latestRecoveryCheckpoint(nn);if(!r)return null;let t=JSON.parse(r.payloadJson),n=Date.now()-Date.parse(r.createdAt);if(!Number.isFinite(n)||n>_s)return null;let o=Number(t.consecutiveFailures);return Number.isFinite(o)&&o>=0?Math.floor(o):null}catch{return g.keeperStoreFailures+=1,null}}function Cr(e){return`mesh-cron-lease:${e}`}function As(e,r){if(W("meshLease")==="off")return;let t=f();if(t)try{let n=t.latestRecoveryCheckpoint(Cr(e));if(n){let o=JSON.parse(n.payloadJson);if((o.leaseToken??null)===(r.leaseToken??null)&&(o.holderBoxId??null)===(r.holderBoxId??null)&&o.authorized===r.authorized)return}t.saveRecoveryCheckpoint({scope:Cr(e),payloadJson:JSON.stringify(r)})}catch{g.meshStoreFailures+=1}}function ws(e,r){let t=W("meshLease");if(t==="off")return null;let n=f();if(!n)return null;try{let o=n.latestRecoveryCheckpoint(Cr(e)),s=o?JSON.parse(o.payloadJson):null,i=s!==null&&((s.leaseToken??null)!==(r?.leaseToken??null)||(s.holderBoxId??null)!==(r?.holderBoxId??null)||(s.authorized??null)!==(r?.authorized??null));return i&&(g.meshLeaseDivergences+=1),t!=="enforce"?null:i&&r?.updatedAt&&s?.updatedAt&&Date.parse(r.updatedAt)>Date.parse(s.updatedAt)?(g.meshEnforceStaleInversions+=1,null):s}catch{return g.meshStoreFailures+=1,null}}function Te(e){return`quota-cooldown:${e}`}var on="quota-preflight";function Os(e,r){if(W("quota")==="off")return;let t=f();if(t)try{t.tryReserveAdmission(Te(e),on,r)}catch{g.quotaStoreFailures+=1}}function Is(e){if(W("quota")==="off")return;let r=f();if(r)try{r.releaseAdmission(Te(e),on)}catch{g.quotaStoreFailures+=1}}function Ts(e,r){let t=W("quota");if(t==="off")return null;let n=f();if(!n)return null;try{let o=n.listAdmissionReservations({keyPrefix:Te(e),limit:50}).find(i=>i.key===Te(e)),s=!!o;return s!==r&&(g.quotaVerdictDivergences+=1),t==="enforce"?{blocked:s,retryAtIso:o?.expiresAt??null}:null}catch{return g.quotaStoreFailures+=1,null}}function Ar(){return{"keeper.storeFailures":g.keeperStoreFailures,"meshLease.storeFailures":g.meshStoreFailures,"meshLease.divergences":g.meshLeaseDivergences,"meshLease.enforceStaleInversions":g.meshEnforceStaleInversions,"quota.storeFailures":g.quotaStoreFailures,"quota.verdictDivergences":g.quotaVerdictDivergences}}function Ns(){g.keeperStoreFailures=0,g.meshStoreFailures=0,g.quotaStoreFailures=0,g.meshLeaseDivergences=0,g.meshEnforceStaleInversions=0,g.quotaVerdictDivergences=0}function Ps(e){let r=ar(),t=A(e?.env??process.env),n=(e?.now??(()=>new Date))().getTime(),o={};if(t.flags.dispatchReceipts!=="off"){Object.assign(o,hr());let s=gr({nowMs:n,hasLiveWorker:e?.hasLiveWorker});o["dispatchReceipts.strandedClaimCandidates"]=s.strandedClaimCandidates,t.flags.dispatchReceipts==="enforce"&&Object.assign(o,_r())}return t.flags.planOutbox!=="off"&&Object.assign(o,tn()),t.flags.admission!=="off"&&(Object.assign(o,br()),t.flags.admission==="enforce"&&Object.assign(o,vr())),(t.flags.keeper!=="off"||t.flags.meshLease!=="off"||t.flags.quota!=="off")&&Object.assign(o,Ar()),{contractVersion:1,observedAt:new Date(n).toISOString(),state:r.state,schemaVersion:r.schemaVersion,recovered:r.recovered,unavailableClass:r.reason?r.reason.split(":")[0]??null:null,flags:t.flags,flagSources:t.sources,flagWarningCount:t.warnings.length,divergenceCounters:o}}export{U as ADMISSION_RESERVATION_TTL_MS,Ie as ADMISSION_SLOT_KEY_PREFIX,X as FilesystemPolicyError,Ft as LOCAL_RUN_STORE_OPEN_RETRY_MS,Bt as LOCAL_RUN_STORE_SURFACES,Pe as LOCAL_SCHEMA_VERSION,ne as SchemaDowngradeRefusedError,Y as SqliteLocalRunStore,os as __resetAdmissionEnforceCountersForTests,rs as __resetAdmissionShadowCountersForTests,ds as __resetDispatchClaimRecoveryForTests,Xo as __resetDispatchReceiptCountersForTests,wo as __resetLocalRunStoreLifecycleForTests,Mo as __resetRemoteSurfaceFlagsCacheForTests,Ns as __resetSmallSurfaceCountersForTests,vs as __resetStartupClaimRecoveryForTests,Eo as __setLocalRunStoreLifecycleTestOverrides,ts as acquireWorkerAdmissionSlot,vr as admissionEnforceCounters,br as admissionShadowCounters,Ko as anyLocalRunStoreSurfaceActive,Ts as assessQuotaCooldownReservation,Ps as buildLocalRunStoreTickPosture,Ne as classifyDatabaseDirectory,Is as clearQuotaCooldownReservation,lr as closeLocalRunStore,_r as dispatchClaimRecoveryCounters,hr as dispatchReceiptCounters,w as dispatchReceiptsMode,Do as extractLocalRunStoreFlagsFromOperatorTickResponse,jt as findLiveProcessByCmdlinePath,f as getLocalRunStore,Ut as getLocalRunStoreLifecycleStatus,dr as getRemoteSurfaceFlags,q as leaseTokenAttempt,Vo as listRecentDispatchStartFailures,xs as maybeRunStartupClaimRecovery,Wo as noteCompletionReplayIfAcked,De as openSqliteLocalRunStoreWithRecovery,Wt as parseLocalRunStoreSurfaceMode,Lo as persistRemoteSurfaceFlags,ar as probeLocalRunStore,ws as readMeshLeaseCheckpoint,Qo as rearmAdmissionAdoptionPass,es as reconcileAdmissionShadow,ns as reconcileNumberedAdmissionSlots,Bo as recordCompletionAckedReceipt,Uo as recordCompletionSentReceipt,Fo as recordDispatchClaimReceipt,Ee as recordDispatchReleasedReceipt,fr as recordDispatchSpawnedReceipt,Yo as recordDispatchStartFailedReceipt,Os as recordQuotaCooldownReservation,xr as recoverStrandedDispatchClaims,$o as releaseReasonClass,kr as releaseWorkerAdmissionSlot,Sr as releaseWorkerSlotReservation,cr as remoteSurfaceFlagsPath,A as resolveLocalRunStoreSurfaceFlags,Cs as restoreKeeperBackoffCheckpoint,Es as saveKeeperBackoffCheckpoint,As as saveMeshLeaseCheckpoint,gr as scanDispatchReceiptInvariants,Ho as shouldShortCircuitCompletionReplay,Ar as smallSurfaceCounters,Zo as takeWorkerSlotReservation};
@@ -1,8 +1,8 @@
1
- var u=(e,r,t)=>()=>{if(t)throw t[0];try{return e&&(r=e(e=0)),r}catch(n){throw t=[n],n}};function J(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 ke(e){let r=e.trim();if(!r)return null;let t=J(r);if(t)return t;let n=[],s=/```(?:json)?\s*([\s\S]*?)```/gi,o;for(;(o=s.exec(r))!==null;){let l=J(o[1]??"");l&&n.push(l)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let l=J(r.slice(i,a+1));l&&n.push(l)}return n.length>0?n[n.length-1]:null}function be(e){let r=e.finalResult??e.final_result;if(r!=null)return typeof r=="string"?ke(r)??(r.trim()||null):r;let t=typeof e.summary=="string"?e.summary.trim():"";if(!t)return null;let n=ke(t);return n||t}var Re=u(()=>{"use strict"});var xe=u(()=>{"use strict"});import{existsSync as jr,mkdirSync as vn,readFileSync as Yr,readdirSync as En,renameSync as Cn,rmSync as An,statSync as Se,writeFileSync as wn}from"node:fs";function q(e){console.error(e),process.exit(1)}function X(e){return process.platform!=="win32"?e:{windowsHide:!0,...e}}function I(e){try{return JSON.parse(e)}catch{return null}}function P(e){try{return Se(e).size}catch{return 0}}function T(e){try{return Se(e).mtime.toISOString()}catch{return null}}function _e(e,r){return jr(e)?Yr(e,"utf8").split(`
1
+ var u=(e,r,t)=>()=>{if(t)throw t[0];try{return e&&(r=e(e=0)),r}catch(n){throw t=[n],n}};function J(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 be(e){let r=e.trim();if(!r)return null;let t=J(r);if(t)return t;let n=[],s=/```(?:json)?\s*([\s\S]*?)```/gi,o;for(;(o=s.exec(r))!==null;){let l=J(o[1]??"");l&&n.push(l)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let l=J(r.slice(i,a+1));l&&n.push(l)}return n.length>0?n[n.length-1]:null}function ke(e){let r=e.finalResult??e.final_result;if(r!=null)return typeof r=="string"?be(r)??(r.trim()||null):r;let t=typeof e.summary=="string"?e.summary.trim():"";if(!t)return null;let n=be(t);return n||t}var Re=u(()=>{"use strict"});var xe=u(()=>{"use strict"});import{existsSync as jr,mkdirSync as vn,readFileSync as Yr,readdirSync as En,renameSync as Cn,rmSync as An,statSync as Se,writeFileSync as wn}from"node:fs";function q(e){console.error(e),process.exit(1)}function X(e){return process.platform!=="win32"?e:{windowsHide:!0,...e}}function I(e){try{return JSON.parse(e)}catch{return null}}function P(e){try{return Se(e).size}catch{return 0}}function T(e){try{return Se(e).mtime.toISOString()}catch{return null}}function _e(e,r){return jr(e)?Yr(e,"utf8").split(`
2
2
  `).slice(-r).join(`
3
3
  `):""}function N(e){if(!e)return!1;try{return process.kill(e,0),!0}catch{return!1}}function ve(e){let r=null,t=-1/0;for(let n of e){if(!n)continue;let s=Date.parse(n);Number.isFinite(s)&&s>t&&(t=s,r=n)}return r}function Z(e){return Math.max(0,Math.round((Date.now()-e)/1e3))}var f=u(()=>{"use strict";xe()});import{existsSync as Vr,readFileSync as Gr}from"node:fs";function Ee(e){return e==="complete"}function Ce(e){return Ee(e.lastHeartbeatPhase)?e.terminalFinalResult!==void 0&&e.terminalFinalResult!==null?e.terminalFinalResult:e.lastHeartbeatSummary?.trim()||"completed":null}function Ae(e){let r={heartbeatCount:0,lastHeartbeatAt:null,lastHeartbeatPhase:null,lastHeartbeatSummary:null,terminalFinalResult:null,heartbeatBlocker:null,timestampAnomalies:[],lastBoxResourceSnapshot:null,lastPrEvidence:[]};if(!Vr(e))return r;let t=Date.now()+zr,n=new Date(t).toISOString(),s=Gr(e,"utf8").split(`
4
- `).filter(Boolean);for(let o of s){let i=I(o);if(!i||typeof i!="object"||Array.isArray(i))continue;let a=i;if(r.heartbeatCount++,a.ts){let l=String(a.ts),c=Date.parse(l);Number.isFinite(c)&&c>t?r.timestampAnomalies.push({kind:"future_heartbeat_timestamp",observedAt:l,clampedTo:n}):r.lastHeartbeatAt=l}a.phase!==void 0&&a.phase!==null&&(r.lastHeartbeatPhase=String(a.phase)),a.summary!==void 0&&a.summary!==null&&(r.lastHeartbeatSummary=String(a.summary)),Ee(r.lastHeartbeatPhase)&&(r.terminalFinalResult=be(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(l=>!!l&&typeof l=="object"&&typeof l.prUrl=="string"))}return r}var zr,we=u(()=>{"use strict";Re();f();zr=6e4});function Ie(e){return e?(e.split("/").pop()??e).replace(/\.exe$/i,"").toLowerCase():null}function K(e){if(!e)return[];let r=[],t="",n,s=!1;for(let o of e){if(s){t+=o,s=!1;continue}if(o==="\\"){s=!0;continue}if(n){o===n?n=void 0:t+=o;continue}if(o==='"'||o==="'"){n=o;continue}if(/\s/.test(o)){t&&(r.push(t),t="");continue}t+=o}return t&&r.push(t),r}function Pe(e){let r=Ie(e[0]);return!!(r&&Jr.has(r))}function Xr(e){let r=e.trim();return r.includes("/")?r.split("/").pop()??r:r}function Zr(e){if(!e||e.includes("*"))return null;let r=Xr(e);return!r||r.includes("/")?null:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(r)?r:null}function Te(e){return!e||e.includes("/")||e.includes("*")?!1:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(e)}function Q(e){if(!e)return!1;let r=e.trim();return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")}function Qr(e){if(!e.startsWith("--glob="))return e;let r=e.slice(7);return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")?`--glob=${r}/**`:e}function et(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;Oe.has(n)&&(t+=1);continue}r.push(n)}}return r}function rt(e){let r=!1,t=e.map((s,o)=>{let i=Qr(s),a=e[o-1];return a&&Oe.has(a)&&s.startsWith("!")&&!s.includes("/")&&!s.endsWith("/**")&&(i=`${s}/**`),i!==s&&(r=!0),i}),n=et(t);if(n.length===2){let[s,o]=n;if(Q(o))return{argv:[t[0]??"rg",s,"-g",`${o}/**`,"."],changed:!0};let i=Zr(o);if(i)return{argv:[t[0]??"rg","-g",i,s,"."],changed:!0}}return r&&n.length===1?{argv:[...t,"."],changed:!0}:{argv:t,changed:r}}function Ne(e){for(let r=1;r<e.length;r+=1){let t=e[r];if(t&&(t==="-c"||t==="-lc"||t==="-cl"||/^-[a-zA-Z]*c[a-zA-Z]*$/u.test(t)))return r+1}return-1}function W(e){let r=e.trim();if(!r)return{command:r,wrapped:!1};let t=K(r);if(!t.length)return{command:r,wrapped:!1};let n=Ie(t[0]);if(!n||!qr.has(n))return{command:r,wrapped:!1};let s=Ne(t);if(s<0||s>=t.length)return{command:r,wrapped:!1};let o=t.slice(s).join(" ").trim();return o?{command:o,wrapped:!0}:{command:r,wrapped:!1}}function tt(e,r){let t=e.trim(),n=K(t),s=Ne(n);if(s<0)return r;let o=n.slice(0,s).join(" "),i=r.includes("'")?`"${r.replace(/"/g,'\\"')}"`:`'${r}'`;return`${o} ${i}`}function nt(e){let r=e.trim(),t=W(r),n=K(t.command);if(!n.length||!Pe(n))return{segment:r,changed:!1};let s=rt(n);if(!s.changed)return{segment:r,changed:!1};let o=s.argv.join(" ");return t.wrapped?{segment:tt(r,o),changed:!0}:{segment:o,changed:!0}}function ee(e){let r=e.trim();if(!r)return{command:r,changed:!1};let t=r.includes("&&")?" && ":r.includes("||")?" || ":"; ",n=r.split(/\s*(?:&&|\|\||;)\s*/u),s=!1,o=n.map(i=>{let a=nt(i);return a.changed&&(s=!0),a.segment});return s?{command:o.join(t),changed:!0}:{command:r,changed:!1}}function Ke(e){let r=W(e).command,t=K(r.trim());return t.length&&Pe(t)?!0:/\b(rg|ripgrep)\b/i.test(r)}function We(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 ot(e){let{pattern:r,target:t}=We(e);return r?Q(t)?{kind:"rg_exclude_syntax",pattern:r,target:t}:Te(t)?{kind:"bad_scope",pattern:r,target:t}:{kind:"not_repo_search",pattern:r,target:t}:{kind:"not_repo_search"}}function st(e){let{pattern:r,target:t}=We(e);if(!r)return null;if(Q(t)){let n=`${t.trim()}/**`;return{command:`rg "${r}" -g '${n}' .`,changed:!0}}return t&&Te(t)?{command:`rg -g ${t} "${r}" .`,changed:!0}:null}function it(e){if(e.kind==="bad_scope"&&e.pattern&&e.target)return`Use \`rg -g '${e.target}' ${e.pattern} .\` from the repo root instead of treating ${e.target} as a folder.`;if(e.kind==="rg_exclude_syntax"&&e.pattern){let r=e.target?`${e.target.trim()}/**`:"!node_modules/**";return`Repo search scope \`${e.target??"!node_modules"}\` is not a valid ripgrep path. Use \`rg "${e.pattern}" -g '${r}' .\` from the repo root (exclude globs need a \`/**\` suffix).`}return e.kind==="no_matches"&&e.pattern?`No matches for "${e.pattern}". Try a broader pattern, drop overly short tokens, or search from the repo root with \`rg "${e.pattern}" .\`.`:null}function at(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 re(e){let r=e.meta?.trim()||(e.command?at(e.command):null)||null;if(r){let t=ot(r),n=it(t);if(n)return n;let s=st(r);if(s?.changed)return`Repo search used an invalid scope. Retry with: \`${s.command}\`.`}if(e.command&&/\b(rg|ripgrep)\b/i.test(e.command)){let t=ee(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 Jr,qr,Oe,Ue=u(()=>{"use strict";Jr=new Set(["rg","ripgrep","grep"]),qr=new Set(["bash","sh","dash","zsh"]),Oe=new Set(["-e","--regexp","-f","--file","-m","--max-count","-A","--after-context","-B","--before-context","-C","--context","-g","--glob","--iglob"])});function v(e,r=200){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function ct(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 E(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function dt(e){let r=e.metadata;if(!E(r))return null;let t=r.vulnerabilities;if(!E(t))return null;let n=o=>typeof t[o]=="number"?t[o]:0,s={info:n("info"),low:n("low"),moderate:n("moderate"),high:n("high"),critical:n("critical"),total:n("total")};return typeof t.total!="number"&&!s.critical&&!s.high&&!s.moderate&&!s.low&&!s.info?null:s}function mt(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 pt(e,r){let t=e.error;if(E(t)){let o=typeof t.summary=="string"?t.summary.trim():"",i=typeof t.code=="string"?t.code.trim():"";if(o)return i?`${i}: ${o}`:o;if(i)return i}let n=typeof e.message=="string"?e.message.trim():"";if(n)return n;let s=r.trim();return s?v(s.split(`
4
+ `).filter(Boolean);for(let o of s){let i=I(o);if(!i||typeof i!="object"||Array.isArray(i))continue;let a=i;if(r.heartbeatCount++,a.ts){let l=String(a.ts),c=Date.parse(l);Number.isFinite(c)&&c>t?r.timestampAnomalies.push({kind:"future_heartbeat_timestamp",observedAt:l,clampedTo:n}):r.lastHeartbeatAt=l}a.phase!==void 0&&a.phase!==null&&(r.lastHeartbeatPhase=String(a.phase)),a.summary!==void 0&&a.summary!==null&&(r.lastHeartbeatSummary=String(a.summary)),Ee(r.lastHeartbeatPhase)&&(r.terminalFinalResult=ke(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(l=>!!l&&typeof l=="object"&&typeof l.prUrl=="string"))}return r}var zr,we=u(()=>{"use strict";Re();f();zr=6e4});function Ie(e){return e?(e.split("/").pop()??e).replace(/\.exe$/i,"").toLowerCase():null}function K(e){if(!e)return[];let r=[],t="",n,s=!1;for(let o of e){if(s){t+=o,s=!1;continue}if(o==="\\"){s=!0;continue}if(n){o===n?n=void 0:t+=o;continue}if(o==='"'||o==="'"){n=o;continue}if(/\s/.test(o)){t&&(r.push(t),t="");continue}t+=o}return t&&r.push(t),r}function Pe(e){let r=Ie(e[0]);return!!(r&&Jr.has(r))}function Xr(e){let r=e.trim();return r.includes("/")?r.split("/").pop()??r:r}function Zr(e){if(!e||e.includes("*"))return null;let r=Xr(e);return!r||r.includes("/")?null:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(r)?r:null}function Te(e){return!e||e.includes("/")||e.includes("*")?!1:/\.(?:json|md|mjs|cjs|js|ts|tsx|yaml|yml)$/iu.test(e)}function Q(e){if(!e)return!1;let r=e.trim();return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")}function Qr(e){if(!e.startsWith("--glob="))return e;let r=e.slice(7);return r.startsWith("!")&&!r.includes("/")&&!r.endsWith("/**")?`--glob=${r}/**`:e}function et(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;Oe.has(n)&&(t+=1);continue}r.push(n)}}return r}function rt(e){let r=!1,t=e.map((s,o)=>{let i=Qr(s),a=e[o-1];return a&&Oe.has(a)&&s.startsWith("!")&&!s.includes("/")&&!s.endsWith("/**")&&(i=`${s}/**`),i!==s&&(r=!0),i}),n=et(t);if(n.length===2){let[s,o]=n;if(Q(o))return{argv:[t[0]??"rg",s,"-g",`${o}/**`,"."],changed:!0};let i=Zr(o);if(i)return{argv:[t[0]??"rg","-g",i,s,"."],changed:!0}}return r&&n.length===1?{argv:[...t,"."],changed:!0}:{argv:t,changed:r}}function Ne(e){for(let r=1;r<e.length;r+=1){let t=e[r];if(t&&(t==="-c"||t==="-lc"||t==="-cl"||/^-[a-zA-Z]*c[a-zA-Z]*$/u.test(t)))return r+1}return-1}function W(e){let r=e.trim();if(!r)return{command:r,wrapped:!1};let t=K(r);if(!t.length)return{command:r,wrapped:!1};let n=Ie(t[0]);if(!n||!qr.has(n))return{command:r,wrapped:!1};let s=Ne(t);if(s<0||s>=t.length)return{command:r,wrapped:!1};let o=t.slice(s).join(" ").trim();return o?{command:o,wrapped:!0}:{command:r,wrapped:!1}}function tt(e,r){let t=e.trim(),n=K(t),s=Ne(n);if(s<0)return r;let o=n.slice(0,s).join(" "),i=r.includes("'")?`"${r.replace(/"/g,'\\"')}"`:`'${r}'`;return`${o} ${i}`}function nt(e){let r=e.trim(),t=W(r),n=K(t.command);if(!n.length||!Pe(n))return{segment:r,changed:!1};let s=rt(n);if(!s.changed)return{segment:r,changed:!1};let o=s.argv.join(" ");return t.wrapped?{segment:tt(r,o),changed:!0}:{segment:o,changed:!0}}function ee(e){let r=e.trim();if(!r)return{command:r,changed:!1};let t=r.includes("&&")?" && ":r.includes("||")?" || ":"; ",n=r.split(/\s*(?:&&|\|\||;)\s*/u),s=!1,o=n.map(i=>{let a=nt(i);return a.changed&&(s=!0),a.segment});return s?{command:o.join(t),changed:!0}:{command:r,changed:!1}}function Ke(e){let r=W(e).command,t=K(r.trim());return t.length&&Pe(t)?!0:/\b(rg|ripgrep)\b/i.test(r)}function We(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 ot(e){let{pattern:r,target:t}=We(e);return r?Q(t)?{kind:"rg_exclude_syntax",pattern:r,target:t}:Te(t)?{kind:"bad_scope",pattern:r,target:t}:{kind:"not_repo_search",pattern:r,target:t}:{kind:"not_repo_search"}}function st(e){let{pattern:r,target:t}=We(e);if(!r)return null;if(Q(t)){let n=`${t.trim()}/**`;return{command:`rg "${r}" -g '${n}' .`,changed:!0}}return t&&Te(t)?{command:`rg -g ${t} "${r}" .`,changed:!0}:null}function it(e){if(e.kind==="bad_scope"&&e.pattern&&e.target)return`Use \`rg -g '${e.target}' ${e.pattern} .\` from the repo root instead of treating ${e.target} as a folder.`;if(e.kind==="rg_exclude_syntax"&&e.pattern){let r=e.target?`${e.target.trim()}/**`:"!node_modules/**";return`Repo search scope \`${e.target??"!node_modules"}\` is not a valid ripgrep path. Use \`rg "${e.pattern}" -g '${r}' .\` from the repo root (exclude globs need a \`/**\` suffix).`}return e.kind==="no_matches"&&e.pattern?`No matches for "${e.pattern}". Try a broader pattern, drop overly short tokens, or search from the repo root with \`rg "${e.pattern}" .\`.`:null}function at(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 re(e){let r=e.meta?.trim()||(e.command?at(e.command):null)||null;if(r){let t=ot(r),n=it(t);if(n)return n;let s=st(r);if(s?.changed)return`Repo search used an invalid scope. Retry with: \`${s.command}\`.`}if(e.command&&/\b(rg|ripgrep)\b/i.test(e.command)){let t=ee(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 Jr,qr,Oe,Ue=u(()=>{"use strict";Jr=new Set(["rg","ripgrep","grep"]),qr=new Set(["bash","sh","dash","zsh"]),Oe=new Set(["-e","--regexp","-f","--file","-m","--max-count","-A","--after-context","-B","--before-context","-C","--context","-g","--glob","--iglob"])});function v(e,r=200){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function ct(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 E(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function dt(e){let r=e.metadata;if(!E(r))return null;let t=r.vulnerabilities;if(!E(t))return null;let n=o=>typeof t[o]=="number"?t[o]:0,s={info:n("info"),low:n("low"),moderate:n("moderate"),high:n("high"),critical:n("critical"),total:n("total")};return typeof t.total!="number"&&!s.critical&&!s.high&&!s.moderate&&!s.low&&!s.info?null:s}function mt(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 pt(e,r){let t=e.error;if(E(t)){let o=typeof t.summary=="string"?t.summary.trim():"",i=typeof t.code=="string"?t.code.trim():"";if(o)return i?`${i}: ${o}`:o;if(i)return i}let n=typeof e.message=="string"?e.message.trim():"";if(n)return n;let s=r.trim();return s?v(s.split(`
5
5
  `).find(Boolean)??s,160):"npm audit failed"}function ft(e){let r=`${e.stdout}
6
- ${e.stderr}`.trim(),t=ct(r);if(!t||!E(t)){let s=v(r||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit failed (invalid or missing JSON): ${s}`,parseError:"invalid_json"}}if(E(t.error))return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit command failed: ${pt(t,e.stderr)}`};let n=dt(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:mt(n),audit:n}:{kind:"command_failure",exitCode:e.exitCode,summary:"npm audit failed: JSON response missing vulnerability metadata",parseError:"missing_metadata"}}function gt(e){return lt.test(e)}function ht(e){let r=W(e).command;return Be.test(e)||Be.test(r)||Ke(e)}function yt(e){let r=re({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&&ut.test(n)){let i=v(n,160);return{kind:"command_failure",exitCode:1,summary:r??`ripgrep failed (exit 1): ${i}`}}let s=ee(e.command),o=s.changed&&!r?` Retry with: \`${s.command}\`.`:"";return{kind:"search_no_matches",exitCode:1,summary:r??`ripgrep: no matches (exit 1).${o} Try a broader pattern or search from the repo root.`}}let t=v(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 De(e){let r=e.stdout??"",t=e.stderr??"",n=e.interleavedOutput??"";if(gt(e.command)){let i=r.trim()||n.trim()||t.trim();return ft({exitCode:e.exitCode,stdout:i,stderr:t})}if(ht(e.command))return yt({command:e.command,exitCode:e.exitCode,stdout:r,stderr:t,interleaved:n});let s=re({command:e.command,exitCode:e.exitCode});if(s&&e.exitCode!==0)return{kind:"command_failure",exitCode:e.exitCode,summary:s};if(e.exitCode===0)return{kind:"success",exitCode:0,summary:"command succeeded (exit 0)"};let o=v(n||r||t||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:`command failed (exit ${e.exitCode}): ${o}`}}var lt,Be,ut,Me=u(()=>{"use strict";Ue();lt=/\bnpm\s+audit\b/i,Be=/\b(rg|ripgrep)\b/i,ut=/\b(error|invalid|unknown|panic|not found)\b/i});function C(e){return typeof e=="string"&&kt.test(e.trim())}function U(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let r=e;return r.is_error===!0||r.providerTerminalError===!0||typeof r.subtype=="string"&&/^error(?:_|$)/.test(r.subtype)}var kt,B=u(()=>{"use strict";kt=/^(?:provider authentication failed:\s*)?(?:(?:Failed to authenticate|authentication (?:failed|error))(?::\s*[^\n.!?]+)?|OAuth session expired and could not be refreshed)[.!]?$/i});import{existsSync as bt,readFileSync as Rt}from"node:fs";function xt(e){let r=e.timestamp_ms;return e.timestamp||e.ts||(r?new Date(r).toISOString():void 0)}function St(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 _t(e,r){e.finalResult=r.result||r.subtype||r.terminal_reason||"completed",U(r)&&(e.providerTerminalError=!0,e.error=String(r.result||r.api_error_status||"stream result error"))}function R(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function vt(e){let r=e.usage;return r&&typeof r=="object"&&!Array.isArray(r)?r:null}function Et(e){if(typeof e.model=="string"&&e.model.trim())return e.model.trim();let r=e.modelUsage;if(r&&typeof r=="object"&&!Array.isArray(r)){let t=Object.keys(r)[0];if(t?.trim())return t.trim()}}function Ct(e,r){let t=vt(r);if(!t)return;let n=R(t.input_tokens)??R(t.inputTokens)??R(t.prompt_tokens),s=R(t.output_tokens)??R(t.outputTokens)??R(t.completion_tokens);if(n===void 0&&s===void 0)return;let o=Et(r)??e.usage?.model;e.usage={...n!==void 0?{inputTokens:n}:{},...s!==void 0?{outputTokens:s}:{},...o?{model:o}:{}}}function At(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,s=n.args,o=s&&typeof s=="object"&&!Array.isArray(s)&&typeof s.command=="string"?String(s.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 l=a,c=typeof l.exitCode=="number"?l.exitCode:0;return{command:o,exitCode:c,stdout:typeof l.stdout=="string"?l.stdout:"",stderr:typeof l.stderr=="string"?l.stderr:"",interleaved:typeof l.interleavedOutput=="string"?l.interleavedOutput:""}}function wt(e,r){r.kind==="success"||r.kind==="search_no_matches"||(e.lastShellOutcome=r)}function Fe(e){let r={firstEventAt:null,lastEventAt:null,currentTool:null,finalResult:null,error:null,lastShellOutcome:null,usage:null};if(!bt(e))return r;let t=Rt(e,"utf8").split(`
6
+ ${e.stderr}`.trim(),t=ct(r);if(!t||!E(t)){let s=v(r||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit failed (invalid or missing JSON): ${s}`,parseError:"invalid_json"}}if(E(t.error))return{kind:"command_failure",exitCode:e.exitCode,summary:`npm audit command failed: ${pt(t,e.stderr)}`};let n=dt(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:mt(n),audit:n}:{kind:"command_failure",exitCode:e.exitCode,summary:"npm audit failed: JSON response missing vulnerability metadata",parseError:"missing_metadata"}}function gt(e){return lt.test(e)}function ht(e){let r=W(e).command;return Be.test(e)||Be.test(r)||Ke(e)}function yt(e){let r=re({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&&ut.test(n)){let i=v(n,160);return{kind:"command_failure",exitCode:1,summary:r??`ripgrep failed (exit 1): ${i}`}}let s=ee(e.command),o=s.changed&&!r?` Retry with: \`${s.command}\`.`:"";return{kind:"search_no_matches",exitCode:1,summary:r??`ripgrep: no matches (exit 1).${o} Try a broader pattern or search from the repo root.`}}let t=v(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 De(e){let r=e.stdout??"",t=e.stderr??"",n=e.interleavedOutput??"";if(gt(e.command)){let i=r.trim()||n.trim()||t.trim();return ft({exitCode:e.exitCode,stdout:i,stderr:t})}if(ht(e.command))return yt({command:e.command,exitCode:e.exitCode,stdout:r,stderr:t,interleaved:n});let s=re({command:e.command,exitCode:e.exitCode});if(s&&e.exitCode!==0)return{kind:"command_failure",exitCode:e.exitCode,summary:s};if(e.exitCode===0)return{kind:"success",exitCode:0,summary:"command succeeded (exit 0)"};let o=v(n||r||t||`exit ${e.exitCode}`,180);return{kind:"command_failure",exitCode:e.exitCode,summary:`command failed (exit ${e.exitCode}): ${o}`}}var lt,Be,ut,Me=u(()=>{"use strict";Ue();lt=/\bnpm\s+audit\b/i,Be=/\b(rg|ripgrep)\b/i,ut=/\b(error|invalid|unknown|panic|not found)\b/i});function C(e){return typeof e=="string"&&bt.test(e.trim())}function U(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let r=e;return r.is_error===!0||r.providerTerminalError===!0||typeof r.subtype=="string"&&/^error(?:_|$)/.test(r.subtype)}var bt,B=u(()=>{"use strict";bt=/^(?:provider authentication failed:\s*)?(?:(?:Failed to authenticate|authentication (?:failed|error))(?::\s*[^\n.!?]+)?|OAuth session expired and could not be refreshed)[.!]?$/i});import{existsSync as kt,readFileSync as Rt}from"node:fs";function xt(e){let r=e.timestamp_ms;return e.timestamp||e.ts||(r?new Date(r).toISOString():void 0)}function St(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 _t(e,r){e.finalResult=r.result||r.subtype||r.terminal_reason||"completed",U(r)&&(e.providerTerminalError=!0,e.error=String(r.result||r.api_error_status||"stream result error"))}function R(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function vt(e){let r=e.usage;return r&&typeof r=="object"&&!Array.isArray(r)?r:null}function Et(e){if(typeof e.model=="string"&&e.model.trim())return e.model.trim();let r=e.modelUsage;if(r&&typeof r=="object"&&!Array.isArray(r)){let t=Object.keys(r)[0];if(t?.trim())return t.trim()}}function Ct(e,r){let t=vt(r);if(!t)return;let n=R(t.input_tokens)??R(t.inputTokens)??R(t.prompt_tokens),s=R(t.output_tokens)??R(t.outputTokens)??R(t.completion_tokens);if(n===void 0&&s===void 0)return;let o=Et(r)??e.usage?.model;e.usage={...n!==void 0?{inputTokens:n}:{},...s!==void 0?{outputTokens:s}:{},...o?{model:o}:{}}}function At(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,s=n.args,o=s&&typeof s=="object"&&!Array.isArray(s)&&typeof s.command=="string"?String(s.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 l=a,c=typeof l.exitCode=="number"?l.exitCode:0;return{command:o,exitCode:c,stdout:typeof l.stdout=="string"?l.stdout:"",stderr:typeof l.stderr=="string"?l.stderr:"",interleaved:typeof l.interleavedOutput=="string"?l.interleavedOutput:""}}function wt(e,r){r.kind==="success"||r.kind==="search_no_matches"||(e.lastShellOutcome=r)}function Fe(e){let r={firstEventAt:null,lastEventAt:null,currentTool:null,finalResult:null,error:null,lastShellOutcome:null,usage:null};if(!kt(e))return r;let t=Rt(e,"utf8").split(`
7
7
  `).filter(Boolean),n=null;for(let s of t){let o=I(s);if(!o||typeof o!="object"||Array.isArray(o))continue;if(o.type==="turn.started"&&(n=null,r.finalResult=null),o.type==="item.completed"){let l=o.item;if(l&&typeof l=="object"&&!Array.isArray(l)){let c=l;c.type==="agent_message"&&typeof c.text=="string"&&c.text.trim()&&(n=c.text)}}o.type==="turn.completed"&&n&&!r.providerTerminalError&&(r.finalResult=n,n=null);let i=xt(o);if(i&&(r.firstEventAt||=i,r.lastEventAt=i),o.type==="stream_event"&&o.event&&typeof o.event=="object"&&o.event.type==="content_block_start"){let l=o.event.content_block;l?.type==="tool_use"&&(r.currentTool=String(l.name||"tool"))}if(o.type==="assistant"&&o.message&&typeof o.message=="object"){let l=o.message.content;if(Array.isArray(l)){let c=l.find(m=>m?.type==="tool_use");c&&(r.currentTool=String(c.name||r.currentTool))}}if(o.type==="tool_call"&&o.subtype==="started"){let l=o.tool_call&&typeof o.tool_call=="object"&&!Array.isArray(o.tool_call)?o.tool_call:void 0,c=St(l);c&&(r.currentTool=c)}let a=At(o);if(a&&wt(r,De({command:a.command,exitCode:a.exitCode,stdout:a.stdout,stderr:a.stderr,interleavedOutput:a.interleaved})),o.type==="result"&&_t(r,o),o.type==="turn.failed"){n=null,r.finalResult=null,r.providerTerminalError=!0;let l=o.error;r.error=typeof l?.message=="string"?l.message:"provider turn failed"}Ct(r,o)}return r}var Le=u(()=>{"use strict";Me();f();B()});function $e(e,r=240){let t=e.replace(/\s+/g," ").trim();return t.length>r?`${t.slice(0,r-1)}\u2026`:t}function te(e){let r=(e??"").trim();if(!r)return null;if(C(r))return{blocked:!0,reason:`provider authentication failed: ${$e(r)}`};for(let t of Ot)if(t.test.test(r))return{blocked:!0,reason:`${t.label}: ${$e(r)}`};return null}var Ot,He=u(()=>{"use strict";B();Ot=[{test:/(?:claude provider refuses to spawn: worker prompt is empty after argv assembly|Input must be provided (?:either )?through stdin or as a prompt argument)/i,label:"provider prompt delivery failed"},{test:/\b(?:invalid|unknown|unsupported|unrecognized)\b[^.\n]*\bmodel\b/i,label:"provider rejected the requested model"},{test:/\bmodel\b[^.\n]*\b(?:not\s+(?:found|supported|available|recognized|valid)|is\s+not\s+valid|does\s+not\s+exist)/i,label:"provider rejected the requested model"},{test:/\b(?:did you mean|available models|choose (?:a|one of)|supported models)\b/i,label:"provider rejected the requested model"},{test:/model preflight failed/i,label:"model/provider preflight failed"},{test:/\b(?:command not found|ENOENT|is the .*CLI on PATH|executable not found|no such file or directory)\b/i,label:"provider CLI is missing or not on PATH"},{test:/\bfailed to spawn\b/i,label:"provider failed to spawn the worker process"},{test:/\b(?:not logged in|unauthorized|authentication (?:failed|required)|invalid api key|missing api key|401)\b/i,label:"provider authentication failed"},{test:/\b(?:out of usage|increase limits?|switch to auto|ask your admin to increase your limit|usage limits?|quota exceeded|insufficient_quota|credits? exhausted|billing|payment required)\b/i,label:"provider quota exhausted"}]});function je(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function It(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 Pt(e){return!e?.checked||e.headIsAncestorOfBase!==!1?null:je(e.head)}function Tt(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 s=t.length>12?t.slice(0,12):t;n.push(`commit ${s} 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 Ye(e){if(e.alive||It(e.finalResult))return null;let r=(e.changedFiles??[]).filter(i=>i.trim()).length,t=je(e.headCommit)??Pt(e.gitAncestry),n=r>0,s=!!t;if(!n&&!s)return{kind:"none",salvageable:!1,uncommittedCount:0,headCommit:null,attentionReason:"process exited without a final result"};let o=n&&s?"both":n?"uncommitted":"committed_ahead";return{kind:o,salvageable:!0,uncommittedCount:r,headCommit:t,attentionReason:Tt(o,r,t)}}var Ve=u(()=>{"use strict"});var x=u(()=>{"use strict"});var Nt,Jn,Kt,qn,Ge=u(()=>{"use strict";Nt=["ANTHROPIC_API_KEY","ANALYST_API_KEY","RECRUITER_API_KEY","AUTH_SECRET","NEXTAUTH_SECRET","DATABASE_URL","PRODUCTION_DATABASE_URL","KYNVER_PRODUCTION_DATABASE_URL","REDIS_URL","GOOGLE_CLIENT_SECRET","GITHUB_CLIENT_SECRET","KYNVER_API_KEY","KYNVER_SERVICE_SECRET","KYNVER_RUNTIME_SECRET","KYNVER_CRON_SECRET","OPENCLAW_CRON_SECRET","QSTASH_TOKEN","QSTASH_CURRENT_SIGNING_KEY","QSTASH_NEXT_SIGNING_KEY","TOOL_SECRETS_KEK","TOOL_EXECUTOR_DISPATCH_SECRET","CLOUDFLARE_API_TOKEN","STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET","STRIPE_IDENTITY_WEBHOOK_SECRET","VOYAGE_API_KEY","PERPLEXITY_API_KEY","FRED_API_KEY","FMP_API_KEY","CURSOR_API_KEY","MEMORY_CONTENT_KEK","LLM_BYOK_KEK","KYNVER_COMMAND_AUTH_KEY","KYNVER_INSTRUCTION_BUNDLE_KEY","KYNVER_MEMORY_LEDGER_KEY","KYNVER_JWKS_PRIVATE_KEY_JWK"],Jn=new Set(Nt),Kt=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY","GEMINI_API_KEY"],qn=new Set(Kt)});import{spawnSync as Je}from"node:child_process";function Wt(e,r,t={}){let n=Je("git",r,X({cwd:e,encoding:"utf8"}));if(n.status!==0&&!t.allowFailure){let s=Ut(e,r,n);if(t.throwError)throw new Error(s);q(s)}return n.stdout||""}function Ut(e,r,t){let n=typeof t.stderr=="string"&&t.stderr.trim()||typeof t.stdout=="string"&&t.stdout.trim()||t.error?.message||`exit ${t.status??"unknown"}`;return`git ${r.join(" ")} failed in ${e}: ${n}`}function qe(e){return Wt(e,["status","--short"],{allowFailure:!0}).split(`
8
- `).map(r=>r.trim()).filter(Boolean)}function A(e,r){try{let t=Je("git",r,X({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 ze(e,r,t){let n=A(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 Xe(e,r="origin/main"){let t=typeof r=="string"?{base:r}:r,n=t.baseCommit?.trim()||t.base?.trim()||"origin/main",s=t.baseCommit?.trim()||null;if(!e)return ne(n,"missing worktree path");let o=A(e,["rev-parse","HEAD"]);if(o.status!==0)return ne(n,o.error||o.stderr||o.stdout||"failed to resolve HEAD");let i;if(s)i=s;else{let p=A(e,["rev-parse",n]);if(p.status!==0)return ne(n,p.error||p.stderr||p.stdout||`failed to resolve ${n}`,o.stdout.trim());i=p.stdout.trim()}let a=o.stdout.trim();if(a===i)return{checked:!0,base:n,head:a,baseHead:i,baseIsAncestorOfHead:!0,headIsAncestorOfBase:!0,relation:"synced"};let l=ze(e,i,a),c=ze(e,a,i),m=l.error||c.error||void 0;if(l.isAncestor==null||c.isAncestor==null)return{checked:!1,base:n,head:a,baseHead:i,baseIsAncestorOfHead:l.isAncestor,headIsAncestorOfBase:c.isAncestor,relation:"unknown",...m?{error:m}:{}};let d=l.isAncestor?"ahead":c.isAncestor?"merged":"diverged";return{checked:!0,base:n,head:a,baseHead:i,baseIsAncestorOfHead:l.isAncestor,headIsAncestorOfBase:c.isAncestor,relation:d,...m?{error:m}:{}}}function ne(e,r,t=null){return{checked:!1,base:e,head:t,baseHead:null,baseIsAncestorOfHead:null,headIsAncestorOfBase:null,relation:"unknown",error:r}}var D=u(()=>{"use strict";x();f();Ge()});function w(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function Bt(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 Dt(e){if(w(e.headCommit)||w(e.prUrl)||w(e.artifactBundlePath)||w(e.patchPath))return!0;let r=e.gitAncestry;return!!(r?.checked&&r.headIsAncestorOfBase===!1&&w(r.head))}function Ze(e){return Bt(e.finalResult)?e.changedFiles.length===0?{blocked:!1}:Dt(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 Qe(e){if(e.blocked)return e.detail??e.reason??"dirty_worktree_no_pr"}var er=u(()=>{"use strict"});function se(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 rr(e){let r=e.targetPrReconciliation??e.target_pr_reconciliation??e.targetPrs??e.target_prs;return Array.isArray(r)?r.length:0}function M(e){let r=e.trim();if(!r)return null;let t=se(r);if(t)return t;let n=[],s=/```(?:json)?\s*([\s\S]*?)```/gi,o;for(;(o=s.exec(r))!==null;){let m=se(o[1]??"");m&&n.push(m)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let m=se(r.slice(i,a+1));m&&n.push(m)}if(n.length===0)return null;let l=n[n.length-1],c=rr(l);for(let m of n){let d=rr(m);d>c&&(l=m,c=d)}return l}var ie=u(()=>{"use strict"});function tr(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 nr(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function Mt(e){return new Set(e.map(r=>nr(tr(r)??r)).filter(Boolean))}function or(e,r,t){let n=tr(e)??e;if(!n)return"unrelated";let s=nr(n);return Mt(r).has(s)?"contract":t?(t.outcome==="skipped"||t.outcome==="blocked")&&t.reason?.trim()?"support":(t.outcome==="merged","unrelated"):"unrelated"}var sr=u(()=>{"use strict"});function S(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function Ft(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"?Object.keys(e).length>0:!0}function k(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`https://github.com/${r[1]}/pull/${r[2]}`:S(e)}function F(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function ir(e){let r=null;if(typeof e=="string"){let s=M(e);s&&(r=s)}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 s of t){if(!s||typeof s!="object"||Array.isArray(s))continue;let o=s,i=k(String(o.prUrl??o.pr_url??"")),a=S(o.outcome);!i||a!=="merged"&&a!=="skipped"&&a!=="blocked"||n.push({prUrl:i,outcome:a,mergeCommit:S(o.mergeCommit??o.merge_commit),reason:S(o.reason)})}return n}function ar(e,r){let t=[],n=k(S(e.prUrl)??"");if(n&&t.push(n),r&&typeof r=="object"&&!Array.isArray(r)){let s=r,o=k(String(s.prUrl??s.pr_url??""));o&&t.push(o)}return[...new Set(t)]}function lr(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(!Ft(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 o=r.repairEnforceOriginalPr?k(S(r.targetPrUrl)??"")??(r.targetPrUrls.length===1?k(r.targetPrUrls[0]):null):null;if(o){let d=ar(t,n);if(!(n&&typeof n=="object"&&!Array.isArray(n)&&n.supersedesOriginalTargetPr===!0)){for(let y of d)if(y!==o)return{blocked:!0,reason:"duplicate_repair_pr",detail:`Repair worker opened or attached PR ${y} instead of canonical target ${o}`}}let h=ir(n).find(y=>y.prUrl===o);if(!h||h.outcome!=="merged"&&!(h.reason?.trim()&&(h.outcome==="skipped"||h.outcome==="blocked")))return{blocked:!0,reason:"missing_repair_target_reconciliation",detail:`Repair worker must reconcile target PR ${o}`}}let i=ir(n),a=new Map(i.map(d=>[F(d.prUrl),d])),l=new Set(r.targetPrUrls.map(d=>F(k(d)??d)).filter(Boolean)),c=ar(t,n);if(r.landingOnly)for(let d of c){let p=a.get(F(d)),g=or(d,r.targetPrUrls,p);if(!(g==="contract"||g==="support"))return l.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 m=[];for(let d of r.targetPrUrls){let p=F(k(d)??d),g=a.get(p);if(!g){m.push(p);continue}g.outcome!=="merged"&&!g.reason?.trim()&&m.push(p)}return m.length>0?{blocked:!0,reason:m.every(d=>a.has(d))?"incomplete_target_pr_landing":"missing_target_pr_reconciliation",detail:`Target PR reconciliation incomplete: ${m.join(", ")}`}:{blocked:!1}}function ur(e){if(e.blocked)return e.detail??e.reason}var cr=u(()=>{"use strict";ie();sr()});function $t(e){let r=Date.now();if(e.providerTerminalError||U(e.finalResult)||e.finalResult&&e.error?.trim()||C(e.error)||C(e.finalResult)){let s=e.error||(typeof e.finalResult=="string"?e.finalResult:"provider terminal error");return{state:"blocked",reason:te(s)?.reason??`provider terminal error: ${s}`}}if(e.completionBlocker&&!dr(e.completionBlocker))return{state:"blocked",reason:e.completionBlocker};if(e.finalResult){if(e.localOnly&&jt(e.finalResult))return{state:"done",reason:"local-only worker superseded by merged PR"};let s={finalResult:e.finalResult,changedFiles:e.changedFiles??[],gitAncestry:e.gitAncestry??null,prUrl:e.prUrl??null},o=Ze(s);if(o.blocked){let i=Qe(o);return{state:"needs_attention",reason:o.reason?`landing blocked (${o.reason}): ${i}`:`landing blocked: ${i}`}}if(e.landingContract){let i=lr({contract:e.landingContract,snapshot:s,finalResult:e.finalResult}),a=ur(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(Ht(e))return{state:"done",reason:"empty abandoned worker record"};let s=te(e.error);if(s)return{state:"blocked",reason:s.reason};let o=Ye({alive:!1,finalResult:null,changedFiles:e.changedFiles,gitAncestry:e.gitAncestry});if(o?.salvageable){let a=e.error?.trim();return{state:"needs_attention",reason:a?`${o.attentionReason} (${a})`:o.attentionReason}}let i=e.error?.trim();return{state:"needs_attention",reason:i?`process exited without a final result: ${i}`:o?.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>Lt)return{state:"needs_attention",reason:`no first stream event ${Z(t)}s after start`};let n=e.lastActivityAt?Date.parse(e.lastActivityAt):NaN;return Number.isFinite(n)&&r-n>L?{state:"stale",reason:`no log/event/heartbeat activity for ${Z(n)}s`}:{state:"ok",reason:"recent activity"}}function dr(e){let r=e?.trim();return r?/completion acknowledged but board not advanced/i.test(r)&&/task already terminal/i.test(r):!1}function Ht(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 jt(e){let r=null;if(typeof e=="string"?r=M(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 Yt(e,r,t){let n=e.completionSnapshot?.finalResult;return e.completionAckSource==="local-pr-merged-reconcile"&&n!==void 0&&n!==null?n:r||(n??Ce(t))}function mr(e,r={}){let t=Fe(e.stdoutPath),n=Ae(e.heartbeatPath),s=typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim().length>0,o=Yt(e,t.finalResult,n),i=s?!1:N(e.pid),a=P(e.stdoutPath),l=P(e.stderrPath),c=P(e.heartbeatPath),m=qe(e.worktreePath),d=Xe(e.worktreePath,{base:r.base,baseCommit:r.baseCommit}),p=ve([t.lastEventAt,n.lastHeartbeatAt,T(e.stdoutPath),T(e.stderrPath),T(e.heartbeatPath)]),g=t.error||!i&&!o&&_e(e.stderrPath,10).trim()||void 0,h=typeof e.completionBlocker=="string"&&e.completionBlocker.trim()?e.completionBlocker.trim():null,y=dr(h)?null:h,$r=e.repairTargetPrUrl?{landingOnly:!1,targetPrUrls:[e.repairTargetPrUrl],targetPrUrl:e.repairTargetPrUrl,repairEnforceOriginalPr:!0}:null,z=$t({alive:i,finalResult:o,firstEventAt:t.firstEventAt,stdoutBytes:a,stderrBytes:l,heartbeatBytes:c,lastActivityAt:p,heartbeatBlocker:n.heartbeatBlocker,startedAt:e.startedAt,error:g,providerTerminalError:t.providerTerminalError,changedFiles:m,gitAncestry:d,completionBlocker:y,landingContract:$r,prUrl:e.repairTargetPrUrl??e.taskPrUrl??null,localOnly:e.localOnly===!0,taskId:e.taskId??null,agentOsId:e.agentOsId??null,reconcileReason:e.reconcileReason??null}),Hr=y||z.state==="blocked"?"blocked":s||z.state==="done"?"done":o?"exited":i?"running":"exited";return{runId:e.runId,worker:e.name,pid:e.pid,alive:i,status:Hr,attention:z,branch:e.branch,worktreePath:e.worktreePath,ownedPaths:e.ownedPaths,stdoutBytes:a,stderrBytes:l,heartbeatBytes:c,firstEventAt:t.firstEventAt,lastEventAt:t.lastEventAt,lastActivityAt:p,currentTool:s?null:t.currentTool,heartbeatCount:n.heartbeatCount,lastHeartbeatAt:n.lastHeartbeatAt,lastHeartbeatPhase:n.lastHeartbeatPhase,lastHeartbeatSummary:n.lastHeartbeatSummary,heartbeatBlocker:n.heartbeatBlocker,timestampAnomalies:n.timestampAnomalies,finalResult:o,error:g,providerTerminalError:t.providerTerminalError,changedFiles:m,gitAncestry:d,instructionPolicyFingerprint:e.instructionPolicyFingerprint??null,instructionPolicyEvidence:e.instructionPolicyEvidence??null,model:e.model??e.orchestrationAudit?.model??null,provider:e.provider??e.orchestrationAudit?.provider??null,usage:t.usage??null,boxKind:e.boxKind??null,boxId:e.boxId??null,runtimeId:e.runtimeId??null,personaSlug:e.personaSlug??null,dispatched:e.dispatched??null,localOnly:e.localOnly??null}}function pr(e){return!!(e.finalResult||e.alive===!1||e.status==="exited"||e.status==="done")}function fr(e){return e.finalResult?e.attention.state==="needs_attention"||e.attention.state==="blocked":!1}var Lt,L,O=u(()=>{"use strict";we();Le();B();He();Ve();D();er();cr();ie();f();Lt=18e4,L=6e5});var kr=u(()=>{"use strict";D()});var ae=u(()=>{"use strict";D();x();kr()});var le=u(()=>{"use strict";f()});var b=u(()=>{"use strict"});var $=u(()=>{"use strict"});var br=u(()=>{"use strict"});var Lo,$o,ue=u(()=>{"use strict";Lo=25*1024*1024*1024,$o=12*1024*1024*1024});var Go,zo,Rr=u(()=>{"use strict";ue();Go=5*1024*1024*1024,zo=10*1024*1024*1024});var es,rs,ce=u(()=>{"use strict";Rr();ue();es=30*1024*1024*1024,rs=15*1024*1024*1024});var xr=u(()=>{"use strict";H();f()});var Sr=u(()=>{"use strict";O()});var Xt,Zt,Er=u(()=>{"use strict";br();_();b();$();j();ce();H();xr();Sr();f();Xt=500*1024*1024,Zt=4*1024*1024*1024});var j=u(()=>{"use strict";Er()});import{homedir as en}from"node:os";import rn from"node:path";var Cr,pe=u(()=>{"use strict";Cr=rn.join(en(),".kynver",".env")});var Ar=u(()=>{"use strict"});var wr=u(()=>{"use strict";Ar()});var Or=u(()=>{"use strict"});var Ir=u(()=>{"use strict";f()});var fe=u(()=>{"use strict";wr();Or();Ir()});var Pr=u(()=>{"use strict"});var Tr=u(()=>{"use strict";Pr()});var Y=u(()=>{"use strict";pe();x();_();fe();Tr()});var Nr=u(()=>{"use strict";b();b()});var Kr=u(()=>{"use strict";pe();fe();Y()});var ge=u(()=>{"use strict"});var Wr=u(()=>{"use strict";f()});import ln from"node:path";var Ci,he=u(()=>{"use strict";x();Wr();Ci=ln.join(".openclaw","harness")});var G=u(()=>{"use strict";_();b();$();j();he()});var Br=u(()=>{"use strict";ae();b();Nr();_();Y();Kr();le();ge();G()});var fn,zi,Dr=u(()=>{"use strict";fn=["claude","cursor","codex","gemini","gemini-api","openai-compatible"],zi=fn.join("|")});import{homedir as gn,totalmem as ia}from"node:os";import ye from"node:path";var Mr,Ra,xa,Sa,_a,_=u(()=>{"use strict";ae();x();le();b();$();j();ce();Y();Br();Dr();G();ge();Mr=ye.join(gn(),".kynver"),Ra=ye.join(Mr,"config.json"),xa=ye.join(Mr,"credentials"),Sa=500*1024*1024,_a=4*1024*1024*1024});var Fr=u(()=>{"use strict";_();he();G();f()});var H=u(()=>{"use strict";Fr();f()});O();var gr="kynver-harness:",Vt="@runner:";function hr(e){return e?.trim()?e.trim():null}function Gt(e){let r=hr(e);if(!r?.startsWith(gr))return null;let t=r.slice(gr.length),n=t.indexOf(Vt);return n>=0?t.slice(0,n).trim()||null:t.trim()||null}function yr(e,r){let t=hr(r);return t?Gt(e)===t:!1}O();f();function zt(e){let{worker:r,status:t,taskLease:n}=e,s=n?.leaseOwner??null;if(r.dispatched&&n){if(n.status==="running"&&s&&!yr(s,r.runId))return{health:"orphaned",reason:`task lease held by ${s}, expected harness run ${r.runId}`};let i=r.leaseToken?.trim()??"",a=n.leaseToken?.trim()??"";if(n.status==="running"&&i&&a&&i!==a)return{health:"orphaned",reason:"task leaseToken superseded on board \u2014 completion replay would fail"};if(n.status==="running"&&!t.alive&&!t.finalResult)return{health:"orphaned",reason:"board task running but worker process is not alive"}}if(r.status==="running"&&!t.alive&&!t.finalResult)return{health:"orphaned",reason:"worker.json still running but process is dead"};if(t.attention.state==="stale")return{health:"stale",reason:t.attention.reason};let o=t.lastHeartbeatAt?Date.parse(t.lastHeartbeatAt):NaN;return t.alive&&Number.isFinite(o)&&Date.now()-o>L?{health:"stale",reason:`heartbeat older than ${Math.floor(L/1e3)}s`}:t.alive&&r.pid&&!N(r.pid)?{health:"orphaned",reason:"pid recorded but process is not alive"}:n?.status==="running"&&!t.alive&&t.finalResult?{health:"healthy",reason:"finished worker awaiting completion replay"}:{health:"healthy",reason:t.attention.reason||"worker within expected lifecycle bounds"}}H();function Lr(e){return!!e.completionReportedAt?.trim()}O();function hn(e){let{worker:r,status:t}=e,n=[];r.localOnly&&n.push("local-only worker (no board linkage)"),(!r.agentOsId||!r.taskId)&&n.push("missing agentOsId/taskId linkage"),Lr(r)&&n.push("completion already acknowledged"),r.completionBlocker&&n.push(r.completionBlocker),t.heartbeatBlocker&&t.alive&&n.push(`worker heartbeat blocker: ${t.heartbeatBlocker}`),t.attention.state==="blocked"&&n.push(t.attention.reason||"worker attention blocked"),fr(t)&&n.push(t.attention.reason||"landing gate blocked");let s=pr(t),o;return s?t.finalResult?o="final_result":t.alive?o="terminal_status":o="process_exited":n.push("worker has not reached a terminal condition"),{eligible:s&&n.length===0,terminalVerified:s,terminalReason:o,blockers:n}}export{hn as assessAutoCompleteEligibility,zt as classifyWorkerHealth,mr as computeWorkerStatus};
8
+ `).map(r=>r.trim()).filter(Boolean)}function A(e,r){try{let t=Je("git",r,X({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 ze(e,r,t){let n=A(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 Xe(e,r="origin/main"){let t=typeof r=="string"?{base:r}:r,n=t.baseCommit?.trim()||t.base?.trim()||"origin/main",s=t.baseCommit?.trim()||null;if(!e)return ne(n,"missing worktree path");let o=A(e,["rev-parse","HEAD"]);if(o.status!==0)return ne(n,o.error||o.stderr||o.stdout||"failed to resolve HEAD");let i;if(s)i=s;else{let p=A(e,["rev-parse",n]);if(p.status!==0)return ne(n,p.error||p.stderr||p.stdout||`failed to resolve ${n}`,o.stdout.trim());i=p.stdout.trim()}let a=o.stdout.trim();if(a===i)return{checked:!0,base:n,head:a,baseHead:i,baseIsAncestorOfHead:!0,headIsAncestorOfBase:!0,relation:"synced"};let l=ze(e,i,a),c=ze(e,a,i),m=l.error||c.error||void 0;if(l.isAncestor==null||c.isAncestor==null)return{checked:!1,base:n,head:a,baseHead:i,baseIsAncestorOfHead:l.isAncestor,headIsAncestorOfBase:c.isAncestor,relation:"unknown",...m?{error:m}:{}};let d=l.isAncestor?"ahead":c.isAncestor?"merged":"diverged";return{checked:!0,base:n,head:a,baseHead:i,baseIsAncestorOfHead:l.isAncestor,headIsAncestorOfBase:c.isAncestor,relation:d,...m?{error:m}:{}}}function ne(e,r,t=null){return{checked:!1,base:e,head:t,baseHead:null,baseIsAncestorOfHead:null,headIsAncestorOfBase:null,relation:"unknown",error:r}}var D=u(()=>{"use strict";x();f();Ge()});function w(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function Bt(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 Dt(e){if(w(e.headCommit)||w(e.prUrl)||w(e.artifactBundlePath)||w(e.patchPath))return!0;let r=e.gitAncestry;return!!(r?.checked&&r.headIsAncestorOfBase===!1&&w(r.head))}function Ze(e){return Bt(e.finalResult)?e.changedFiles.length===0?{blocked:!1}:Dt(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 Qe(e){if(e.blocked)return e.detail??e.reason??"dirty_worktree_no_pr"}var er=u(()=>{"use strict"});function se(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 rr(e){let r=e.targetPrReconciliation??e.target_pr_reconciliation??e.targetPrs??e.target_prs;return Array.isArray(r)?r.length:0}function M(e){let r=e.trim();if(!r)return null;let t=se(r);if(t)return t;let n=[],s=/```(?:json)?\s*([\s\S]*?)```/gi,o;for(;(o=s.exec(r))!==null;){let m=se(o[1]??"");m&&n.push(m)}let i=r.indexOf("{"),a=r.lastIndexOf("}");if(i>=0&&a>i){let m=se(r.slice(i,a+1));m&&n.push(m)}if(n.length===0)return null;let l=n[n.length-1],c=rr(l);for(let m of n){let d=rr(m);d>c&&(l=m,c=d)}return l}var ie=u(()=>{"use strict"});function tr(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 nr(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function Mt(e){return new Set(e.map(r=>nr(tr(r)??r)).filter(Boolean))}function or(e,r,t){let n=tr(e)??e;if(!n)return"unrelated";let s=nr(n);return Mt(r).has(s)?"contract":t?(t.outcome==="skipped"||t.outcome==="blocked")&&t.reason?.trim()?"support":(t.outcome==="merged","unrelated"):"unrelated"}var sr=u(()=>{"use strict"});function S(e){if(typeof e!="string")return null;let r=e.trim();return r.length?r:null}function Ft(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="object"?Object.keys(e).length>0:!0}function b(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`https://github.com/${r[1]}/pull/${r[2]}`:S(e)}function F(e){let r=e.trim().match(/github\.com\/([^/]+\/[^/]+)\/(?:pull|pulls)\/(\d+)/i);return r?`${r[1].toLowerCase()}/pull/${r[2]}`:e.trim().toLowerCase()}function ir(e){let r=null;if(typeof e=="string"){let s=M(e);s&&(r=s)}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 s of t){if(!s||typeof s!="object"||Array.isArray(s))continue;let o=s,i=b(String(o.prUrl??o.pr_url??"")),a=S(o.outcome);!i||a!=="merged"&&a!=="skipped"&&a!=="blocked"||n.push({prUrl:i,outcome:a,mergeCommit:S(o.mergeCommit??o.merge_commit),reason:S(o.reason)})}return n}function ar(e,r){let t=[],n=b(S(e.prUrl)??"");if(n&&t.push(n),r&&typeof r=="object"&&!Array.isArray(r)){let s=r,o=b(String(s.prUrl??s.pr_url??""));o&&t.push(o)}return[...new Set(t)]}function lr(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(!Ft(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 o=r.repairEnforceOriginalPr?b(S(r.targetPrUrl)??"")??(r.targetPrUrls.length===1?b(r.targetPrUrls[0]):null):null;if(o){let d=ar(t,n);if(!(n&&typeof n=="object"&&!Array.isArray(n)&&n.supersedesOriginalTargetPr===!0)){for(let y of d)if(y!==o)return{blocked:!0,reason:"duplicate_repair_pr",detail:`Repair worker opened or attached PR ${y} instead of canonical target ${o}`}}let h=ir(n).find(y=>y.prUrl===o);if(!h||h.outcome!=="merged"&&!(h.reason?.trim()&&(h.outcome==="skipped"||h.outcome==="blocked")))return{blocked:!0,reason:"missing_repair_target_reconciliation",detail:`Repair worker must reconcile target PR ${o}`}}let i=ir(n),a=new Map(i.map(d=>[F(d.prUrl),d])),l=new Set(r.targetPrUrls.map(d=>F(b(d)??d)).filter(Boolean)),c=ar(t,n);if(r.landingOnly)for(let d of c){let p=a.get(F(d)),g=or(d,r.targetPrUrls,p);if(!(g==="contract"||g==="support"))return l.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 m=[];for(let d of r.targetPrUrls){let p=F(b(d)??d),g=a.get(p);if(!g){m.push(p);continue}g.outcome!=="merged"&&!g.reason?.trim()&&m.push(p)}return m.length>0?{blocked:!0,reason:m.every(d=>a.has(d))?"incomplete_target_pr_landing":"missing_target_pr_reconciliation",detail:`Target PR reconciliation incomplete: ${m.join(", ")}`}:{blocked:!1}}function ur(e){if(e.blocked)return e.detail??e.reason}var cr=u(()=>{"use strict";ie();sr()});function $t(e){let r=Date.now();if(e.providerTerminalError||U(e.finalResult)||e.finalResult&&e.error?.trim()||C(e.error)||C(e.finalResult)){let s=e.error||(typeof e.finalResult=="string"?e.finalResult:"provider terminal error");return{state:"blocked",reason:te(s)?.reason??`provider terminal error: ${s}`}}if(e.completionBlocker&&!dr(e.completionBlocker))return{state:"blocked",reason:e.completionBlocker};if(e.finalResult){if(e.localOnly&&jt(e.finalResult))return{state:"done",reason:"local-only worker superseded by merged PR"};let s={finalResult:e.finalResult,changedFiles:e.changedFiles??[],gitAncestry:e.gitAncestry??null,prUrl:e.prUrl??null},o=Ze(s);if(o.blocked){let i=Qe(o);return{state:"needs_attention",reason:o.reason?`landing blocked (${o.reason}): ${i}`:`landing blocked: ${i}`}}if(e.landingContract){let i=lr({contract:e.landingContract,snapshot:s,finalResult:e.finalResult}),a=ur(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(Ht(e))return{state:"done",reason:"empty abandoned worker record"};let s=te(e.error);if(s)return{state:"blocked",reason:s.reason};let o=Ye({alive:!1,finalResult:null,changedFiles:e.changedFiles,gitAncestry:e.gitAncestry});if(o?.salvageable){let a=e.error?.trim();return{state:"needs_attention",reason:a?`${o.attentionReason} (${a})`:o.attentionReason}}let i=e.error?.trim();return{state:"needs_attention",reason:i?`process exited without a final result: ${i}`:o?.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>Lt)return{state:"needs_attention",reason:`no first stream event ${Z(t)}s after start`};let n=e.lastActivityAt?Date.parse(e.lastActivityAt):NaN;return Number.isFinite(n)&&r-n>L?{state:"stale",reason:`no log/event/heartbeat activity for ${Z(n)}s`}:{state:"ok",reason:"recent activity"}}function dr(e){let r=e?.trim();return r?/completion acknowledged but board not advanced/i.test(r)&&/task already terminal/i.test(r):!1}function Ht(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 jt(e){let r=null;if(typeof e=="string"?r=M(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 Yt(e,r,t){let n=e.completionSnapshot?.finalResult;return e.completionAckSource==="local-pr-merged-reconcile"&&n!==void 0&&n!==null?n:r||(n??Ce(t))}function mr(e,r={}){let t=Fe(e.stdoutPath),n=Ae(e.heartbeatPath),s=typeof e.completionReportedAt=="string"&&e.completionReportedAt.trim().length>0,o=Yt(e,t.finalResult,n),i=s?!1:N(e.pid),a=P(e.stdoutPath),l=P(e.stderrPath),c=P(e.heartbeatPath),m=qe(e.worktreePath),d=Xe(e.worktreePath,{base:r.base,baseCommit:r.baseCommit}),p=ve([t.lastEventAt,n.lastHeartbeatAt,T(e.stdoutPath),T(e.stderrPath),T(e.heartbeatPath)]),g=t.error||!i&&!o&&_e(e.stderrPath,10).trim()||void 0,h=typeof e.completionBlocker=="string"&&e.completionBlocker.trim()?e.completionBlocker.trim():null,y=dr(h)?null:h,$r=e.repairTargetPrUrl?{landingOnly:!1,targetPrUrls:[e.repairTargetPrUrl],targetPrUrl:e.repairTargetPrUrl,repairEnforceOriginalPr:!0}:null,z=$t({alive:i,finalResult:o,firstEventAt:t.firstEventAt,stdoutBytes:a,stderrBytes:l,heartbeatBytes:c,lastActivityAt:p,heartbeatBlocker:n.heartbeatBlocker,startedAt:e.startedAt,error:g,providerTerminalError:t.providerTerminalError,changedFiles:m,gitAncestry:d,completionBlocker:y,landingContract:$r,prUrl:e.repairTargetPrUrl??e.taskPrUrl??null,localOnly:e.localOnly===!0,taskId:e.taskId??null,agentOsId:e.agentOsId??null,reconcileReason:e.reconcileReason??null}),Hr=y||z.state==="blocked"?"blocked":s||z.state==="done"?"done":o?"exited":i?"running":"exited";return{runId:e.runId,worker:e.name,pid:e.pid,alive:i,status:Hr,attention:z,branch:e.branch,worktreePath:e.worktreePath,ownedPaths:e.ownedPaths,stdoutBytes:a,stderrBytes:l,heartbeatBytes:c,firstEventAt:t.firstEventAt,lastEventAt:t.lastEventAt,lastActivityAt:p,currentTool:s?null:t.currentTool,heartbeatCount:n.heartbeatCount,lastHeartbeatAt:n.lastHeartbeatAt,lastHeartbeatPhase:n.lastHeartbeatPhase,lastHeartbeatSummary:n.lastHeartbeatSummary,heartbeatBlocker:n.heartbeatBlocker,timestampAnomalies:n.timestampAnomalies,finalResult:o,error:g,providerTerminalError:t.providerTerminalError,changedFiles:m,gitAncestry:d,instructionPolicyFingerprint:e.instructionPolicyFingerprint??null,instructionPolicyEvidence:e.instructionPolicyEvidence??null,model:e.model??e.orchestrationAudit?.model??null,provider:e.provider??e.orchestrationAudit?.provider??null,usage:t.usage??null,boxKind:e.boxKind??null,boxId:e.boxId??null,runtimeId:e.runtimeId??null,personaSlug:e.personaSlug??null,dispatched:e.dispatched??null,localOnly:e.localOnly??null}}function pr(e){return!!(e.finalResult||e.alive===!1||e.status==="exited"||e.status==="done")}function fr(e){return e.finalResult?e.attention.state==="needs_attention"||e.attention.state==="blocked":!1}var Lt,L,O=u(()=>{"use strict";we();Le();B();He();Ve();D();er();cr();ie();f();Lt=18e4,L=6e5});var br=u(()=>{"use strict";D()});var ae=u(()=>{"use strict";D();x();br()});var le=u(()=>{"use strict";f()});var k=u(()=>{"use strict"});var $=u(()=>{"use strict"});var kr=u(()=>{"use strict"});var Lo,$o,ue=u(()=>{"use strict";Lo=25*1024*1024*1024,$o=12*1024*1024*1024});var Go,zo,Rr=u(()=>{"use strict";ue();Go=5*1024*1024*1024,zo=10*1024*1024*1024});var es,rs,ce=u(()=>{"use strict";Rr();ue();es=30*1024*1024*1024,rs=15*1024*1024*1024});var xr=u(()=>{"use strict";H();f()});var Sr=u(()=>{"use strict";O()});var Xt,Zt,Er=u(()=>{"use strict";kr();_();k();$();j();ce();H();xr();Sr();f();Xt=500*1024*1024,Zt=4*1024*1024*1024});var j=u(()=>{"use strict";Er()});import{homedir as en}from"node:os";import rn from"node:path";var Cr,pe=u(()=>{"use strict";Cr=rn.join(en(),".kynver",".env")});var Ar=u(()=>{"use strict"});var wr=u(()=>{"use strict";Ar()});var Or=u(()=>{"use strict"});var Ir=u(()=>{"use strict";f()});var fe=u(()=>{"use strict";wr();Or();Ir()});var Pr=u(()=>{"use strict"});var Tr=u(()=>{"use strict";Pr()});var Y=u(()=>{"use strict";pe();x();_();fe();Tr()});var Nr=u(()=>{"use strict";k();k()});var Kr=u(()=>{"use strict";pe();fe();Y()});var ge=u(()=>{"use strict"});var Wr=u(()=>{"use strict";f()});import ln from"node:path";var Ci,he=u(()=>{"use strict";x();Wr();Ci=ln.join(".openclaw","harness")});var G=u(()=>{"use strict";_();k();$();j();he()});var Br=u(()=>{"use strict";ae();k();Nr();_();Y();Kr();le();ge();G()});var fn,zi,Dr=u(()=>{"use strict";fn=["claude","cursor","codex","gemini","gemini-api","openai-compatible"],zi=fn.join("|")});import{homedir as gn,totalmem as ia}from"node:os";import ye from"node:path";var Mr,Ra,xa,Sa,_a,_=u(()=>{"use strict";ae();x();le();k();$();j();ce();Y();Br();Dr();G();ge();Mr=ye.join(gn(),".kynver"),Ra=ye.join(Mr,"config.json"),xa=ye.join(Mr,"credentials"),Sa=500*1024*1024,_a=4*1024*1024*1024});var Fr=u(()=>{"use strict";_();he();G();f()});var H=u(()=>{"use strict";Fr();f()});O();var gr="kynver-harness:",Vt="@runner:";function hr(e){return e?.trim()?e.trim():null}function Gt(e){let r=hr(e);if(!r?.startsWith(gr))return null;let t=r.slice(gr.length),n=t.indexOf(Vt);return n>=0?t.slice(0,n).trim()||null:t.trim()||null}function yr(e,r){let t=hr(r);return t?Gt(e)===t:!1}O();f();function zt(e){let{worker:r,status:t,taskLease:n}=e,s=n?.leaseOwner??null;if(r.dispatched&&n){if(n.status==="running"&&s&&!yr(s,r.runId))return{health:"orphaned",reason:`task lease held by ${s}, expected harness run ${r.runId}`};let i=r.leaseToken?.trim()??"",a=n.leaseToken?.trim()??"";if(n.status==="running"&&i&&a&&i!==a)return{health:"orphaned",reason:"task leaseToken superseded on board \u2014 completion replay would fail"};if(n.status==="running"&&!t.alive&&!t.finalResult)return{health:"orphaned",reason:"board task running but worker process is not alive"}}if(r.status==="running"&&!t.alive&&!t.finalResult)return{health:"orphaned",reason:"worker.json still running but process is dead"};if(t.attention.state==="stale")return{health:"stale",reason:t.attention.reason};let o=t.lastHeartbeatAt?Date.parse(t.lastHeartbeatAt):NaN;return t.alive&&Number.isFinite(o)&&Date.now()-o>L?{health:"stale",reason:`heartbeat older than ${Math.floor(L/1e3)}s`}:t.alive&&r.pid&&!N(r.pid)?{health:"orphaned",reason:"pid recorded but process is not alive"}:n?.status==="running"&&!t.alive&&t.finalResult?{health:"healthy",reason:"finished worker awaiting completion replay"}:{health:"healthy",reason:t.attention.reason||"worker within expected lifecycle bounds"}}H();function Lr(e){return!!e.completionReportedAt?.trim()}O();function hn(e){let{worker:r,status:t}=e,n=[];r.localOnly&&n.push("local-only worker (no board linkage)"),(!r.agentOsId||!r.taskId)&&n.push("missing agentOsId/taskId linkage"),Lr(r)&&n.push("completion already acknowledged"),r.completionBlocker&&n.push(r.completionBlocker),t.heartbeatBlocker&&t.alive&&n.push(`worker heartbeat blocker: ${t.heartbeatBlocker}`),t.attention.state==="blocked"&&n.push(t.attention.reason||"worker attention blocked"),fr(t)&&n.push(t.attention.reason||"landing gate blocked");let s=pr(t),o;return s?t.finalResult?o="final_result":t.alive?o="terminal_status":o="process_exited":n.push("worker has not reached a terminal condition"),{eligible:s&&n.length===0,terminalVerified:s,terminalReason:o,blockers:n}}export{hn as assessAutoCompleteEligibility,zt as classifyWorkerHealth,mr as computeWorkerStatus};