@kynver-app/runtime 0.2.56 → 0.2.62

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"],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 kr}from"node:os";import vr from"node:path";function sn(r){return r==="~"?kr():r.startsWith("~/")||r.startsWith("~\\")?vr.join(kr(),r.slice(2)):r}function K(r){return vr.resolve(sn(r))}var V=c(()=>{"use strict"});import{existsSync as Os,mkdirSync as an,readFileSync as cn,readdirSync as ws,renameSync as ln,rmSync as un,statSync as Is,writeFileSync as dn}from"node:fs";import{randomBytes as mn}from"node:crypto";import pn from"node:path";function Oe(r){console.error(r),process.exit(1)}function Q(r,e){try{return JSON.parse(cn(r,"utf8"))}catch(t){if(arguments.length>1)return e;Oe(`failed to read ${r}: ${t.message}`)}}function we(r,e){an(pn.dirname(r),{recursive:!0});let t=`${r}.${process.pid}.${mn(4).toString("hex")}.tmp`;try{dn(t,`${JSON.stringify(e,null,2)}
2
+ `),ln(t,r)}catch(n){try{un(t,{force:!0})}catch{}throw n}}function Ie(r){return String(r).replace(/\/+$/,"")}var k=c(()=>{"use strict"});var fn,Ls,gn,Ds,_r=c(()=>{"use strict";fn=["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"],Ls=new Set(fn),gn=["GITHUB_TOKEN","GH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CODEX_API_KEY","GEMINI_API_KEY"],Ds=new Set(gn)});var Te=c(()=>{"use strict";V();k();_r()});var Ne=c(()=>{"use strict";Te();V()});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 oe(r,e){return r[e]?.trim()||null}function xr(r){let e=r?.split(":")[0]?.trim();return e?F(e):null}function G(r=process.env,e={}){let t=[],n=xr(e.boxId),o=xr(oe(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=oe(r,"KYNVER_BOX_KIND");if(i)return o&&o!==F(i)&&t.push(`KYNVER_BOX_ID=${oe(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=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 Xs,Qs,Le=c(()=>{"use strict";Xs=25*1024*1024*1024,Qs=12*1024*1024*1024});var ni,oi,Cr=c(()=>{"use strict";Le();ni=5*1024*1024*1024,oi=10*1024*1024*1024});var ui,di,De=c(()=>{"use strict";Cr();Le();ui=30*1024*1024*1024,di=15*1024*1024*1024});function Ar(){return wr()}var ae=c(()=>{"use strict";Ke();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 Kr=c(()=>{"use strict"});var Fr=c(()=>{"use strict"});var Fe=c(()=>{"use strict"});var Br=c(()=>{"use strict"});var Wr=c(()=>{"use strict";Fe();Br()});var Ur=c(()=>{"use strict";Nr();Dr();Mr();Kr();Te();Fr();Wr();Fe();k()});var $r=c(()=>{"use strict";Ur()});function Hr(r,e={}){let t=e.perWorkerMemBytes??Be,n=e.memReserveBytes??We,o=e.memUtilization??Ue,s=Math.max(0,Math.floor(r*o)-n),i=Math.max(1,Math.floor(s/t));return Math.min(i,ce)}var Be,We,Ue,ce,jr=c(()=>{"use strict";Er();I();M();ie();le();De();ae();Ir();$r();k();Be=500*1024*1024,We=4*1024*1024*1024,Ue=.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,We),s=Math.min(1,Math.max(.1,Number(e.memUtilization)>0?Number(e.memUtilization):Ue)),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 kn}from"node:os";import vn from"node:path";var Yr,He=c(()=>{"use strict";Yr=vn.join(kn(),".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 Cn,readdirSync as de,renameSync as Zr,statSync as An}from"node:fs";import N from"node:path";function rt(r){try{return An(r).isDirectory()}catch{return!1}}function On(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 wn(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 In(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 Tn(r){let e=N.join(r,"ghost");return T(e)?!T(N.join(e,"runs")):In(r)}function tt(r){return wn(r.sharedRoot)?On(r.forgeRoot)?Tn(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){Cn(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 Nn}from"node:os";import S from"node:path";function Ye(r=process.env){return r.HOME?.trim()||Nn()}function Ve(r=process.env){return S.join(Ye(r),".kynver","harness")}function me(r){let e=S.resolve(K(r.trim()));for(;Pn.has(S.basename(e));)e=S.dirname(e);return e}function Ln(r,e=process.env){return S.join(Ve(e),r)}function Dn(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=Ln(r.boxKind,e);if(b(S.join(o,"runs"))||b(o)&&!Mn(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"&&Dn(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 Mn(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,Pn,Ge=c(()=>{"use strict";V();ot();st=S.join(".openclaw","harness");Pn=new Set(["runs","worktrees"])});import it from"node:os";function fe(r){return r?.trim()?r.trim():null}function Kn(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=x(),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??Kn(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()});var Un,Zc,ct=c(()=>{"use strict";Un=["claude","cursor","codex","gemini","gemini-api","openai-compatible"],Zc=Un.join("|")});import{existsSync as ut,mkdirSync as $n,readFileSync as dt,writeFileSync as Hn}from"node:fs";import{homedir as jn,totalmem as cl}from"node:os";import Je from"node:path";function Yn(r){return{...r,...r.harnessRoot?.trim()?{harnessRoot:K(r.harnessRoot.trim())}:{},...r.defaultRepo?.trim()?{defaultRepo:K(r.defaultRepo.trim())}:{}}}function x(){if(!ut(lt))return{};try{return Yn(JSON.parse(dt(lt,"utf8")))}catch{return{}}}function mt(){if(!ut(qe))return{};try{return JSON.parse(dt(qe,"utf8"))}catch{return{}}}function Vn(r){$n(ze,{recursive:!0}),Hn(qe,`${JSON.stringify(r,null,2)}
3
+ `,{mode:384})}function pt(){return process.env.KYNVER_API_KEY?process.env.KYNVER_API_KEY:mt().apiKey}function Gn(r,e){Vn({...mt(),runnerToken:e,runnerTokenAgentOsId:r})}function qn(r){let e=ft(r);return e||zn("requires --base-url, KYNVER_API_URL, KYNVER_CRON_FIRE_BASE_URL, or ~/.kynver/config.json apiBaseUrl"),e}function ft(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 e?Ie(String(e)):void 0}async function gt(r,e,t){let n=pt(),o=ft(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 Jn(e,{baseUrl:o,apiKey:n});return s&&s!==r?(Gn(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 Jn(r,e){let t=e?.apiKey||pt();if(!t)throw new Error("API key required \u2014 run `kynver login` first");let o=`${qn(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 zn(r){console.error(r),process.exit(1)}var ze,lt,qe,kl,vl,I=c(()=>{"use strict";Ne();V();k();M();ie();le();De();ue();at();ct();he();ze=Je.join(jn(),".kynver"),lt=Je.join(ze,"config.json"),qe=Je.join(ze,"credentials");kl=500*1024*1024,vl=4*1024*1024*1024});import ht 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=x(),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 ht.join(ye(r),"runs")}function Xn(r){return ht.join(ye(r),"worktrees")}function wr(){let r=Xe();return{harnessRoot:r,runsDir:Or(r),worktreesDir:Xn(r)}}var Ke=c(()=>{"use strict";I();Ge();he();k()});import{existsSync as Bt,realpathSync as Wt,readFileSync as Ut}from"node:fs";import Sr from"node:path";var $t=new Set(["ext4","ext3","ext2","btrfs","xfs","f2fs","zfs","tmpfs","overlay","overlayfs"]),Ht=new Set(["9p","drvfs","nfs","nfs4","cifs","smb","smbfs","smb3","sshfs","fuse.sshfs","davfs","davfs2","glusterfs","ceph","lustre","afs","vboxsf","prl_fs","virtiofs"]);function jt(){try{return Ut("/proc/self/mounts","utf8")}catch{return null}}function Yt(r){let e=Sr.resolve(r);for(let t=0;t<64;t+=1){if(Bt(e))try{return Wt.native(e)}catch{return e}let n=Sr.dirname(e);if(n===e)return e;e=n}return e}function Vt(r){return r.replace(/\\(\d{3})/g,(e,t)=>String.fromCharCode(Number.parseInt(t,8)))}function Gt(r){let e=[];for(let t of r.split(`
4
+ `)){let n=t.trim().split(/\s+/);n.length<3||e.push({mountPoint:Vt(n[1]),fsType:n[2]})}return e}function qt(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??Yt)(r),o=(e?.mountsSource??jt)();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=qt(n,Gt(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 Ht.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}:$t.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"}},Jt=[`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 zt(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=zt(r);if(t!==null&&t>1)throw new ne(t,1);r.exec("BEGIN IMMEDIATE");try{for(let n of Jt)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 Xt}from"node:fs";import Qt from"node:path";import{DatabaseSync as Zt}from"node:sqlite";var X=class extends Error{constructor(e){super(`local-run-store refused: ${e}`),this.name="FilesystemPolicyError"}},en="local-run-store.sqlite",rn=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);Xt(e.directory,{recursive:!0,mode:448});let n=Qt.join(e.directory,e.filename??en),o=new Zt(n,{timeout:e.busyTimeoutMs??rn}),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
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 tn,renameSync as nn}from"node:fs";function on(r,e){let t=`${r}.quarantine-${e}`;for(let n of["","-wal","-shm"]){let o=`${r}${n}`;tn(o)&&nn(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=on(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")}}Ke();function Qn(){if(process.env.KYNVER_LRS_TEST_CLASSIFY_BYPASS==="1")return{mountsSource:()=>"/dev/vda / ext4 rw 0 0",resolveRealPath:()=>"/tmp/kynver-lrs-test/db"}}function Zn(){return yt.classifyOptions??Qn()}var yt={};function eo(r){yt=r}var Rt=300*1e3,P=null,ee=0;function ro(r){ee+=1;try{let e=Zn(),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 to(r,e){return r.store||r.permanentRefusal?!1:r.failedAtMs===null?!0:e-r.failedAtMs>=Rt}function f(r=Date.now()){let e=Xe();return(!P||P.status.harnessRoot!==e||to(P,r))&&(Ze(),P=ro(e)),P.store}function St(){return P?P.status:{state:"unopened",harnessRoot:null,databasePath:null,schemaVersion:null,recovered:!1,quarantinedTo:null,reason:null,openAttempts:ee}}function Qe(){return f(),St()}function Ze(){try{P?.store?.close()}catch{}P=null}function no(){Ze(),ee=0}I();k();import{existsSync as oo,readFileSync as so}from"node:fs";import{homedir as io}from"node:os";import ao from"node:path";var co=3e4,_=null;function er(r){let e=r.replace(/[^A-Za-z0-9_-]/g,"_");return ao.join(io(),".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 lo(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 uo(r,e){try{let t=er(r),n={contractVersion:1,agentOsId:r,flags:rr(e),deliveredAt:new Date().toISOString()};we(t,n),_={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(_&&r-_.loadedAtMs<co)return _.flags;try{let e=x().agentOsId?.trim();if(!e)return _={flags:{},loadedAtMs:r,file:null},_.flags;let t=er(e);if(!oo(t))return _={flags:{},loadedAtMs:r,file:t},_.flags;let n=JSON.parse(so(t,"utf8")),o=n?.contractVersion===1?rr(n.flags):{};return _={flags:o,loadedAtMs:r,file:t},o}catch{return _={flags:{},loadedAtMs:r,file:null},_.flags}}function mo(){_=null}var bt=[{key:"dispatchReceipts",env:"KYNVER_LRS_DISPATCH_RECEIPTS",milestone:"D1"},{key:"admission",env:"KYNVER_LRS_ADMISSION",milestone:"D2"},{key:"planOutbox",env:"KYNVER_LRS_PLAN_OUTBOX",milestone:"D3"},{key:"keeper",env:"KYNVER_LRS_KEEPER",milestone:"D4"},{key:"meshLease",env:"KYNVER_LRS_MESH_LEASE",milestone:"D4"},{key:"quota",env:"KYNVER_LRS_QUOTA",milestone:"D4"}];function kt(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 bt){let i=r[s.env];if(typeof i=="string"&&i.trim()!==""){let l=kt(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 po(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 fo(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 go(r){re("completion-sent",r)}function ho(r,e){re("completion-acked",r,{outcome:e})}function yo(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 Ro(r){let e=String(r??"").split(":")[0]?.trim()??"";return e.length>0?e.slice(0,64):"unknown"}function So(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 bo=600*1e3;function ko(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 vo(r,e){if(O()!=="enforce")return[];let t=f();if(!t)return[];let n=e?.nowMs??Date.now(),o=e?.windowMs??bo;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 _o=900*1e3,vt=10080*60*1e3,xo=1440*60*1e3,Eo=500,Co=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??_o;try{let s=t.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(n-vt).toISOString(),limit:Eo}),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>=xo&&a.length+5<=Co&&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>=vt}).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 Ao(){R.storeFailures=0,R.completionReplaysObserved=0,R.completionReplaysShortCircuited=0,R.agedReceiptsPruned=0}import{readdirSync as Do,readFileSync as Mo}from"node:fs";var B=900*1e3,lr="admission-shadow",cr="worker-slot:",E={storeFailures:0,missingForLive:0,deadSlotsReleased:0},Se=!1;function Oo(){Se=!1}function W(r=process.env){return A(r).flags.admission}function be(r,e){return`${cr}${r}:${e}`}function wo(r,e){if(W()==="off")return;let t=f();if(t)try{t.tryReserveAdmission(be(r,e),lr,B)}catch{E.storeFailures+=1}}function ur(r,e){if(W()==="off")return;let t=f();if(t)try{t.releaseAdmission(be(r,e),lr)}catch{E.storeFailures+=1}}function Io(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=>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 To(){E.storeFailures=0,E.missingForLive=0,E.deadSlotsReleased=0,Se=!1}var _e="worker-slot-n:",ke=64;function _t(r){return`${_e}${r}`}function ve(r,e){return`${r}:${e}`}var C={enforceStoreFailures:0,admissionsRefusedSlots:0,admissionsRefusedDiskBackstop:0};function No(r){if(W()!=="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(_t(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(W()==="off")return;let t=f();if(t)try{let n=ve(r,e),o=t.listAdmissionReservations({keyPrefix:_e,limit:ke});for(let s of o)s.owner===n&&t.releaseAdmission(s.key,n)}catch{C.enforceStoreFailures+=1}}function Po(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=>ve(l.runId,l.workerName))),o=t.listAdmissionReservations({keyPrefix:_e,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(_t(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 Lo(){C.enforceStoreFailures=0,C.admissionsRefusedSlots=0,C.admissionsRefusedDiskBackstop=0}var Ko="dispatch:claim:",Fo=900*1e3,Bo=10080*60*1e3,Wo=200,w={recoveredStrandedClaims:0,recoveryDeferredOrphans:0,recoveryStoreFailures:0};function xt(r){if(process.platform!=="linux"||!r.trim())return null;let e=[];try{e=Do("/proc")}catch{return null}for(let t of e)if(/^\d+$/.test(t)&&Number(t)!==process.pid)try{if(Mo(`/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??Fo,i=r.findOrphanPid??xt,a=[],u;try{u=n.listOperationReceipts({operation:"dispatch-claim",recordedAfter:new Date(o-Bo).toISOString(),limit:Wo})}catch{return w.recoveryStoreFailures+=1,t}for(let l of u){let m=l.idempotencyKey.slice(Ko.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 Uo(){w.recoveredStrandedClaims=0,w.recoveryDeferredOrphans=0,w.recoveryStoreFailures=0}ae();import Xo from"node:path";var $o="kynver-harness:",Ho="@runner:";function Et(r,e){let t=r.trim(),n=e.trim();return`${$o}${t}${Ho}${n}`}I();import Ot from"node:os";var jo="embedded-1",Yo=[{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"}],Vo={"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
+ `)},Go={"harness.maxTaskAttempts":4,"harness.dispatchCooldownMs":5e3,"daemon.idleIntervalMs":5*6e4,"daemon.maxIdleStreak":10},Ct={version:jo,generatedAt:"1970-01-01T00:00:00.000Z",personas:Yo,instructions:Vo,policyThresholds:Go};var qo=Ct;function At(){return qo.version}M();function L(r){return r?.trim()?r.trim():null}function wt(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)??Ot.hostname(),hostname:L(e.HOSTNAME)??Ot.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:At()}}function It(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 Nt(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 Jo(r,e){let t=Nt(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 zo(r,e){let t=Nt(e);return{ok:!1,status:0,response:{error:r instanceof Error?r.message:String(r),timeoutMs:t}}}async function Tt(r,e,t,n){try{return await Jo(async o=>{let s=await fetch(r,{method:"POST",headers:It(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 zo(o,n?.timeoutMs)}}async function Pt(r,e,t,n){let o=await Tt(r,e,t,{timeoutMs:n.timeoutMs});if(o.ok||o.status!==401)return o;let s=await gt(e,n.agentOsId,{baseUrl:n.baseUrl});return s.ok?{...await Tt(r,s.token,t,{timeoutMs:n.timeoutMs}),refreshedAuth:!0}:{...o,authRefreshFailure:s.reason}}async function Lt(r){let e=`${r.baseUrl}/api/agent-os/by-id/${encodeURIComponent(r.agentOsId)}/tasks/${encodeURIComponent(r.taskId)}/release`,t;try{t=await Pt(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 Qo(){hr=!1}async function Zo(r){if(hr||O()!=="enforce")return null;hr=!0;try{let e=wt().runnerId,t=await fr({hasLiveWorker:r.hasLiveWorker,worktreePathFor:({runId:n,workerName:o})=>Xo.join(Ar().worktreesDir,n,o),releaseClaim:async({taskId:n,leaseToken:o,runId:s})=>{let i=await Lt({baseUrl:r.baseUrl,secret:r.secret,agentOsId:r.agentOsId,taskId:n,leaseOwner:Et(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 Au=600*1e3,te={storeFailures:0,corruptItemsSeen:0,corruptItemsQuarantined:0,duplicateDrainsObserved:0,halfArchivesCompleted:0};function Dt(){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 Mt="daemon-keeper",es=1800*1e3;function rs(r){if(U("keeper")==="off")return;let e=f();if(e)try{e.saveRecoveryCheckpoint({scope:Mt,payloadJson:JSON.stringify(r)})}catch{g.keeperStoreFailures+=1}}function ts(){if(U("keeper")!=="enforce")return null;let r=f();if(!r)return null;try{let e=r.latestRecoveryCheckpoint(Mt);if(!e)return null;let t=JSON.parse(e.payloadJson),n=Date.now()-Date.parse(e.createdAt);if(!Number.isFinite(n)||n>es)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 ns(r,e){if(U("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 os(r,e){let t=U("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 xe(r){return`quota-cooldown:${r}`}var Kt="quota-preflight";function ss(r,e){if(U("quota")==="off")return;let t=f();if(t)try{t.tryReserveAdmission(xe(r),Kt,e)}catch{g.quotaStoreFailures+=1}}function is(r){if(U("quota")==="off")return;let e=f();if(e)try{e.releaseAdmission(xe(r),Kt)}catch{g.quotaStoreFailures+=1}}function as(r,e){let t=U("quota");if(t==="off")return null;let n=f();if(!n)return null;try{let o=n.listAdmissionReservations({keyPrefix:xe(r),limit:50}).find(i=>i.key===xe(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 cs(){g.keeperStoreFailures=0,g.meshStoreFailures=0,g.quotaStoreFailures=0,g.meshLeaseDivergences=0,g.meshEnforceStaleInversions=0,g.quotaVerdictDivergences=0}function ls(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,Dt()),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,_e as ADMISSION_SLOT_KEY_PREFIX,X as FilesystemPolicyError,Rt as LOCAL_RUN_STORE_OPEN_RETRY_MS,bt as LOCAL_RUN_STORE_SURFACES,Ce as LOCAL_SCHEMA_VERSION,ne as SchemaDowngradeRefusedError,Y as SqliteLocalRunStore,Lo as __resetAdmissionEnforceCountersForTests,To as __resetAdmissionShadowCountersForTests,Uo as __resetDispatchClaimRecoveryForTests,Ao as __resetDispatchReceiptCountersForTests,no as __resetLocalRunStoreLifecycleForTests,mo as __resetRemoteSurfaceFlagsCacheForTests,cs as __resetSmallSurfaceCountersForTests,Qo as __resetStartupClaimRecoveryForTests,eo as __setLocalRunStoreLifecycleTestOverrides,No as acquireWorkerAdmissionSlot,pr as admissionEnforceCounters,dr as admissionShadowCounters,po as anyLocalRunStoreSurfaceActive,as as assessQuotaCooldownReservation,ls as buildLocalRunStoreTickPosture,Ee as classifyDatabaseDirectory,is as clearQuotaCooldownReservation,Ze as closeLocalRunStore,gr as dispatchClaimRecoveryCounters,ar as dispatchReceiptCounters,O as dispatchReceiptsMode,lo as extractLocalRunStoreFlagsFromOperatorTickResponse,xt as findLiveProcessByCmdlinePath,f as getLocalRunStore,St as getLocalRunStoreLifecycleStatus,tr as getRemoteSurfaceFlags,q as leaseTokenAttempt,vo as listRecentDispatchStartFailures,Zo as maybeRunStartupClaimRecovery,yo as noteCompletionReplayIfAcked,Ae as openSqliteLocalRunStoreWithRecovery,kt as parseLocalRunStoreSurfaceMode,uo as persistRemoteSurfaceFlags,Qe as probeLocalRunStore,os as readMeshLeaseCheckpoint,Oo as rearmAdmissionAdoptionPass,Io as reconcileAdmissionShadow,Po as reconcileNumberedAdmissionSlots,ho as recordCompletionAckedReceipt,go as recordCompletionSentReceipt,fo as recordDispatchClaimReceipt,Re as recordDispatchReleasedReceipt,sr as recordDispatchSpawnedReceipt,ko as recordDispatchStartFailedReceipt,ss as recordQuotaCooldownReservation,fr as recoverStrandedDispatchClaims,Ro as releaseReasonClass,mr as releaseWorkerAdmissionSlot,ur as releaseWorkerSlotReservation,er as remoteSurfaceFlagsPath,A as resolveLocalRunStoreSurfaceFlags,ts as restoreKeeperBackoffCheckpoint,rs as saveKeeperBackoffCheckpoint,ns as saveMeshLeaseCheckpoint,ir as scanDispatchReceiptInvariants,So as shouldShortCircuitCompletionReplay,Rr as smallSurfaceCounters,wo as takeWorkerSlotReservation};