@kynver-app/runtime 0.2.59 → 0.2.65

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 c=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};import{homedir as kr}from"node:os";import vr from"node:path";function on(r){return r==="~"?kr():r.startsWith("~/")||r.startsWith("~\\")?vr.join(kr(),r.slice(2)):r}function F(r){return vr.resolve(on(r))}var V=c(()=>{"use strict"});import{existsSync as Cs,mkdirSync as sn,readFileSync as an,readdirSync as As,renameSync as cn,rmSync as ln,statSync as Os,writeFileSync as un}from"node:fs";import{randomBytes as dn}from"node:crypto";import mn from"node:path";function Oe(r){console.error(r),process.exit(1)}function Q(r,e){try{return JSON.parse(an(r,"utf8"))}catch(t){if(arguments.length>1)return e;Oe(`failed to read ${r}: ${t.message}`)}}function we(r,e){sn(mn.dirname(r),{recursive:!0});let t=`${r}.${process.pid}.${dn(4).toString("hex")}.tmp`;try{un(t,`${JSON.stringify(e,null,2)}
2
- `),cn(t,r)}catch(n){try{ln(t,{force:!0})}catch{}throw n}}function Ie(r){return String(r).replace(/\/+$/,"")}var k=c(()=>{"use strict"});var pn,Ns,fn,Ps,xr=c(()=>{"use strict";pn=["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"],Ns=new Set(pn),fn=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY","GEMINI_API_KEY"],Ps=new Set(fn)});var Te=c(()=>{"use strict";V();k();xr()});var Ne=c(()=>{"use strict";Te();V()});function K(r){let e=(r??"").trim().toLowerCase();return e==="ghost"||e==="forge"||e==="box"?e:e.includes("forge")?"forge":e.includes("ghost")||e.includes("openclaw")?"ghost":"box"}function oe(r,e){return r[e]?.trim()||null}function _r(r){let e=r?.split(":")[0]?.trim();return e?K(e):null}function G(r=process.env,e={}){let t=[],n=_r(e.boxId),o=_r(oe(r,"KYNVER_BOX_ID")),s=e.boxKind?.trim();if(s)return n&&n!==K(s)&&t.push(`config.boxId=${e.boxId} conflicts with boxKind=${s}; using explicit boxKind=${s}`),{boxKind:K(s),source:"config",slugInferenceBlocked:!1,warnings:t};let i=oe(r,"KYNVER_BOX_KIND");if(i)return o&&o!==K(i)&&t.push(`KYNVER_BOX_ID=${oe(r,"KYNVER_BOX_ID")} conflicts with KYNVER_BOX_KIND=${i}; using explicit KYNVER_BOX_KIND=${i}`),{boxKind:K(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=oe(r,"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=c(()=>{"use strict"});function Pe(r,e){return r==="forge"?4:Math.max(1,e)}function se(r,e){return r==="forge"?Math.min(Math.max(1,e),4):Math.max(1,e)}var ie=c(()=>{"use strict"});var Er=c(()=>{"use strict"});var Js,zs,Le=c(()=>{"use strict";Js=25*1024*1024*1024,zs=12*1024*1024*1024});var ri,ti,Cr=c(()=>{"use strict";Le();ri=5*1024*1024*1024,ti=10*1024*1024*1024});var ci,li,De=c(()=>{"use strict";Cr();Le();ci=30*1024*1024*1024,li=15*1024*1024*1024});function Ar(){return wr()}var ae=c(()=>{"use strict";Fe();k()});var Ir=c(()=>{"use strict";ae();k()});var Tr=c(()=>{"use strict"});var Nr=c(()=>{"use strict";Tr();k()});var Pr=c(()=>{"use strict"});var Lr=c(()=>{"use strict";Pr()});var Dr=c(()=>{"use strict";Lr();k()});var Mr=c(()=>{"use strict"});var Fr=c(()=>{"use strict"});var Kr=c(()=>{"use strict"});var Ke=c(()=>{"use strict"});var Br=c(()=>{"use strict"});var Ur=c(()=>{"use strict";Ke();Br()});var Wr=c(()=>{"use strict";Nr();Dr();Mr();Fr();Te();Kr();Ur();Ke();k()});var $r=c(()=>{"use strict";Wr()});function Hr(r,e={}){let t=e.perWorkerMemBytes??Be,n=e.memReserveBytes??Ue,o=e.memUtilization??We,s=Math.max(0,Math.floor(r*o)-n),i=Math.max(1,Math.floor(s/t));return Math.min(i,ce)}var Be,Ue,We,ce,jr=c(()=>{"use strict";Er();I();M();ie();le();De();ae();Ir();$r();k();Be=500*1024*1024,Ue=4*1024*1024*1024,We=.85,ce=64});function Z(r,e){let t=Number(r);return!Number.isFinite(t)||t<=0?e:Math.floor(t)}function $e(r){let e=r.config??{},t=r.env??process.env,n=Z(e.perWorkerMemBytes,Be),o=Z(e.memReserveBytes,Ue),s=Math.min(1,Math.max(.1,Number(e.memUtilization)>0?Number(e.memUtilization):We)),i=Hr(r.totalMemBytes,{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s});if(r.configuredMaxWorkersOverride!==void 0&&r.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:Z(r.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(e.maxConcurrentWorkers!==void 0&&e.maxConcurrentWorkers!==null){let l=Z(e.maxConcurrentWorkers,0)||null;if(l)return{configuredMaxWorkers:Math.min(l,ce),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,ce),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var le=c(()=>{"use strict";jr()});import{homedir as bn}from"node:os";import kn from"node:path";var Yr,He=c(()=>{"use strict";Yr=kn.join(bn(),".kynver",".env")});var Vr=c(()=>{"use strict"});var Gr=c(()=>{"use strict";Vr()});var qr=c(()=>{"use strict"});var je=c(()=>{"use strict";Gr();qr()});var Jr=c(()=>{"use strict"});var zr=c(()=>{"use strict";Jr()});var ue=c(()=>{"use strict";He();V();I();je();zr()});var Xr=c(()=>{"use strict";M();M()});var Qr=c(()=>{"use strict";He();je();ue()});import{existsSync as T,mkdirSync as En,readdirSync as de,renameSync as Zr,statSync as Cn}from"node:fs";import N from"node:path";function rt(r){try{return Cn(r).isDirectory()}catch{return!1}}function An(r){if(!T(r))return!0;for(let e of et){let t=N.join(r,e);if(T(t)&&(!rt(t)||de(t).length>0))return!1}return!0}function On(r){let e=N.join(r,"runs");if(!T(e)||!rt(e))return!1;for(let t of de(e,{withFileTypes:!0})){if(!t.isDirectory()||t.name==="runs")continue;let n=N.join(e,t.name,"run.json");if(Q(n,void 0)?.id)return!0}return!1}function wn(r){let e=N.join(r,"runs");if(!T(e))return!1;for(let t of de(e,{withFileTypes:!0})){if(!t.isDirectory())continue;if(Q(N.join(e,t.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function In(r){let e=N.join(r,"ghost");return T(e)?!T(N.join(e,"runs")):wn(r)}function tt(r){return On(r.sharedRoot)?An(r.forgeRoot)?In(r.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 nt(r,e){En(e,{recursive:!0});for(let t of et){let n=N.join(r,t),o=N.join(e,t);if(T(n)){if(T(o)&&de(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(T(o)){Zr(n,o);continue}Zr(n,o)}}}var et,ot=c(()=>{"use strict";k();et=["runs","worktrees"]});import{existsSync as b}from"node:fs";import{homedir as Tn}from"node:os";import S from"node:path";function Ye(r=process.env){return r.HOME?.trim()||Tn()}function Ve(r=process.env){return S.join(Ye(r),".kynver","harness")}function me(r){let e=S.resolve(F(r.trim()));for(;Nn.has(S.basename(e));)e=S.dirname(e);return e}function Pn(r,e=process.env){return S.join(Ve(e),r)}function Ln(r=process.env){let e=Ve(r);if(b(S.join(e,"runs")))return!0;if(b(e)&&!b(S.join(e,"ghost"))&&!b(S.join(e,"forge")))return b(e);let t=S.join(Ye(r),st);return b(t)}function pe(r){let e=r.env??process.env,t=e.KYNVER_HARNESS_ROOT?.trim()||e.OPUS_HARNESS_ROOT?.trim();if(t)return{harnessRoot:me(t),source:"env"};let n=r.configuredHarnessRoot?.trim();if(n)return{harnessRoot:me(n),source:"config"};let o=Pn(r.boxKind,e);if(b(S.join(o,"runs"))||b(o)&&!Dn(o))return{harnessRoot:o,source:"box_scoped"};let i=Ve(e);if(r.boxKind==="forge"){let a=tt({sharedRoot:i,forgeRoot:o});if(a.action==="blocked")return{harnessRoot:o,source:"box_scoped",migrationBlocker:a.blocker};if(a.action==="migrate")return r.allowForgeLegacyMigration!==!1&&nt(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(r.boxKind==="ghost"&&Ln(e)){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(Ye(e),st);if(b(u))return{harnessRoot:u,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function Dn(r){if(!b(r))return!0;for(let e of["runs","worktrees"]){let t=S.join(r,e);if(b(t))return!1}return!0}var st,Nn,Ge=c(()=>{"use strict";V();ot();st=S.join(".openclaw","harness");Nn=new Set(["runs","worktrees"])});import it from"node:os";function fe(r){return r?.trim()?r.trim():null}function Mn(r,e){let t=e.trim().toLowerCase()||"host";return`${r}-${t}`.replace(/[^a-z0-9._-]+/g,"-")}function Fn(r){return r.KYNVER_DISPATCH_STRICT_IDENTITY==="1"||r.KYNVER_DISPATCH_STRICT_IDENTITY==="true"||r.KYNVER_DAEMON_STRICT_IDENTITY==="1"||r.KYNVER_DAEMON_STRICT_IDENTITY==="true"}function ge(r=_(),e=process.env,t={}){let n=G(e,r),o=[...n.warnings],s=[],i=!!(r.boxKind?.trim()||fe(e.KYNVER_BOX_KIND)),a=t.strict===!0||Fn(e);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=fe(r.runnerId),l=fe(e.KYNVER_RUNTIME_ID)??fe(e.OPENCLAW_RUNTIME_ID),m=u??l??Mn(n.boxKind,it.hostname()),p=u?"config":l?"env":"derived";p==="derived"&&o.push(`runnerId not persisted \u2014 using derived id "${m}"; run \`kynver setup --box-kind ${n.boxKind}\` to persist runner identity`);let d=$e({config:r,env:e,totalMemBytes:it.totalmem()}),$=se(n.boxKind,d.configuredMaxWorkers??Pe(n.boxKind,d.autoCap)),v=pe({boxKind:n.boxKind,configuredHarnessRoot:r.harnessRoot,env:e});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:m,runnerIdSource:p,maxConcurrentWorkers:$,workerCapSource:d.workerCapSource,harnessRoot:v.harnessRoot,harnessRootSource:v.source},errors:s,warnings:o}}var he=c(()=>{"use strict";I();M();ie();le();Ge()});var at=c(()=>{"use strict";Ne();M();Xr();I();ue();Qr();k();he()});import{existsSync as lt,mkdirSync as Un,readFileSync as ut,writeFileSync as Wn}from"node:fs";import{homedir as $n,totalmem as nl}from"node:os";import Je from"node:path";function Hn(r){return{...r,...r.harnessRoot?.trim()?{harnessRoot:F(r.harnessRoot.trim())}:{},...r.defaultRepo?.trim()?{defaultRepo:F(r.defaultRepo.trim())}:{}}}function _(){if(!lt(ct))return{};try{return Hn(JSON.parse(ut(ct,"utf8")))}catch{return{}}}function dt(){if(!lt(qe))return{};try{return JSON.parse(ut(qe,"utf8"))}catch{return{}}}function jn(r){Un(ze,{recursive:!0}),Wn(qe,`${JSON.stringify(r,null,2)}
3
- `,{mode:384})}function mt(){return process.env.KYNVER_API_KEY?process.env.KYNVER_API_KEY:dt().apiKey}function Yn(r,e){jn({...dt(),runnerToken:e,runnerTokenAgentOsId:r})}function Vn(r){let e=pt(r);return e||qn("requires --base-url, KYNVER_API_URL, KYNVER_CRON_FIRE_BASE_URL, or ~/.kynver/config.json apiBaseUrl"),e}function pt(r){let e=r||process.env.KYNVER_API_URL||process.env.KYNVER_CRON_FIRE_BASE_URL||process.env.OPENCLAW_CRON_FIRE_BASE_URL||_().apiBaseUrl;return e?Ie(String(e)):void 0}async function ft(r,e,t){let n=mt(),o=pt(t?.baseUrl);if(!n)return{ok:!1,reason:"KYNVER_API_KEY is required to refresh a rejected runner token"};if(!e)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 Gn(e,{baseUrl:o,apiKey:n});return s&&s!==r?(Yn(e,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 Gn(r,e){let t=e?.apiKey||mt();if(!t)throw new Error("API key required \u2014 run `kynver login` first");let o=`${Vn(e?.baseUrl)}/api/agent-os/by-id/${encodeURIComponent(r)}/runner-credentials`,s=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({})}),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 qn(r){console.error(r),process.exit(1)}var ze,ct,qe,gl,hl,I=c(()=>{"use strict";Ne();V();k();M();ie();le();De();ue();at();he();ze=Je.join($n(),".kynver"),ct=Je.join(ze,"config.json"),qe=Je.join(ze,"credentials");gl=500*1024*1024,hl=4*1024*1024*1024});import gt from"node:path";function ye(r){return me(r)}function Xe(){let r=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(r)return ye(r);let e=_(),t=e.harnessRoot?.trim();if(t)return ye(t);let n=ge(e,process.env);return n.identity?n.identity.harnessRoot:pe({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function Or(r){return gt.join(ye(r),"runs")}function Jn(r){return gt.join(ye(r),"worktrees")}function wr(){let r=Xe();return{harnessRoot:r,runsDir:Or(r),worktreesDir:Jn(r)}}var Fe=c(()=>{"use strict";I();Ge();he();k()});import{existsSync as Kt,realpathSync as Bt,readFileSync as Ut}from"node:fs";import Sr from"node:path";var Wt=new Set(["ext4","ext3","ext2","btrfs","xfs","f2fs","zfs","tmpfs","overlay","overlayfs"]),$t=new Set(["9p","drvfs","nfs","nfs4","cifs","smb","smbfs","smb3","sshfs","fuse.sshfs","davfs","davfs2","glusterfs","ceph","lustre","afs","vboxsf","prl_fs","virtiofs"]);function Ht(){try{return Ut("/proc/self/mounts","utf8")}catch{return null}}function jt(r){let e=Sr.resolve(r);for(let t=0;t<64;t+=1){if(Kt(e))try{return Bt.native(e)}catch{return e}let n=Sr.dirname(e);if(n===e)return e;e=n}return e}function Yt(r){return r.replace(/\\(\d{3})/g,(e,t)=>String.fromCharCode(Number.parseInt(t,8)))}function Vt(r){let e=[];for(let t of r.split(`
4
- `)){let n=t.trim().split(/\s+/);n.length<3||e.push({mountPoint:Yt(n[1]),fsType:n[2]})}return e}function Gt(r,e){let t=null;for(let n of e){let o=n.mountPoint.endsWith("/")?n.mountPoint:`${n.mountPoint}/`;(r===n.mountPoint||`${r}/`.startsWith(o))&&(!t||n.mountPoint.length>t.mountPoint.length)&&(t=n)}return t}function Ee(r,e){let n=(e?.resolveRealPath??jt)(r),o=(e?.mountsSource??Ht)();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=Gt(n,Vt(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 $t.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}:Wt.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 Ce=1,ne=class extends Error{constructor(e,t){super(`local-run-store schema version ${e} is newer than this runtime supports (${t}); refusing to open. Upgrade the runtime or quarantine the database deliberately.`),this.name="SchemaDowngradeRefusedError"}},qt=[`CREATE TABLE IF NOT EXISTS local_meta (
1
+ var c=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};import{homedir as _r}from"node:os";import xr from"node:path";function pn(r){return r==="~"?_r():r.startsWith("~/")||r.startsWith("~\\")?xr.join(_r(),r.slice(2)):r}function K(r){return xr.resolve(pn(r))}var V=c(()=>{"use strict"});import{existsSync as Ms,mkdirSync as fn,readFileSync as gn,readdirSync as Ks,renameSync as hn,rmSync as yn,statSync as Fs,writeFileSync as Rn}from"node:fs";import{randomBytes as Sn}from"node:crypto";import bn from"node:path";function Ie(r){console.error(r),process.exit(1)}function Q(r,e){try{return JSON.parse(gn(r,"utf8"))}catch(t){if(arguments.length>1)return e;Ie(`failed to read ${r}: ${t.message}`)}}function Te(r,e){fn(bn.dirname(r),{recursive:!0});let t=`${r}.${process.pid}.${Sn(4).toString("hex")}.tmp`;try{Rn(t,`${JSON.stringify(e,null,2)}
2
+ `),hn(t,r)}catch(n){try{yn(t,{force:!0})}catch{}throw n}}function oe(r){return String(r).replace(/\/+$/,"")}var v=c(()=>{"use strict"});var kn,$s,vn,Hs,Er=c(()=>{"use strict";kn=["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"],$s=new Set(kn),vn=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY","GEMINI_API_KEY"],Hs=new Set(vn)});var se=c(()=>{"use strict";V();v();Er()});var Cr=c(()=>{"use strict";se()});var Ne=c(()=>{"use strict";se();V();Cr()});function wr(r){let e=oe(r);try{let t=new URL(e);return t.hostname.toLowerCase()===Ar?(t.hostname=`www.${Ar}`,oe(t.toString())):e}catch{return e}}function Pe(r){if(r?.trim())return wr(oe(r.trim()))}async function Ir(r,e,t=fetch){let n=wr(r),o=new Headers(e?.headers),s=0;for(;s<=Or;){let i=await t(n,{...e,headers:o,redirect:"manual"});if(i.status<300||i.status>=400)return i;let a=i.headers.get("location");if(!a)return i;n=new URL(a,n).toString(),s+=1}throw new Error(`kynver API fetch exceeded ${Or} redirects for ${r}`)}var Ar,Or,Le=c(()=>{"use strict";v();Ar="kynver.com";Or=10});function F(r){let e=(r??"").trim().toLowerCase();return e==="ghost"||e==="forge"||e==="box"?e:e.includes("forge")?"forge":e.includes("ghost")||e.includes("openclaw")?"ghost":"box"}function ie(r,e){return r[e]?.trim()||null}function Tr(r){let e=r?.split(":")[0]?.trim();return e?F(e):null}function G(r=process.env,e={}){let t=[],n=Tr(e.boxId),o=Tr(ie(r,"KYNVER_BOX_ID")),s=e.boxKind?.trim();if(s)return n&&n!==F(s)&&t.push(`config.boxId=${e.boxId} conflicts with boxKind=${s}; using explicit boxKind=${s}`),{boxKind:F(s),source:"config",slugInferenceBlocked:!1,warnings:t};let i=ie(r,"KYNVER_BOX_KIND");if(i)return o&&o!==F(i)&&t.push(`KYNVER_BOX_ID=${ie(r,"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=ie(r,"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=c(()=>{"use strict"});function De(r,e){return r==="forge"?4:Math.max(1,e)}function ae(r,e){return r==="forge"?Math.min(Math.max(1,e),4):Math.max(1,e)}var ce=c(()=>{"use strict"});var Nr=c(()=>{"use strict"});var ui,di,Me=c(()=>{"use strict";ui=25*1024*1024*1024,di=12*1024*1024*1024});var hi,yi,Pr=c(()=>{"use strict";Me();hi=5*1024*1024*1024,yi=10*1024*1024*1024});var _i,xi,Ke=c(()=>{"use strict";Pr();Me();_i=30*1024*1024*1024,xi=15*1024*1024*1024});function Lr(){return Mr()}var le=c(()=>{"use strict";Be();v()});var Kr=c(()=>{"use strict";le();v()});var Fr=c(()=>{"use strict"});var Br=c(()=>{"use strict";Fr();v()});var Wr=c(()=>{"use strict"});var Ur=c(()=>{"use strict";Wr()});var $r=c(()=>{"use strict";Ur();v()});var Hr=c(()=>{"use strict"});var jr=c(()=>{"use strict"});var Yr=c(()=>{"use strict"});var We=c(()=>{"use strict"});var Vr=c(()=>{"use strict"});var Gr=c(()=>{"use strict";We();Vr()});var qr=c(()=>{"use strict";Br();$r();Hr();jr();se();Yr();Gr();We();v()});var Jr=c(()=>{"use strict";qr()});function zr(r,e={}){let t=e.perWorkerMemBytes??Ue,n=e.memReserveBytes??$e,o=e.memUtilization??He,s=Math.max(0,Math.floor(r*o)-n),i=Math.max(1,Math.floor(s/t));return Math.min(i,ue)}var Ue,$e,He,ue,Xr=c(()=>{"use strict";Nr();I();M();ce();de();Ke();le();Kr();Jr();v();Ue=500*1024*1024,$e=4*1024*1024*1024,He=.85,ue=64});function Z(r,e){let t=Number(r);return!Number.isFinite(t)||t<=0?e:Math.floor(t)}function je(r){let e=r.config??{},t=r.env??process.env,n=Z(e.perWorkerMemBytes,Ue),o=Z(e.memReserveBytes,$e),s=Math.min(1,Math.max(.1,Number(e.memUtilization)>0?Number(e.memUtilization):He)),i=zr(r.totalMemBytes,{perWorkerMemBytes:n,memReserveBytes:o,memUtilization:s});if(r.configuredMaxWorkersOverride!==void 0&&r.configuredMaxWorkersOverride!==null)return{configuredMaxWorkers:Z(r.configuredMaxWorkersOverride,i),autoCap:i,workerCapSource:"workspace_override"};if(e.maxConcurrentWorkers!==void 0&&e.maxConcurrentWorkers!==null){let l=Z(e.maxConcurrentWorkers,0)||null;if(l)return{configuredMaxWorkers:Math.min(l,ue),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,ue),autoCap:i,workerCapSource:"env"}:{configuredMaxWorkers:null,autoCap:i,workerCapSource:"auto"}}var de=c(()=>{"use strict";Xr()});import{homedir as wn}from"node:os";import In from"node:path";var Qr,Ye=c(()=>{"use strict";Qr=In.join(wn(),".kynver",".env")});var Zr=c(()=>{"use strict"});var et=c(()=>{"use strict";Zr()});var rt=c(()=>{"use strict"});var Ve=c(()=>{"use strict";et();rt()});var tt=c(()=>{"use strict"});var nt=c(()=>{"use strict";tt()});var me=c(()=>{"use strict";Ye();V();I();Ve();nt()});var ot=c(()=>{"use strict";M();M()});var st=c(()=>{"use strict";Ye();Ve();me()});import{existsSync as T,mkdirSync as Ln,readdirSync as pe,renameSync as it,statSync as Dn}from"node:fs";import N from"node:path";function ct(r){try{return Dn(r).isDirectory()}catch{return!1}}function Mn(r){if(!T(r))return!0;for(let e of at){let t=N.join(r,e);if(T(t)&&(!ct(t)||pe(t).length>0))return!1}return!0}function Kn(r){let e=N.join(r,"runs");if(!T(e)||!ct(e))return!1;for(let t of pe(e,{withFileTypes:!0})){if(!t.isDirectory()||t.name==="runs")continue;let n=N.join(e,t.name,"run.json");if(Q(n,void 0)?.id)return!0}return!1}function Fn(r){let e=N.join(r,"runs");if(!T(e))return!1;for(let t of pe(e,{withFileTypes:!0})){if(!t.isDirectory())continue;if(Q(N.join(e,t.name,"run.json"),void 0)?.boxKind==="ghost")return!0}return!1}function Bn(r){let e=N.join(r,"ghost");return T(e)?!T(N.join(e,"runs")):Fn(r)}function lt(r){return Kn(r.sharedRoot)?Mn(r.forgeRoot)?Bn(r.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 ut(r,e){Ln(e,{recursive:!0});for(let t of at){let n=N.join(r,t),o=N.join(e,t);if(T(n)){if(T(o)&&pe(o).length>0)throw new Error(`Forge legacy harness migration failed: ${o} is not empty`);if(T(o)){it(n,o);continue}it(n,o)}}}var at,dt=c(()=>{"use strict";v();at=["runs","worktrees"]});import{existsSync as b}from"node:fs";import{homedir as Wn}from"node:os";import S from"node:path";function Ge(r=process.env){return r.HOME?.trim()||Wn()}function qe(r=process.env){return S.join(Ge(r),".kynver","harness")}function fe(r){let e=S.resolve(K(r.trim()));for(;Un.has(S.basename(e));)e=S.dirname(e);return e}function $n(r,e=process.env){return S.join(qe(e),r)}function Hn(r=process.env){let e=qe(r);if(b(S.join(e,"runs")))return!0;if(b(e)&&!b(S.join(e,"ghost"))&&!b(S.join(e,"forge")))return b(e);let t=S.join(Ge(r),mt);return b(t)}function ge(r){let e=r.env??process.env,t=e.KYNVER_HARNESS_ROOT?.trim()||e.OPUS_HARNESS_ROOT?.trim();if(t)return{harnessRoot:fe(t),source:"env"};let n=r.configuredHarnessRoot?.trim();if(n)return{harnessRoot:fe(n),source:"config"};let o=$n(r.boxKind,e);if(b(S.join(o,"runs"))||b(o)&&!jn(o))return{harnessRoot:o,source:"box_scoped"};let i=qe(e);if(r.boxKind==="forge"){let a=lt({sharedRoot:i,forgeRoot:o});if(a.action==="blocked")return{harnessRoot:o,source:"box_scoped",migrationBlocker:a.blocker};if(a.action==="migrate")return r.allowForgeLegacyMigration!==!1&&ut(i,o),{harnessRoot:o,source:"legacy_migrated"}}if(r.boxKind==="ghost"&&Hn(e)){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(Ge(e),mt);if(b(u))return{harnessRoot:u,source:"legacy_shared"}}return{harnessRoot:o,source:"box_scoped"}}function jn(r){if(!b(r))return!0;for(let e of["runs","worktrees"]){let t=S.join(r,e);if(b(t))return!1}return!0}var mt,Un,Je=c(()=>{"use strict";V();dt();mt=S.join(".openclaw","harness");Un=new Set(["runs","worktrees"])});import pt from"node:os";function he(r){return r?.trim()?r.trim():null}function Yn(r,e){let t=e.trim().toLowerCase()||"host";return`${r}-${t}`.replace(/[^a-z0-9._-]+/g,"-")}function Vn(r){return r.KYNVER_DISPATCH_STRICT_IDENTITY==="1"||r.KYNVER_DISPATCH_STRICT_IDENTITY==="true"||r.KYNVER_DAEMON_STRICT_IDENTITY==="1"||r.KYNVER_DAEMON_STRICT_IDENTITY==="true"}function ye(r=x(),e=process.env,t={}){let n=G(e,r),o=[...n.warnings],s=[],i=!!(r.boxKind?.trim()||he(e.KYNVER_BOX_KIND)),a=t.strict===!0||Vn(e);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=he(r.runnerId),l=he(e.KYNVER_RUNTIME_ID)??he(e.OPENCLAW_RUNTIME_ID),m=u??l??Yn(n.boxKind,pt.hostname()),p=u?"config":l?"env":"derived";p==="derived"&&o.push(`runnerId not persisted \u2014 using derived id "${m}"; run \`kynver setup --box-kind ${n.boxKind}\` to persist runner identity`);let d=je({config:r,env:e,totalMemBytes:pt.totalmem()}),$=ae(n.boxKind,d.configuredMaxWorkers??De(n.boxKind,d.autoCap)),k=ge({boxKind:n.boxKind,configuredHarnessRoot:r.harnessRoot,env:e});return k.migrationBlocker&&s.push(k.migrationBlocker),s.length>0?{ok:!1,identity:null,errors:s,warnings:o}:{ok:!0,identity:{boxKind:n.boxKind,boxKindSource:n.source,runnerId:m,runnerIdSource:p,maxConcurrentWorkers:$,workerCapSource:d.workerCapSource,harnessRoot:k.harnessRoot,harnessRootSource:k.source},errors:s,warnings:o}}var Re=c(()=>{"use strict";I();M();ce();de();Je()});var ft=c(()=>{"use strict";Ne();M();ot();I();me();st();Le();Re()});var Jn,ml,gt=c(()=>{"use strict";Jn=["claude","cursor","codex","gemini","gemini-api","openai-compatible"],ml=Jn.join("|")});import{existsSync as yt,mkdirSync as zn,readFileSync as Rt,writeFileSync as Xn}from"node:fs";import{homedir as Qn,totalmem as kl}from"node:os";import Xe from"node:path";function Zn(r){return{...r,...r.harnessRoot?.trim()?{harnessRoot:K(r.harnessRoot.trim())}:{},...r.defaultRepo?.trim()?{defaultRepo:K(r.defaultRepo.trim())}:{}}}function x(){if(!yt(ht))return{};try{return Zn(JSON.parse(Rt(ht,"utf8")))}catch{return{}}}function St(){if(!yt(ze))return{};try{return JSON.parse(Rt(ze,"utf8"))}catch{return{}}}function eo(r){zn(Qe,{recursive:!0}),Xn(ze,`${JSON.stringify(r,null,2)}
3
+ `,{mode:384})}function bt(){return process.env.KYNVER_API_KEY?process.env.KYNVER_API_KEY:St().apiKey}function ro(r,e){eo({...St(),runnerToken:e,runnerTokenAgentOsId:r})}function to(r){let e=kt(r);return e||oo("requires --base-url, KYNVER_API_URL, KYNVER_CRON_FIRE_BASE_URL, or ~/.kynver/config.json apiBaseUrl"),e}function kt(r){let e=r||process.env.KYNVER_API_URL||process.env.KYNVER_CRON_FIRE_BASE_URL||process.env.OPENCLAW_CRON_FIRE_BASE_URL||x().apiBaseUrl;return Pe(String(e))}async function vt(r,e,t){let n=bt(),o=kt(t?.baseUrl);if(!n)return{ok:!1,reason:"KYNVER_API_KEY is required to refresh a rejected runner token"};if(!e)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 no(e,{baseUrl:o,apiKey:n});return s&&s!==r?(ro(e,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 no(r,e){let t=e?.apiKey||bt();if(!t)throw new Error("API key required \u2014 run `kynver login` first");let o=`${to(e?.baseUrl)}/api/agent-os/by-id/${encodeURIComponent(r)}/runner-credentials`,s=await Ir(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({})}),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 oo(r){console.error(r),process.exit(1)}var Qe,ht,ze,Ll,Dl,I=c(()=>{"use strict";Ne();V();Le();M();ce();de();Ke();me();ft();gt();Re();Qe=Xe.join(Qn(),".kynver"),ht=Xe.join(Qe,"config.json"),ze=Xe.join(Qe,"credentials");Ll=500*1024*1024,Dl=4*1024*1024*1024});import _t from"node:path";function Se(r){return fe(r)}function Ze(){let r=process.env.KYNVER_HARNESS_ROOT||process.env.OPUS_HARNESS_ROOT;if(r)return Se(r);let e=x(),t=e.harnessRoot?.trim();if(t)return Se(t);let n=ye(e,process.env);return n.identity?n.identity.harnessRoot:ge({boxKind:"forge",configuredHarnessRoot:null}).harnessRoot}function Dr(r){return _t.join(Se(r),"runs")}function so(r){return _t.join(Se(r),"worktrees")}function Mr(){let r=Ze();return{harnessRoot:r,runsDir:Dr(r),worktreesDir:so(r)}}var Be=c(()=>{"use strict";I();Je();Re();v()});import{existsSync as Vt,realpathSync as Gt,readFileSync as qt}from"node:fs";import kr from"node:path";var Jt=new Set(["ext4","ext3","ext2","btrfs","xfs","f2fs","zfs","tmpfs","overlay","overlayfs"]),zt=new Set(["9p","drvfs","nfs","nfs4","cifs","smb","smbfs","smb3","sshfs","fuse.sshfs","davfs","davfs2","glusterfs","ceph","lustre","afs","vboxsf","prl_fs","virtiofs"]);function Xt(){try{return qt("/proc/self/mounts","utf8")}catch{return null}}function Qt(r){let e=kr.resolve(r);for(let t=0;t<64;t+=1){if(Vt(e))try{return Gt.native(e)}catch{return e}let n=kr.dirname(e);if(n===e)return e;e=n}return e}function Zt(r){return r.replace(/\\(\d{3})/g,(e,t)=>String.fromCharCode(Number.parseInt(t,8)))}function en(r){let e=[];for(let t of r.split(`
4
+ `)){let n=t.trim().split(/\s+/);n.length<3||e.push({mountPoint:Zt(n[1]),fsType:n[2]})}return e}function rn(r,e){let t=null;for(let n of e){let o=n.mountPoint.endsWith("/")?n.mountPoint:`${n.mountPoint}/`;(r===n.mountPoint||`${r}/`.startsWith(o))&&(!t||n.mountPoint.length>t.mountPoint.length)&&(t=n)}return t}function Ae(r,e){let n=(e?.resolveRealPath??Qt)(r),o=(e?.mountsSource??Xt)();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=rn(n,en(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 zt.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}:Jt.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 Oe=1,ne=class extends Error{constructor(e,t){super(`local-run-store schema version ${e} is newer than this runtime supports (${t}); refusing to open. Upgrade the runtime or quarantine the database deliberately.`),this.name="SchemaDowngradeRefusedError"}},tn=[`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 c=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}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 Jt(r){if(!r.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'local_meta'").get())return null;let t=r.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 br(r,e){let t=Jt(r);if(t!==null&&t>1)throw new ne(t,1);r.exec("BEGIN IMMEDIATE");try{for(let n of qt)r.exec(n);r.prepare("INSERT INTO local_meta (key, value) VALUES ('schema_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(String(1)),r.prepare("INSERT INTO local_meta (key, value) VALUES ('schema_applied_at', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(e),r.exec("COMMIT")}catch(n){throw r.exec("ROLLBACK"),n}}import{mkdirSync as zt}from"node:fs";import Xt from"node:path";import{DatabaseSync as Qt}from"node:sqlite";var X=class extends Error{constructor(e){super(`local-run-store refused: ${e}`),this.name="FilesystemPolicyError"}},Zt="local-run-store.sqlite",en=5e3,Y=class r{db;now;databasePath;constructor(e,t,n){this.db=e,this.databasePath=t,this.now=n}static open(e){let t=Ee(e.directory,e.classifyOptions);if(t.verdict!=="accepted")throw new X(t.reason);zt(e.directory,{recursive:!0,mode:448});let n=Xt.join(e.directory,e.filename??Zt),o=new Qt(n,{timeout:e.busyTimeoutMs??en}),s=e.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"),br(o,s().toISOString())}catch(i){throw o.close(),i}return new r(o,n,s)}inImmediateTransaction(e){this.db.exec("BEGIN IMMEDIATE");try{let t=e();return this.db.exec("COMMIT"),t}catch(t){throw this.db.exec("ROLLBACK"),t}}registerProcessIdentity(e){let t=this.now().toISOString();return this.inImmediateTransaction(()=>{this.db.prepare(`INSERT INTO process_identity
30
+ ) STRICT`];function nn(r){if(!r.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'local_meta'").get())return null;let t=r.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 vr(r,e){let t=nn(r);if(t!==null&&t>1)throw new ne(t,1);r.exec("BEGIN IMMEDIATE");try{for(let n of tn)r.exec(n);r.prepare("INSERT INTO local_meta (key, value) VALUES ('schema_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(String(1)),r.prepare("INSERT INTO local_meta (key, value) VALUES ('schema_applied_at', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(e),r.exec("COMMIT")}catch(n){throw r.exec("ROLLBACK"),n}}import{mkdirSync as on}from"node:fs";import sn from"node:path";import{DatabaseSync as an}from"node:sqlite";var X=class extends Error{constructor(e){super(`local-run-store refused: ${e}`),this.name="FilesystemPolicyError"}},cn="local-run-store.sqlite",ln=5e3,Y=class r{db;now;databasePath;constructor(e,t,n){this.db=e,this.databasePath=t,this.now=n}static open(e){let t=Ae(e.directory,e.classifyOptions);if(t.verdict!=="accepted")throw new X(t.reason);on(e.directory,{recursive:!0,mode:448});let n=sn.join(e.directory,e.filename??cn),o=new an(n,{timeout:e.busyTimeoutMs??ln}),s=e.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"),vr(o,s().toISOString())}catch(i){throw o.close(),i}return new r(o,n,s)}inImmediateTransaction(e){this.db.exec("BEGIN IMMEDIATE");try{let t=e();return this.db.exec("COMMIT"),t}catch(t){throw this.db.exec("ROLLBACK"),t}}registerProcessIdentity(e){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
@@ -51,8 +51,8 @@ var c=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}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(e){return e.length===0?0:this.inImmediateTransaction(()=>{let t=this.db.prepare("DELETE FROM operation_receipts WHERE idempotency_key = ?"),n=0;for(let o of e)n+=Number(t.run(o).changes);return n})}getOperationReceipt(e){let t=this.db.prepare(`SELECT idempotency_key, operation, result_json, recorded_at
52
52
  FROM operation_receipts WHERE idempotency_key = ?`).get(e);return t?{idempotencyKey:t.idempotency_key,operation:t.operation,resultJson:t.result_json,recordedAt:t.recorded_at}:null}saveRecoveryCheckpoint(e){return this.inImmediateTransaction(()=>{let t=this.db.prepare("SELECT COALESCE(MAX(seq), 0) AS max_seq FROM recovery_checkpoints WHERE scope = ?").get(e.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(e.scope,n,e.payloadJson,this.now().toISOString()),{seq:n}})}latestRecoveryCheckpoint(e){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(e);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(e){let t=this.db.prepare(`PRAGMA ${e}`).get();return String(Object.values(t)[0])}close(){this.db.close()}};import{existsSync as rn,renameSync as tn}from"node:fs";function nn(r,e){let t=`${r}.quarantine-${e}`;for(let n of["","-wal","-shm"]){let o=`${r}${n}`;rn(o)&&tn(o,`${t}${n}`)}return t}function Ae(r){let e=r.quarantineStamp??(r.now??(()=>new Date))().toISOString().replace(/[:.]/g,"-"),t=null;try{let s=Y.open(r);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=`${r.directory}/${r.filename??"local-run-store.sqlite"}`,o=nn(n,e);try{return{store:Y.open(r),recovered:!0,quarantinedTo:o}}catch(s){throw new AggregateError([t,s].filter(Boolean),"local-run-store rebuild after quarantine failed")}}Fe();function zn(){if(process.env.KYNVER_LRS_TEST_CLASSIFY_BYPASS==="1")return{mountsSource:()=>"/dev/vda / ext4 rw 0 0",resolveRealPath:()=>"/tmp/kynver-lrs-test/db"}}function Xn(){return ht.classifyOptions??zn()}var ht={};function Qn(r){ht=r}var yt=300*1e3,P=null,ee=0;function Zn(r){ee+=1;try{let e=Xn(),t=Ae({directory:r,...e?{classifyOptions:e}:{}});return{store:t.store,status:{state:"open",harnessRoot:r,databasePath:t.store.databasePath,schemaVersion:t.store.localSchemaVersion(),recovered:t.recovered,quarantinedTo:t.quarantinedTo,reason:null,openAttempts:ee},failedAtMs:null,permanentRefusal:!1}}catch(e){return{store:null,status:{state:"unavailable",harnessRoot:r,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:`${e.name}: ${e.message}`,openAttempts:ee},failedAtMs:Date.now(),permanentRefusal:e.name==="FilesystemPolicyError"||e.name==="SchemaDowngradeRefusedError"}}}function eo(r,e){return r.store||r.permanentRefusal?!1:r.failedAtMs===null?!0:e-r.failedAtMs>=yt}function f(r=Date.now()){let e=Xe();return(!P||P.status.harnessRoot!==e||eo(P,r))&&(Ze(),P=Zn(e)),P.store}function Rt(){return P?P.status:{state:"unopened",harnessRoot:null,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:null,openAttempts:ee}}function Qe(){return f(),Rt()}function Ze(){try{P?.store?.close()}catch{}P=null}function ro(){Ze(),ee=0}I();k();import{existsSync as to,readFileSync as no}from"node:fs";import{homedir as oo}from"node:os";import so from"node:path";var io=3e4,x=null;function er(r){let e=r.replace(/[^A-Za-z0-9_-]/g,"_");return so.join(oo(),".kynver",`local-run-store-flags-${e}.json`)}function rr(r){if(!r||typeof r!="object"||Array.isArray(r))return{};let e=r,t={},n=["dispatchReceipts","admission","planOutbox","keeper","meshLease","quota"];for(let o of n){let s=e[o];(s==="off"||s==="shadow"||s==="enforce")&&(t[o]=s)}return t}function ao(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let e=r.response;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.localRunStoreFlags;return t===void 0?null:rr(t)}function co(r,e){try{let t=er(r),n={contractVersion:1,agentOsId:r,flags:rr(e),deliveredAt:new Date().toISOString()};we(t,n),x={flags:n.flags,loadedAtMs:Date.now(),file:t}}catch{}}function tr(r=Date.now()){if(process.env.KYNVER_LRS_REMOTE_FLAGS_DISABLED==="1")return{};if(x&&r-x.loadedAtMs<io)return x.flags;try{let e=_().agentOsId?.trim();if(!e)return x={flags:{},loadedAtMs:r,file:null},x.flags;let t=er(e);if(!to(t))return x={flags:{},loadedAtMs:r,file:t},x.flags;let n=JSON.parse(no(t,"utf8")),o=n?.contractVersion===1?rr(n.flags):{};return x={flags:o,loadedAtMs:r,file:t},o}catch{return x={flags:{},loadedAtMs:r,file:null},x.flags}}function lo(){x=null}var St=[{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 bt(r){let e=r?.trim().toLowerCase()??"";return e===""?{mode:"off",unknown:!1}:e==="off"||e==="shadow"||e==="enforce"?{mode:e,unknown:!1}:{mode:"off",unknown:!0}}function A(r=process.env){let e={},t={},n=[],o=tr();for(let s of St){let i=r[s.env];if(typeof i=="string"&&i.trim()!==""){let l=bt(i);e[s.key]=l.mode,t[s.key]="env",l.unknown&&n.push(`${s.env}='${i}' is not off|shadow|enforce \u2014 treating as off`);continue}let u=o[s.key];if(u){e[s.key]=u,t[s.key]="server";continue}e[s.key]="off",t[s.key]="default"}return{flags:e,sources:t,warnings:n}}function uo(r){return Object.values(r).some(e=>e!=="off")}var R={storeFailures:0,completionReplaysObserved:0,completionReplaysShortCircuited:0,agedReceiptsPruned:0};function O(r=process.env){return A(r).flags.dispatchReceipts}function nr(r){return O(r)!=="off"}function or(r,e){return`dispatch:${r}:${e.taskId}:${e.leaseToken}`}function re(r,e,t){if(!nr())return;let n=f();if(n)try{n.recordOperationReceipt({idempotencyKey:or(r,e),operation:`dispatch-${r}`,resultJson:t===void 0?null:JSON.stringify(t)})}catch{R.storeFailures+=1}}function mo(r){re("claim",r,{runId:r.runId,workerName:r.workerName,provider:r.provider})}function sr(r){re("spawned",r)}function Re(r,e){re("released",r,{reasonClass:e})}function po(r){re("completion-sent",r)}function fo(r,e){re("completion-acked",r,{outcome:e})}function go(r){if(!nr())return!1;let e=f();if(!e)return!1;try{let t=e.getOperationReceipt(or("completion-acked",r));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 ho(r){let e=String(r??"").split(":")[0]?.trim()??"";return e.length>0?e.slice(0,64):"unknown"}function yo(r){if(O()!=="enforce")return!1;let e=f();if(!e)return!1;try{let t=e.getOperationReceipt(or("completion-acked",r));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 Ro=600*1e3;function So(r,e){if(O()!=="enforce")return;let t=f();if(t)try{t.recordOperationReceipt({idempotencyKey:`dispatch:start-failed:${r}:${e}`,operation:"dispatch-start-failed",resultJson:JSON.stringify({runId:e})})}catch{R.storeFailures+=1}}function bo(r,e){if(O()!=="enforce")return[];let t=f();if(!t)return[];let n=e?.nowMs??Date.now(),o=e?.windowMs??Ro;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===r:!1}catch{return!1}}).map(s=>{let i=s.idempotencyKey.slice(22);return i.slice(0,i.length-(r.length+1))}).filter(s=>s.length>0)}catch{return R.storeFailures+=1,[]}}function q(r){let e=r.split(":")[0]??"",t=Number(e);return Number.isInteger(t)&&t>=0?t:null}var ko=900*1e3,kt=10080*60*1e3,vo=1440*60*1e3,xo=500,_o=300;function ir(r){let e={scannedClaims:0,strandedClaimCandidates:0,prunedReceipts:0};if(!nr())return e;let t=f();if(!t)return e;let n=r?.nowMs??Date.now(),o=r?.strandedAfterMs??ko;try{let s=t.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(n-kt).toISOString(),limit:xo}),i=0,a=[];for(let l of s){let m=l.idempotencyKey.slice(15),p=Date.parse(l.recordedAt);if(!Number.isFinite(p)||n-p<o)continue;let d=t.getOperationReceipt(`dispatch:spawned:${m}`),$=t.getOperationReceipt(`dispatch:released:${m}`);if(d||$){n-p>=vo&&a.length+5<=_o&&a.push(l.idempotencyKey,`dispatch:spawned:${m}`,`dispatch:released:${m}`,`dispatch:completion-sent:${m}`,`dispatch:completion-acked:${m}`);continue}let v=m.split(":")[0]??"",H=q(m.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),D=q(j);return D===null||D>=H}))continue;let y=!1;if(r?.hasLiveWorker&&l.resultJson)try{let h=JSON.parse(l.resultJson);h.runId&&h.workerName&&(y=r.hasLiveWorker({runId:h.runId,workerName:h.workerName}))}catch{y=!1}y||(i+=1)}let u=a.length>0?t.deleteOperationReceiptsByKeys(a):0;if(O()==="enforce"){let l=t.listOperationReceipts({limit:100}).filter(m=>{let p=Date.parse(m.recordedAt);return Number.isFinite(p)&&n-p>=kt}).map(m=>m.idempotencyKey);if(l.length>0){let m=t.deleteOperationReceiptsByKeys(l);u+=m,R.agedReceiptsPruned+=m}}return{scannedClaims:s.length,strandedClaimCandidates:i,prunedReceipts:u}}catch{return R.storeFailures+=1,e}}function ar(){return{"dispatchReceipts.storeFailures":R.storeFailures,"dispatchReceipts.completionReplaysObserved":R.completionReplaysObserved,"dispatchReceipts.completionReplaysShortCircuited":R.completionReplaysShortCircuited,"dispatchReceipts.agedReceiptsPruned":R.agedReceiptsPruned}}function Eo(){R.storeFailures=0,R.completionReplaysObserved=0,R.completionReplaysShortCircuited=0,R.agedReceiptsPruned=0}import{readdirSync as Po,readFileSync as Lo}from"node:fs";var B=900*1e3,lr="admission-shadow",cr="worker-slot:",E={storeFailures:0,missingForLive:0,deadSlotsReleased:0},Se=!1;function Co(){Se=!1}function U(r=process.env){return A(r).flags.admission}function be(r,e){return`${cr}${r}:${e}`}function Ao(r,e){if(U()==="off")return;let t=f();if(t)try{t.tryReserveAdmission(be(r,e),lr,B)}catch{E.storeFailures+=1}}function ur(r,e){if(U()==="off")return;let t=f();if(t)try{t.releaseAdmission(be(r,e),lr)}catch{E.storeFailures+=1}}function Oo(r){let e={liveReservations:0,refreshed:0,deadReleased:0,missingForLive:0,orphaned:0,adoptionPass:!1};if(U()==="off")return e;let t=f();if(!t)return e;try{let n=new Set(r.liveWorkers.map(d=>be(d.runId,d.workerName))),o=t.listAdmissionReservations({keyPrefix:cr,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=!Se;Se=!0,!u&&i>0&&(E.missingForLive+=i);let l=0;for(let d of r.liveWorkers)t.tryReserveAdmission(be(d.runId,d.workerName),lr,B),l+=1;let m=0;for(let d of o)n.has(d.key)||t.releaseAdmission(d.key,d.owner)&&(m+=1,E.deadSlotsReleased+=1);return{liveReservations:t.listAdmissionReservations({keyPrefix:cr,limit:500}).length,refreshed:l,deadReleased:m,missingForLive:i,orphaned:a,adoptionPass:u}}catch{return E.storeFailures+=1,e}}function dr(){return{"admission.storeFailures":E.storeFailures,"admission.missingForLive":E.missingForLive,"admission.deadSlotsReleased":E.deadSlotsReleased}}function wo(){E.storeFailures=0,E.missingForLive=0,E.deadSlotsReleased=0,Se=!1}var xe="worker-slot-n:",ke=64;function vt(r){return`${xe}${r}`}function ve(r,e){return`${r}:${e}`}var C={enforceStoreFailures:0,admissionsRefusedSlots:0,admissionsRefusedDiskBackstop:0};function Io(r){if(U()!=="enforce")return{admitted:!0};let e=f();if(!e)return{admitted:!0};let t=Math.max(0,Math.min(ke,Math.floor(r.maxSlots)));if(r.diskActiveWorkers>=t)return C.admissionsRefusedDiskBackstop+=1,{admitted:!1,reason:"disk_backstop"};try{let n=ve(r.runId,r.workerName);for(let o=0;o<t;o+=1)if(e.tryReserveAdmission(vt(o),n,B).acquired)return{admitted:!0,slot:o};return C.admissionsRefusedSlots+=1,{admitted:!1,reason:"slots_exhausted"}}catch{return C.enforceStoreFailures+=1,{admitted:!0}}}function mr(r,e){if(U()==="off")return;let t=f();if(t)try{let n=ve(r,e),o=t.listAdmissionReservations({keyPrefix:xe,limit:ke});for(let s of o)s.owner===n&&t.releaseAdmission(s.key,n)}catch{C.enforceStoreFailures+=1}}function To(r){let e={refreshed:0,deadReleased:0,adopted:0};if(U()!=="enforce")return e;let t=f();if(!t)return e;try{let n=new Set(r.liveWorkers.map(l=>ve(l.runId,l.workerName))),o=t.listAdmissionReservations({keyPrefix:xe,limit:ke}),s=0,i=0,a=new Set;for(let l of o)n.has(l.owner)?(t.tryReserveAdmission(l.key,l.owner,B),a.add(l.owner),s+=1):t.releaseAdmission(l.key,l.owner)&&(i+=1);let u=0;for(let l of r.liveWorkers){let m=ve(l.runId,l.workerName);if(!a.has(m)){for(let p=0;p<ke;p+=1)if(t.tryReserveAdmission(vt(p),m,B).acquired){u+=1;break}}}return{refreshed:s,deadReleased:i,adopted:u}}catch{return C.enforceStoreFailures+=1,e}}function pr(){return{"admission.enforceStoreFailures":C.enforceStoreFailures,"admission.refusedSlotsExhausted":C.admissionsRefusedSlots,"admission.refusedDiskBackstop":C.admissionsRefusedDiskBackstop}}function No(){C.enforceStoreFailures=0,C.admissionsRefusedSlots=0,C.admissionsRefusedDiskBackstop=0}var Do="dispatch:claim:",Mo=900*1e3,Fo=10080*60*1e3,Ko=200,w={recoveredStrandedClaims:0,recoveryDeferredOrphans:0,recoveryStoreFailures:0};function xt(r){if(process.platform!=="linux"||!r.trim())return null;let e=[];try{e=Po("/proc")}catch{return null}for(let t of e)if(/^\d+$/.test(t)&&Number(t)!==process.pid)try{if(Lo(`/proc/${t}/cmdline`,"utf8").replace(/\0/g," ").includes(r))return Number(t)}catch{}return null}async function fr(r){let e=O(),t={mode:e,scanned:0,outcomes:[]};if(e!=="enforce")return t;let n=f();if(!n)return t;let o=r.nowMs??Date.now(),s=r.strandedAfterMs??Mo,i=r.findOrphanPid??xt,a=[],u;try{u=n.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(o-Fo).toISOString(),limit:Ko})}catch{return w.recoveryStoreFailures+=1,t}for(let l of u){let m=l.idempotencyKey.slice(Do.length),p=m.split(":")[0]??"",d=m.slice(p.length+1);if(!(!p||!d))try{let $=Date.parse(l.recordedAt);if(!Number.isFinite($)||o-$<s||n.getOperationReceipt(`dispatch:spawned:${m}`)||n.getOperationReceipt(`dispatch:released:${m}`))continue;let v=q(d);if(n.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${p}:`,limit:10}).some(D=>{if(v===null)return!0;let z=q(D.idempotencyKey.slice(`dispatch:completion-acked:${p}:`.length));return z===null||z>=v}))continue;let J={};try{J=l.resultJson?JSON.parse(l.resultJson):{}}catch{J={}}let y=J.runId??null,h=J.workerName??null;if(y&&h&&r.hasLiveWorker({runId:y,workerName:h})){sr({taskId:p,leaseToken:d}),a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"finalized_late"});continue}if(y&&h){let D=r.worktreePathFor({runId:y,workerName:h}),z=D?i(D):null;if(z!==null){w.recoveryDeferredOrphans+=1,a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"deferred_orphan",detail:`live pid ${z} references ${D}`});continue}}if(!y){a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"skipped",detail:"claim intent missing runId \u2014 cannot resolve lease owner"});continue}let j=await r.releaseClaim({taskId:p,leaseToken:d,runId:y});j.released?(Re({taskId:p,leaseToken:d},"restart_recovery"),h&&(ur(y,h),mr(y,h)),w.recoveredStrandedClaims+=1,a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"released"})):j.transportError?a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"deferred_transport",detail:j.detail}):(Re({taskId:p,leaseToken:d},"restart_recovery_refused"),a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"release_refused",detail:j.detail}))}catch{w.recoveryStoreFailures+=1}}return{mode:e,scanned:u.length,outcomes:a}}function gr(){return{"dispatchReceipts.recoveredStrandedClaims":w.recoveredStrandedClaims,"dispatchReceipts.recoveryDeferredOrphans":w.recoveryDeferredOrphans,"dispatchReceipts.recoveryStoreFailures":w.recoveryStoreFailures}}function Bo(){w.recoveredStrandedClaims=0,w.recoveryDeferredOrphans=0,w.recoveryStoreFailures=0}ae();import Jo from"node:path";var Uo="kynver-harness:",Wo="@runner:";function _t(r,e){let t=r.trim(),n=e.trim();return`${Uo}${t}${Wo}${n}`}I();import At from"node:os";var $o="embedded-1",Ho=[{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"}],jo={"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(e);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(e){let t=this.db.prepare(`PRAGMA ${e}`).get();return String(Object.values(t)[0])}close(){this.db.close()}};import{existsSync as un,renameSync as dn}from"node:fs";function mn(r,e){let t=`${r}.quarantine-${e}`;for(let n of["","-wal","-shm"]){let o=`${r}${n}`;un(o)&&dn(o,`${t}${n}`)}return t}function we(r){let e=r.quarantineStamp??(r.now??(()=>new Date))().toISOString().replace(/[:.]/g,"-"),t=null;try{let s=Y.open(r);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=`${r.directory}/${r.filename??"local-run-store.sqlite"}`,o=mn(n,e);try{return{store:Y.open(r),recovered:!0,quarantinedTo:o}}catch(s){throw new AggregateError([t,s].filter(Boolean),"local-run-store rebuild after quarantine failed")}}Be();function io(){if(process.env.KYNVER_LRS_TEST_CLASSIFY_BYPASS==="1")return{mountsSource:()=>"/dev/vda / ext4 rw 0 0",resolveRealPath:()=>"/tmp/kynver-lrs-test/db"}}function ao(){return xt.classifyOptions??io()}var xt={};function co(r){xt=r}var Et=300*1e3,P=null,ee=0;function lo(r){ee+=1;try{let e=ao(),t=we({directory:r,...e?{classifyOptions:e}:{}});return{store:t.store,status:{state:"open",harnessRoot:r,databasePath:t.store.databasePath,schemaVersion:t.store.localSchemaVersion(),recovered:t.recovered,quarantinedTo:t.quarantinedTo,reason:null,openAttempts:ee},failedAtMs:null,permanentRefusal:!1}}catch(e){return{store:null,status:{state:"unavailable",harnessRoot:r,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:`${e.name}: ${e.message}`,openAttempts:ee},failedAtMs:Date.now(),permanentRefusal:e.name==="FilesystemPolicyError"||e.name==="SchemaDowngradeRefusedError"}}}function uo(r,e){return r.store||r.permanentRefusal?!1:r.failedAtMs===null?!0:e-r.failedAtMs>=Et}function f(r=Date.now()){let e=Ze();return(!P||P.status.harnessRoot!==e||uo(P,r))&&(rr(),P=lo(e)),P.store}function Ct(){return P?P.status:{state:"unopened",harnessRoot:null,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:null,openAttempts:ee}}function er(){return f(),Ct()}function rr(){try{P?.store?.close()}catch{}P=null}function mo(){rr(),ee=0}I();v();import{existsSync as po,readFileSync as fo}from"node:fs";import{homedir as go}from"node:os";import ho from"node:path";var yo=3e4,_=null;function tr(r){let e=r.replace(/[^A-Za-z0-9_-]/g,"_");return ho.join(go(),".kynver",`local-run-store-flags-${e}.json`)}function nr(r){if(!r||typeof r!="object"||Array.isArray(r))return{};let e=r,t={},n=["dispatchReceipts","admission","planOutbox","keeper","meshLease","quota"];for(let o of n){let s=e[o];(s==="off"||s==="shadow"||s==="enforce")&&(t[o]=s)}return t}function Ro(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let e=r.response;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.localRunStoreFlags;return t===void 0?null:nr(t)}function So(r,e){try{let t=tr(r),n={contractVersion:1,agentOsId:r,flags:nr(e),deliveredAt:new Date().toISOString()};Te(t,n),_={flags:n.flags,loadedAtMs:Date.now(),file:t}}catch{}}function or(r=Date.now()){if(process.env.KYNVER_LRS_REMOTE_FLAGS_DISABLED==="1")return{};if(_&&r-_.loadedAtMs<yo)return _.flags;try{let e=x().agentOsId?.trim();if(!e)return _={flags:{},loadedAtMs:r,file:null},_.flags;let t=tr(e);if(!po(t))return _={flags:{},loadedAtMs:r,file:t},_.flags;let n=JSON.parse(fo(t,"utf8")),o=n?.contractVersion===1?nr(n.flags):{};return _={flags:o,loadedAtMs:r,file:t},o}catch{return _={flags:{},loadedAtMs:r,file:null},_.flags}}function bo(){_=null}var At=[{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 Ot(r){let e=r?.trim().toLowerCase()??"";return e===""?{mode:"off",unknown:!1}:e==="off"||e==="shadow"||e==="enforce"?{mode:e,unknown:!1}:{mode:"off",unknown:!0}}function A(r=process.env){let e={},t={},n=[],o=or();for(let s of At){let i=r[s.env];if(typeof i=="string"&&i.trim()!==""){let l=Ot(i);e[s.key]=l.mode,t[s.key]="env",l.unknown&&n.push(`${s.env}='${i}' is not off|shadow|enforce \u2014 treating as off`);continue}let u=o[s.key];if(u){e[s.key]=u,t[s.key]="server";continue}e[s.key]="off",t[s.key]="default"}return{flags:e,sources:t,warnings:n}}function ko(r){return Object.values(r).some(e=>e!=="off")}var R={storeFailures:0,completionReplaysObserved:0,completionReplaysShortCircuited:0,agedReceiptsPruned:0};function O(r=process.env){return A(r).flags.dispatchReceipts}function sr(r){return O(r)!=="off"}function ir(r,e){return`dispatch:${r}:${e.taskId}:${e.leaseToken}`}function re(r,e,t){if(!sr())return;let n=f();if(n)try{n.recordOperationReceipt({idempotencyKey:ir(r,e),operation:`dispatch-${r}`,resultJson:t===void 0?null:JSON.stringify(t)})}catch{R.storeFailures+=1}}function vo(r){re("claim",r,{runId:r.runId,workerName:r.workerName,provider:r.provider})}function ar(r){re("spawned",r)}function be(r,e){re("released",r,{reasonClass:e})}function _o(r){re("completion-sent",r)}function xo(r,e){re("completion-acked",r,{outcome:e})}function Eo(r){if(!sr())return!1;let e=f();if(!e)return!1;try{let t=e.getOperationReceipt(ir("completion-acked",r));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 Co(r){let e=String(r??"").split(":")[0]?.trim()??"";return e.length>0?e.slice(0,64):"unknown"}function Ao(r){if(O()!=="enforce")return!1;let e=f();if(!e)return!1;try{let t=e.getOperationReceipt(ir("completion-acked",r));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 Oo=600*1e3;function wo(r,e){if(O()!=="enforce")return;let t=f();if(t)try{t.recordOperationReceipt({idempotencyKey:`dispatch:start-failed:${r}:${e}`,operation:"dispatch-start-failed",resultJson:JSON.stringify({runId:e})})}catch{R.storeFailures+=1}}function Io(r,e){if(O()!=="enforce")return[];let t=f();if(!t)return[];let n=e?.nowMs??Date.now(),o=e?.windowMs??Oo;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===r:!1}catch{return!1}}).map(s=>{let i=s.idempotencyKey.slice(22);return i.slice(0,i.length-(r.length+1))}).filter(s=>s.length>0)}catch{return R.storeFailures+=1,[]}}function q(r){let e=r.split(":")[0]??"",t=Number(e);return Number.isInteger(t)&&t>=0?t:null}var To=900*1e3,wt=10080*60*1e3,No=1440*60*1e3,Po=500,Lo=300;function cr(r){let e={scannedClaims:0,strandedClaimCandidates:0,prunedReceipts:0};if(!sr())return e;let t=f();if(!t)return e;let n=r?.nowMs??Date.now(),o=r?.strandedAfterMs??To;try{let s=t.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(n-wt).toISOString(),limit:Po}),i=0,a=[];for(let l of s){let m=l.idempotencyKey.slice(15),p=Date.parse(l.recordedAt);if(!Number.isFinite(p)||n-p<o)continue;let d=t.getOperationReceipt(`dispatch:spawned:${m}`),$=t.getOperationReceipt(`dispatch:released:${m}`);if(d||$){n-p>=No&&a.length+5<=Lo&&a.push(l.idempotencyKey,`dispatch:spawned:${m}`,`dispatch:released:${m}`,`dispatch:completion-sent:${m}`,`dispatch:completion-acked:${m}`);continue}let k=m.split(":")[0]??"",H=q(m.slice(k.length+1));if((k?t.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${k}:`,limit:10}):[]).some(h=>{if(H===null)return!0;let j=h.idempotencyKey.slice(`dispatch:completion-acked:${k}:`.length),D=q(j);return D===null||D>=H}))continue;let y=!1;if(r?.hasLiveWorker&&l.resultJson)try{let h=JSON.parse(l.resultJson);h.runId&&h.workerName&&(y=r.hasLiveWorker({runId:h.runId,workerName:h.workerName}))}catch{y=!1}y||(i+=1)}let u=a.length>0?t.deleteOperationReceiptsByKeys(a):0;if(O()==="enforce"){let l=t.listOperationReceipts({limit:100}).filter(m=>{let p=Date.parse(m.recordedAt);return Number.isFinite(p)&&n-p>=wt}).map(m=>m.idempotencyKey);if(l.length>0){let m=t.deleteOperationReceiptsByKeys(l);u+=m,R.agedReceiptsPruned+=m}}return{scannedClaims:s.length,strandedClaimCandidates:i,prunedReceipts:u}}catch{return R.storeFailures+=1,e}}function lr(){return{"dispatchReceipts.storeFailures":R.storeFailures,"dispatchReceipts.completionReplaysObserved":R.completionReplaysObserved,"dispatchReceipts.completionReplaysShortCircuited":R.completionReplaysShortCircuited,"dispatchReceipts.agedReceiptsPruned":R.agedReceiptsPruned}}function Do(){R.storeFailures=0,R.completionReplaysObserved=0,R.completionReplaysShortCircuited=0,R.agedReceiptsPruned=0}import{readdirSync as Ho,readFileSync as jo}from"node:fs";var B=900*1e3,dr="admission-shadow",ur="worker-slot:",E={storeFailures:0,missingForLive:0,deadSlotsReleased:0},ke=!1;function Mo(){ke=!1}function W(r=process.env){return A(r).flags.admission}function ve(r,e){return`${ur}${r}:${e}`}function Ko(r,e){if(W()==="off")return;let t=f();if(t)try{t.tryReserveAdmission(ve(r,e),dr,B)}catch{E.storeFailures+=1}}function mr(r,e){if(W()==="off")return;let t=f();if(t)try{t.releaseAdmission(ve(r,e),dr)}catch{E.storeFailures+=1}}function Fo(r){let e={liveReservations:0,refreshed:0,deadReleased:0,missingForLive:0,orphaned:0,adoptionPass:!1};if(W()==="off")return e;let t=f();if(!t)return e;try{let n=new Set(r.liveWorkers.map(d=>ve(d.runId,d.workerName))),o=t.listAdmissionReservations({keyPrefix:ur,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=!ke;ke=!0,!u&&i>0&&(E.missingForLive+=i);let l=0;for(let d of r.liveWorkers)t.tryReserveAdmission(ve(d.runId,d.workerName),dr,B),l+=1;let m=0;for(let d of o)n.has(d.key)||t.releaseAdmission(d.key,d.owner)&&(m+=1,E.deadSlotsReleased+=1);return{liveReservations:t.listAdmissionReservations({keyPrefix:ur,limit:500}).length,refreshed:l,deadReleased:m,missingForLive:i,orphaned:a,adoptionPass:u}}catch{return E.storeFailures+=1,e}}function pr(){return{"admission.storeFailures":E.storeFailures,"admission.missingForLive":E.missingForLive,"admission.deadSlotsReleased":E.deadSlotsReleased}}function Bo(){E.storeFailures=0,E.missingForLive=0,E.deadSlotsReleased=0,ke=!1}var Ee="worker-slot-n:",_e=64;function It(r){return`${Ee}${r}`}function xe(r,e){return`${r}:${e}`}var C={enforceStoreFailures:0,admissionsRefusedSlots:0,admissionsRefusedDiskBackstop:0};function Wo(r){if(W()!=="enforce")return{admitted:!0};let e=f();if(!e)return{admitted:!0};let t=Math.max(0,Math.min(_e,Math.floor(r.maxSlots)));if(r.diskActiveWorkers>=t)return C.admissionsRefusedDiskBackstop+=1,{admitted:!1,reason:"disk_backstop"};try{let n=xe(r.runId,r.workerName);for(let o=0;o<t;o+=1)if(e.tryReserveAdmission(It(o),n,B).acquired)return{admitted:!0,slot:o};return C.admissionsRefusedSlots+=1,{admitted:!1,reason:"slots_exhausted"}}catch{return C.enforceStoreFailures+=1,{admitted:!0}}}function fr(r,e){if(W()==="off")return;let t=f();if(t)try{let n=xe(r,e),o=t.listAdmissionReservations({keyPrefix:Ee,limit:_e});for(let s of o)s.owner===n&&t.releaseAdmission(s.key,n)}catch{C.enforceStoreFailures+=1}}function Uo(r){let e={refreshed:0,deadReleased:0,adopted:0};if(W()!=="enforce")return e;let t=f();if(!t)return e;try{let n=new Set(r.liveWorkers.map(l=>xe(l.runId,l.workerName))),o=t.listAdmissionReservations({keyPrefix:Ee,limit:_e}),s=0,i=0,a=new Set;for(let l of o)n.has(l.owner)?(t.tryReserveAdmission(l.key,l.owner,B),a.add(l.owner),s+=1):t.releaseAdmission(l.key,l.owner)&&(i+=1);let u=0;for(let l of r.liveWorkers){let m=xe(l.runId,l.workerName);if(!a.has(m)){for(let p=0;p<_e;p+=1)if(t.tryReserveAdmission(It(p),m,B).acquired){u+=1;break}}}return{refreshed:s,deadReleased:i,adopted:u}}catch{return C.enforceStoreFailures+=1,e}}function gr(){return{"admission.enforceStoreFailures":C.enforceStoreFailures,"admission.refusedSlotsExhausted":C.admissionsRefusedSlots,"admission.refusedDiskBackstop":C.admissionsRefusedDiskBackstop}}function $o(){C.enforceStoreFailures=0,C.admissionsRefusedSlots=0,C.admissionsRefusedDiskBackstop=0}var Yo="dispatch:claim:",Vo=900*1e3,Go=10080*60*1e3,qo=200,w={recoveredStrandedClaims:0,recoveryDeferredOrphans:0,recoveryStoreFailures:0};function Tt(r){if(process.platform!=="linux"||!r.trim())return null;let e=[];try{e=Ho("/proc")}catch{return null}for(let t of e)if(/^\d+$/.test(t)&&Number(t)!==process.pid)try{if(jo(`/proc/${t}/cmdline`,"utf8").replace(/\0/g," ").includes(r))return Number(t)}catch{}return null}async function hr(r){let e=O(),t={mode:e,scanned:0,outcomes:[]};if(e!=="enforce")return t;let n=f();if(!n)return t;let o=r.nowMs??Date.now(),s=r.strandedAfterMs??Vo,i=r.findOrphanPid??Tt,a=[],u;try{u=n.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(o-Go).toISOString(),limit:qo})}catch{return w.recoveryStoreFailures+=1,t}for(let l of u){let m=l.idempotencyKey.slice(Yo.length),p=m.split(":")[0]??"",d=m.slice(p.length+1);if(!(!p||!d))try{let $=Date.parse(l.recordedAt);if(!Number.isFinite($)||o-$<s||n.getOperationReceipt(`dispatch:spawned:${m}`)||n.getOperationReceipt(`dispatch:released:${m}`))continue;let k=q(d);if(n.listOperationReceipts({keyPrefix:`dispatch:completion-acked:${p}:`,limit:10}).some(D=>{if(k===null)return!0;let z=q(D.idempotencyKey.slice(`dispatch:completion-acked:${p}:`.length));return z===null||z>=k}))continue;let J={};try{J=l.resultJson?JSON.parse(l.resultJson):{}}catch{J={}}let y=J.runId??null,h=J.workerName??null;if(y&&h&&r.hasLiveWorker({runId:y,workerName:h})){ar({taskId:p,leaseToken:d}),a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"finalized_late"});continue}if(y&&h){let D=r.worktreePathFor({runId:y,workerName:h}),z=D?i(D):null;if(z!==null){w.recoveryDeferredOrphans+=1,a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"deferred_orphan",detail:`live pid ${z} references ${D}`});continue}}if(!y){a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"skipped",detail:"claim intent missing runId \u2014 cannot resolve lease owner"});continue}let j=await r.releaseClaim({taskId:p,leaseToken:d,runId:y});j.released?(be({taskId:p,leaseToken:d},"restart_recovery"),h&&(mr(y,h),fr(y,h)),w.recoveredStrandedClaims+=1,a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"released"})):j.transportError?a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"deferred_transport",detail:j.detail}):(be({taskId:p,leaseToken:d},"restart_recovery_refused"),a.push({taskId:p,leaseToken:d,runId:y,workerName:h,action:"release_refused",detail:j.detail}))}catch{w.recoveryStoreFailures+=1}}return{mode:e,scanned:u.length,outcomes:a}}function yr(){return{"dispatchReceipts.recoveredStrandedClaims":w.recoveredStrandedClaims,"dispatchReceipts.recoveryDeferredOrphans":w.recoveryDeferredOrphans,"dispatchReceipts.recoveryStoreFailures":w.recoveryStoreFailures}}function Jo(){w.recoveredStrandedClaims=0,w.recoveryDeferredOrphans=0,w.recoveryStoreFailures=0}le();import ss from"node:path";var zo="kynver-harness:",Xo="@runner:";function Nt(r,e){let t=r.trim(),n=e.trim();return`${zo}${t}${Xo}${n}`}I();import Dt from"node:os";var Qo="embedded-1",Zo=[{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"}],es={"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
- `)},Yo={"harness.maxTaskAttempts":4,"harness.dispatchCooldownMs":5e3,"daemon.idleIntervalMs":5*6e4,"daemon.maxIdleStreak":10},Et={version:$o,generatedAt:"1970-01-01T00:00:00.000Z",personas:Ho,instructions:jo,policyThresholds:Yo};var Vo=Et;function Ct(){return Vo.version}M();function L(r){return r?.trim()?r.trim():null}function Ot(r={}){let e=r.env??process.env,t=_();return{runnerId:L(t.runnerId)??L(e.KYNVER_RUNTIME_ID)??L(e.OPENCLAW_RUNTIME_ID)??L(e.HOSTNAME)??At.hostname(),hostname:L(e.HOSTNAME)??At.hostname(),profile:L(e.KYNVER_RUNNER_PROFILE)??L(e.OPENCLAW_RUNNER_PROFILE),harnessRepo:L(e.KYNVER_HARNESS_REPO)??L(e.KYNVER_DEFAULT_REPO),runId:r.runId??null,instructionBundleVersion:Ct()}}function wt(r){let e=String(r).trim();return e.startsWith("krc1.")?{"Content-Type":"application/json","X-Kynver-Runner-Token":e}:{"Content-Type":"application/json","X-Kynver-Cron-Secret":e,"X-OpenClaw-Cron-Secret":e,"X-Kynver-Runtime-Secret":e}}I();function Tt(r){if(r!==void 0&&Number.isFinite(r)&&r>0)return Math.floor(r);let e=Number(process.env.KYNVER_CALLBACK_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):3e4}async function Go(r,e){let t=Tt(e),n=new AbortController,o;try{return await Promise.race([r(n.signal),new Promise((s,i)=>{o=setTimeout(()=>{n.abort(),i(new Error(`callback timeout after ${t}ms`))},t)})])}finally{o&&clearTimeout(o)}}function qo(r,e){let t=Tt(e);return{ok:!1,status:0,response:{error:r instanceof Error?r.message:String(r),timeoutMs:t}}}async function It(r,e,t,n){try{return await Go(async o=>{let s=await fetch(r,{method:"POST",headers:wt(e),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 qo(o,n?.timeoutMs)}}async function Nt(r,e,t,n){let o=await It(r,e,t,{timeoutMs:n.timeoutMs});if(o.ok||o.status!==401)return o;let s=await ft(e,n.agentOsId,{baseUrl:n.baseUrl});return s.ok?{...await It(r,s.token,t,{timeoutMs:n.timeoutMs}),refreshedAuth:!0}:{...o,authRefreshFailure:s.reason}}async function Pt(r){let e=`${r.baseUrl}/api/agent-os/by-id/${encodeURIComponent(r.agentOsId)}/tasks/${encodeURIComponent(r.taskId)}/release`,t;try{t=await Nt(e,r.secret,{agentOsId:r.agentOsId,leaseOwner:r.leaseOwner,...r.leaseToken?.trim()?{leaseToken:r.leaseToken.trim()}:{},...r.failureDetail?{failureDetail:r.failureDetail}:{}},{agentOsId:r.agentOsId,baseUrl:r.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 hr=!1;function zo(){hr=!1}async function Xo(r){if(hr||O()!=="enforce")return null;hr=!0;try{let e=Ot().runnerId,t=await fr({hasLiveWorker:r.hasLiveWorker,worktreePathFor:({runId:n,workerName:o})=>Jo.join(Ar().worktreesDir,n,o),releaseClaim:async({taskId:n,leaseToken:o,runId:s})=>{let i=await Pt({baseUrl:r.baseUrl,secret:r.secret,agentOsId:r.agentOsId,taskId:n,leaseOwner:_t(s,e),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 ku=600*1e3,te={storeFailures:0,corruptItemsSeen:0,corruptItemsQuarantined:0,duplicateDrainsObserved:0,halfArchivesCompleted:0};function Lt(){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(r){return A(process.env).flags[r]}var Dt="daemon-keeper",Qo=1800*1e3;function Zo(r){if(W("keeper")==="off")return;let e=f();if(e)try{e.saveRecoveryCheckpoint({scope:Dt,payloadJson:JSON.stringify(r)})}catch{g.keeperStoreFailures+=1}}function es(){if(W("keeper")!=="enforce")return null;let r=f();if(!r)return null;try{let e=r.latestRecoveryCheckpoint(Dt);if(!e)return null;let t=JSON.parse(e.payloadJson),n=Date.now()-Date.parse(e.createdAt);if(!Number.isFinite(n)||n>Qo)return null;let o=Number(t.consecutiveFailures);return Number.isFinite(o)&&o>=0?Math.floor(o):null}catch{return g.keeperStoreFailures+=1,null}}function yr(r){return`mesh-cron-lease:${r}`}function rs(r,e){if(W("meshLease")==="off")return;let t=f();if(t)try{let n=t.latestRecoveryCheckpoint(yr(r));if(n){let o=JSON.parse(n.payloadJson);if((o.leaseToken??null)===(e.leaseToken??null)&&(o.holderBoxId??null)===(e.holderBoxId??null)&&o.authorized===e.authorized)return}t.saveRecoveryCheckpoint({scope:yr(r),payloadJson:JSON.stringify(e)})}catch{g.meshStoreFailures+=1}}function ts(r,e){let t=W("meshLease");if(t==="off")return null;let n=f();if(!n)return null;try{let o=n.latestRecoveryCheckpoint(yr(r)),s=o?JSON.parse(o.payloadJson):null,i=s!==null&&((s.leaseToken??null)!==(e?.leaseToken??null)||(s.holderBoxId??null)!==(e?.holderBoxId??null)||(s.authorized??null)!==(e?.authorized??null));return i&&(g.meshLeaseDivergences+=1),t!=="enforce"?null:i&&e?.updatedAt&&s?.updatedAt&&Date.parse(e.updatedAt)>Date.parse(s.updatedAt)?(g.meshEnforceStaleInversions+=1,null):s}catch{return g.meshStoreFailures+=1,null}}function _e(r){return`quota-cooldown:${r}`}var Mt="quota-preflight";function ns(r,e){if(W("quota")==="off")return;let t=f();if(t)try{t.tryReserveAdmission(_e(r),Mt,e)}catch{g.quotaStoreFailures+=1}}function os(r){if(W("quota")==="off")return;let e=f();if(e)try{e.releaseAdmission(_e(r),Mt)}catch{g.quotaStoreFailures+=1}}function ss(r,e){let t=W("quota");if(t==="off")return null;let n=f();if(!n)return null;try{let o=n.listAdmissionReservations({keyPrefix:_e(r),limit:50}).find(i=>i.key===_e(r)),s=!!o;return s!==e&&(g.quotaVerdictDivergences+=1),t==="enforce"?{blocked:s,retryAtIso:o?.expiresAt??null}:null}catch{return g.quotaStoreFailures+=1,null}}function Rr(){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 is(){g.keeperStoreFailures=0,g.meshStoreFailures=0,g.quotaStoreFailures=0,g.meshLeaseDivergences=0,g.meshEnforceStaleInversions=0,g.quotaVerdictDivergences=0}function as(r){let e=Qe(),t=A(r?.env??process.env),n=(r?.now??(()=>new Date))().getTime(),o={};if(t.flags.dispatchReceipts!=="off"){Object.assign(o,ar());let s=ir({nowMs:n,hasLiveWorker:r?.hasLiveWorker});o["dispatchReceipts.strandedClaimCandidates"]=s.strandedClaimCandidates,t.flags.dispatchReceipts==="enforce"&&Object.assign(o,gr())}return t.flags.planOutbox!=="off"&&Object.assign(o,Lt()),t.flags.admission!=="off"&&(Object.assign(o,dr()),t.flags.admission==="enforce"&&Object.assign(o,pr())),(t.flags.keeper!=="off"||t.flags.meshLease!=="off"||t.flags.quota!=="off")&&Object.assign(o,Rr()),{contractVersion:1,observedAt:new Date(n).toISOString(),state:e.state,schemaVersion:e.schemaVersion,recovered:e.recovered,unavailableClass:e.reason?e.reason.split(":")[0]??null:null,flags:t.flags,flagSources:t.sources,flagWarningCount:t.warnings.length,divergenceCounters:o}}export{B as ADMISSION_RESERVATION_TTL_MS,xe as ADMISSION_SLOT_KEY_PREFIX,X as FilesystemPolicyError,yt as LOCAL_RUN_STORE_OPEN_RETRY_MS,St as LOCAL_RUN_STORE_SURFACES,Ce as LOCAL_SCHEMA_VERSION,ne as SchemaDowngradeRefusedError,Y as SqliteLocalRunStore,No as __resetAdmissionEnforceCountersForTests,wo as __resetAdmissionShadowCountersForTests,Bo as __resetDispatchClaimRecoveryForTests,Eo as __resetDispatchReceiptCountersForTests,ro as __resetLocalRunStoreLifecycleForTests,lo as __resetRemoteSurfaceFlagsCacheForTests,is as __resetSmallSurfaceCountersForTests,zo as __resetStartupClaimRecoveryForTests,Qn as __setLocalRunStoreLifecycleTestOverrides,Io as acquireWorkerAdmissionSlot,pr as admissionEnforceCounters,dr as admissionShadowCounters,uo as anyLocalRunStoreSurfaceActive,ss as assessQuotaCooldownReservation,as as buildLocalRunStoreTickPosture,Ee as classifyDatabaseDirectory,os as clearQuotaCooldownReservation,Ze as closeLocalRunStore,gr as dispatchClaimRecoveryCounters,ar as dispatchReceiptCounters,O as dispatchReceiptsMode,ao as extractLocalRunStoreFlagsFromOperatorTickResponse,xt as findLiveProcessByCmdlinePath,f as getLocalRunStore,Rt as getLocalRunStoreLifecycleStatus,tr as getRemoteSurfaceFlags,q as leaseTokenAttempt,bo as listRecentDispatchStartFailures,Xo as maybeRunStartupClaimRecovery,go as noteCompletionReplayIfAcked,Ae as openSqliteLocalRunStoreWithRecovery,bt as parseLocalRunStoreSurfaceMode,co as persistRemoteSurfaceFlags,Qe as probeLocalRunStore,ts as readMeshLeaseCheckpoint,Co as rearmAdmissionAdoptionPass,Oo as reconcileAdmissionShadow,To as reconcileNumberedAdmissionSlots,fo as recordCompletionAckedReceipt,po as recordCompletionSentReceipt,mo as recordDispatchClaimReceipt,Re as recordDispatchReleasedReceipt,sr as recordDispatchSpawnedReceipt,So as recordDispatchStartFailedReceipt,ns as recordQuotaCooldownReservation,fr as recoverStrandedDispatchClaims,ho as releaseReasonClass,mr as releaseWorkerAdmissionSlot,ur as releaseWorkerSlotReservation,er as remoteSurfaceFlagsPath,A as resolveLocalRunStoreSurfaceFlags,es as restoreKeeperBackoffCheckpoint,Zo as saveKeeperBackoffCheckpoint,rs as saveMeshLeaseCheckpoint,ir as scanDispatchReceiptInvariants,yo as shouldShortCircuitCompletionReplay,Rr as smallSurfaceCounters,Ao as takeWorkerSlotReservation};
58
+ `)},rs={"harness.maxTaskAttempts":4,"harness.dispatchCooldownMs":5e3,"daemon.idleIntervalMs":5*6e4,"daemon.maxIdleStreak":10},Pt={version:Qo,generatedAt:"1970-01-01T00:00:00.000Z",personas:Zo,instructions:es,policyThresholds:rs};var ts=Pt;function Lt(){return ts.version}M();function L(r){return r?.trim()?r.trim():null}function Mt(r={}){let e=r.env??process.env,t=x();return{runnerId:L(t.runnerId)??L(e.KYNVER_RUNTIME_ID)??L(e.OPENCLAW_RUNTIME_ID)??L(e.HOSTNAME)??Dt.hostname(),hostname:L(e.HOSTNAME)??Dt.hostname(),profile:L(e.KYNVER_RUNNER_PROFILE)??L(e.OPENCLAW_RUNNER_PROFILE),harnessRepo:L(e.KYNVER_HARNESS_REPO)??L(e.KYNVER_DEFAULT_REPO),runId:r.runId??null,instructionBundleVersion:Lt()}}function Kt(r){let e=String(r).trim();return e.startsWith("krc1.")?{"Content-Type":"application/json","X-Kynver-Runner-Token":e}:{"Content-Type":"application/json","X-Kynver-Cron-Secret":e,"X-OpenClaw-Cron-Secret":e,"X-Kynver-Runtime-Secret":e}}I();function Bt(r){if(r!==void 0&&Number.isFinite(r)&&r>0)return Math.floor(r);let e=Number(process.env.KYNVER_CALLBACK_TIMEOUT_MS);return Number.isFinite(e)&&e>0?Math.floor(e):3e4}async function ns(r,e){let t=Bt(e),n=new AbortController,o;try{return await Promise.race([r(n.signal),new Promise((s,i)=>{o=setTimeout(()=>{n.abort(),i(new Error(`callback timeout after ${t}ms`))},t)})])}finally{o&&clearTimeout(o)}}function os(r,e){let t=Bt(e);return{ok:!1,status:0,response:{error:r instanceof Error?r.message:String(r),timeoutMs:t}}}async function Ft(r,e,t,n){try{return await ns(async o=>{let s=await fetch(r,{method:"POST",headers:Kt(e),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 os(o,n?.timeoutMs)}}async function Wt(r,e,t,n){let o=await Ft(r,e,t,{timeoutMs:n.timeoutMs});if(o.ok||o.status!==401)return o;let s=await vt(e,n.agentOsId,{baseUrl:n.baseUrl});return s.ok?{...await Ft(r,s.token,t,{timeoutMs:n.timeoutMs}),refreshedAuth:!0}:{...o,authRefreshFailure:s.reason}}async function Ut(r){let e=`${r.baseUrl}/api/agent-os/by-id/${encodeURIComponent(r.agentOsId)}/tasks/${encodeURIComponent(r.taskId)}/release`,t;try{t=await Wt(e,r.secret,{agentOsId:r.agentOsId,leaseOwner:r.leaseOwner,...r.leaseToken?.trim()?{leaseToken:r.leaseToken.trim()}:{},...r.failureDetail?{failureDetail:r.failureDetail}:{}},{agentOsId:r.agentOsId,baseUrl:r.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 Rr=!1;function is(){Rr=!1}async function as(r){if(Rr||O()!=="enforce")return null;Rr=!0;try{let e=Mt().runnerId,t=await hr({hasLiveWorker:r.hasLiveWorker,worktreePathFor:({runId:n,workerName:o})=>ss.join(Lr().worktreesDir,n,o),releaseClaim:async({taskId:n,leaseToken:o,runId:s})=>{let i=await Ut({baseUrl:r.baseUrl,secret:r.secret,agentOsId:r.agentOsId,taskId:n,leaseOwner:Nt(s,e),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 Wu=600*1e3,te={storeFailures:0,corruptItemsSeen:0,corruptItemsQuarantined:0,duplicateDrainsObserved:0,halfArchivesCompleted:0};function $t(){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 U(r){return A(process.env).flags[r]}var Ht="daemon-keeper",cs=1800*1e3;function ls(r){if(U("keeper")==="off")return;let e=f();if(e)try{e.saveRecoveryCheckpoint({scope:Ht,payloadJson:JSON.stringify(r)})}catch{g.keeperStoreFailures+=1}}function us(){if(U("keeper")!=="enforce")return null;let r=f();if(!r)return null;try{let e=r.latestRecoveryCheckpoint(Ht);if(!e)return null;let t=JSON.parse(e.payloadJson),n=Date.now()-Date.parse(e.createdAt);if(!Number.isFinite(n)||n>cs)return null;let o=Number(t.consecutiveFailures);return Number.isFinite(o)&&o>=0?Math.floor(o):null}catch{return g.keeperStoreFailures+=1,null}}function Sr(r){return`mesh-cron-lease:${r}`}function ds(r,e){if(U("meshLease")==="off")return;let t=f();if(t)try{let n=t.latestRecoveryCheckpoint(Sr(r));if(n){let o=JSON.parse(n.payloadJson);if((o.leaseToken??null)===(e.leaseToken??null)&&(o.holderBoxId??null)===(e.holderBoxId??null)&&o.authorized===e.authorized)return}t.saveRecoveryCheckpoint({scope:Sr(r),payloadJson:JSON.stringify(e)})}catch{g.meshStoreFailures+=1}}function ms(r,e){let t=U("meshLease");if(t==="off")return null;let n=f();if(!n)return null;try{let o=n.latestRecoveryCheckpoint(Sr(r)),s=o?JSON.parse(o.payloadJson):null,i=s!==null&&((s.leaseToken??null)!==(e?.leaseToken??null)||(s.holderBoxId??null)!==(e?.holderBoxId??null)||(s.authorized??null)!==(e?.authorized??null));return i&&(g.meshLeaseDivergences+=1),t!=="enforce"?null:i&&e?.updatedAt&&s?.updatedAt&&Date.parse(e.updatedAt)>Date.parse(s.updatedAt)?(g.meshEnforceStaleInversions+=1,null):s}catch{return g.meshStoreFailures+=1,null}}function Ce(r){return`quota-cooldown:${r}`}var jt="quota-preflight";function ps(r,e){if(U("quota")==="off")return;let t=f();if(t)try{t.tryReserveAdmission(Ce(r),jt,e)}catch{g.quotaStoreFailures+=1}}function fs(r){if(U("quota")==="off")return;let e=f();if(e)try{e.releaseAdmission(Ce(r),jt)}catch{g.quotaStoreFailures+=1}}function gs(r,e){let t=U("quota");if(t==="off")return null;let n=f();if(!n)return null;try{let o=n.listAdmissionReservations({keyPrefix:Ce(r),limit:50}).find(i=>i.key===Ce(r)),s=!!o;return s!==e&&(g.quotaVerdictDivergences+=1),t==="enforce"?{blocked:s,retryAtIso:o?.expiresAt??null}:null}catch{return g.quotaStoreFailures+=1,null}}function br(){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 hs(){g.keeperStoreFailures=0,g.meshStoreFailures=0,g.quotaStoreFailures=0,g.meshLeaseDivergences=0,g.meshEnforceStaleInversions=0,g.quotaVerdictDivergences=0}function ys(r){let e=er(),t=A(r?.env??process.env),n=(r?.now??(()=>new Date))().getTime(),o={};if(t.flags.dispatchReceipts!=="off"){Object.assign(o,lr());let s=cr({nowMs:n,hasLiveWorker:r?.hasLiveWorker});o["dispatchReceipts.strandedClaimCandidates"]=s.strandedClaimCandidates,t.flags.dispatchReceipts==="enforce"&&Object.assign(o,yr())}return t.flags.planOutbox!=="off"&&Object.assign(o,$t()),t.flags.admission!=="off"&&(Object.assign(o,pr()),t.flags.admission==="enforce"&&Object.assign(o,gr())),(t.flags.keeper!=="off"||t.flags.meshLease!=="off"||t.flags.quota!=="off")&&Object.assign(o,br()),{contractVersion:1,observedAt:new Date(n).toISOString(),state:e.state,schemaVersion:e.schemaVersion,recovered:e.recovered,unavailableClass:e.reason?e.reason.split(":")[0]??null:null,flags:t.flags,flagSources:t.sources,flagWarningCount:t.warnings.length,divergenceCounters:o}}export{B as ADMISSION_RESERVATION_TTL_MS,Ee as ADMISSION_SLOT_KEY_PREFIX,X as FilesystemPolicyError,Et as LOCAL_RUN_STORE_OPEN_RETRY_MS,At as LOCAL_RUN_STORE_SURFACES,Oe as LOCAL_SCHEMA_VERSION,ne as SchemaDowngradeRefusedError,Y as SqliteLocalRunStore,$o as __resetAdmissionEnforceCountersForTests,Bo as __resetAdmissionShadowCountersForTests,Jo as __resetDispatchClaimRecoveryForTests,Do as __resetDispatchReceiptCountersForTests,mo as __resetLocalRunStoreLifecycleForTests,bo as __resetRemoteSurfaceFlagsCacheForTests,hs as __resetSmallSurfaceCountersForTests,is as __resetStartupClaimRecoveryForTests,co as __setLocalRunStoreLifecycleTestOverrides,Wo as acquireWorkerAdmissionSlot,gr as admissionEnforceCounters,pr as admissionShadowCounters,ko as anyLocalRunStoreSurfaceActive,gs as assessQuotaCooldownReservation,ys as buildLocalRunStoreTickPosture,Ae as classifyDatabaseDirectory,fs as clearQuotaCooldownReservation,rr as closeLocalRunStore,yr as dispatchClaimRecoveryCounters,lr as dispatchReceiptCounters,O as dispatchReceiptsMode,Ro as extractLocalRunStoreFlagsFromOperatorTickResponse,Tt as findLiveProcessByCmdlinePath,f as getLocalRunStore,Ct as getLocalRunStoreLifecycleStatus,or as getRemoteSurfaceFlags,q as leaseTokenAttempt,Io as listRecentDispatchStartFailures,as as maybeRunStartupClaimRecovery,Eo as noteCompletionReplayIfAcked,we as openSqliteLocalRunStoreWithRecovery,Ot as parseLocalRunStoreSurfaceMode,So as persistRemoteSurfaceFlags,er as probeLocalRunStore,ms as readMeshLeaseCheckpoint,Mo as rearmAdmissionAdoptionPass,Fo as reconcileAdmissionShadow,Uo as reconcileNumberedAdmissionSlots,xo as recordCompletionAckedReceipt,_o as recordCompletionSentReceipt,vo as recordDispatchClaimReceipt,be as recordDispatchReleasedReceipt,ar as recordDispatchSpawnedReceipt,wo as recordDispatchStartFailedReceipt,ps as recordQuotaCooldownReservation,hr as recoverStrandedDispatchClaims,Co as releaseReasonClass,fr as releaseWorkerAdmissionSlot,mr as releaseWorkerSlotReservation,tr as remoteSurfaceFlagsPath,A as resolveLocalRunStoreSurfaceFlags,us as restoreKeeperBackoffCheckpoint,ls as saveKeeperBackoffCheckpoint,ds as saveMeshLeaseCheckpoint,cr as scanDispatchReceiptInvariants,Ao as shouldShortCircuitCompletionReplay,br as smallSurfaceCounters,Ko as takeWorkerSlotReservation};